Allow LaTeX_CLASS_OPTIONS to set options, also from a property
[org-mode.git] / lisp / org.el
blob5616c5e711b9565e460c4b40188e03792baf6712
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
3565 org-archive-subtree-default
3566 org-archive-subtree-default-with-confirmation)))
3568 ;; Autoload Column View Code
3570 (declare-function org-columns-number-to-string "org-colview")
3571 (declare-function org-columns-get-format-and-top-level "org-colview")
3572 (declare-function org-columns-compute "org-colview")
3574 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3575 '(org-columns-number-to-string org-columns-get-format-and-top-level
3576 org-columns-compute org-agenda-columns org-columns-remove-overlays
3577 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3579 ;; Autoload ID code
3581 (declare-function org-id-store-link "org-id")
3582 (declare-function org-id-locations-load "org-id")
3583 (declare-function org-id-locations-save "org-id")
3584 (defvar org-id-track-globally)
3585 (org-autoload "org-id"
3586 '(org-id-get-create org-id-new org-id-copy org-id-get
3587 org-id-get-with-outline-path-completion
3588 org-id-get-with-outline-drilling
3589 org-id-goto org-id-find org-id-store-link))
3591 ;; Autoload Plotting Code
3593 (org-autoload "org-plot"
3594 '(org-plot/gnuplot))
3596 ;;; Variables for pre-computed regular expressions, all buffer local
3598 (defvar org-drawer-regexp nil
3599 "Matches first line of a hidden block.")
3600 (make-variable-buffer-local 'org-drawer-regexp)
3601 (defvar org-todo-regexp nil
3602 "Matches any of the TODO state keywords.")
3603 (make-variable-buffer-local 'org-todo-regexp)
3604 (defvar org-not-done-regexp nil
3605 "Matches any of the TODO state keywords except the last one.")
3606 (make-variable-buffer-local 'org-not-done-regexp)
3607 (defvar org-not-done-heading-regexp nil
3608 "Matches a TODO headline that is not done.")
3609 (make-variable-buffer-local 'org-not-done-regexp)
3610 (defvar org-todo-line-regexp nil
3611 "Matches a headline and puts TODO state into group 2 if present.")
3612 (make-variable-buffer-local 'org-todo-line-regexp)
3613 (defvar org-complex-heading-regexp nil
3614 "Matches a headline and puts everything into groups:
3615 group 1: the stars
3616 group 2: The todo keyword, maybe
3617 group 3: Priority cookie
3618 group 4: True headline
3619 group 5: Tags")
3620 (make-variable-buffer-local 'org-complex-heading-regexp)
3621 (defvar org-complex-heading-regexp-format nil)
3622 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3623 (defvar org-todo-line-tags-regexp nil
3624 "Matches a headline and puts TODO state into group 2 if present.
3625 Also put tags into group 4 if tags are present.")
3626 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3627 (defvar org-nl-done-regexp nil
3628 "Matches newline followed by a headline with the DONE keyword.")
3629 (make-variable-buffer-local 'org-nl-done-regexp)
3630 (defvar org-looking-at-done-regexp nil
3631 "Matches the DONE keyword a point.")
3632 (make-variable-buffer-local 'org-looking-at-done-regexp)
3633 (defvar org-ds-keyword-length 12
3634 "Maximum length of the Deadline and SCHEDULED keywords.")
3635 (make-variable-buffer-local 'org-ds-keyword-length)
3636 (defvar org-deadline-regexp nil
3637 "Matches the DEADLINE keyword.")
3638 (make-variable-buffer-local 'org-deadline-regexp)
3639 (defvar org-deadline-time-regexp nil
3640 "Matches the DEADLINE keyword together with a time stamp.")
3641 (make-variable-buffer-local 'org-deadline-time-regexp)
3642 (defvar org-deadline-line-regexp nil
3643 "Matches the DEADLINE keyword and the rest of the line.")
3644 (make-variable-buffer-local 'org-deadline-line-regexp)
3645 (defvar org-scheduled-regexp nil
3646 "Matches the SCHEDULED keyword.")
3647 (make-variable-buffer-local 'org-scheduled-regexp)
3648 (defvar org-scheduled-time-regexp nil
3649 "Matches the SCHEDULED keyword together with a time stamp.")
3650 (make-variable-buffer-local 'org-scheduled-time-regexp)
3651 (defvar org-closed-time-regexp nil
3652 "Matches the CLOSED keyword together with a time stamp.")
3653 (make-variable-buffer-local 'org-closed-time-regexp)
3655 (defvar org-keyword-time-regexp nil
3656 "Matches any of the 4 keywords, together with the time stamp.")
3657 (make-variable-buffer-local 'org-keyword-time-regexp)
3658 (defvar org-keyword-time-not-clock-regexp nil
3659 "Matches any of the 3 keywords, together with the time stamp.")
3660 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3661 (defvar org-maybe-keyword-time-regexp nil
3662 "Matches a timestamp, possibly preceeded by a keyword.")
3663 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3664 (defvar org-planning-or-clock-line-re nil
3665 "Matches a line with planning or clock info.")
3666 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3668 (defconst org-plain-time-of-day-regexp
3669 (concat
3670 "\\(\\<[012]?[0-9]"
3671 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3672 "\\(--?"
3673 "\\(\\<[012]?[0-9]"
3674 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3675 "\\)?")
3676 "Regular expression to match a plain time or time range.
3677 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3678 groups carry important information:
3679 0 the full match
3680 1 the first time, range or not
3681 8 the second time, if it is a range.")
3683 (defconst org-plain-time-extension-regexp
3684 (concat
3685 "\\(\\<[012]?[0-9]"
3686 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3687 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3688 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3689 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3690 groups carry important information:
3691 0 the full match
3692 7 hours of duration
3693 9 minutes of duration")
3695 (defconst org-stamp-time-of-day-regexp
3696 (concat
3697 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3698 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3699 "\\(--?"
3700 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3701 "Regular expression to match a timestamp time or time range.
3702 After a match, the following groups carry important information:
3703 0 the full match
3704 1 date plus weekday, for back referencing to make sure both times are on the same day
3705 2 the first time, range or not
3706 4 the second time, if it is a range.")
3708 (defconst org-startup-options
3709 '(("fold" org-startup-folded t)
3710 ("overview" org-startup-folded t)
3711 ("nofold" org-startup-folded nil)
3712 ("showall" org-startup-folded nil)
3713 ("showeverything" org-startup-folded showeverything)
3714 ("content" org-startup-folded content)
3715 ("indent" org-startup-indented t)
3716 ("noindent" org-startup-indented nil)
3717 ("hidestars" org-hide-leading-stars t)
3718 ("showstars" org-hide-leading-stars nil)
3719 ("odd" org-odd-levels-only t)
3720 ("oddeven" org-odd-levels-only nil)
3721 ("align" org-startup-align-all-tables t)
3722 ("noalign" org-startup-align-all-tables nil)
3723 ("customtime" org-display-custom-times t)
3724 ("logdone" org-log-done time)
3725 ("lognotedone" org-log-done note)
3726 ("nologdone" org-log-done nil)
3727 ("lognoteclock-out" org-log-note-clock-out t)
3728 ("nolognoteclock-out" org-log-note-clock-out nil)
3729 ("logrepeat" org-log-repeat state)
3730 ("lognoterepeat" org-log-repeat note)
3731 ("nologrepeat" org-log-repeat nil)
3732 ("logreschedule" org-log-reschedule time)
3733 ("lognotereschedule" org-log-reschedule note)
3734 ("nologreschedule" org-log-reschedule nil)
3735 ("logredeadline" org-log-redeadline time)
3736 ("lognoteredeadline" org-log-redeadline note)
3737 ("nologredeadline" org-log-redeadline nil)
3738 ("fninline" org-footnote-define-inline t)
3739 ("nofninline" org-footnote-define-inline nil)
3740 ("fnlocal" org-footnote-section nil)
3741 ("fnauto" org-footnote-auto-label t)
3742 ("fnprompt" org-footnote-auto-label nil)
3743 ("fnconfirm" org-footnote-auto-label confirm)
3744 ("fnplain" org-footnote-auto-label plain)
3745 ("fnadjust" org-footnote-auto-adjust t)
3746 ("nofnadjust" org-footnote-auto-adjust nil)
3747 ("constcgs" constants-unit-system cgs)
3748 ("constSI" constants-unit-system SI)
3749 ("noptag" org-tag-persistent-alist nil)
3750 ("hideblocks" org-hide-block-startup t)
3751 ("nohideblocks" org-hide-block-startup nil))
3752 "Variable associated with STARTUP options for org-mode.
3753 Each element is a list of three items: The startup options as written
3754 in the #+STARTUP line, the corresponding variable, and the value to
3755 set this variable to if the option is found. An optional forth element PUSH
3756 means to push this value onto the list in the variable.")
3758 (defun org-set-regexps-and-options ()
3759 "Precompute regular expressions for current buffer."
3760 (when (org-mode-p)
3761 (org-set-local 'org-todo-kwd-alist nil)
3762 (org-set-local 'org-todo-key-alist nil)
3763 (org-set-local 'org-todo-key-trigger nil)
3764 (org-set-local 'org-todo-keywords-1 nil)
3765 (org-set-local 'org-done-keywords nil)
3766 (org-set-local 'org-todo-heads nil)
3767 (org-set-local 'org-todo-sets nil)
3768 (org-set-local 'org-todo-log-states nil)
3769 (org-set-local 'org-file-properties nil)
3770 (org-set-local 'org-file-tags nil)
3771 (let ((re (org-make-options-regexp
3772 '("CATEGORY" "TODO" "COLUMNS"
3773 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3774 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3775 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3776 (splitre "[ \t]+")
3777 kwds kws0 kwsa key log value cat arch tags const links hw dws
3778 tail sep kws1 prio props ftags drawers
3779 ext-setup-or-nil setup-contents (start 0))
3780 (save-excursion
3781 (save-restriction
3782 (widen)
3783 (goto-char (point-min))
3784 (while (or (and ext-setup-or-nil
3785 (string-match re ext-setup-or-nil start)
3786 (setq start (match-end 0)))
3787 (and (setq ext-setup-or-nil nil start 0)
3788 (re-search-forward re nil t)))
3789 (setq key (upcase (match-string 1 ext-setup-or-nil))
3790 value (org-match-string-no-properties 2 ext-setup-or-nil))
3791 (cond
3792 ((equal key "CATEGORY")
3793 (if (string-match "[ \t]+$" value)
3794 (setq value (replace-match "" t t value)))
3795 (setq cat value))
3796 ((member key '("SEQ_TODO" "TODO"))
3797 (push (cons 'sequence (org-split-string value splitre)) kwds))
3798 ((equal key "TYP_TODO")
3799 (push (cons 'type (org-split-string value splitre)) kwds))
3800 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3801 ;; general TODO-like setup
3802 (push (cons (intern (downcase (match-string 1 key)))
3803 (org-split-string value splitre)) kwds))
3804 ((equal key "TAGS")
3805 (setq tags (append tags (if tags '("\\n") nil)
3806 (org-split-string value splitre))))
3807 ((equal key "COLUMNS")
3808 (org-set-local 'org-columns-default-format value))
3809 ((equal key "LINK")
3810 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3811 (push (cons (match-string 1 value)
3812 (org-trim (match-string 2 value)))
3813 links)))
3814 ((equal key "PRIORITIES")
3815 (setq prio (org-split-string value " +")))
3816 ((equal key "PROPERTY")
3817 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3818 (push (cons (match-string 1 value) (match-string 2 value))
3819 props)))
3820 ((equal key "FILETAGS")
3821 (when (string-match "\\S-" value)
3822 (setq ftags
3823 (append
3824 ftags
3825 (apply 'append
3826 (mapcar (lambda (x) (org-split-string x ":"))
3827 (org-split-string value)))))))
3828 ((equal key "DRAWERS")
3829 (setq drawers (org-split-string value splitre)))
3830 ((equal key "CONSTANTS")
3831 (setq const (append const (org-split-string value splitre))))
3832 ((equal key "STARTUP")
3833 (let ((opts (org-split-string value splitre))
3834 l var val)
3835 (while (setq l (pop opts))
3836 (when (setq l (assoc l org-startup-options))
3837 (setq var (nth 1 l) val (nth 2 l))
3838 (if (not (nth 3 l))
3839 (set (make-local-variable var) val)
3840 (if (not (listp (symbol-value var)))
3841 (set (make-local-variable var) nil))
3842 (set (make-local-variable var) (symbol-value var))
3843 (add-to-list var val))))))
3844 ((equal key "ARCHIVE")
3845 (string-match " *$" value)
3846 (setq arch (replace-match "" t t value))
3847 (remove-text-properties 0 (length arch)
3848 '(face t fontified t) arch))
3849 ((equal key "SETUPFILE")
3850 (setq setup-contents (org-file-contents
3851 (expand-file-name
3852 (org-remove-double-quotes value))
3853 'noerror))
3854 (if (not ext-setup-or-nil)
3855 (setq ext-setup-or-nil setup-contents start 0)
3856 (setq ext-setup-or-nil
3857 (concat (substring ext-setup-or-nil 0 start)
3858 "\n" setup-contents "\n"
3859 (substring ext-setup-or-nil start)))))
3860 ))))
3861 (when cat
3862 (org-set-local 'org-category (intern cat))
3863 (push (cons "CATEGORY" cat) props))
3864 (when prio
3865 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3866 (setq prio (mapcar 'string-to-char prio))
3867 (org-set-local 'org-highest-priority (nth 0 prio))
3868 (org-set-local 'org-lowest-priority (nth 1 prio))
3869 (org-set-local 'org-default-priority (nth 2 prio)))
3870 (and props (org-set-local 'org-file-properties (nreverse props)))
3871 (and ftags (org-set-local 'org-file-tags
3872 (mapcar 'org-add-prop-inherited ftags)))
3873 (and drawers (org-set-local 'org-drawers drawers))
3874 (and arch (org-set-local 'org-archive-location arch))
3875 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3876 ;; Process the TODO keywords
3877 (unless kwds
3878 ;; Use the global values as if they had been given locally.
3879 (setq kwds (default-value 'org-todo-keywords))
3880 (if (stringp (car kwds))
3881 (setq kwds (list (cons org-todo-interpretation
3882 (default-value 'org-todo-keywords)))))
3883 (setq kwds (reverse kwds)))
3884 (setq kwds (nreverse kwds))
3885 (let (inter kws kw)
3886 (while (setq kws (pop kwds))
3887 (let ((kws (or
3888 (run-hook-with-args-until-success
3889 'org-todo-setup-filter-hook kws)
3890 kws)))
3891 (setq inter (pop kws) sep (member "|" kws)
3892 kws0 (delete "|" (copy-sequence kws))
3893 kwsa nil
3894 kws1 (mapcar
3895 (lambda (x)
3896 ;; 1 2
3897 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3898 (progn
3899 (setq kw (match-string 1 x)
3900 key (and (match-end 2) (match-string 2 x))
3901 log (org-extract-log-state-settings x))
3902 (push (cons kw (and key (string-to-char key))) kwsa)
3903 (and log (push log org-todo-log-states))
3905 (error "Invalid TODO keyword %s" x)))
3906 kws0)
3907 kwsa (if kwsa (append '((:startgroup))
3908 (nreverse kwsa)
3909 '((:endgroup))))
3910 hw (car kws1)
3911 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3912 tail (list inter hw (car dws) (org-last dws))))
3913 (add-to-list 'org-todo-heads hw 'append)
3914 (push kws1 org-todo-sets)
3915 (setq org-done-keywords (append org-done-keywords dws nil))
3916 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3917 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3918 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3919 (setq org-todo-sets (nreverse org-todo-sets)
3920 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3921 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3922 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3923 ;; Process the constants
3924 (when const
3925 (let (e cst)
3926 (while (setq e (pop const))
3927 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3928 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3929 (setq org-table-formula-constants-local cst)))
3931 ;; Process the tags.
3932 (when tags
3933 (let (e tgs)
3934 (while (setq e (pop tags))
3935 (cond
3936 ((equal e "{") (push '(:startgroup) tgs))
3937 ((equal e "}") (push '(:endgroup) tgs))
3938 ((equal e "\\n") (push '(:newline) tgs))
3939 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3940 (push (cons (match-string 1 e)
3941 (string-to-char (match-string 2 e)))
3942 tgs))
3943 (t (push (list e) tgs))))
3944 (org-set-local 'org-tag-alist nil)
3945 (while (setq e (pop tgs))
3946 (or (and (stringp (car e))
3947 (assoc (car e) org-tag-alist))
3948 (push e org-tag-alist)))))
3950 ;; Compute the regular expressions and other local variables
3951 (if (not org-done-keywords)
3952 (setq org-done-keywords (and org-todo-keywords-1
3953 (list (org-last org-todo-keywords-1)))))
3954 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3955 (length org-scheduled-string)
3956 (length org-clock-string)
3957 (length org-closed-string)))
3958 org-drawer-regexp
3959 (concat "^[ \t]*:\\("
3960 (mapconcat 'regexp-quote org-drawers "\\|")
3961 "\\):[ \t]*$")
3962 org-not-done-keywords
3963 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3964 org-todo-regexp
3965 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3966 "\\|") "\\)\\>")
3967 org-not-done-regexp
3968 (concat "\\<\\("
3969 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3970 "\\)\\>")
3971 org-not-done-heading-regexp
3972 (concat "^\\(\\*+\\)[ \t]+\\("
3973 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3974 "\\)\\>")
3975 org-todo-line-regexp
3976 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3977 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3978 "\\)\\>\\)?[ \t]*\\(.*\\)")
3979 org-complex-heading-regexp
3980 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3981 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3982 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3983 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3984 org-complex-heading-regexp-format
3985 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3986 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3987 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3988 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3989 org-nl-done-regexp
3990 (concat "\n\\*+[ \t]+"
3991 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3992 "\\)" "\\>")
3993 org-todo-line-tags-regexp
3994 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3995 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3996 (org-re
3997 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3998 org-looking-at-done-regexp
3999 (concat "^" "\\(?:"
4000 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4001 "\\>")
4002 org-deadline-regexp (concat "\\<" org-deadline-string)
4003 org-deadline-time-regexp
4004 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4005 org-deadline-line-regexp
4006 (concat "\\<\\(" org-deadline-string "\\).*")
4007 org-scheduled-regexp
4008 (concat "\\<" org-scheduled-string)
4009 org-scheduled-time-regexp
4010 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4011 org-closed-time-regexp
4012 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4013 org-keyword-time-regexp
4014 (concat "\\<\\(" org-scheduled-string
4015 "\\|" org-deadline-string
4016 "\\|" org-closed-string
4017 "\\|" org-clock-string "\\)"
4018 " *[[<]\\([^]>]+\\)[]>]")
4019 org-keyword-time-not-clock-regexp
4020 (concat "\\<\\(" org-scheduled-string
4021 "\\|" org-deadline-string
4022 "\\|" org-closed-string
4023 "\\)"
4024 " *[[<]\\([^]>]+\\)[]>]")
4025 org-maybe-keyword-time-regexp
4026 (concat "\\(\\<\\(" org-scheduled-string
4027 "\\|" org-deadline-string
4028 "\\|" org-closed-string
4029 "\\|" org-clock-string "\\)\\)?"
4030 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4031 org-planning-or-clock-line-re
4032 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4033 "\\|" org-deadline-string
4034 "\\|" org-closed-string "\\|" org-clock-string
4035 "\\)\\>\\)")
4037 (org-compute-latex-and-specials-regexp)
4038 (org-set-font-lock-defaults))))
4040 (defun org-file-contents (file &optional noerror)
4041 "Return the contents of FILE, as a string."
4042 (if (or (not file)
4043 (not (file-readable-p file)))
4044 (if noerror
4045 (progn
4046 (message "Cannot read file %s" file)
4047 (ding) (sit-for 2)
4049 (error "Cannot read file %s" file))
4050 (with-temp-buffer
4051 (insert-file-contents file)
4052 (buffer-string))))
4054 (defun org-extract-log-state-settings (x)
4055 "Extract the log state setting from a TODO keyword string.
4056 This will extract info from a string like \"WAIT(w@/!)\"."
4057 (let (kw key log1 log2)
4058 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4059 (setq kw (match-string 1 x)
4060 key (and (match-end 2) (match-string 2 x))
4061 log1 (and (match-end 3) (match-string 3 x))
4062 log2 (and (match-end 4) (match-string 4 x)))
4063 (and (or log1 log2)
4064 (list kw
4065 (and log1 (if (equal log1 "!") 'time 'note))
4066 (and log2 (if (equal log2 "!") 'time 'note)))))))
4068 (defun org-remove-keyword-keys (list)
4069 "Remove a pair of parenthesis at the end of each string in LIST."
4070 (mapcar (lambda (x)
4071 (if (string-match "(.*)$" x)
4072 (substring x 0 (match-beginning 0))
4074 list))
4076 ;; FIXME: this could be done much better, using second characters etc.
4077 (defun org-assign-fast-keys (alist)
4078 "Assign fast keys to a keyword-key alist.
4079 Respect keys that are already there."
4080 (let (new e k c c1 c2 (char ?a))
4081 (while (setq e (pop alist))
4082 (cond
4083 ((equal e '(:startgroup)) (push e new))
4084 ((equal e '(:endgroup)) (push e new))
4085 ((equal e '(:newline)) (push e new))
4087 (setq k (car e) c2 nil)
4088 (if (cdr e)
4089 (setq c (cdr e))
4090 ;; automatically assign a character.
4091 (setq c1 (string-to-char
4092 (downcase (substring
4093 k (if (= (string-to-char k) ?@) 1 0)))))
4094 (if (or (rassoc c1 new) (rassoc c1 alist))
4095 (while (or (rassoc char new) (rassoc char alist))
4096 (setq char (1+ char)))
4097 (setq c2 c1))
4098 (setq c (or c2 char)))
4099 (push (cons k c) new))))
4100 (nreverse new)))
4102 ;;; Some variables used in various places
4104 (defvar org-window-configuration nil
4105 "Used in various places to store a window configuration.")
4106 (defvar org-selected-window nil
4107 "Used in various places to store a window configuration.")
4108 (defvar org-finish-function nil
4109 "Function to be called when `C-c C-c' is used.
4110 This is for getting out of special buffers like remember.")
4113 ;; FIXME: Occasionally check by commenting these, to make sure
4114 ;; no other functions uses these, forgetting to let-bind them.
4115 (defvar entry)
4116 (defvar last-state)
4117 (defvar date)
4119 ;; Defined somewhere in this file, but used before definition.
4120 (defvar org-html-entities)
4121 (defvar org-struct-menu)
4122 (defvar org-org-menu)
4123 (defvar org-tbl-menu)
4125 ;;;; Define the Org-mode
4127 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4128 (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."))
4131 ;; We use a before-change function to check if a table might need
4132 ;; an update.
4133 (defvar org-table-may-need-update t
4134 "Indicates that a table might need an update.
4135 This variable is set by `org-before-change-function'.
4136 `org-table-align' sets it back to nil.")
4137 (defun org-before-change-function (beg end)
4138 "Every change indicates that a table might need an update."
4139 (setq org-table-may-need-update t))
4140 (defvar org-mode-map)
4141 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4142 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4143 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4144 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4145 (defvar org-table-buffer-is-an nil)
4146 (defconst org-outline-regexp "\\*+ ")
4148 ;;;###autoload
4149 (define-derived-mode org-mode outline-mode "Org"
4150 "Outline-based notes management and organizer, alias
4151 \"Carsten's outline-mode for keeping track of everything.\"
4153 Org-mode develops organizational tasks around a NOTES file which
4154 contains information about projects as plain text. Org-mode is
4155 implemented on top of outline-mode, which is ideal to keep the content
4156 of large files well structured. It supports ToDo items, deadlines and
4157 time stamps, which magically appear in the diary listing of the Emacs
4158 calendar. Tables are easily created with a built-in table editor.
4159 Plain text URL-like links connect to websites, emails (VM), Usenet
4160 messages (Gnus), BBDB entries, and any files related to the project.
4161 For printing and sharing of notes, an Org-mode file (or a part of it)
4162 can be exported as a structured ASCII or HTML file.
4164 The following commands are available:
4166 \\{org-mode-map}"
4168 ;; Get rid of Outline menus, they are not needed
4169 ;; Need to do this here because define-derived-mode sets up
4170 ;; the keymap so late. Still, it is a waste to call this each time
4171 ;; we switch another buffer into org-mode.
4172 (if (featurep 'xemacs)
4173 (when (boundp 'outline-mode-menu-heading)
4174 ;; Assume this is Greg's port, it used easymenu
4175 (easy-menu-remove outline-mode-menu-heading)
4176 (easy-menu-remove outline-mode-menu-show)
4177 (easy-menu-remove outline-mode-menu-hide))
4178 (define-key org-mode-map [menu-bar headings] 'undefined)
4179 (define-key org-mode-map [menu-bar hide] 'undefined)
4180 (define-key org-mode-map [menu-bar show] 'undefined))
4182 (org-load-modules-maybe)
4183 (easy-menu-add org-org-menu)
4184 (easy-menu-add org-tbl-menu)
4185 (org-install-agenda-files-menu)
4186 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4187 (org-add-to-invisibility-spec '(org-cwidth))
4188 (org-add-to-invisibility-spec '(org-hide-block . t))
4189 (when (featurep 'xemacs)
4190 (org-set-local 'line-move-ignore-invisible t))
4191 (org-set-local 'outline-regexp org-outline-regexp)
4192 (org-set-local 'outline-level 'org-outline-level)
4193 (when (and org-ellipsis
4194 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4195 (fboundp 'make-glyph-code))
4196 (unless org-display-table
4197 (setq org-display-table (make-display-table)))
4198 (set-display-table-slot
4199 org-display-table 4
4200 (vconcat (mapcar
4201 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4202 org-ellipsis)))
4203 (if (stringp org-ellipsis) org-ellipsis "..."))))
4204 (setq buffer-display-table org-display-table))
4205 (org-set-regexps-and-options)
4206 (when (and org-tag-faces (not org-tags-special-faces-re))
4207 ;; tag faces set outside customize.... force initialization.
4208 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4209 ;; Calc embedded
4210 (org-set-local 'calc-embedded-open-mode "# ")
4211 (modify-syntax-entry ?# "<")
4212 (modify-syntax-entry ?@ "w")
4213 (if org-startup-truncated (setq truncate-lines t))
4214 (org-set-local 'font-lock-unfontify-region-function
4215 'org-unfontify-region)
4216 ;; Activate before-change-function
4217 (org-set-local 'org-table-may-need-update t)
4218 (org-add-hook 'before-change-functions 'org-before-change-function nil
4219 'local)
4220 ;; Check for running clock before killing a buffer
4221 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4222 ;; Paragraphs and auto-filling
4223 (org-set-autofill-regexps)
4224 (setq indent-line-function 'org-indent-line-function)
4225 (org-update-radio-target-regexp)
4226 ;; Make sure dependence stuff works reliably, even for users who set it
4227 ;; too late :-(
4228 (if org-enforce-todo-dependencies
4229 (add-hook 'org-blocker-hook
4230 'org-block-todo-from-children-or-siblings-or-parent)
4231 (remove-hook 'org-blocker-hook
4232 'org-block-todo-from-children-or-siblings-or-parent))
4233 (if org-enforce-todo-checkbox-dependencies
4234 (add-hook 'org-blocker-hook
4235 'org-block-todo-from-checkboxes)
4236 (remove-hook 'org-blocker-hook
4237 'org-block-todo-from-checkboxes))
4239 ;; Comment characters
4240 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4241 (org-set-local 'comment-padding " ")
4243 ;; Align options lines
4244 (org-set-local
4245 'align-mode-rules-list
4246 '((org-in-buffer-settings
4247 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4248 (modes . '(org-mode)))))
4250 ;; Imenu
4251 (org-set-local 'imenu-create-index-function
4252 'org-imenu-get-tree)
4254 ;; Make isearch reveal context
4255 (if (or (featurep 'xemacs)
4256 (not (boundp 'outline-isearch-open-invisible-function)))
4257 ;; Emacs 21 and XEmacs make use of the hook
4258 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4259 ;; Emacs 22 deals with this through a special variable
4260 (org-set-local 'outline-isearch-open-invisible-function
4261 (lambda (&rest ignore) (org-show-context 'isearch))))
4263 ;; If empty file that did not turn on org-mode automatically, make it to.
4264 (if (and org-insert-mode-line-in-empty-file
4265 (interactive-p)
4266 (= (point-min) (point-max)))
4267 (insert "# -*- mode: org -*-\n\n"))
4269 (unless org-inhibit-startup
4270 (when org-startup-align-all-tables
4271 (let ((bmp (buffer-modified-p)))
4272 (org-table-map-tables 'org-table-align)
4273 (set-buffer-modified-p bmp)))
4274 (when org-startup-indented
4275 (require 'org-indent)
4276 (org-indent-mode 1))
4277 (org-set-startup-visibility)))
4279 (when (fboundp 'abbrev-table-put)
4280 (abbrev-table-put org-mode-abbrev-table
4281 :parents (list text-mode-abbrev-table)))
4283 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4285 (defun org-current-time ()
4286 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4287 (if (> (car org-time-stamp-rounding-minutes) 1)
4288 (let ((r (car org-time-stamp-rounding-minutes))
4289 (time (decode-time)))
4290 (apply 'encode-time
4291 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4292 (nthcdr 2 time))))
4293 (current-time)))
4295 ;;;; Font-Lock stuff, including the activators
4297 (defvar org-mouse-map (make-sparse-keymap))
4298 (org-defkey org-mouse-map
4299 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4300 (org-defkey org-mouse-map
4301 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4302 (when org-mouse-1-follows-link
4303 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4304 (when org-tab-follows-link
4305 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4306 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4308 (require 'font-lock)
4310 (defconst org-non-link-chars "]\t\n\r<>")
4311 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4312 "shell" "elisp"))
4313 (defvar org-link-types-re nil
4314 "Matches a link that has a url-like prefix like \"http:\"")
4315 (defvar org-link-re-with-space nil
4316 "Matches a link with spaces, optional angular brackets around it.")
4317 (defvar org-link-re-with-space2 nil
4318 "Matches a link with spaces, optional angular brackets around it.")
4319 (defvar org-link-re-with-space3 nil
4320 "Matches a link with spaces, only for internal part in bracket links.")
4321 (defvar org-angle-link-re nil
4322 "Matches link with angular brackets, spaces are allowed.")
4323 (defvar org-plain-link-re nil
4324 "Matches plain link, without spaces.")
4325 (defvar org-bracket-link-regexp nil
4326 "Matches a link in double brackets.")
4327 (defvar org-bracket-link-analytic-regexp nil
4328 "Regular expression used to analyze links.
4329 Here is what the match groups contain after a match:
4330 1: http:
4331 2: http
4332 3: path
4333 4: [desc]
4334 5: desc")
4335 (defvar org-bracket-link-analytic-regexp++ nil
4336 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4337 (defvar org-any-link-re nil
4338 "Regular expression matching any link.")
4340 (defun org-make-link-regexps ()
4341 "Update the link regular expressions.
4342 This should be called after the variable `org-link-types' has changed."
4343 (setq org-link-types-re
4344 (concat
4345 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4346 org-link-re-with-space
4347 (concat
4348 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4349 "\\([^" org-non-link-chars " ]"
4350 "[^" org-non-link-chars "]*"
4351 "[^" org-non-link-chars " ]\\)>?")
4352 org-link-re-with-space2
4353 (concat
4354 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4355 "\\([^" org-non-link-chars " ]"
4356 "[^\t\n\r]*"
4357 "[^" org-non-link-chars " ]\\)>?")
4358 org-link-re-with-space3
4359 (concat
4360 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4361 "\\([^" org-non-link-chars " ]"
4362 "[^\t\n\r]*\\)")
4363 org-angle-link-re
4364 (concat
4365 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4366 "\\([^" org-non-link-chars " ]"
4367 "[^" org-non-link-chars "]*"
4368 "\\)>")
4369 org-plain-link-re
4370 (concat
4371 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4372 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4373 org-bracket-link-regexp
4374 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4375 org-bracket-link-analytic-regexp
4376 (concat
4377 "\\[\\["
4378 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4379 "\\([^]]+\\)"
4380 "\\]"
4381 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4382 "\\]")
4383 org-bracket-link-analytic-regexp++
4384 (concat
4385 "\\[\\["
4386 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4387 "\\([^]]+\\)"
4388 "\\]"
4389 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4390 "\\]")
4391 org-any-link-re
4392 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4393 org-angle-link-re "\\)\\|\\("
4394 org-plain-link-re "\\)")))
4396 (org-make-link-regexps)
4398 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4399 "Regular expression for fast time stamp matching.")
4400 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4401 "Regular expression for fast time stamp matching.")
4402 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4403 "Regular expression matching time strings for analysis.
4404 This one does not require the space after the date, so it can be used
4405 on a string that terminates immediately after the date.")
4406 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4407 "Regular expression matching time strings for analysis.")
4408 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4409 "Regular expression matching time stamps, with groups.")
4410 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4411 "Regular expression matching time stamps (also [..]), with groups.")
4412 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4413 "Regular expression matching a time stamp range.")
4414 (defconst org-tr-regexp-both
4415 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4416 "Regular expression matching a time stamp range.")
4417 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4418 org-ts-regexp "\\)?")
4419 "Regular expression matching a time stamp or time stamp range.")
4420 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4421 org-ts-regexp-both "\\)?")
4422 "Regular expression matching a time stamp or time stamp range.
4423 The time stamps may be either active or inactive.")
4425 (defvar org-emph-face nil)
4427 (defun org-do-emphasis-faces (limit)
4428 "Run through the buffer and add overlays to links."
4429 (let (rtn a)
4430 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4431 (if (not (= (char-after (match-beginning 3))
4432 (char-after (match-beginning 4))))
4433 (progn
4434 (setq rtn t)
4435 (setq a (assoc (match-string 3) org-emphasis-alist))
4436 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4437 'face
4438 (nth 1 a))
4439 (and (nth 4 a)
4440 (org-remove-flyspell-overlays-in
4441 (match-beginning 0) (match-end 0)))
4442 (add-text-properties (match-beginning 2) (match-end 2)
4443 '(font-lock-multiline t))
4444 (when org-hide-emphasis-markers
4445 (add-text-properties (match-end 4) (match-beginning 5)
4446 '(invisible org-link))
4447 (add-text-properties (match-beginning 3) (match-end 3)
4448 '(invisible org-link)))))
4449 (backward-char 1))
4450 rtn))
4452 (defun org-emphasize (&optional char)
4453 "Insert or change an emphasis, i.e. a font like bold or italic.
4454 If there is an active region, change that region to a new emphasis.
4455 If there is no region, just insert the marker characters and position
4456 the cursor between them.
4457 CHAR should be either the marker character, or the first character of the
4458 HTML tag associated with that emphasis. If CHAR is a space, the means
4459 to remove the emphasis of the selected region.
4460 If char is not given (for example in an interactive call) it
4461 will be prompted for."
4462 (interactive)
4463 (let ((eal org-emphasis-alist) e det
4464 (erc org-emphasis-regexp-components)
4465 (prompt "")
4466 (string "") beg end move tag c s)
4467 (if (org-region-active-p)
4468 (setq beg (region-beginning) end (region-end)
4469 string (buffer-substring beg end))
4470 (setq move t))
4472 (while (setq e (pop eal))
4473 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4474 c (aref tag 0))
4475 (push (cons c (string-to-char (car e))) det)
4476 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4477 (substring tag 1)))))
4478 (setq det (nreverse det))
4479 (unless char
4480 (message "%s" (concat "Emphasis marker or tag:" prompt))
4481 (setq char (read-char-exclusive)))
4482 (setq char (or (cdr (assoc char det)) char))
4483 (if (equal char ?\ )
4484 (setq s "" move nil)
4485 (unless (assoc (char-to-string char) org-emphasis-alist)
4486 (error "No such emphasis marker: \"%c\"" char))
4487 (setq s (char-to-string char)))
4488 (while (and (> (length string) 1)
4489 (equal (substring string 0 1) (substring string -1))
4490 (assoc (substring string 0 1) org-emphasis-alist))
4491 (setq string (substring string 1 -1)))
4492 (setq string (concat s string s))
4493 (if beg (delete-region beg end))
4494 (unless (or (bolp)
4495 (string-match (concat "[" (nth 0 erc) "\n]")
4496 (char-to-string (char-before (point)))))
4497 (insert " "))
4498 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4499 (char-to-string (char-after (point))))
4500 (insert " ") (backward-char 1))
4501 (insert string)
4502 (and move (backward-char 1))))
4504 (defconst org-nonsticky-props
4505 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4507 (defsubst org-rear-nonsticky-at (pos)
4508 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4510 (defun org-activate-plain-links (limit)
4511 "Run through the buffer and add overlays to links."
4512 (catch 'exit
4513 (let (f)
4514 (if (re-search-forward org-plain-link-re limit t)
4515 (progn
4516 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4517 (setq f (get-text-property (match-beginning 0) 'face))
4518 (if (or (eq f 'org-tag)
4519 (and (listp f) (memq 'org-tag f)))
4521 (add-text-properties (match-beginning 0) (match-end 0)
4522 (list 'mouse-face 'highlight
4523 'face 'org-link
4524 'keymap org-mouse-map))
4525 (org-rear-nonsticky-at (match-end 0)))
4526 t)))))
4528 (defun org-activate-code (limit)
4529 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4530 (progn
4531 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4532 (remove-text-properties (match-beginning 0) (match-end 0)
4533 '(display t invisible t intangible t))
4534 t)))
4536 (defun org-fontify-meta-lines-and-blocks (limit)
4537 "Fontify #+ lines and blocks, in the correct ways."
4538 (let ((case-fold-search t))
4539 (if (re-search-forward
4540 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4541 limit t)
4542 (let ((beg (match-beginning 0))
4543 (beg1 (line-beginning-position 2))
4544 (dc1 (downcase (match-string 2)))
4545 (dc3 (downcase (match-string 3)))
4546 end end1 quoting block-type)
4547 (cond
4548 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4549 ;; a single line of backend-specific content
4550 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4551 (remove-text-properties (match-beginning 0) (match-end 0)
4552 '(display t invisible t intangible t))
4553 (add-text-properties (match-beginning 1) (match-end 3)
4554 '(font-lock-fontified t face org-meta-line))
4555 (add-text-properties (match-beginning 6) (match-end 6)
4556 '(font-lock-fontified t face org-block))
4558 ((and (match-end 4) (equal dc3 "begin"))
4559 ;; Truely a block
4560 (setq block-type (downcase (match-string 5))
4561 quoting (member block-type org-protecting-blocks))
4562 (when (re-search-forward
4563 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4564 nil t) ;; on purpose, we look further than LIMIT
4565 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4566 (when quoting
4567 (remove-text-properties beg end
4568 '(display t invisible t intangible t)))
4569 (add-text-properties
4570 beg end
4571 '(font-lock-fontified t font-lock-multiline t))
4572 (add-text-properties beg beg1 '(face org-meta-line))
4573 (add-text-properties end1 end '(face org-meta-line))
4574 (cond
4575 (quoting
4576 (add-text-properties beg1 end1 '(face org-block)))
4577 ((string= block-type "quote")
4578 (add-text-properties beg1 end1 '(face org-quote)))
4579 ((string= block-type "verse")
4580 (add-text-properties beg1 end1 '(face org-verse))))
4582 ((not (member (char-after beg) '(?\ ?\t)))
4583 ;; just any other in-buffer setting, but not indented
4584 (add-text-properties
4585 beg (match-end 0)
4586 '(font-lock-fontified t face org-meta-line))
4588 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4589 "orgtbl:" "tblfm:" "tblname:"))
4590 (and (match-end 4) (equal dc3 "attr")))
4591 (add-text-properties
4592 beg (match-end 0)
4593 '(font-lock-fontified t face org-meta-line))
4595 ((member dc3 '(" " ""))
4596 (add-text-properties
4597 beg (match-end 0)
4598 '(font-lock-fontified t face font-lock-comment-face)))
4599 (t nil))))))
4601 (defun org-activate-angle-links (limit)
4602 "Run through the buffer and add overlays to links."
4603 (if (re-search-forward org-angle-link-re limit t)
4604 (progn
4605 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4606 (add-text-properties (match-beginning 0) (match-end 0)
4607 (list 'mouse-face 'highlight
4608 'keymap org-mouse-map))
4609 (org-rear-nonsticky-at (match-end 0))
4610 t)))
4612 (defun org-activate-footnote-links (limit)
4613 "Run through the buffer and add overlays to links."
4614 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4615 limit t)
4616 (progn
4617 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4618 (add-text-properties (match-beginning 2) (match-end 2)
4619 (list 'mouse-face 'highlight
4620 'keymap org-mouse-map
4621 'help-echo
4622 (if (= (point-at-bol) (match-beginning 2))
4623 "Footnote definition"
4624 "Footnote reference")
4626 (org-rear-nonsticky-at (match-end 2))
4627 t)))
4629 (defun org-activate-bracket-links (limit)
4630 "Run through the buffer and add overlays to bracketed links."
4631 (if (re-search-forward org-bracket-link-regexp limit t)
4632 (let* ((help (concat "LINK: "
4633 (org-match-string-no-properties 1)))
4634 ;; FIXME: above we should remove the escapes.
4635 ;; but that requires another match, protecting match data,
4636 ;; a lot of overhead for font-lock.
4637 (ip (org-maybe-intangible
4638 (list 'invisible 'org-link
4639 'keymap org-mouse-map 'mouse-face 'highlight
4640 'font-lock-multiline t 'help-echo help)))
4641 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4642 'font-lock-multiline t 'help-echo help)))
4643 ;; We need to remove the invisible property here. Table narrowing
4644 ;; may have made some of this invisible.
4645 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4646 (remove-text-properties (match-beginning 0) (match-end 0)
4647 '(invisible nil))
4648 (if (match-end 3)
4649 (progn
4650 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4651 (org-rear-nonsticky-at (match-beginning 3))
4652 (add-text-properties (match-beginning 3) (match-end 3) vp)
4653 (org-rear-nonsticky-at (match-end 3))
4654 (add-text-properties (match-end 3) (match-end 0) ip)
4655 (org-rear-nonsticky-at (match-end 0)))
4656 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4657 (org-rear-nonsticky-at (match-beginning 1))
4658 (add-text-properties (match-beginning 1) (match-end 1) vp)
4659 (org-rear-nonsticky-at (match-end 1))
4660 (add-text-properties (match-end 1) (match-end 0) ip)
4661 (org-rear-nonsticky-at (match-end 0)))
4662 t)))
4664 (defun org-activate-dates (limit)
4665 "Run through the buffer and add overlays to dates."
4666 (if (re-search-forward org-tsr-regexp-both limit t)
4667 (progn
4668 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4669 (add-text-properties (match-beginning 0) (match-end 0)
4670 (list 'mouse-face 'highlight
4671 'keymap org-mouse-map))
4672 (org-rear-nonsticky-at (match-end 0))
4673 (when org-display-custom-times
4674 (if (match-end 3)
4675 (org-display-custom-time (match-beginning 3) (match-end 3)))
4676 (org-display-custom-time (match-beginning 1) (match-end 1)))
4677 t)))
4679 (defvar org-target-link-regexp nil
4680 "Regular expression matching radio targets in plain text.")
4681 (make-variable-buffer-local 'org-target-link-regexp)
4682 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4683 "Regular expression matching a link target.")
4684 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4685 "Regular expression matching a radio target.")
4686 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4687 "Regular expression matching any target.")
4689 (defun org-activate-target-links (limit)
4690 "Run through the buffer and add overlays to target matches."
4691 (when org-target-link-regexp
4692 (let ((case-fold-search t))
4693 (if (re-search-forward org-target-link-regexp limit t)
4694 (progn
4695 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4696 (add-text-properties (match-beginning 0) (match-end 0)
4697 (list 'mouse-face 'highlight
4698 'keymap org-mouse-map
4699 'help-echo "Radio target link"
4700 'org-linked-text t))
4701 (org-rear-nonsticky-at (match-end 0))
4702 t)))))
4704 (defun org-update-radio-target-regexp ()
4705 "Find all radio targets in this file and update the regular expression."
4706 (interactive)
4707 (when (memq 'radio org-activate-links)
4708 (setq org-target-link-regexp
4709 (org-make-target-link-regexp (org-all-targets 'radio)))
4710 (org-restart-font-lock)))
4712 (defun org-hide-wide-columns (limit)
4713 (let (s e)
4714 (setq s (text-property-any (point) (or limit (point-max))
4715 'org-cwidth t))
4716 (when s
4717 (setq e (next-single-property-change s 'org-cwidth))
4718 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4719 (goto-char e)
4720 t)))
4722 (defvar org-latex-and-specials-regexp nil
4723 "Regular expression for highlighting export special stuff.")
4724 (defvar org-match-substring-regexp)
4725 (defvar org-match-substring-with-braces-regexp)
4727 ;; This should be with the exporter code, but we also use if for font-locking
4728 (defconst org-export-html-special-string-regexps
4729 '(("\\\\-" . "&shy;")
4730 ("---\\([^-]\\)" . "&mdash;\\1")
4731 ("--\\([^-]\\)" . "&ndash;\\1")
4732 ("\\.\\.\\." . "&hellip;"))
4733 "Regular expressions for special string conversion.")
4736 (defun org-compute-latex-and-specials-regexp ()
4737 "Compute regular expression for stuff treated specially by exporters."
4738 (if (not org-highlight-latex-fragments-and-specials)
4739 (org-set-local 'org-latex-and-specials-regexp nil)
4740 (require 'org-exp)
4741 (let*
4742 ((matchers (plist-get org-format-latex-options :matchers))
4743 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4744 org-latex-regexps)))
4745 (options (org-combine-plists (org-default-export-plist)
4746 (org-infile-export-plist)))
4747 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4748 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4749 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4750 (org-export-html-expand (plist-get options :expand-quoted-html))
4751 (org-export-with-special-strings (plist-get options :special-strings))
4752 (re-sub
4753 (cond
4754 ((equal org-export-with-sub-superscripts '{})
4755 (list org-match-substring-with-braces-regexp))
4756 (org-export-with-sub-superscripts
4757 (list org-match-substring-regexp))
4758 (t nil)))
4759 (re-latex
4760 (if org-export-with-LaTeX-fragments
4761 (mapcar (lambda (x) (nth 1 x)) latexs)))
4762 (re-macros
4763 (if org-export-with-TeX-macros
4764 (list (concat "\\\\"
4765 (regexp-opt
4766 (append (mapcar 'car org-html-entities)
4767 (if (boundp 'org-latex-entities)
4768 (mapcar (lambda (x)
4769 (or (car-safe x) x))
4770 org-latex-entities)
4771 nil))
4772 'words))) ; FIXME
4774 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4775 (re-special (if org-export-with-special-strings
4776 (mapcar (lambda (x) (car x))
4777 org-export-html-special-string-regexps)))
4778 (re-rest
4779 (delq nil
4780 (list
4781 (if org-export-html-expand "@<[^>\n]+>")
4782 ))))
4783 (org-set-local
4784 'org-latex-and-specials-regexp
4785 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4786 re-rest) "\\|")))))
4788 (defun org-do-latex-and-special-faces (limit)
4789 "Run through the buffer and add overlays to links."
4790 (when org-latex-and-specials-regexp
4791 (let (rtn d)
4792 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4793 limit t))
4794 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4795 'face))
4796 '(org-code org-verbatim underline)))
4797 (progn
4798 (setq rtn t
4799 d (cond ((member (char-after (1+ (match-beginning 0)))
4800 '(?_ ?^)) 1)
4801 (t 0)))
4802 (font-lock-prepend-text-property
4803 (+ d (match-beginning 0)) (match-end 0)
4804 'face 'org-latex-and-export-specials)
4805 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4806 '(font-lock-multiline t)))))
4807 rtn)))
4809 (defun org-restart-font-lock ()
4810 "Restart font-lock-mode, to force refontification."
4811 (when (and (boundp 'font-lock-mode) font-lock-mode)
4812 (font-lock-mode -1)
4813 (font-lock-mode 1)))
4815 (defun org-all-targets (&optional radio)
4816 "Return a list of all targets in this file.
4817 With optional argument RADIO, only find radio targets."
4818 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4819 rtn)
4820 (save-excursion
4821 (goto-char (point-min))
4822 (while (re-search-forward re nil t)
4823 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4824 rtn)))
4826 (defun org-make-target-link-regexp (targets)
4827 "Make regular expression matching all strings in TARGETS.
4828 The regular expression finds the targets also if there is a line break
4829 between words."
4830 (and targets
4831 (concat
4832 "\\<\\("
4833 (mapconcat
4834 (lambda (x)
4835 (while (string-match " +" x)
4836 (setq x (replace-match "\\s-+" t t x)))
4838 targets
4839 "\\|")
4840 "\\)\\>")))
4842 (defun org-activate-tags (limit)
4843 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4844 (progn
4845 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4846 (add-text-properties (match-beginning 1) (match-end 1)
4847 (list 'mouse-face 'highlight
4848 'keymap org-mouse-map))
4849 (org-rear-nonsticky-at (match-end 1))
4850 t)))
4852 (defun org-outline-level ()
4853 "Compute the outline level of the heading at point.
4854 This function assumes that the cursor is at the beginning of a line matched
4855 by outline-regexp. Otherwise it returns garbage.
4856 If this is called at a normal headline, the level is the number of stars.
4857 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4858 For plain list items, if they are matched by `outline-regexp', this returns
4859 1000 plus the line indentation."
4860 (save-excursion
4861 (looking-at outline-regexp)
4862 (if (match-beginning 1)
4863 (+ (org-get-string-indentation (match-string 1)) 1000)
4864 (1- (- (match-end 0) (match-beginning 0))))))
4866 (defvar org-font-lock-keywords nil)
4868 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4869 "Regular expression matching a property line.")
4871 (defvar org-font-lock-hook nil
4872 "Functions to be called for special font lock stuff.")
4874 (defun org-font-lock-hook (limit)
4875 (run-hook-with-args 'org-font-lock-hook limit))
4877 (defun org-set-font-lock-defaults ()
4878 (let* ((em org-fontify-emphasized-text)
4879 (lk org-activate-links)
4880 (org-font-lock-extra-keywords
4881 (list
4882 ;; Call the hook
4883 '(org-font-lock-hook)
4884 ;; Headlines
4885 `(,(if org-fontify-whole-heading-line
4886 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4887 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4888 (1 (org-get-level-face 1))
4889 (2 (org-get-level-face 2))
4890 (3 (org-get-level-face 3)))
4891 ;; Table lines
4892 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4893 (1 'org-table t))
4894 ;; Table internals
4895 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4896 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4897 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4898 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4899 ;; Drawers
4900 (list org-drawer-regexp '(0 'org-special-keyword t))
4901 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4902 ;; Properties
4903 (list org-property-re
4904 '(1 'org-special-keyword t)
4905 '(3 'org-property-value t))
4906 ;; Links
4907 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4908 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4909 (if (memq 'plain lk) '(org-activate-plain-links))
4910 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4911 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4912 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4913 (if (memq 'footnote lk) '(org-activate-footnote-links
4914 (2 'org-footnote t)))
4915 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4916 '(org-hide-wide-columns (0 nil append))
4917 ;; TODO lines
4918 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4919 '(1 (org-get-todo-face 1) t))
4920 ;; DONE
4921 (if org-fontify-done-headline
4922 (list (concat "^[*]+ +\\<\\("
4923 (mapconcat 'regexp-quote org-done-keywords "\\|")
4924 "\\)\\(.*\\)")
4925 '(2 'org-headline-done t))
4926 nil)
4927 ;; Priorities
4928 '(org-font-lock-add-priority-faces)
4929 ;; Tags
4930 '(org-font-lock-add-tag-faces)
4931 ;; Special keywords
4932 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4933 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4934 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4935 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4936 ;; Emphasis
4937 (if em
4938 (if (featurep 'xemacs)
4939 '(org-do-emphasis-faces (0 nil append))
4940 '(org-do-emphasis-faces)))
4941 ;; Checkboxes
4942 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4943 2 'org-checkbox prepend)
4944 (if org-provide-checkbox-statistics
4945 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4946 (0 (org-get-checkbox-statistics-face) t)))
4947 ;; Description list items
4948 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4949 2 'bold prepend)
4950 ;; ARCHIVEd headings
4951 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4952 '(1 'org-archived prepend))
4953 ;; Specials
4954 '(org-do-latex-and-special-faces)
4955 ;; Code
4956 '(org-activate-code (1 'org-code t))
4957 ;; COMMENT
4958 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4959 "\\|" org-quote-string "\\)\\>")
4960 '(1 'org-special-keyword t))
4961 '("^#.*" (0 'font-lock-comment-face t))
4962 ;; Blocks and meta lines
4963 '(org-fontify-meta-lines-and-blocks)
4965 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4966 ;; Now set the full font-lock-keywords
4967 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4968 (org-set-local 'font-lock-defaults
4969 '(org-font-lock-keywords t nil nil backward-paragraph))
4970 (kill-local-variable 'font-lock-keywords) nil))
4972 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4973 "Fontify string S like in Org-mode"
4974 (with-temp-buffer
4975 (insert s)
4976 (let ((org-odd-levels-only odd-levels))
4977 (org-mode)
4978 (font-lock-fontify-buffer)
4979 (buffer-string))))
4981 (defvar org-m nil)
4982 (defvar org-l nil)
4983 (defvar org-f nil)
4984 (defun org-get-level-face (n)
4985 "Get the right face for match N in font-lock matching of headlines."
4986 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4987 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4988 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4989 (cond
4990 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4991 ((eq n 2) org-f)
4992 (t (if org-level-color-stars-only nil org-f))))
4994 (defun org-get-todo-face (kwd)
4995 "Get the right face for a TODO keyword KWD.
4996 If KWD is a number, get the corresponding match group."
4997 (if (numberp kwd) (setq kwd (match-string kwd)))
4998 (or (cdr (assoc kwd org-todo-keyword-faces))
4999 (and (member kwd org-done-keywords) 'org-done)
5000 'org-todo))
5002 (defun org-font-lock-add-tag-faces (limit)
5003 "Add the special tag faces."
5004 (when (and org-tag-faces org-tags-special-faces-re)
5005 (while (re-search-forward org-tags-special-faces-re limit t)
5006 (add-text-properties (match-beginning 1) (match-end 1)
5007 (list 'face (org-get-tag-face 1)
5008 'font-lock-fontified t))
5009 (backward-char 1))))
5011 (defun org-font-lock-add-priority-faces (limit)
5012 "Add the special priority faces."
5013 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5014 (add-text-properties
5015 (match-beginning 0) (match-end 0)
5016 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5017 org-priority-faces))
5018 'org-special-keyword)
5019 'font-lock-fontified t))))
5021 (defun org-get-tag-face (kwd)
5022 "Get the right face for a TODO keyword KWD.
5023 If KWD is a number, get the corresponding match group."
5024 (if (numberp kwd) (setq kwd (match-string kwd)))
5025 (or (cdr (assoc kwd org-tag-faces))
5026 'org-tag))
5028 (defun org-unfontify-region (beg end &optional maybe_loudly)
5029 "Remove fontification and activation overlays from links."
5030 (font-lock-default-unfontify-region beg end)
5031 (let* ((buffer-undo-list t)
5032 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5033 (inhibit-modification-hooks t)
5034 deactivate-mark buffer-file-name buffer-file-truename)
5035 (remove-text-properties
5036 beg end
5037 (if org-indent-mode
5038 ;; also remove line-prefix and wrap-prefix properties
5039 '(mouse-face t keymap t org-linked-text t
5040 invisible t intangible t
5041 line-prefix t wrap-prefix t
5042 org-no-flyspell t)
5043 '(mouse-face t keymap t org-linked-text t
5044 invisible t intangible t
5045 org-no-flyspell t)))))
5047 ;;;; Visibility cycling, including org-goto and indirect buffer
5049 ;;; Cycling
5051 (defvar org-cycle-global-status nil)
5052 (make-variable-buffer-local 'org-cycle-global-status)
5053 (defvar org-cycle-subtree-status nil)
5054 (make-variable-buffer-local 'org-cycle-subtree-status)
5056 ;;;###autoload
5058 (defvar org-inlinetask-min-level)
5060 (defun org-cycle (&optional arg)
5061 "TAB-action and visibility cycling for Org-mode.
5063 This is the command invoked in Org-mode by the TAB key. Its main purpose
5064 is outline visibility cycling, but it also invokes other actions
5065 in special contexts.
5067 - When this function is called with a prefix argument, rotate the entire
5068 buffer through 3 states (global cycling)
5069 1. OVERVIEW: Show only top-level headlines.
5070 2. CONTENTS: Show all headlines of all levels, but no body text.
5071 3. SHOW ALL: Show everything.
5072 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5073 determined by the variable `org-startup-folded', and by any VISIBILITY
5074 properties in the buffer.
5075 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5076 including any drawers.
5078 - When inside a table, re-align the table and move to the next field.
5080 - When point is at the beginning of a headline, rotate the subtree started
5081 by this line through 3 different states (local cycling)
5082 1. FOLDED: Only the main headline is shown.
5083 2. CHILDREN: The main headline and the direct children are shown.
5084 From this state, you can move to one of the children
5085 and zoom in further.
5086 3. SUBTREE: Show the entire subtree, including body text.
5087 If there is no subtree, switch directly from CHILDREN to FOLDED.
5089 - When there is a numeric prefix, go up to a heading with level ARG, do
5090 a `show-subtree' and return to the previous cursor position. If ARG
5091 is negative, go up that many levels.
5093 - When point is not at the beginning of a headline, execute the global
5094 binding for TAB, which is re-indenting the line. See the option
5095 `org-cycle-emulate-tab' for details.
5097 - Special case: if point is at the beginning of the buffer and there is
5098 no headline in line 1, this function will act as if called with prefix arg.
5099 But only if also the variable `org-cycle-global-at-bob' is t."
5100 (interactive "P")
5101 (org-load-modules-maybe)
5102 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5103 (and org-cycle-level-after-item/entry-creation
5104 (or (org-cycle-level)
5105 (org-cycle-item-indentation))))
5106 (let* ((limit-level
5107 (or org-cycle-max-level
5108 (and (boundp 'org-inlinetask-min-level)
5109 org-inlinetask-min-level
5110 (1- org-inlinetask-min-level))))
5111 (nstars (and limit-level
5112 (if org-odd-levels-only
5113 (and limit-level (1- (* limit-level 2)))
5114 limit-level)))
5115 (outline-regexp
5116 (cond
5117 ((not (org-mode-p)) outline-regexp)
5118 ((or (eq org-cycle-include-plain-lists 'integrate)
5119 (and org-cycle-include-plain-lists (org-at-item-p)))
5120 (concat "\\(?:\\*"
5121 (if nstars (format "\\{1,%d\\}" nstars) "+")
5122 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5123 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5124 (bob-special (and org-cycle-global-at-bob (bobp)
5125 (not (looking-at outline-regexp))))
5126 (org-cycle-hook
5127 (if bob-special
5128 (delq 'org-optimize-window-after-visibility-change
5129 (copy-sequence org-cycle-hook))
5130 org-cycle-hook))
5131 (pos (point)))
5133 (if (or bob-special (equal arg '(4)))
5134 ;; special case: use global cycling
5135 (setq arg t))
5137 (cond
5139 ((equal arg '(16))
5140 (org-set-startup-visibility)
5141 (message "Startup visibility, plus VISIBILITY properties"))
5143 ((equal arg '(64))
5144 (show-all)
5145 (message "Entire buffer visible, including drawers"))
5147 ((org-at-table-p 'any)
5148 ;; Enter the table or move to the next field in the table
5149 (or (org-table-recognize-table.el)
5150 (progn
5151 (if arg (org-table-edit-field t)
5152 (org-table-justify-field-maybe)
5153 (call-interactively 'org-table-next-field)))))
5155 ((run-hook-with-args-until-success
5156 'org-tab-after-check-for-table-hook))
5158 ((eq arg t) ;; Global cycling
5159 (org-cycle-internal-global))
5161 ((and org-drawers org-drawer-regexp
5162 (save-excursion
5163 (beginning-of-line 1)
5164 (looking-at org-drawer-regexp)))
5165 ;; Toggle block visibility
5166 (org-flag-drawer
5167 (not (get-char-property (match-end 0) 'invisible))))
5169 ((integerp arg)
5170 ;; Show-subtree, ARG levels up from here.
5171 (save-excursion
5172 (org-back-to-heading)
5173 (outline-up-heading (if (< arg 0) (- arg)
5174 (- (funcall outline-level) arg)))
5175 (org-show-subtree)))
5177 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5178 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5180 (org-cycle-internal-local))
5182 ;; TAB emulation and template completion
5183 (buffer-read-only (org-back-to-heading))
5185 ((run-hook-with-args-until-success
5186 'org-tab-after-check-for-cycling-hook))
5188 ((org-try-structure-completion))
5190 ((org-try-cdlatex-tab))
5192 ((run-hook-with-args-until-success
5193 'org-tab-before-tab-emulation-hook))
5195 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5196 (or (not (bolp))
5197 (not (looking-at outline-regexp))))
5198 (call-interactively (global-key-binding "\t")))
5200 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5201 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5202 (or (and (eq org-cycle-emulate-tab 'white)
5203 (= (match-end 0) (point-at-eol)))
5204 (and (eq org-cycle-emulate-tab 'whitestart)
5205 (>= (match-end 0) pos))))
5207 (eq org-cycle-emulate-tab t))
5208 (call-interactively (global-key-binding "\t")))
5210 (t (save-excursion
5211 (org-back-to-heading)
5212 (org-cycle)))))))
5214 (defun org-cycle-internal-global ()
5215 "Do the global cycling action."
5216 (cond
5217 ((and (eq last-command this-command)
5218 (eq org-cycle-global-status 'overview))
5219 ;; We just created the overview - now do table of contents
5220 ;; This can be slow in very large buffers, so indicate action
5221 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5222 (message "CONTENTS...")
5223 (org-content)
5224 (message "CONTENTS...done")
5225 (setq org-cycle-global-status 'contents)
5226 (run-hook-with-args 'org-cycle-hook 'contents))
5228 ((and (eq last-command this-command)
5229 (eq org-cycle-global-status 'contents))
5230 ;; We just showed the table of contents - now show everything
5231 (run-hook-with-args 'org-pre-cycle-hook 'all)
5232 (show-all)
5233 (message "SHOW ALL")
5234 (setq org-cycle-global-status 'all)
5235 (run-hook-with-args 'org-cycle-hook 'all))
5238 ;; Default action: go to overview
5239 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5240 (org-overview)
5241 (message "OVERVIEW")
5242 (setq org-cycle-global-status 'overview)
5243 (run-hook-with-args 'org-cycle-hook 'overview))))
5245 (defun org-cycle-internal-local ()
5246 "Do the local cycling action."
5247 (org-back-to-heading)
5248 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5249 ;; First, some boundaries
5250 (save-excursion
5251 (org-back-to-heading)
5252 (setq level (funcall outline-level))
5253 (save-excursion
5254 (beginning-of-line 2)
5255 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5256 ; XEmacs does not have `next-single-char-property-change'
5257 ; I'm not sure about Emacs 21.
5258 (while (and (not (eobp)) ;; this is like `next-line'
5259 (get-char-property (1- (point)) 'invisible))
5260 (beginning-of-line 2))
5261 (while (and (not (eobp)) ;; this is like `next-line'
5262 (get-char-property (1- (point)) 'invisible))
5263 (goto-char (next-single-char-property-change (point) 'invisible))
5264 ;;;??? (or (bolp) (beginning-of-line 2))))
5265 (and (eolp) (beginning-of-line 2))))
5266 (setq eol (point)))
5267 (outline-end-of-heading) (setq eoh (point))
5268 (save-excursion
5269 (outline-next-heading)
5270 (setq has-children (and (org-at-heading-p t)
5271 (> (funcall outline-level) level))))
5272 (org-end-of-subtree t)
5273 (unless (eobp)
5274 (skip-chars-forward " \t\n")
5275 (beginning-of-line 1) ; in case this is an item
5277 (setq eos (if (eobp) (point) (1- (point)))))
5278 ;; Find out what to do next and set `this-command'
5279 (cond
5280 ((= eos eoh)
5281 ;; Nothing is hidden behind this heading
5282 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5283 (message "EMPTY ENTRY")
5284 (setq org-cycle-subtree-status nil)
5285 (save-excursion
5286 (goto-char eos)
5287 (outline-next-heading)
5288 (if (org-invisible-p) (org-flag-heading nil))))
5289 ((and (or (>= eol eos)
5290 (not (string-match "\\S-" (buffer-substring eol eos))))
5291 (or has-children
5292 (not (setq children-skipped
5293 org-cycle-skip-children-state-if-no-children))))
5294 ;; Entire subtree is hidden in one line: children view
5295 (run-hook-with-args 'org-pre-cycle-hook 'children)
5296 (org-show-entry)
5297 (show-children)
5298 (message "CHILDREN")
5299 (save-excursion
5300 (goto-char eos)
5301 (outline-next-heading)
5302 (if (org-invisible-p) (org-flag-heading nil)))
5303 (setq org-cycle-subtree-status 'children)
5304 (run-hook-with-args 'org-cycle-hook 'children))
5305 ((or children-skipped
5306 (and (eq last-command this-command)
5307 (eq org-cycle-subtree-status 'children)))
5308 ;; We just showed the children, or no children are there,
5309 ;; now show everything.
5310 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5311 (org-show-subtree)
5312 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5313 (setq org-cycle-subtree-status 'subtree)
5314 (run-hook-with-args 'org-cycle-hook 'subtree))
5316 ;; Default action: hide the subtree.
5317 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5318 (hide-subtree)
5319 (message "FOLDED")
5320 (setq org-cycle-subtree-status 'folded)
5321 (run-hook-with-args 'org-cycle-hook 'folded)))))
5323 ;;;###autoload
5324 (defun org-global-cycle (&optional arg)
5325 "Cycle the global visibility. For details see `org-cycle'.
5326 With C-u prefix arg, switch to startup visibility.
5327 With a numeric prefix, show all headlines up to that level."
5328 (interactive "P")
5329 (let ((org-cycle-include-plain-lists
5330 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5331 (cond
5332 ((integerp arg)
5333 (show-all)
5334 (hide-sublevels arg)
5335 (setq org-cycle-global-status 'contents))
5336 ((equal arg '(4))
5337 (org-set-startup-visibility)
5338 (message "Startup visibility, plus VISIBILITY properties."))
5340 (org-cycle '(4))))))
5342 (defun org-set-startup-visibility ()
5343 "Set the visibility required by startup options and properties."
5344 (cond
5345 ((eq org-startup-folded t)
5346 (org-cycle '(4)))
5347 ((eq org-startup-folded 'content)
5348 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5349 (org-cycle '(4)) (org-cycle '(4)))))
5350 (unless (eq org-startup-folded 'showeverything)
5351 (if org-hide-block-startup (org-hide-block-all))
5352 (org-set-visibility-according-to-property 'no-cleanup)
5353 (org-cycle-hide-archived-subtrees 'all)
5354 (org-cycle-hide-drawers 'all)
5355 (org-cycle-show-empty-lines 'all)))
5357 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5358 "Switch subtree visibilities according to :VISIBILITY: property."
5359 (interactive)
5360 (let (org-show-entry-below state)
5361 (save-excursion
5362 (goto-char (point-min))
5363 (while (re-search-forward
5364 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5365 nil t)
5366 (setq state (match-string 1))
5367 (save-excursion
5368 (org-back-to-heading t)
5369 (hide-subtree)
5370 (org-reveal)
5371 (cond
5372 ((equal state '("fold" "folded"))
5373 (hide-subtree))
5374 ((equal state "children")
5375 (org-show-hidden-entry)
5376 (show-children))
5377 ((equal state "content")
5378 (save-excursion
5379 (save-restriction
5380 (org-narrow-to-subtree)
5381 (org-content))))
5382 ((member state '("all" "showall"))
5383 (show-subtree)))))
5384 (unless no-cleanup
5385 (org-cycle-hide-archived-subtrees 'all)
5386 (org-cycle-hide-drawers 'all)
5387 (org-cycle-show-empty-lines 'all)))))
5389 (defun org-overview ()
5390 "Switch to overview mode, showing only top-level headlines.
5391 Really, this shows all headlines with level equal or greater than the level
5392 of the first headline in the buffer. This is important, because if the
5393 first headline is not level one, then (hide-sublevels 1) gives confusing
5394 results."
5395 (interactive)
5396 (let ((level (save-excursion
5397 (goto-char (point-min))
5398 (if (re-search-forward (concat "^" outline-regexp) nil t)
5399 (progn
5400 (goto-char (match-beginning 0))
5401 (funcall outline-level))))))
5402 (and level (hide-sublevels level))))
5404 (defun org-content (&optional arg)
5405 "Show all headlines in the buffer, like a table of contents.
5406 With numerical argument N, show content up to level N."
5407 (interactive "P")
5408 (save-excursion
5409 ;; Visit all headings and show their offspring
5410 (and (integerp arg) (org-overview))
5411 (goto-char (point-max))
5412 (catch 'exit
5413 (while (and (progn (condition-case nil
5414 (outline-previous-visible-heading 1)
5415 (error (goto-char (point-min))))
5417 (looking-at outline-regexp))
5418 (if (integerp arg)
5419 (show-children (1- arg))
5420 (show-branches))
5421 (if (bobp) (throw 'exit nil))))))
5424 (defun org-optimize-window-after-visibility-change (state)
5425 "Adjust the window after a change in outline visibility.
5426 This function is the default value of the hook `org-cycle-hook'."
5427 (when (get-buffer-window (current-buffer))
5428 (cond
5429 ((eq state 'content) nil)
5430 ((eq state 'all) nil)
5431 ((eq state 'folded) nil)
5432 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5433 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5435 (defun org-remove-empty-overlays-at (pos)
5436 "Remove outline overlays that do not contain non-white stuff."
5437 (mapc
5438 (lambda (o)
5439 (and (eq 'outline (org-overlay-get o 'invisible))
5440 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5441 (org-overlay-end o))))
5442 (org-delete-overlay o)))
5443 (org-overlays-at pos)))
5445 (defun org-clean-visibility-after-subtree-move ()
5446 "Fix visibility issues after moving a subtree."
5447 ;; First, find a reasonable region to look at:
5448 ;; Start two siblings above, end three below
5449 (let* ((beg (save-excursion
5450 (and (org-get-last-sibling)
5451 (org-get-last-sibling))
5452 (point)))
5453 (end (save-excursion
5454 (and (org-get-next-sibling)
5455 (org-get-next-sibling)
5456 (org-get-next-sibling))
5457 (if (org-at-heading-p)
5458 (point-at-eol)
5459 (point))))
5460 (level (looking-at "\\*+"))
5461 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5462 (save-excursion
5463 (save-restriction
5464 (narrow-to-region beg end)
5465 (when re
5466 ;; Properly fold already folded siblings
5467 (goto-char (point-min))
5468 (while (re-search-forward re nil t)
5469 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5470 (hide-entry))))
5471 (org-cycle-show-empty-lines 'overview)
5472 (org-cycle-hide-drawers 'overview)))))
5474 (defun org-cycle-show-empty-lines (state)
5475 "Show empty lines above all visible headlines.
5476 The region to be covered depends on STATE when called through
5477 `org-cycle-hook'. Lisp program can use t for STATE to get the
5478 entire buffer covered. Note that an empty line is only shown if there
5479 are at least `org-cycle-separator-lines' empty lines before the headline."
5480 (when (not (= org-cycle-separator-lines 0))
5481 (save-excursion
5482 (let* ((n (abs org-cycle-separator-lines))
5483 (re (cond
5484 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5485 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5486 (t (let ((ns (number-to-string (- n 2))))
5487 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5488 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5489 beg end b e)
5490 (cond
5491 ((memq state '(overview contents t))
5492 (setq beg (point-min) end (point-max)))
5493 ((memq state '(children folded))
5494 (setq beg (point) end (progn (org-end-of-subtree t t)
5495 (beginning-of-line 2)
5496 (point)))))
5497 (when beg
5498 (goto-char beg)
5499 (while (re-search-forward re end t)
5500 (unless (get-char-property (match-end 1) 'invisible)
5501 (setq e (match-end 1))
5502 (if (< org-cycle-separator-lines 0)
5503 (setq b (save-excursion
5504 (goto-char (match-beginning 0))
5505 (org-back-over-empty-lines)
5506 (if (save-excursion
5507 (goto-char (max (point-min) (1- (point))))
5508 (org-on-heading-p))
5509 (1- (point))
5510 (point))))
5511 (setq b (match-beginning 1)))
5512 (outline-flag-region b e nil)))))))
5513 ;; Never hide empty lines at the end of the file.
5514 (save-excursion
5515 (goto-char (point-max))
5516 (outline-previous-heading)
5517 (outline-end-of-heading)
5518 (if (and (looking-at "[ \t\n]+")
5519 (= (match-end 0) (point-max)))
5520 (outline-flag-region (point) (match-end 0) nil))))
5522 (defun org-show-empty-lines-in-parent ()
5523 "Move to the parent and re-show empty lines before visible headlines."
5524 (save-excursion
5525 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5526 (org-cycle-show-empty-lines context))))
5528 (defun org-files-list ()
5529 "Return `org-agenda-files' list, plus all open org-mode files.
5530 This is useful for operations that need to scan all of a user's
5531 open and agenda-wise Org files."
5532 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5533 (dolist (buf (buffer-list))
5534 (with-current-buffer buf
5535 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5536 (let ((file (expand-file-name (buffer-file-name))))
5537 (unless (member file files)
5538 (push file files))))))
5539 files))
5541 (defsubst org-entry-beginning-position ()
5542 "Return the beginning position of the current entry."
5543 (save-excursion (outline-back-to-heading t) (point)))
5545 (defsubst org-entry-end-position ()
5546 "Return the end position of the current entry."
5547 (save-excursion (outline-next-heading) (point)))
5549 (defun org-cycle-hide-drawers (state)
5550 "Re-hide all drawers after a visibility state change."
5551 (when (and (org-mode-p)
5552 (not (memq state '(overview folded contents))))
5553 (save-excursion
5554 (let* ((globalp (memq state '(contents all)))
5555 (beg (if globalp (point-min) (point)))
5556 (end (if globalp (point-max)
5557 (if (eq state 'children)
5558 (save-excursion (outline-next-heading) (point))
5559 (org-end-of-subtree t)))))
5560 (goto-char beg)
5561 (while (re-search-forward org-drawer-regexp end t)
5562 (org-flag-drawer t))))))
5564 (defun org-flag-drawer (flag)
5565 (save-excursion
5566 (beginning-of-line 1)
5567 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5568 (let ((b (match-end 0))
5569 (outline-regexp org-outline-regexp))
5570 (if (re-search-forward
5571 "^[ \t]*:END:"
5572 (save-excursion (outline-next-heading) (point)) t)
5573 (outline-flag-region b (point-at-eol) flag)
5574 (error ":END: line missing at position %s" b))))))
5576 (defun org-subtree-end-visible-p ()
5577 "Is the end of the current subtree visible?"
5578 (pos-visible-in-window-p
5579 (save-excursion (org-end-of-subtree t) (point))))
5581 (defun org-first-headline-recenter (&optional N)
5582 "Move cursor to the first headline and recenter the headline.
5583 Optional argument N means, put the headline into the Nth line of the window."
5584 (goto-char (point-min))
5585 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5586 (beginning-of-line)
5587 (recenter (prefix-numeric-value N))))
5589 ;;; Folding of blocks
5591 (defconst org-block-regexp
5593 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5594 "Regular expression for hiding blocks.")
5596 (defvar org-hide-block-overlays nil
5597 "Overlays hiding blocks.")
5598 (make-variable-buffer-local 'org-hide-block-overlays)
5600 (defun org-block-map (function &optional start end)
5601 "Call func at the head of all source blocks in the current
5602 buffer. Optional arguments START and END can be used to limit
5603 the range."
5604 (let ((start (or start (point-min)))
5605 (end (or end (point-max))))
5606 (save-excursion
5607 (goto-char start)
5608 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5609 (save-excursion
5610 (save-match-data
5611 (goto-char (match-beginning 0))
5612 (funcall function)))))))
5614 (defun org-hide-block-toggle-all ()
5615 "Toggle the visibility of all blocks in the current buffer."
5616 (org-block-map #'org-hide-block-toggle))
5618 (defun org-hide-block-all ()
5619 "Fold all blocks in the current buffer."
5620 (interactive)
5621 (org-show-block-all)
5622 (org-block-map #'org-hide-block-toggle-maybe))
5624 (defun org-show-block-all ()
5625 "Unfold all blocks in the current buffer."
5626 (mapc 'org-delete-overlay org-hide-block-overlays)
5627 (setq org-hide-block-overlays nil))
5629 (defun org-hide-block-toggle-maybe ()
5630 "Toggle visibility of block at point."
5631 (interactive)
5632 (let ((case-fold-search t))
5633 (if (save-excursion
5634 (beginning-of-line 1)
5635 (looking-at org-block-regexp))
5636 (progn (org-hide-block-toggle)
5637 t) ;; to signal that we took action
5638 nil))) ;; to signal that we did not
5640 (defun org-hide-block-toggle (&optional force)
5641 "Toggle the visibility of the current block."
5642 (interactive)
5643 (save-excursion
5644 (beginning-of-line)
5645 (if (re-search-forward org-block-regexp nil t)
5646 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5647 (end (match-end 0)) ;; end of entire body
5649 (if (memq t (mapcar (lambda (overlay)
5650 (eq (org-overlay-get overlay 'invisible)
5651 'org-hide-block))
5652 (org-overlays-at start)))
5653 (if (or (not force) (eq force 'off))
5654 (mapc (lambda (ov)
5655 (when (member ov org-hide-block-overlays)
5656 (setq org-hide-block-overlays
5657 (delq ov org-hide-block-overlays)))
5658 (when (eq (org-overlay-get ov 'invisible)
5659 'org-hide-block)
5660 (org-delete-overlay ov)))
5661 (org-overlays-at start)))
5662 (setq ov (org-make-overlay start end))
5663 (org-overlay-put ov 'invisible 'org-hide-block)
5664 ;; make the block accessible to isearch
5665 (org-overlay-put
5666 ov 'isearch-open-invisible
5667 (lambda (ov)
5668 (when (member ov org-hide-block-overlays)
5669 (setq org-hide-block-overlays
5670 (delq ov org-hide-block-overlays)))
5671 (when (eq (org-overlay-get ov 'invisible)
5672 'org-hide-block)
5673 (org-delete-overlay ov))))
5674 (push ov org-hide-block-overlays)))
5675 (error "Not looking at a source block"))))
5677 ;; org-tab-after-check-for-cycling-hook
5678 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5679 ;; Remove overlays when changing major mode
5680 (add-hook 'org-mode-hook
5681 (lambda () (org-add-hook 'change-major-mode-hook
5682 'org-show-block-all 'append 'local)))
5684 ;;; Org-goto
5686 (defvar org-goto-window-configuration nil)
5687 (defvar org-goto-marker nil)
5688 (defvar org-goto-map
5689 (let ((map (make-sparse-keymap)))
5690 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5691 (while (setq cmd (pop cmds))
5692 (substitute-key-definition cmd cmd map global-map)))
5693 (suppress-keymap map)
5694 (org-defkey map "\C-m" 'org-goto-ret)
5695 (org-defkey map [(return)] 'org-goto-ret)
5696 (org-defkey map [(left)] 'org-goto-left)
5697 (org-defkey map [(right)] 'org-goto-right)
5698 (org-defkey map [(control ?g)] 'org-goto-quit)
5699 (org-defkey map "\C-i" 'org-cycle)
5700 (org-defkey map [(tab)] 'org-cycle)
5701 (org-defkey map [(down)] 'outline-next-visible-heading)
5702 (org-defkey map [(up)] 'outline-previous-visible-heading)
5703 (if org-goto-auto-isearch
5704 (if (fboundp 'define-key-after)
5705 (define-key-after map [t] 'org-goto-local-auto-isearch)
5706 nil)
5707 (org-defkey map "q" 'org-goto-quit)
5708 (org-defkey map "n" 'outline-next-visible-heading)
5709 (org-defkey map "p" 'outline-previous-visible-heading)
5710 (org-defkey map "f" 'outline-forward-same-level)
5711 (org-defkey map "b" 'outline-backward-same-level)
5712 (org-defkey map "u" 'outline-up-heading))
5713 (org-defkey map "/" 'org-occur)
5714 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5715 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5716 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5717 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5718 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5719 map))
5721 (defconst org-goto-help
5722 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5723 RET=jump to location [Q]uit and return to previous location
5724 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5726 (defvar org-goto-start-pos) ; dynamically scoped parameter
5728 ;; FIXME: Docstring does not mention both interfaces
5729 (defun org-goto (&optional alternative-interface)
5730 "Look up a different location in the current file, keeping current visibility.
5732 When you want look-up or go to a different location in a document, the
5733 fastest way is often to fold the entire buffer and then dive into the tree.
5734 This method has the disadvantage, that the previous location will be folded,
5735 which may not be what you want.
5737 This command works around this by showing a copy of the current buffer
5738 in an indirect buffer, in overview mode. You can dive into the tree in
5739 that copy, use org-occur and incremental search to find a location.
5740 When pressing RET or `Q', the command returns to the original buffer in
5741 which the visibility is still unchanged. After RET is will also jump to
5742 the location selected in the indirect buffer and expose the
5743 the headline hierarchy above."
5744 (interactive "P")
5745 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5746 (org-refile-use-outline-path t)
5747 (org-refile-target-verify-function nil)
5748 (interface
5749 (if (not alternative-interface)
5750 org-goto-interface
5751 (if (eq org-goto-interface 'outline)
5752 'outline-path-completion
5753 'outline)))
5754 (org-goto-start-pos (point))
5755 (selected-point
5756 (if (eq interface 'outline)
5757 (car (org-get-location (current-buffer) org-goto-help))
5758 (nth 3 (org-refile-get-location "Goto: ")))))
5759 (if selected-point
5760 (progn
5761 (org-mark-ring-push org-goto-start-pos)
5762 (goto-char selected-point)
5763 (if (or (org-invisible-p) (org-invisible-p2))
5764 (org-show-context 'org-goto)))
5765 (message "Quit"))))
5767 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5768 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5769 (defvar org-goto-local-auto-isearch-map) ; defined below
5771 (defun org-get-location (buf help)
5772 "Let the user select a location in the Org-mode buffer BUF.
5773 This function uses a recursive edit. It returns the selected position
5774 or nil."
5775 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5776 (isearch-hide-immediately nil)
5777 (isearch-search-fun-function
5778 (lambda () 'org-goto-local-search-headings))
5779 (org-goto-selected-point org-goto-exit-command))
5780 (save-excursion
5781 (save-window-excursion
5782 (delete-other-windows)
5783 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5784 (switch-to-buffer
5785 (condition-case nil
5786 (make-indirect-buffer (current-buffer) "*org-goto*")
5787 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5788 (with-output-to-temp-buffer "*Help*"
5789 (princ help))
5790 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5791 (setq buffer-read-only nil)
5792 (let ((org-startup-truncated t)
5793 (org-startup-folded nil)
5794 (org-startup-align-all-tables nil))
5795 (org-mode)
5796 (org-overview))
5797 (setq buffer-read-only t)
5798 (if (and (boundp 'org-goto-start-pos)
5799 (integer-or-marker-p org-goto-start-pos))
5800 (let ((org-show-hierarchy-above t)
5801 (org-show-siblings t)
5802 (org-show-following-heading t))
5803 (goto-char org-goto-start-pos)
5804 (and (org-invisible-p) (org-show-context)))
5805 (goto-char (point-min)))
5806 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5807 (message "Select location and press RET")
5808 (use-local-map org-goto-map)
5809 (recursive-edit)
5811 (kill-buffer "*org-goto*")
5812 (cons org-goto-selected-point org-goto-exit-command)))
5814 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5815 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5816 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5817 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5819 (defun org-goto-local-search-headings (string bound noerror)
5820 "Search and make sure that any matches are in headlines."
5821 (catch 'return
5822 (while (if isearch-forward
5823 (search-forward string bound noerror)
5824 (search-backward string bound noerror))
5825 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5826 (and (member :headline context)
5827 (not (member :tags context))))
5828 (throw 'return (point))))))
5830 (defun org-goto-local-auto-isearch ()
5831 "Start isearch."
5832 (interactive)
5833 (goto-char (point-min))
5834 (let ((keys (this-command-keys)))
5835 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5836 (isearch-mode t)
5837 (isearch-process-search-char (string-to-char keys)))))
5839 (defun org-goto-ret (&optional arg)
5840 "Finish `org-goto' by going to the new location."
5841 (interactive "P")
5842 (setq org-goto-selected-point (point)
5843 org-goto-exit-command 'return)
5844 (throw 'exit nil))
5846 (defun org-goto-left ()
5847 "Finish `org-goto' by going to the new location."
5848 (interactive)
5849 (if (org-on-heading-p)
5850 (progn
5851 (beginning-of-line 1)
5852 (setq org-goto-selected-point (point)
5853 org-goto-exit-command 'left)
5854 (throw 'exit nil))
5855 (error "Not on a heading")))
5857 (defun org-goto-right ()
5858 "Finish `org-goto' by going to the new location."
5859 (interactive)
5860 (if (org-on-heading-p)
5861 (progn
5862 (setq org-goto-selected-point (point)
5863 org-goto-exit-command 'right)
5864 (throw 'exit nil))
5865 (error "Not on a heading")))
5867 (defun org-goto-quit ()
5868 "Finish `org-goto' without cursor motion."
5869 (interactive)
5870 (setq org-goto-selected-point nil)
5871 (setq org-goto-exit-command 'quit)
5872 (throw 'exit nil))
5874 ;;; Indirect buffer display of subtrees
5876 (defvar org-indirect-dedicated-frame nil
5877 "This is the frame being used for indirect tree display.")
5878 (defvar org-last-indirect-buffer nil)
5880 (defun org-tree-to-indirect-buffer (&optional arg)
5881 "Create indirect buffer and narrow it to current subtree.
5882 With numerical prefix ARG, go up to this level and then take that tree.
5883 If ARG is negative, go up that many levels.
5884 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5885 indirect buffer previously made with this command, to avoid proliferation of
5886 indirect buffers. However, when you call the command with a `C-u' prefix, or
5887 when `org-indirect-buffer-display' is `new-frame', the last buffer
5888 is kept so that you can work with several indirect buffers at the same time.
5889 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5890 requests that a new frame be made for the new buffer, so that the dedicated
5891 frame is not changed."
5892 (interactive "P")
5893 (let ((cbuf (current-buffer))
5894 (cwin (selected-window))
5895 (pos (point))
5896 beg end level heading ibuf)
5897 (save-excursion
5898 (org-back-to-heading t)
5899 (when (numberp arg)
5900 (setq level (org-outline-level))
5901 (if (< arg 0) (setq arg (+ level arg)))
5902 (while (> (setq level (org-outline-level)) arg)
5903 (outline-up-heading 1 t)))
5904 (setq beg (point)
5905 heading (org-get-heading))
5906 (org-end-of-subtree t t) (setq end (point)))
5907 (if (and (buffer-live-p org-last-indirect-buffer)
5908 (not (eq org-indirect-buffer-display 'new-frame))
5909 (not arg))
5910 (kill-buffer org-last-indirect-buffer))
5911 (setq ibuf (org-get-indirect-buffer cbuf)
5912 org-last-indirect-buffer ibuf)
5913 (cond
5914 ((or (eq org-indirect-buffer-display 'new-frame)
5915 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5916 (select-frame (make-frame))
5917 (delete-other-windows)
5918 (switch-to-buffer ibuf)
5919 (org-set-frame-title heading))
5920 ((eq org-indirect-buffer-display 'dedicated-frame)
5921 (raise-frame
5922 (select-frame (or (and org-indirect-dedicated-frame
5923 (frame-live-p org-indirect-dedicated-frame)
5924 org-indirect-dedicated-frame)
5925 (setq org-indirect-dedicated-frame (make-frame)))))
5926 (delete-other-windows)
5927 (switch-to-buffer ibuf)
5928 (org-set-frame-title (concat "Indirect: " heading)))
5929 ((eq org-indirect-buffer-display 'current-window)
5930 (switch-to-buffer ibuf))
5931 ((eq org-indirect-buffer-display 'other-window)
5932 (pop-to-buffer ibuf))
5933 (t (error "Invalid value")))
5934 (if (featurep 'xemacs)
5935 (save-excursion (org-mode) (turn-on-font-lock)))
5936 (narrow-to-region beg end)
5937 (show-all)
5938 (goto-char pos)
5939 (and (window-live-p cwin) (select-window cwin))))
5941 (defun org-get-indirect-buffer (&optional buffer)
5942 (setq buffer (or buffer (current-buffer)))
5943 (let ((n 1) (base (buffer-name buffer)) bname)
5944 (while (buffer-live-p
5945 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5946 (setq n (1+ n)))
5947 (condition-case nil
5948 (make-indirect-buffer buffer bname 'clone)
5949 (error (make-indirect-buffer buffer bname)))))
5951 (defun org-set-frame-title (title)
5952 "Set the title of the current frame to the string TITLE."
5953 ;; FIXME: how to name a single frame in XEmacs???
5954 (unless (featurep 'xemacs)
5955 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5957 ;;;; Structure editing
5959 ;;; Inserting headlines
5961 (defun org-previous-line-empty-p ()
5962 (save-excursion
5963 (and (not (bobp))
5964 (or (beginning-of-line 0) t)
5965 (save-match-data
5966 (looking-at "[ \t]*$")))))
5968 (defun org-insert-heading (&optional force-heading)
5969 "Insert a new heading or item with same depth at point.
5970 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5971 If point is at the beginning of a headline, insert a sibling before the
5972 current headline. If point is not at the beginning, do not split the line,
5973 but create the new headline after the current line."
5974 (interactive "P")
5975 (if (or (= (buffer-size) 0)
5976 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
5977 (org-on-heading-p))))
5978 (not (org-in-item-p))))
5979 (insert "\n* ")
5980 (when (or force-heading (not (org-insert-item)))
5981 (let* ((empty-line-p nil)
5982 (head (save-excursion
5983 (condition-case nil
5984 (progn
5985 (org-back-to-heading)
5986 (setq empty-line-p (org-previous-line-empty-p))
5987 (match-string 0))
5988 (error "*"))))
5989 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5990 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5991 pos hide-previous previous-pos)
5992 (cond
5993 ((and (org-on-heading-p) (bolp)
5994 (or (bobp)
5995 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5996 ;; insert before the current line
5997 (open-line (if blank 2 1)))
5998 ((and (bolp)
5999 (not org-insert-heading-respect-content)
6000 (or (bobp)
6001 (save-excursion
6002 (backward-char 1) (not (org-invisible-p)))))
6003 ;; insert right here
6004 nil)
6006 ;; somewhere in the line
6007 (save-excursion
6008 (setq previous-pos (point-at-bol))
6009 (end-of-line)
6010 (setq hide-previous (org-invisible-p)))
6011 (and org-insert-heading-respect-content (org-show-subtree))
6012 (let ((split
6013 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6014 (save-excursion
6015 (let ((p (point)))
6016 (goto-char (point-at-bol))
6017 (and (looking-at org-complex-heading-regexp)
6018 (> p (match-beginning 4)))))))
6019 tags pos)
6020 (cond
6021 (org-insert-heading-respect-content
6022 (org-end-of-subtree nil t)
6023 (or (bolp) (newline))
6024 (or (org-previous-line-empty-p)
6025 (and blank (newline)))
6026 (open-line 1))
6027 ((org-on-heading-p)
6028 (when hide-previous
6029 (show-children)
6030 (org-show-entry))
6031 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6032 (setq tags (and (match-end 2) (match-string 2)))
6033 (and (match-end 1)
6034 (delete-region (match-beginning 1) (match-end 1)))
6035 (setq pos (point-at-bol))
6036 (or split (end-of-line 1))
6037 (delete-horizontal-space)
6038 (newline (if blank 2 1))
6039 (when tags
6040 (save-excursion
6041 (goto-char pos)
6042 (end-of-line 1)
6043 (insert " " tags)
6044 (org-set-tags nil 'align))))
6046 (or split (end-of-line 1))
6047 (newline (if blank 2 1)))))))
6048 (insert head) (just-one-space)
6049 (setq pos (point))
6050 (end-of-line 1)
6051 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6052 (when (and org-insert-heading-respect-content hide-previous)
6053 (save-excursion
6054 (goto-char previous-pos)
6055 (hide-subtree)))
6056 (run-hooks 'org-insert-heading-hook)))))
6058 (defun org-get-heading (&optional no-tags)
6059 "Return the heading of the current entry, without the stars."
6060 (save-excursion
6061 (org-back-to-heading t)
6062 (if (looking-at
6063 (if no-tags
6064 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6065 "\\*+[ \t]+\\([^\r\n]*\\)"))
6066 (match-string 1) "")))
6068 (defun org-heading-components ()
6069 "Return the components of the current heading.
6070 This is a list with the following elements:
6071 - the level as an integer
6072 - the reduced level, different if `org-odd-levels-only' is set.
6073 - the TODO keyword, or nil
6074 - the priority character, like ?A, or nil if no priority is given
6075 - the headline text itself, or the tags string if no headline text
6076 - the tags string, or nil."
6077 (save-excursion
6078 (org-back-to-heading t)
6079 (if (looking-at org-complex-heading-regexp)
6080 (list (length (match-string 1))
6081 (org-reduced-level (length (match-string 1)))
6082 (org-match-string-no-properties 2)
6083 (and (match-end 3) (aref (match-string 3) 2))
6084 (org-match-string-no-properties 4)
6085 (org-match-string-no-properties 5)))))
6087 (defun org-get-entry ()
6088 "Get the entry text, after heading, entire subtree."
6089 (save-excursion
6090 (org-back-to-heading t)
6091 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6093 (defun org-insert-heading-after-current ()
6094 "Insert a new heading with same level as current, after current subtree."
6095 (interactive)
6096 (org-back-to-heading)
6097 (org-insert-heading)
6098 (org-move-subtree-down)
6099 (end-of-line 1))
6101 (defun org-insert-heading-respect-content ()
6102 (interactive)
6103 (let ((org-insert-heading-respect-content t))
6104 (org-insert-heading t)))
6106 (defun org-insert-todo-heading-respect-content (&optional force-state)
6107 (interactive "P")
6108 (let ((org-insert-heading-respect-content t))
6109 (org-insert-todo-heading force-state t)))
6111 (defun org-insert-todo-heading (arg &optional force-heading)
6112 "Insert a new heading with the same level and TODO state as current heading.
6113 If the heading has no TODO state, or if the state is DONE, use the first
6114 state (TODO by default). Also with prefix arg, force first state."
6115 (interactive "P")
6116 (when (or force-heading (not (org-insert-item 'checkbox)))
6117 (org-insert-heading force-heading)
6118 (save-excursion
6119 (org-back-to-heading)
6120 (outline-previous-heading)
6121 (looking-at org-todo-line-regexp))
6122 (let*
6123 ((new-mark-x
6124 (if (or arg
6125 (not (match-beginning 2))
6126 (member (match-string 2) org-done-keywords))
6127 (car org-todo-keywords-1)
6128 (match-string 2)))
6129 (new-mark
6131 (run-hook-with-args-until-success
6132 'org-todo-get-default-hook new-mark-x nil)
6133 new-mark-x)))
6134 (beginning-of-line 1)
6135 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6136 (if org-treat-insert-todo-heading-as-state-change
6137 (org-todo new-mark)
6138 (insert new-mark " "))))
6139 (when org-provide-todo-statistics
6140 (org-update-parent-todo-statistics))))
6142 (defun org-insert-subheading (arg)
6143 "Insert a new subheading and demote it.
6144 Works for outline headings and for plain lists alike."
6145 (interactive "P")
6146 (org-insert-heading arg)
6147 (cond
6148 ((org-on-heading-p) (org-do-demote))
6149 ((org-at-item-p) (org-indent-item 1))))
6151 (defun org-insert-todo-subheading (arg)
6152 "Insert a new subheading with TODO keyword or checkbox and demote it.
6153 Works for outline headings and for plain lists alike."
6154 (interactive "P")
6155 (org-insert-todo-heading arg)
6156 (cond
6157 ((org-on-heading-p) (org-do-demote))
6158 ((org-at-item-p) (org-indent-item 1))))
6160 ;;; Promotion and Demotion
6162 (defvar org-after-demote-entry-hook nil
6163 "Hook run after an entry has been demoted.
6164 The cursor will be at the beginning of the entry.
6165 When a subtree is being demoted, the hook will be called for each node.")
6167 (defvar org-after-promote-entry-hook nil
6168 "Hook run after an entry has been promoted.
6169 The cursor will be at the beginning of the entry.
6170 When a subtree is being promoted, the hook will be called for each node.")
6172 (defun org-promote-subtree ()
6173 "Promote the entire subtree.
6174 See also `org-promote'."
6175 (interactive)
6176 (save-excursion
6177 (org-map-tree 'org-promote))
6178 (org-fix-position-after-promote))
6180 (defun org-demote-subtree ()
6181 "Demote the entire subtree. See `org-demote'.
6182 See also `org-promote'."
6183 (interactive)
6184 (save-excursion
6185 (org-map-tree 'org-demote))
6186 (org-fix-position-after-promote))
6189 (defun org-do-promote ()
6190 "Promote the current heading higher up the tree.
6191 If the region is active in `transient-mark-mode', promote all headings
6192 in the region."
6193 (interactive)
6194 (save-excursion
6195 (if (org-region-active-p)
6196 (org-map-region 'org-promote (region-beginning) (region-end))
6197 (org-promote)))
6198 (org-fix-position-after-promote))
6200 (defun org-do-demote ()
6201 "Demote the current heading lower down the tree.
6202 If the region is active in `transient-mark-mode', demote all headings
6203 in the region."
6204 (interactive)
6205 (save-excursion
6206 (if (org-region-active-p)
6207 (org-map-region 'org-demote (region-beginning) (region-end))
6208 (org-demote)))
6209 (org-fix-position-after-promote))
6211 (defun org-fix-position-after-promote ()
6212 "Make sure that after pro/demotion cursor position is right."
6213 (let ((pos (point)))
6214 (when (save-excursion
6215 (beginning-of-line 1)
6216 (looking-at org-todo-line-regexp)
6217 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6218 (cond ((eobp) (insert " "))
6219 ((eolp) (insert " "))
6220 ((equal (char-after) ?\ ) (forward-char 1))))))
6222 (defun org-current-level ()
6223 "Return the level of the current entry, or nil if before the first headline.
6224 The level is the number of stars at the beginning of the headline."
6225 (save-excursion
6226 (condition-case nil
6227 (progn
6228 (org-back-to-heading t)
6229 (funcall outline-level))
6230 (error nil))))
6232 (defun org-reduced-level (l)
6233 "Compute the effective level of a heading.
6234 This takes into account the setting of `org-odd-levels-only'."
6235 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6237 (defun org-get-valid-level (level &optional change)
6238 "Rectify a level change under the influence of `org-odd-levels-only'
6239 LEVEL is a current level, CHANGE is by how much the level should be
6240 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6241 even level numbers will become the next higher odd number."
6242 (if org-odd-levels-only
6243 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6244 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6245 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6246 (max 1 (+ level (or change 0)))))
6248 (if (boundp 'define-obsolete-function-alias)
6249 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6250 (define-obsolete-function-alias 'org-get-legal-level
6251 'org-get-valid-level)
6252 (define-obsolete-function-alias 'org-get-legal-level
6253 'org-get-valid-level "23.1")))
6255 (defun org-promote ()
6256 "Promote the current heading higher up the tree.
6257 If the region is active in `transient-mark-mode', promote all headings
6258 in the region."
6259 (org-back-to-heading t)
6260 (let* ((level (save-match-data (funcall outline-level)))
6261 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6262 (diff (abs (- level (length up-head) -1))))
6263 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6264 (replace-match up-head nil t)
6265 ;; Fixup tag positioning
6266 (and org-auto-align-tags (org-set-tags nil t))
6267 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6268 (run-hooks 'org-after-promote-entry-hook)))
6270 (defun org-demote ()
6271 "Demote the current heading lower down the tree.
6272 If the region is active in `transient-mark-mode', demote all headings
6273 in the region."
6274 (org-back-to-heading t)
6275 (let* ((level (save-match-data (funcall outline-level)))
6276 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6277 (diff (abs (- level (length down-head) -1))))
6278 (replace-match down-head nil t)
6279 ;; Fixup tag positioning
6280 (and org-auto-align-tags (org-set-tags nil t))
6281 (if org-adapt-indentation (org-fixup-indentation diff))
6282 (run-hooks 'org-after-demote-entry-hook)))
6284 (defvar org-tab-ind-state nil)
6286 (defun org-cycle-level ()
6287 (let ((org-adapt-indentation nil))
6288 (when (and (looking-at "[ \t]*$")
6289 (org-looking-back
6290 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6291 (setq this-command 'org-cycle-level)
6292 (if (eq last-command 'org-cycle-level)
6293 (condition-case nil
6294 (progn (org-do-promote)
6295 (if (equal org-tab-ind-state (org-current-level))
6296 (org-do-promote)))
6297 (error
6298 (progn
6299 (save-excursion
6300 (beginning-of-line 1)
6301 (and (looking-at "\\*+")
6302 (replace-match
6303 (make-string org-tab-ind-state ?*))))
6304 (setq this-command 'org-cycle))))
6305 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6306 (org-do-demote))
6307 t)))
6309 (defun org-map-tree (fun)
6310 "Call FUN for every heading underneath the current one."
6311 (org-back-to-heading)
6312 (let ((level (funcall outline-level)))
6313 (save-excursion
6314 (funcall fun)
6315 (while (and (progn
6316 (outline-next-heading)
6317 (> (funcall outline-level) level))
6318 (not (eobp)))
6319 (funcall fun)))))
6321 (defun org-map-region (fun beg end)
6322 "Call FUN for every heading between BEG and END."
6323 (let ((org-ignore-region t))
6324 (save-excursion
6325 (setq end (copy-marker end))
6326 (goto-char beg)
6327 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6328 (< (point) end))
6329 (funcall fun))
6330 (while (and (progn
6331 (outline-next-heading)
6332 (< (point) end))
6333 (not (eobp)))
6334 (funcall fun)))))
6336 (defun org-fixup-indentation (diff)
6337 "Change the indentation in the current entry by DIFF
6338 However, if any line in the current entry has no indentation, or if it
6339 would end up with no indentation after the change, nothing at all is done."
6340 (save-excursion
6341 (let ((end (save-excursion (outline-next-heading)
6342 (point-marker)))
6343 (prohibit (if (> diff 0)
6344 "^\\S-"
6345 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6346 col)
6347 (unless (save-excursion (end-of-line 1)
6348 (re-search-forward prohibit end t))
6349 (while (and (< (point) end)
6350 (re-search-forward "^[ \t]+" end t))
6351 (goto-char (match-end 0))
6352 (setq col (current-column))
6353 (if (< diff 0) (replace-match ""))
6354 (org-indent-to-column (+ diff col))))
6355 (move-marker end nil))))
6357 (defun org-convert-to-odd-levels ()
6358 "Convert an org-mode file with all levels allowed to one with odd levels.
6359 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6360 level 5 etc."
6361 (interactive)
6362 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6363 (let ((outline-regexp org-outline-regexp)
6364 (outline-level 'org-outline-level)
6365 (org-odd-levels-only nil) n)
6366 (save-excursion
6367 (goto-char (point-min))
6368 (while (re-search-forward "^\\*\\*+ " nil t)
6369 (setq n (- (length (match-string 0)) 2))
6370 (while (>= (setq n (1- n)) 0)
6371 (org-demote))
6372 (end-of-line 1))))))
6374 (defun org-convert-to-oddeven-levels ()
6375 "Convert an org-mode file with only odd levels to one with odd and even levels.
6376 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6377 section with an even level, conversion would destroy the structure of the file. An error
6378 is signaled in this case."
6379 (interactive)
6380 (goto-char (point-min))
6381 ;; First check if there are no even levels
6382 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6383 (org-show-context t)
6384 (error "Not all levels are odd in this file. Conversion not possible"))
6385 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6386 (let ((outline-regexp org-outline-regexp)
6387 (outline-level 'org-outline-level)
6388 (org-odd-levels-only nil) n)
6389 (save-excursion
6390 (goto-char (point-min))
6391 (while (re-search-forward "^\\*\\*+ " nil t)
6392 (setq n (/ (1- (length (match-string 0))) 2))
6393 (while (>= (setq n (1- n)) 0)
6394 (org-promote))
6395 (end-of-line 1))))))
6397 (defun org-tr-level (n)
6398 "Make N odd if required."
6399 (if org-odd-levels-only (1+ (/ n 2)) n))
6401 ;;; Vertical tree motion, cutting and pasting of subtrees
6403 (defun org-move-subtree-up (&optional arg)
6404 "Move the current subtree up past ARG headlines of the same level."
6405 (interactive "p")
6406 (org-move-subtree-down (- (prefix-numeric-value arg))))
6408 (defun org-move-subtree-down (&optional arg)
6409 "Move the current subtree down past ARG headlines of the same level."
6410 (interactive "p")
6411 (setq arg (prefix-numeric-value arg))
6412 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6413 'org-get-last-sibling))
6414 (ins-point (make-marker))
6415 (cnt (abs arg))
6416 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6417 ;; Select the tree
6418 (org-back-to-heading)
6419 (setq beg0 (point))
6420 (save-excursion
6421 (setq ne-beg (org-back-over-empty-lines))
6422 (setq beg (point)))
6423 (save-match-data
6424 (save-excursion (outline-end-of-heading)
6425 (setq folded (org-invisible-p)))
6426 (outline-end-of-subtree))
6427 (outline-next-heading)
6428 (setq ne-end (org-back-over-empty-lines))
6429 (setq end (point))
6430 (goto-char beg0)
6431 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6432 ;; include less whitespace
6433 (save-excursion
6434 (goto-char beg)
6435 (forward-line (- ne-beg ne-end))
6436 (setq beg (point))))
6437 ;; Find insertion point, with error handling
6438 (while (> cnt 0)
6439 (or (and (funcall movfunc) (looking-at outline-regexp))
6440 (progn (goto-char beg0)
6441 (error "Cannot move past superior level or buffer limit")))
6442 (setq cnt (1- cnt)))
6443 (if (> arg 0)
6444 ;; Moving forward - still need to move over subtree
6445 (progn (org-end-of-subtree t t)
6446 (save-excursion
6447 (org-back-over-empty-lines)
6448 (or (bolp) (newline)))))
6449 (setq ne-ins (org-back-over-empty-lines))
6450 (move-marker ins-point (point))
6451 (setq txt (buffer-substring beg end))
6452 (org-save-markers-in-region beg end)
6453 (delete-region beg end)
6454 (org-remove-empty-overlays-at beg)
6455 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6456 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6457 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6458 (let ((bbb (point)))
6459 (insert-before-markers txt)
6460 (org-reinstall-markers-in-region bbb)
6461 (move-marker ins-point bbb))
6462 (or (bolp) (insert "\n"))
6463 (setq ins-end (point))
6464 (goto-char ins-point)
6465 (org-skip-whitespace)
6466 (when (and (< arg 0)
6467 (org-first-sibling-p)
6468 (> ne-ins ne-beg))
6469 ;; Move whitespace back to beginning
6470 (save-excursion
6471 (goto-char ins-end)
6472 (let ((kill-whole-line t))
6473 (kill-line (- ne-ins ne-beg)) (point)))
6474 (insert (make-string (- ne-ins ne-beg) ?\n)))
6475 (move-marker ins-point nil)
6476 (if folded
6477 (hide-subtree)
6478 (org-show-entry)
6479 (show-children)
6480 (org-cycle-hide-drawers 'children))
6481 (org-clean-visibility-after-subtree-move)))
6483 (defvar org-subtree-clip ""
6484 "Clipboard for cut and paste of subtrees.
6485 This is actually only a copy of the kill, because we use the normal kill
6486 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6488 (defvar org-subtree-clip-folded nil
6489 "Was the last copied subtree folded?
6490 This is used to fold the tree back after pasting.")
6492 (defun org-cut-subtree (&optional n)
6493 "Cut the current subtree into the clipboard.
6494 With prefix arg N, cut this many sequential subtrees.
6495 This is a short-hand for marking the subtree and then cutting it."
6496 (interactive "p")
6497 (org-copy-subtree n 'cut))
6499 (defun org-copy-subtree (&optional n cut force-store-markers)
6500 "Cut the current subtree into the clipboard.
6501 With prefix arg N, cut this many sequential subtrees.
6502 This is a short-hand for marking the subtree and then copying it.
6503 If CUT is non-nil, actually cut the subtree.
6504 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6505 of some markers in the region, even if CUT is non-nil. This is
6506 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6507 (interactive "p")
6508 (let (beg end folded (beg0 (point)))
6509 (if (interactive-p)
6510 (org-back-to-heading nil) ; take what looks like a subtree
6511 (org-back-to-heading t)) ; take what is really there
6512 (org-back-over-empty-lines)
6513 (setq beg (point))
6514 (skip-chars-forward " \t\r\n")
6515 (save-match-data
6516 (save-excursion (outline-end-of-heading)
6517 (setq folded (org-invisible-p)))
6518 (condition-case nil
6519 (org-forward-same-level (1- n) t)
6520 (error nil))
6521 (org-end-of-subtree t t))
6522 (org-back-over-empty-lines)
6523 (setq end (point))
6524 (goto-char beg0)
6525 (when (> end beg)
6526 (setq org-subtree-clip-folded folded)
6527 (when (or cut force-store-markers)
6528 (org-save-markers-in-region beg end))
6529 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6530 (setq org-subtree-clip (current-kill 0))
6531 (message "%s: Subtree(s) with %d characters"
6532 (if cut "Cut" "Copied")
6533 (length org-subtree-clip)))))
6535 (defun org-paste-subtree (&optional level tree for-yank)
6536 "Paste the clipboard as a subtree, with modification of headline level.
6537 The entire subtree is promoted or demoted in order to match a new headline
6538 level.
6540 If the cursor is at the beginning of a headline, the same level as
6541 that headline is used to paste the tree
6543 If not, the new level is derived from the *visible* headings
6544 before and after the insertion point, and taken to be the inferior headline
6545 level of the two. So if the previous visible heading is level 3 and the
6546 next is level 4 (or vice versa), level 4 will be used for insertion.
6547 This makes sure that the subtree remains an independent subtree and does
6548 not swallow low level entries.
6550 You can also force a different level, either by using a numeric prefix
6551 argument, or by inserting the heading marker by hand. For example, if the
6552 cursor is after \"*****\", then the tree will be shifted to level 5.
6554 If optional TREE is given, use this text instead of the kill ring.
6556 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6557 move back over whitespace before inserting, and move point to the end of
6558 the inserted text when done."
6559 (interactive "P")
6560 (setq tree (or tree (and kill-ring (current-kill 0))))
6561 (unless (org-kill-is-subtree-p tree)
6562 (error "%s"
6563 (substitute-command-keys
6564 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6565 (let* ((visp (not (org-invisible-p)))
6566 (txt tree)
6567 (^re (concat "^\\(" outline-regexp "\\)"))
6568 (re (concat "\\(" outline-regexp "\\)"))
6569 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6571 (old-level (if (string-match ^re txt)
6572 (- (match-end 0) (match-beginning 0) 1)
6573 -1))
6574 (force-level (cond (level (prefix-numeric-value level))
6575 ((and (looking-at "[ \t]*$")
6576 (string-match
6577 ^re_ (buffer-substring
6578 (point-at-bol) (point))))
6579 (- (match-end 1) (match-beginning 1)))
6580 ((and (bolp)
6581 (looking-at org-outline-regexp))
6582 (- (match-end 0) (point) 1))
6583 (t nil)))
6584 (previous-level (save-excursion
6585 (condition-case nil
6586 (progn
6587 (outline-previous-visible-heading 1)
6588 (if (looking-at re)
6589 (- (match-end 0) (match-beginning 0) 1)
6591 (error 1))))
6592 (next-level (save-excursion
6593 (condition-case nil
6594 (progn
6595 (or (looking-at outline-regexp)
6596 (outline-next-visible-heading 1))
6597 (if (looking-at re)
6598 (- (match-end 0) (match-beginning 0) 1)
6600 (error 1))))
6601 (new-level (or force-level (max previous-level next-level)))
6602 (shift (if (or (= old-level -1)
6603 (= new-level -1)
6604 (= old-level new-level))
6606 (- new-level old-level)))
6607 (delta (if (> shift 0) -1 1))
6608 (func (if (> shift 0) 'org-demote 'org-promote))
6609 (org-odd-levels-only nil)
6610 beg end newend)
6611 ;; Remove the forced level indicator
6612 (if force-level
6613 (delete-region (point-at-bol) (point)))
6614 ;; Paste
6615 (beginning-of-line 1)
6616 (unless for-yank (org-back-over-empty-lines))
6617 (setq beg (point))
6618 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6619 (insert-before-markers txt)
6620 (unless (string-match "\n\\'" txt) (insert "\n"))
6621 (setq newend (point))
6622 (org-reinstall-markers-in-region beg)
6623 (setq end (point))
6624 (goto-char beg)
6625 (skip-chars-forward " \t\n\r")
6626 (setq beg (point))
6627 (if (and (org-invisible-p) visp)
6628 (save-excursion (outline-show-heading)))
6629 ;; Shift if necessary
6630 (unless (= shift 0)
6631 (save-restriction
6632 (narrow-to-region beg end)
6633 (while (not (= shift 0))
6634 (org-map-region func (point-min) (point-max))
6635 (setq shift (+ delta shift)))
6636 (goto-char (point-min))
6637 (setq newend (point-max))))
6638 (when (or (interactive-p) for-yank)
6639 (message "Clipboard pasted as level %d subtree" new-level))
6640 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6641 kill-ring
6642 (eq org-subtree-clip (current-kill 0))
6643 org-subtree-clip-folded)
6644 ;; The tree was folded before it was killed/copied
6645 (hide-subtree))
6646 (and for-yank (goto-char newend))))
6648 (defun org-kill-is-subtree-p (&optional txt)
6649 "Check if the current kill is an outline subtree, or a set of trees.
6650 Returns nil if kill does not start with a headline, or if the first
6651 headline level is not the largest headline level in the tree.
6652 So this will actually accept several entries of equal levels as well,
6653 which is OK for `org-paste-subtree'.
6654 If optional TXT is given, check this string instead of the current kill."
6655 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6656 (start-level (and kill
6657 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6658 org-outline-regexp "\\)")
6659 kill)
6660 (- (match-end 2) (match-beginning 2) 1)))
6661 (re (concat "^" org-outline-regexp))
6662 (start (1+ (or (match-beginning 2) -1))))
6663 (if (not start-level)
6664 (progn
6665 nil) ;; does not even start with a heading
6666 (catch 'exit
6667 (while (setq start (string-match re kill (1+ start)))
6668 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6669 (throw 'exit nil)))
6670 t))))
6672 (defvar org-markers-to-move nil
6673 "Markers that should be moved with a cut-and-paste operation.
6674 Those markers are stored together with their positions relative to
6675 the start of the region.")
6677 (defun org-save-markers-in-region (beg end)
6678 "Check markers in region.
6679 If these markers are between BEG and END, record their position relative
6680 to BEG, so that after moving the block of text, we can put the markers back
6681 into place.
6682 This function gets called just before an entry or tree gets cut from the
6683 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6684 called immediately, to move the markers with the entries."
6685 (setq org-markers-to-move nil)
6686 (when (featurep 'org-clock)
6687 (org-clock-save-markers-for-cut-and-paste beg end))
6688 (when (featurep 'org-agenda)
6689 (org-agenda-save-markers-for-cut-and-paste beg end)))
6691 (defun org-check-and-save-marker (marker beg end)
6692 "Check if MARKER is between BEG and END.
6693 If yes, remember the marker and the distance to BEG."
6694 (when (and (marker-buffer marker)
6695 (equal (marker-buffer marker) (current-buffer)))
6696 (if (and (>= marker beg) (< marker end))
6697 (push (cons marker (- marker beg)) org-markers-to-move))))
6699 (defun org-reinstall-markers-in-region (beg)
6700 "Move all remembered markers to their position relative to BEG."
6701 (mapc (lambda (x)
6702 (move-marker (car x) (+ beg (cdr x))))
6703 org-markers-to-move)
6704 (setq org-markers-to-move nil))
6706 (defun org-narrow-to-subtree ()
6707 "Narrow buffer to the current subtree."
6708 (interactive)
6709 (save-excursion
6710 (save-match-data
6711 (narrow-to-region
6712 (progn (org-back-to-heading t) (point))
6713 (progn (org-end-of-subtree t t) (point))))))
6715 (defun org-clone-subtree-with-time-shift (n &optional shift)
6716 "Clone the task (subtree) at point N times.
6717 The clones will be inserted as siblings.
6719 In interactive use, the user will be prompted for the number of clones
6720 to be produced, and for a time SHIFT, which may be a repeater as used
6721 in time stamps, for example `+3d'.
6723 When a valid repeater is given and the entry contains any time stamps,
6724 the clones will become a sequence in time, with time stamps in the
6725 subtree shifted for each clone produced. If SHIFT is nil or the
6726 empty string, time stamps will be left alone.
6728 If the original subtree did contain time stamps with a repeater,
6729 the following will happen:
6730 - the repeater will be removed in each clone
6731 - an additional clone will be produced, with the current, unshifted
6732 date(s) in the entry.
6733 - the original entry will be placed *after* all the clones, with
6734 repeater intact.
6735 - the start days in the repeater in the original entry will be shifted
6736 to past the last clone.
6737 I this way you can spell out a number of instances of a repeating task,
6738 and still retain the repeater to cover future instances of the task."
6739 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6740 (let (beg end template task
6741 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6742 (if (not (and (integerp n) (> n 0)))
6743 (error "Invalid number of replications %s" n))
6744 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6745 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6746 shift)))
6747 (error "Invalid shift specification %s" shift))
6748 (when doshift
6749 (setq shift-n (string-to-number (match-string 1 shift))
6750 shift-what (cdr (assoc (match-string 2 shift)
6751 '(("d" . day) ("w" . week)
6752 ("m" . month) ("y" . year))))))
6753 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6754 (setq nmin 1 nmax n)
6755 (org-back-to-heading t)
6756 (setq beg (point))
6757 (org-end-of-subtree t t)
6758 (or (bolp) (insert "\n"))
6759 (setq end (point))
6760 (setq template (buffer-substring beg end))
6761 (when (and doshift
6762 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6763 (delete-region beg end)
6764 (setq end beg)
6765 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6766 (goto-char end)
6767 (loop for n from nmin to nmax do
6768 (if (not doshift)
6769 (setq task template)
6770 (with-temp-buffer
6771 (insert template)
6772 (org-mode)
6773 (goto-char (point-min))
6774 (while (re-search-forward org-ts-regexp-both nil t)
6775 (org-timestamp-change (* n shift-n) shift-what))
6776 (unless (= n n-no-remove)
6777 (goto-char (point-min))
6778 (while (re-search-forward org-ts-regexp nil t)
6779 (save-excursion
6780 (goto-char (match-beginning 0))
6781 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6782 (delete-region (match-beginning 1) (match-end 1))))))
6783 (setq task (buffer-string))))
6784 (insert task))
6785 (goto-char beg)))
6787 ;;; Outline Sorting
6789 (defun org-sort (with-case)
6790 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6791 Optional argument WITH-CASE means sort case-sensitively.
6792 With a double prefix argument, also remove duplicate entries."
6793 (interactive "P")
6794 (if (org-at-table-p)
6795 (org-call-with-arg 'org-table-sort-lines with-case)
6796 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6798 (defun org-sort-remove-invisible (s)
6799 (remove-text-properties 0 (length s) org-rm-props s)
6800 (while (string-match org-bracket-link-regexp s)
6801 (setq s (replace-match (if (match-end 2)
6802 (match-string 3 s)
6803 (match-string 1 s)) t t s)))
6806 (defvar org-priority-regexp) ; defined later in the file
6808 (defvar org-after-sorting-entries-or-items-hook nil
6809 "Hook that is run after a bunch of entries or items have been sorted.
6810 When children are sorted, the cursor is in the parent line when this
6811 hook gets called. When a region or a plain list is sorted, the cursor
6812 will be in the first entry of the sorted region/list.")
6814 (defun org-sort-entries-or-items
6815 (&optional with-case sorting-type getkey-func compare-func property)
6816 "Sort entries on a certain level of an outline tree, or plain list items.
6817 If there is an active region, the entries in the region are sorted.
6818 Else, if the cursor is before the first entry, sort the top-level items.
6819 Else, the children of the entry at point are sorted.
6820 If the cursor is at the first item in a plain list, the list items will be
6821 sorted.
6823 Sorting can be alphabetically, numerically, by date/time as given by
6824 a time stamp, by a property or by priority.
6826 The command prompts for the sorting type unless it has been given to the
6827 function through the SORTING-TYPE argument, which needs to a character,
6828 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6829 precise meaning of each character:
6831 n Numerically, by converting the beginning of the entry/item to a number.
6832 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6833 t By date/time, either the first active time stamp in the entry, or, if
6834 none exist, by the first inactive one.
6835 In items, only the first line will be checked.
6836 s By the scheduled date/time.
6837 d By deadline date/time.
6838 c By creation time, which is assumed to be the first inactive time stamp
6839 at the beginning of a line.
6840 p By priority according to the cookie.
6841 r By the value of a property.
6843 Capital letters will reverse the sort order.
6845 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6846 called with point at the beginning of the record. It must return either
6847 a string or a number that should serve as the sorting key for that record.
6849 Comparing entries ignores case by default. However, with an optional argument
6850 WITH-CASE, the sorting considers case as well."
6851 (interactive "P")
6852 (let ((case-func (if with-case 'identity 'downcase))
6853 start beg end stars re re2
6854 txt what tmp plain-list-p)
6855 ;; Find beginning and end of region to sort
6856 (cond
6857 ((org-region-active-p)
6858 ;; we will sort the region
6859 (setq end (region-end)
6860 what "region")
6861 (goto-char (region-beginning))
6862 (if (not (org-on-heading-p)) (outline-next-heading))
6863 (setq start (point)))
6864 ((org-at-item-p)
6865 ;; we will sort this plain list
6866 (org-beginning-of-item-list) (setq start (point))
6867 (org-end-of-item-list)
6868 (or (bolp) (insert "\n"))
6869 (setq end (point))
6870 (goto-char start)
6871 (setq plain-list-p t
6872 what "plain list"))
6873 ((or (org-on-heading-p)
6874 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6875 ;; we will sort the children of the current headline
6876 (org-back-to-heading)
6877 (setq start (point)
6878 end (progn (org-end-of-subtree t t)
6879 (or (bolp) (insert "\n"))
6880 (org-back-over-empty-lines)
6881 (point))
6882 what "children")
6883 (goto-char start)
6884 (show-subtree)
6885 (outline-next-heading))
6887 ;; we will sort the top-level entries in this file
6888 (goto-char (point-min))
6889 (or (org-on-heading-p) (outline-next-heading))
6890 (setq start (point))
6891 (goto-char (point-max))
6892 (beginning-of-line 1)
6893 (when (looking-at ".*?\\S-")
6894 ;; File ends in a non-white line
6895 (end-of-line 1)
6896 (insert "\n"))
6897 (setq end (point-max))
6898 (setq what "top-level")
6899 (goto-char start)
6900 (show-all)))
6902 (setq beg (point))
6903 (if (>= beg end) (error "Nothing to sort"))
6905 (unless plain-list-p
6906 (looking-at "\\(\\*+\\)")
6907 (setq stars (match-string 1)
6908 re (concat "^" (regexp-quote stars) " +")
6909 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6910 txt (buffer-substring beg end))
6911 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6912 (if (and (not (equal stars "*")) (string-match re2 txt))
6913 (error "Region to sort contains a level above the first entry")))
6915 (unless sorting-type
6916 (message
6917 (if plain-list-p
6918 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6919 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6920 [t]ime [s]cheduled [d]eadline [c]reated
6921 A/N/T/S/D/C/P/O/F means reversed:")
6922 what)
6923 (setq sorting-type (read-char-exclusive))
6925 (and (= (downcase sorting-type) ?f)
6926 (setq getkey-func
6927 (org-icompleting-read "Sort using function: "
6928 obarray 'fboundp t nil nil))
6929 (setq getkey-func (intern getkey-func)))
6931 (and (= (downcase sorting-type) ?r)
6932 (setq property
6933 (org-icompleting-read "Property: "
6934 (mapcar 'list (org-buffer-property-keys t))
6935 nil t))))
6937 (message "Sorting entries...")
6939 (save-restriction
6940 (narrow-to-region start end)
6942 (let ((dcst (downcase sorting-type))
6943 (case-fold-search nil)
6944 (now (current-time)))
6945 (sort-subr
6946 (/= dcst sorting-type)
6947 ;; This function moves to the beginning character of the "record" to
6948 ;; be sorted.
6949 (if plain-list-p
6950 (lambda nil
6951 (if (org-at-item-p) t (goto-char (point-max))))
6952 (lambda nil
6953 (if (re-search-forward re nil t)
6954 (goto-char (match-beginning 0))
6955 (goto-char (point-max)))))
6956 ;; This function moves to the last character of the "record" being
6957 ;; sorted.
6958 (if plain-list-p
6959 'org-end-of-item
6960 (lambda nil
6961 (save-match-data
6962 (condition-case nil
6963 (outline-forward-same-level 1)
6964 (error
6965 (goto-char (point-max)))))))
6967 ;; This function returns the value that gets sorted against.
6968 (if plain-list-p
6969 (lambda nil
6970 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6971 (cond
6972 ((= dcst ?n)
6973 (string-to-number (buffer-substring (match-end 0)
6974 (point-at-eol))))
6975 ((= dcst ?a)
6976 (buffer-substring (match-end 0) (point-at-eol)))
6977 ((= dcst ?t)
6978 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6979 (re-search-forward org-ts-regexp-both
6980 (point-at-eol) t))
6981 (org-time-string-to-seconds (match-string 0))
6982 (org-float-time now)))
6983 ((= dcst ?f)
6984 (if getkey-func
6985 (progn
6986 (setq tmp (funcall getkey-func))
6987 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6988 tmp)
6989 (error "Invalid key function `%s'" getkey-func)))
6990 (t (error "Invalid sorting type `%c'" sorting-type)))))
6991 (lambda nil
6992 (cond
6993 ((= dcst ?n)
6994 (if (looking-at org-complex-heading-regexp)
6995 (string-to-number (match-string 4))
6996 nil))
6997 ((= dcst ?a)
6998 (if (looking-at org-complex-heading-regexp)
6999 (funcall case-func (match-string 4))
7000 nil))
7001 ((= dcst ?t)
7002 (let ((end (save-excursion (outline-next-heading) (point))))
7003 (if (or (re-search-forward org-ts-regexp end t)
7004 (re-search-forward org-ts-regexp-both end t))
7005 (org-time-string-to-seconds (match-string 0))
7006 (org-float-time now))))
7007 ((= dcst ?c)
7008 (let ((end (save-excursion (outline-next-heading) (point))))
7009 (if (re-search-forward
7010 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7011 end t)
7012 (org-time-string-to-seconds (match-string 0))
7013 (org-float-time now))))
7014 ((= dcst ?s)
7015 (let ((end (save-excursion (outline-next-heading) (point))))
7016 (if (re-search-forward org-scheduled-time-regexp end t)
7017 (org-time-string-to-seconds (match-string 1))
7018 (org-float-time now))))
7019 ((= dcst ?d)
7020 (let ((end (save-excursion (outline-next-heading) (point))))
7021 (if (re-search-forward org-deadline-time-regexp end t)
7022 (org-time-string-to-seconds (match-string 1))
7023 (org-float-time now))))
7024 ((= dcst ?p)
7025 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7026 (string-to-char (match-string 2))
7027 org-default-priority))
7028 ((= dcst ?r)
7029 (or (org-entry-get nil property) ""))
7030 ((= dcst ?o)
7031 (if (looking-at org-complex-heading-regexp)
7032 (- 9999 (length (member (match-string 2)
7033 org-todo-keywords-1)))))
7034 ((= dcst ?f)
7035 (if getkey-func
7036 (progn
7037 (setq tmp (funcall getkey-func))
7038 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7039 tmp)
7040 (error "Invalid key function `%s'" getkey-func)))
7041 (t (error "Invalid sorting type `%c'" sorting-type)))))
7043 (cond
7044 ((= dcst ?a) 'string<)
7045 ((= dcst ?f) compare-func)
7046 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7047 (t nil)))))
7048 (run-hooks 'org-after-sorting-entries-or-items-hook)
7049 (message "Sorting entries...done")))
7051 (defun org-do-sort (table what &optional with-case sorting-type)
7052 "Sort TABLE of WHAT according to SORTING-TYPE.
7053 The user will be prompted for the SORTING-TYPE if the call to this
7054 function does not specify it. WHAT is only for the prompt, to indicate
7055 what is being sorted. The sorting key will be extracted from
7056 the car of the elements of the table.
7057 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7058 (unless sorting-type
7059 (message
7060 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7061 what)
7062 (setq sorting-type (read-char-exclusive)))
7063 (let ((dcst (downcase sorting-type))
7064 extractfun comparefun)
7065 ;; Define the appropriate functions
7066 (cond
7067 ((= dcst ?n)
7068 (setq extractfun 'string-to-number
7069 comparefun (if (= dcst sorting-type) '< '>)))
7070 ((= dcst ?a)
7071 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7072 (lambda(x) (downcase (org-sort-remove-invisible x))))
7073 comparefun (if (= dcst sorting-type)
7074 'string<
7075 (lambda (a b) (and (not (string< a b))
7076 (not (string= a b)))))))
7077 ((= dcst ?t)
7078 (setq extractfun
7079 (lambda (x)
7080 (if (or (string-match org-ts-regexp x)
7081 (string-match org-ts-regexp-both x))
7082 (org-float-time
7083 (org-time-string-to-time (match-string 0 x)))
7085 comparefun (if (= dcst sorting-type) '< '>)))
7086 (t (error "Invalid sorting type `%c'" sorting-type)))
7088 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7089 table)
7090 (lambda (a b) (funcall comparefun (car a) (car b))))))
7093 ;;; The orgstruct minor mode
7095 ;; Define a minor mode which can be used in other modes in order to
7096 ;; integrate the org-mode structure editing commands.
7098 ;; This is really a hack, because the org-mode structure commands use
7099 ;; keys which normally belong to the major mode. Here is how it
7100 ;; works: The minor mode defines all the keys necessary to operate the
7101 ;; structure commands, but wraps the commands into a function which
7102 ;; tests if the cursor is currently at a headline or a plain list
7103 ;; item. If that is the case, the structure command is used,
7104 ;; temporarily setting many Org-mode variables like regular
7105 ;; expressions for filling etc. However, when any of those keys is
7106 ;; used at a different location, function uses `key-binding' to look
7107 ;; up if the key has an associated command in another currently active
7108 ;; keymap (minor modes, major mode, global), and executes that
7109 ;; command. There might be problems if any of the keys is otherwise
7110 ;; used as a prefix key.
7112 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7113 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7114 ;; addresses this by checking explicitly for both bindings.
7116 (defvar orgstruct-mode-map (make-sparse-keymap)
7117 "Keymap for the minor `orgstruct-mode'.")
7119 (defvar org-local-vars nil
7120 "List of local variables, for use by `orgstruct-mode'")
7122 ;;;###autoload
7123 (define-minor-mode orgstruct-mode
7124 "Toggle the minor more `orgstruct-mode'.
7125 This mode is for using Org-mode structure commands in other modes.
7126 The following key behave as if Org-mode was active, if the cursor
7127 is on a headline, or on a plain list item (both in the definition
7128 of Org-mode).
7130 M-up Move entry/item up
7131 M-down Move entry/item down
7132 M-left Promote
7133 M-right Demote
7134 M-S-up Move entry/item up
7135 M-S-down Move entry/item down
7136 M-S-left Promote subtree
7137 M-S-right Demote subtree
7138 M-q Fill paragraph and items like in Org-mode
7139 C-c ^ Sort entries
7140 C-c - Cycle list bullet
7141 TAB Cycle item visibility
7142 M-RET Insert new heading/item
7143 S-M-RET Insert new TODO heading / Checkbox item
7144 C-c C-c Set tags / toggle checkbox"
7145 nil " OrgStruct" nil
7146 (org-load-modules-maybe)
7147 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7149 ;;;###autoload
7150 (defun turn-on-orgstruct ()
7151 "Unconditionally turn on `orgstruct-mode'."
7152 (orgstruct-mode 1))
7154 (defun orgstruct++-mode (&optional arg)
7155 "Toggle `orgstruct-mode', the enhanced version of it.
7156 In addition to setting orgstruct-mode, this also exports all indentation
7157 and autofilling variables from org-mode into the buffer. It will also
7158 recognize item context in multiline items.
7159 Note that turning off orgstruct-mode will *not* remove the
7160 indentation/paragraph settings. This can only be done by refreshing the
7161 major mode, for example with \\[normal-mode]."
7162 (interactive "P")
7163 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7164 (if (< arg 1)
7165 (orgstruct-mode -1)
7166 (orgstruct-mode 1)
7167 (let (var val)
7168 (mapc
7169 (lambda (x)
7170 (when (string-match
7171 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7172 (symbol-name (car x)))
7173 (setq var (car x) val (nth 1 x))
7174 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7175 org-local-vars)
7176 (org-set-local 'orgstruct-is-++ t))))
7178 (defvar orgstruct-is-++ nil
7179 "Is orgstruct-mode in ++ version in the current-buffer?")
7180 (make-variable-buffer-local 'orgstruct-is-++)
7182 ;;;###autoload
7183 (defun turn-on-orgstruct++ ()
7184 "Unconditionally turn on `orgstruct++-mode'."
7185 (orgstruct++-mode 1))
7187 (defun orgstruct-error ()
7188 "Error when there is no default binding for a structure key."
7189 (interactive)
7190 (error "This key has no function outside structure elements"))
7192 (defun orgstruct-setup ()
7193 "Setup orgstruct keymaps."
7194 (let ((nfunc 0)
7195 (bindings
7196 (list
7197 '([(meta up)] org-metaup)
7198 '([(meta down)] org-metadown)
7199 '([(meta left)] org-metaleft)
7200 '([(meta right)] org-metaright)
7201 '([(meta shift up)] org-shiftmetaup)
7202 '([(meta shift down)] org-shiftmetadown)
7203 '([(meta shift left)] org-shiftmetaleft)
7204 '([(meta shift right)] org-shiftmetaright)
7205 '([?\e (up)] org-metaup)
7206 '([?\e (down)] org-metadown)
7207 '([?\e (left)] org-metaleft)
7208 '([?\e (right)] org-metaright)
7209 '([?\e (shift up)] org-shiftmetaup)
7210 '([?\e (shift down)] org-shiftmetadown)
7211 '([?\e (shift left)] org-shiftmetaleft)
7212 '([?\e (shift right)] org-shiftmetaright)
7213 '([(shift up)] org-shiftup)
7214 '([(shift down)] org-shiftdown)
7215 '([(shift left)] org-shiftleft)
7216 '([(shift right)] org-shiftright)
7217 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7218 '("\M-q" fill-paragraph)
7219 '("\C-c^" org-sort)
7220 '("\C-c-" org-cycle-list-bullet)))
7221 elt key fun cmd)
7222 (while (setq elt (pop bindings))
7223 (setq nfunc (1+ nfunc))
7224 (setq key (org-key (car elt))
7225 fun (nth 1 elt)
7226 cmd (orgstruct-make-binding fun nfunc key))
7227 (org-defkey orgstruct-mode-map key cmd))
7229 ;; Special treatment needed for TAB and RET
7230 (org-defkey orgstruct-mode-map [(tab)]
7231 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7232 (org-defkey orgstruct-mode-map "\C-i"
7233 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7235 (org-defkey orgstruct-mode-map "\M-\C-m"
7236 (orgstruct-make-binding 'org-insert-heading 105
7237 "\M-\C-m" [(meta return)]))
7238 (org-defkey orgstruct-mode-map [(meta return)]
7239 (orgstruct-make-binding 'org-insert-heading 106
7240 [(meta return)] "\M-\C-m"))
7242 (org-defkey orgstruct-mode-map [(shift meta return)]
7243 (orgstruct-make-binding 'org-insert-todo-heading 107
7244 [(meta return)] "\M-\C-m"))
7246 (org-defkey orgstruct-mode-map "\e\C-m"
7247 (orgstruct-make-binding 'org-insert-heading 108
7248 "\e\C-m" [?\e (return)]))
7249 (org-defkey orgstruct-mode-map [?\e (return)]
7250 (orgstruct-make-binding 'org-insert-heading 109
7251 [?\e (return)] "\e\C-m"))
7252 (org-defkey orgstruct-mode-map [?\e (shift return)]
7253 (orgstruct-make-binding 'org-insert-todo-heading 110
7254 [?\e (return)] "\e\C-m"))
7256 (unless org-local-vars
7257 (setq org-local-vars (org-get-local-variables)))
7261 (defun orgstruct-make-binding (fun n &rest keys)
7262 "Create a function for binding in the structure minor mode.
7263 FUN is the command to call inside a table. N is used to create a unique
7264 command name. KEYS are keys that should be checked in for a command
7265 to execute outside of tables."
7266 (eval
7267 (list 'defun
7268 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7269 '(arg)
7270 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7271 "Outside of structure, run the binding of `"
7272 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7273 "'.")
7274 '(interactive "p")
7275 (list 'if
7276 `(org-context-p 'headline 'item
7277 (and orgstruct-is-++
7278 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7279 'item-body))
7280 (list 'org-run-like-in-org-mode (list 'quote fun))
7281 (list 'let '(orgstruct-mode)
7282 (list 'call-interactively
7283 (append '(or)
7284 (mapcar (lambda (k)
7285 (list 'key-binding k))
7286 keys)
7287 '('orgstruct-error))))))))
7289 (defun org-context-p (&rest contexts)
7290 "Check if local context is any of CONTEXTS.
7291 Possible values in the list of contexts are `table', `headline', and `item'."
7292 (let ((pos (point)))
7293 (goto-char (point-at-bol))
7294 (prog1 (or (and (memq 'table contexts)
7295 (looking-at "[ \t]*|"))
7296 (and (memq 'headline contexts)
7297 ;;????????? (looking-at "\\*+"))
7298 (looking-at outline-regexp))
7299 (and (memq 'item contexts)
7300 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7301 (and (memq 'item-body contexts)
7302 (org-in-item-p)))
7303 (goto-char pos))))
7305 (defun org-get-local-variables ()
7306 "Return a list of all local variables in an org-mode buffer."
7307 (let (varlist)
7308 (with-current-buffer (get-buffer-create "*Org tmp*")
7309 (erase-buffer)
7310 (org-mode)
7311 (setq varlist (buffer-local-variables)))
7312 (kill-buffer "*Org tmp*")
7313 (delq nil
7314 (mapcar
7315 (lambda (x)
7316 (setq x
7317 (if (symbolp x)
7318 (list x)
7319 (list (car x) (list 'quote (cdr x)))))
7320 (if (string-match
7321 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7322 (symbol-name (car x)))
7323 x nil))
7324 varlist))))
7326 ;;;###autoload
7327 (defun org-run-like-in-org-mode (cmd)
7328 "Run a command, pretending that the current buffer is in Org-mode.
7329 This will temporarily bind local variables that are typically bound in
7330 Org-mode to the values they have in Org-mode, and then interactively
7331 call CMD."
7332 (org-load-modules-maybe)
7333 (unless org-local-vars
7334 (setq org-local-vars (org-get-local-variables)))
7335 (eval (list 'let org-local-vars
7336 (list 'call-interactively (list 'quote cmd)))))
7338 ;;;; Archiving
7340 (defun org-get-category (&optional pos)
7341 "Get the category applying to position POS."
7342 (get-text-property (or pos (point)) 'org-category))
7344 (defun org-refresh-category-properties ()
7345 "Refresh category text properties in the buffer."
7346 (let ((def-cat (cond
7347 ((null org-category)
7348 (if buffer-file-name
7349 (file-name-sans-extension
7350 (file-name-nondirectory buffer-file-name))
7351 "???"))
7352 ((symbolp org-category) (symbol-name org-category))
7353 (t org-category)))
7354 beg end cat pos optionp)
7355 (org-unmodified
7356 (save-excursion
7357 (save-restriction
7358 (widen)
7359 (goto-char (point-min))
7360 (put-text-property (point) (point-max) 'org-category def-cat)
7361 (while (re-search-forward
7362 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7363 (setq pos (match-end 0)
7364 optionp (equal (char-after (match-beginning 0)) ?#)
7365 cat (org-trim (match-string 2)))
7366 (if optionp
7367 (setq beg (point-at-bol) end (point-max))
7368 (org-back-to-heading t)
7369 (setq beg (point) end (org-end-of-subtree t t)))
7370 (put-text-property beg end 'org-category cat)
7371 (goto-char pos)))))))
7374 ;;;; Link Stuff
7376 ;;; Link abbreviations
7378 (defun org-link-expand-abbrev (link)
7379 "Apply replacements as defined in `org-link-abbrev-alist."
7380 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7381 (let* ((key (match-string 1 link))
7382 (as (or (assoc key org-link-abbrev-alist-local)
7383 (assoc key org-link-abbrev-alist)))
7384 (tag (and (match-end 2) (match-string 3 link)))
7385 rpl)
7386 (if (not as)
7387 link
7388 (setq rpl (cdr as))
7389 (cond
7390 ((symbolp rpl) (funcall rpl tag))
7391 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7392 ((string-match "%h" rpl)
7393 (replace-match (url-hexify-string (or tag "")) t t rpl))
7394 (t (concat rpl tag)))))
7395 link))
7397 ;;; Storing and inserting links
7399 (defvar org-insert-link-history nil
7400 "Minibuffer history for links inserted with `org-insert-link'.")
7402 (defvar org-stored-links nil
7403 "Contains the links stored with `org-store-link'.")
7405 (defvar org-store-link-plist nil
7406 "Plist with info about the most recently link created with `org-store-link'.")
7408 (defvar org-link-protocols nil
7409 "Link protocols added to Org-mode using `org-add-link-type'.")
7411 (defvar org-store-link-functions nil
7412 "List of functions that are called to create and store a link.
7413 Each function will be called in turn until one returns a non-nil
7414 value. Each function should check if it is responsible for creating
7415 this link (for example by looking at the major mode).
7416 If not, it must exit and return nil.
7417 If yes, it should return a non-nil value after a calling
7418 `org-store-link-props' with a list of properties and values.
7419 Special properties are:
7421 :type The link prefix. like \"http\". This must be given.
7422 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7423 This is obligatory as well.
7424 :description Optional default description for the second pair
7425 of brackets in an Org-mode link. The user can still change
7426 this when inserting this link into an Org-mode buffer.
7428 In addition to these, any additional properties can be specified
7429 and then used in remember templates.")
7431 (defun org-add-link-type (type &optional follow export)
7432 "Add TYPE to the list of `org-link-types'.
7433 Re-compute all regular expressions depending on `org-link-types'
7435 FOLLOW and EXPORT are two functions.
7437 FOLLOW should take the link path as the single argument and do whatever
7438 is necessary to follow the link, for example find a file or display
7439 a mail message.
7441 EXPORT should format the link path for export to one of the export formats.
7442 It should be a function accepting three arguments:
7444 path the path of the link, the text after the prefix (like \"http:\")
7445 desc the description of the link, if any, nil if there was no description
7446 format the export format, a symbol like `html' or `latex'.
7448 The function may use the FORMAT information to return different values
7449 depending on the format. The return value will be put literally into
7450 the exported file.
7451 Org-mode has a built-in default for exporting links. If you are happy with
7452 this default, there is no need to define an export function for the link
7453 type. For a simple example of an export function, see `org-bbdb.el'."
7454 (add-to-list 'org-link-types type t)
7455 (org-make-link-regexps)
7456 (if (assoc type org-link-protocols)
7457 (setcdr (assoc type org-link-protocols) (list follow export))
7458 (push (list type follow export) org-link-protocols)))
7460 (defvar org-agenda-buffer-name)
7462 ;;;###autoload
7463 (defun org-store-link (arg)
7464 "\\<org-mode-map>Store an org-link to the current location.
7465 This link is added to `org-stored-links' and can later be inserted
7466 into an org-buffer with \\[org-insert-link].
7468 For some link types, a prefix arg is interpreted:
7469 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7470 For file links, arg negates `org-context-in-file-links'."
7471 (interactive "P")
7472 (org-load-modules-maybe)
7473 (setq org-store-link-plist nil) ; reset
7474 (let ((outline-regexp (org-get-limited-outline-regexp))
7475 link cpltxt desc description search txt custom-id)
7476 (cond
7478 ((run-hook-with-args-until-success 'org-store-link-functions)
7479 (setq link (plist-get org-store-link-plist :link)
7480 desc (or (plist-get org-store-link-plist :description) link)))
7482 ((equal (buffer-name) "*Org Edit Src Example*")
7483 (let (label gc)
7484 (while (or (not label)
7485 (save-excursion
7486 (save-restriction
7487 (widen)
7488 (goto-char (point-min))
7489 (re-search-forward
7490 (regexp-quote (format org-coderef-label-format label))
7491 nil t))))
7492 (when label (message "Label exists already") (sit-for 2))
7493 (setq label (read-string "Code line label: " label)))
7494 (end-of-line 1)
7495 (setq link (format org-coderef-label-format label))
7496 (setq gc (- 79 (length link)))
7497 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7498 (insert link)
7499 (setq link (concat "(" label ")") desc nil)))
7501 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7502 ;; We are in the agenda, link to referenced location
7503 (let ((m (or (get-text-property (point) 'org-hd-marker)
7504 (get-text-property (point) 'org-marker))))
7505 (when m
7506 (org-with-point-at m
7507 (call-interactively 'org-store-link)))))
7509 ((eq major-mode 'calendar-mode)
7510 (let ((cd (calendar-cursor-to-date)))
7511 (setq link
7512 (format-time-string
7513 (car org-time-stamp-formats)
7514 (apply 'encode-time
7515 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7516 nil nil nil))))
7517 (org-store-link-props :type "calendar" :date cd)))
7519 ((eq major-mode 'w3-mode)
7520 (setq cpltxt (if (and (buffer-name)
7521 (not (string-match "Untitled" (buffer-name))))
7522 (buffer-name)
7523 (url-view-url t))
7524 link (org-make-link (url-view-url t)))
7525 (org-store-link-props :type "w3" :url (url-view-url t)))
7527 ((eq major-mode 'w3m-mode)
7528 (setq cpltxt (or w3m-current-title w3m-current-url)
7529 link (org-make-link w3m-current-url))
7530 (org-store-link-props :type "w3m" :url (url-view-url t)))
7532 ((setq search (run-hook-with-args-until-success
7533 'org-create-file-search-functions))
7534 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7535 "::" search))
7536 (setq cpltxt (or description link)))
7538 ((eq major-mode 'image-mode)
7539 (setq cpltxt (concat "file:"
7540 (abbreviate-file-name buffer-file-name))
7541 link (org-make-link cpltxt))
7542 (org-store-link-props :type "image" :file buffer-file-name))
7544 ((eq major-mode 'dired-mode)
7545 ;; link to the file in the current line
7546 (setq cpltxt (concat "file:"
7547 (abbreviate-file-name
7548 (expand-file-name
7549 (dired-get-filename nil t))))
7550 link (org-make-link cpltxt)))
7552 ((and buffer-file-name (org-mode-p))
7553 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7554 (cond
7555 ((org-in-regexp "<<\\(.*?\\)>>")
7556 (setq cpltxt
7557 (concat "file:"
7558 (abbreviate-file-name buffer-file-name)
7559 "::" (match-string 1))
7560 link (org-make-link cpltxt)))
7561 ((and (featurep 'org-id)
7562 (or (eq org-link-to-org-use-id t)
7563 (and (eq org-link-to-org-use-id 'create-if-interactive)
7564 (interactive-p))
7565 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7566 (interactive-p)
7567 (not custom-id))
7568 (and org-link-to-org-use-id
7569 (condition-case nil
7570 (org-entry-get nil "ID")
7571 (error nil)))))
7572 ;; We can make a link using the ID.
7573 (setq link (condition-case nil
7574 (prog1 (org-id-store-link)
7575 (setq desc (plist-get org-store-link-plist
7576 :description)))
7577 (error
7578 ;; probably before first headline, link to file only
7579 (concat "file:"
7580 (abbreviate-file-name buffer-file-name))))))
7582 ;; Just link to current headline
7583 (setq cpltxt (concat "file:"
7584 (abbreviate-file-name buffer-file-name)))
7585 ;; Add a context search string
7586 (when (org-xor org-context-in-file-links arg)
7587 (setq txt (cond
7588 ((org-on-heading-p) nil)
7589 ((org-region-active-p)
7590 (buffer-substring (region-beginning) (region-end)))
7591 (t nil)))
7592 (when (or (null txt) (string-match "\\S-" txt))
7593 (setq cpltxt
7594 (concat cpltxt "::"
7595 (condition-case nil
7596 (org-make-org-heading-search-string txt)
7597 (error "")))
7598 desc (or (nth 4 (ignore-errors
7599 (org-heading-components))) "NONE"))))
7600 (if (string-match "::\\'" cpltxt)
7601 (setq cpltxt (substring cpltxt 0 -2)))
7602 (setq link (org-make-link cpltxt)))))
7604 ((buffer-file-name (buffer-base-buffer))
7605 ;; Just link to this file here.
7606 (setq cpltxt (concat "file:"
7607 (abbreviate-file-name
7608 (buffer-file-name (buffer-base-buffer)))))
7609 ;; Add a context string
7610 (when (org-xor org-context-in-file-links arg)
7611 (setq txt (if (org-region-active-p)
7612 (buffer-substring (region-beginning) (region-end))
7613 (buffer-substring (point-at-bol) (point-at-eol))))
7614 ;; Only use search option if there is some text.
7615 (when (string-match "\\S-" txt)
7616 (setq cpltxt
7617 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7618 desc "NONE")))
7619 (setq link (org-make-link cpltxt)))
7621 ((interactive-p)
7622 (error "Cannot link to a buffer which is not visiting a file"))
7624 (t (setq link nil)))
7626 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7627 (setq link (or link cpltxt)
7628 desc (or desc cpltxt))
7629 (if (equal desc "NONE") (setq desc nil))
7631 (if (and (or (interactive-p) executing-kbd-macro) link)
7632 (progn
7633 (setq org-stored-links
7634 (cons (list link desc) org-stored-links))
7635 (message "Stored: %s" (or desc link))
7636 (when custom-id
7637 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7638 "::#" custom-id))
7639 (setq org-stored-links
7640 (cons (list link desc) org-stored-links))))
7641 (and link (org-make-link-string link desc)))))
7643 (defun org-store-link-props (&rest plist)
7644 "Store link properties, extract names and addresses."
7645 (let (x adr)
7646 (when (setq x (plist-get plist :from))
7647 (setq adr (mail-extract-address-components x))
7648 (setq plist (plist-put plist :fromname (car adr)))
7649 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7650 (when (setq x (plist-get plist :to))
7651 (setq adr (mail-extract-address-components x))
7652 (setq plist (plist-put plist :toname (car adr)))
7653 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7654 (let ((from (plist-get plist :from))
7655 (to (plist-get plist :to)))
7656 (when (and from to org-from-is-user-regexp)
7657 (setq plist
7658 (plist-put plist :fromto
7659 (if (string-match org-from-is-user-regexp from)
7660 (concat "to %t")
7661 (concat "from %f"))))))
7662 (setq org-store-link-plist plist))
7664 (defun org-add-link-props (&rest plist)
7665 "Add these properties to the link property list."
7666 (let (key value)
7667 (while plist
7668 (setq key (pop plist) value (pop plist))
7669 (setq org-store-link-plist
7670 (plist-put org-store-link-plist key value)))))
7672 (defun org-email-link-description (&optional fmt)
7673 "Return the description part of an email link.
7674 This takes information from `org-store-link-plist' and formats it
7675 according to FMT (default from `org-email-link-description-format')."
7676 (setq fmt (or fmt org-email-link-description-format))
7677 (let* ((p org-store-link-plist)
7678 (to (plist-get p :toaddress))
7679 (from (plist-get p :fromaddress))
7680 (table
7681 (list
7682 (cons "%c" (plist-get p :fromto))
7683 (cons "%F" (plist-get p :from))
7684 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7685 (cons "%T" (plist-get p :to))
7686 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7687 (cons "%s" (plist-get p :subject))
7688 (cons "%m" (plist-get p :message-id)))))
7689 (when (string-match "%c" fmt)
7690 ;; Check if the user wrote this message
7691 (if (and org-from-is-user-regexp from to
7692 (save-match-data (string-match org-from-is-user-regexp from)))
7693 (setq fmt (replace-match "to %t" t t fmt))
7694 (setq fmt (replace-match "from %f" t t fmt))))
7695 (org-replace-escapes fmt table)))
7697 (defun org-make-org-heading-search-string (&optional string heading)
7698 "Make search string for STRING or current headline."
7699 (interactive)
7700 (let ((s (or string (org-get-heading))))
7701 (unless (and string (not heading))
7702 ;; We are using a headline, clean up garbage in there.
7703 (if (string-match org-todo-regexp s)
7704 (setq s (replace-match "" t t s)))
7705 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7706 (setq s (replace-match "" t t s)))
7707 (setq s (org-trim s))
7708 (if (string-match (concat "^\\(" org-quote-string "\\|"
7709 org-comment-string "\\)") s)
7710 (setq s (replace-match "" t t s)))
7711 (while (string-match org-ts-regexp s)
7712 (setq s (replace-match "" t t s))))
7713 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7714 (setq s (replace-match " " t t s)))
7715 (or string (setq s (concat "*" s))) ; Add * for headlines
7716 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7718 (defun org-make-link (&rest strings)
7719 "Concatenate STRINGS."
7720 (apply 'concat strings))
7722 (defun org-make-link-string (link &optional description)
7723 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7724 (unless (string-match "\\S-" link)
7725 (error "Empty link"))
7726 (when (and description
7727 (stringp description)
7728 (not (string-match "\\S-" description)))
7729 (setq description nil))
7730 (when (stringp description)
7731 ;; Remove brackets from the description, they are fatal.
7732 (while (string-match "\\[" description)
7733 (setq description (replace-match "{" t t description)))
7734 (while (string-match "\\]" description)
7735 (setq description (replace-match "}" t t description))))
7736 (when (equal (org-link-escape link) description)
7737 ;; No description needed, it is identical
7738 (setq description nil))
7739 (when (and (not description)
7740 (not (equal link (org-link-escape link))))
7741 (setq description (org-extract-attributes link)))
7742 (concat "[[" (org-link-escape link) "]"
7743 (if description (concat "[" description "]") "")
7744 "]"))
7746 (defconst org-link-escape-chars
7747 '((?\ . "%20")
7748 (?\[ . "%5B")
7749 (?\] . "%5D")
7750 (?\340 . "%E0") ; `a
7751 (?\342 . "%E2") ; ^a
7752 (?\347 . "%E7") ; ,c
7753 (?\350 . "%E8") ; `e
7754 (?\351 . "%E9") ; 'e
7755 (?\352 . "%EA") ; ^e
7756 (?\356 . "%EE") ; ^i
7757 (?\364 . "%F4") ; ^o
7758 (?\371 . "%F9") ; `u
7759 (?\373 . "%FB") ; ^u
7760 (?\; . "%3B")
7761 (?? . "%3F")
7762 (?= . "%3D")
7763 (?+ . "%2B")
7765 "Association list of escapes for some characters problematic in links.
7766 This is the list that is used for internal purposes.")
7768 (defvar org-url-encoding-use-url-hexify nil)
7770 (defconst org-link-escape-chars-browser
7771 '((?\ . "%20")) ; 32 for the SPC char
7772 "Association list of escapes for some characters problematic in links.
7773 This is the list that is used before handing over to the browser.")
7775 (defun org-link-escape (text &optional table)
7776 "Escape characters in TEXT that are problematic for links."
7777 (if org-url-encoding-use-url-hexify
7778 (url-hexify-string text)
7779 (setq table (or table org-link-escape-chars))
7780 (when text
7781 (let ((re (mapconcat (lambda (x) (regexp-quote
7782 (char-to-string (car x))))
7783 table "\\|")))
7784 (while (string-match re text)
7785 (setq text
7786 (replace-match
7787 (cdr (assoc (string-to-char (match-string 0 text))
7788 table))
7789 t t text)))
7790 text))))
7792 (defun org-link-unescape (text &optional table)
7793 "Reverse the action of `org-link-escape'."
7794 (if org-url-encoding-use-url-hexify
7795 (url-unhex-string text)
7796 (setq table (or table org-link-escape-chars))
7797 (when text
7798 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7799 table "\\|")))
7800 (while (string-match re text)
7801 (setq text
7802 (replace-match
7803 (char-to-string (car (rassoc (match-string 0 text) table)))
7804 t t text)))
7805 text))))
7807 (defun org-xor (a b)
7808 "Exclusive or."
7809 (if a (not b) b))
7811 (defun org-fixup-message-id-for-http (s)
7812 "Replace special characters in a message id, so it can be used in an http query."
7813 (while (string-match "<" s)
7814 (setq s (replace-match "%3C" t t s)))
7815 (while (string-match ">" s)
7816 (setq s (replace-match "%3E" t t s)))
7817 (while (string-match "@" s)
7818 (setq s (replace-match "%40" t t s)))
7821 ;;;###autoload
7822 (defun org-insert-link-global ()
7823 "Insert a link like Org-mode does.
7824 This command can be called in any mode to insert a link in Org-mode syntax."
7825 (interactive)
7826 (org-load-modules-maybe)
7827 (org-run-like-in-org-mode 'org-insert-link))
7829 (defun org-insert-link (&optional complete-file link-location)
7830 "Insert a link. At the prompt, enter the link.
7832 Completion can be used to insert any of the link protocol prefixes like
7833 http or ftp in use.
7835 The history can be used to select a link previously stored with
7836 `org-store-link'. When the empty string is entered (i.e. if you just
7837 press RET at the prompt), the link defaults to the most recently
7838 stored link. As SPC triggers completion in the minibuffer, you need to
7839 use M-SPC or C-q SPC to force the insertion of a space character.
7841 You will also be prompted for a description, and if one is given, it will
7842 be displayed in the buffer instead of the link.
7844 If there is already a link at point, this command will allow you to edit link
7845 and description parts.
7847 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7848 be selected using completion. The path to the file will be relative to the
7849 current directory if the file is in the current directory or a subdirectory.
7850 Otherwise, the link will be the absolute path as completed in the minibuffer
7851 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7852 option `org-link-file-path-type'.
7854 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7855 the current directory or below.
7857 With three \\[universal-argument] prefixes, negate the meaning of
7858 `org-keep-stored-link-after-insertion'.
7860 If `org-make-link-description-function' is non-nil, this function will be
7861 called with the link target, and the result will be the default
7862 link description.
7864 If the LINK-LOCATION parameter is non-nil, this value will be
7865 used as the link location instead of reading one interactively."
7866 (interactive "P")
7867 (let* ((wcf (current-window-configuration))
7868 (region (if (org-region-active-p)
7869 (buffer-substring (region-beginning) (region-end))))
7870 (remove (and region (list (region-beginning) (region-end))))
7871 (desc region)
7872 tmphist ; byte-compile incorrectly complains about this
7873 (link link-location)
7874 entry file all-prefixes)
7875 (cond
7876 (link-location) ; specified by arg, just use it.
7877 ((org-in-regexp org-bracket-link-regexp 1)
7878 ;; We do have a link at point, and we are going to edit it.
7879 (setq remove (list (match-beginning 0) (match-end 0)))
7880 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7881 (setq link (read-string "Link: "
7882 (org-link-unescape
7883 (org-match-string-no-properties 1)))))
7884 ((or (org-in-regexp org-angle-link-re)
7885 (org-in-regexp org-plain-link-re))
7886 ;; Convert to bracket link
7887 (setq remove (list (match-beginning 0) (match-end 0))
7888 link (read-string "Link: "
7889 (org-remove-angle-brackets (match-string 0)))))
7890 ((member complete-file '((4) (16)))
7891 ;; Completing read for file names.
7892 (setq link (org-file-complete-link complete-file)))
7894 ;; Read link, with completion for stored links.
7895 (with-output-to-temp-buffer "*Org Links*"
7896 (princ "Insert a link.
7897 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7898 (when org-stored-links
7899 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7900 (princ (mapconcat
7901 (lambda (x)
7902 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7903 (reverse org-stored-links) "\n"))))
7904 (let ((cw (selected-window)))
7905 (select-window (get-buffer-window "*Org Links*"))
7906 (setq truncate-lines t)
7907 (unless (pos-visible-in-window-p (point-max))
7908 (org-fit-window-to-buffer))
7909 (and (window-live-p cw) (select-window cw)))
7910 ;; Fake a link history, containing the stored links.
7911 (setq tmphist (append (mapcar 'car org-stored-links)
7912 org-insert-link-history))
7913 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7914 (mapcar 'car org-link-abbrev-alist)
7915 org-link-types))
7916 (unwind-protect
7917 (progn
7918 (setq link
7919 (let ((org-completion-use-ido nil)
7920 (org-completion-use-iswitchb nil))
7921 (org-completing-read
7922 "Link: "
7923 (append
7924 (mapcar (lambda (x) (list (concat x ":")))
7925 all-prefixes)
7926 (mapcar 'car org-stored-links))
7927 nil nil nil
7928 'tmphist
7929 (car (car org-stored-links)))))
7930 (if (not (string-match "\\S-" link))
7931 (error "No link selected"))
7932 (if (or (member link all-prefixes)
7933 (and (equal ":" (substring link -1))
7934 (member (substring link 0 -1) all-prefixes)
7935 (setq link (substring link 0 -1))))
7936 (setq link (org-link-try-special-completion link))))
7937 (set-window-configuration wcf)
7938 (kill-buffer "*Org Links*"))
7939 (setq entry (assoc link org-stored-links))
7940 (or entry (push link org-insert-link-history))
7941 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7942 (not org-keep-stored-link-after-insertion))
7943 (setq org-stored-links (delq (assoc link org-stored-links)
7944 org-stored-links)))
7945 (setq desc (or desc (nth 1 entry)))))
7947 (if (string-match org-plain-link-re link)
7948 ;; URL-like link, normalize the use of angular brackets.
7949 (setq link (org-make-link (org-remove-angle-brackets link))))
7951 ;; Check if we are linking to the current file with a search option
7952 ;; If yes, simplify the link by using only the search option.
7953 (when (and buffer-file-name
7954 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7955 (let* ((path (match-string 1 link))
7956 (case-fold-search nil)
7957 (search (match-string 2 link)))
7958 (save-match-data
7959 (if (equal (file-truename buffer-file-name) (file-truename path))
7960 ;; We are linking to this same file, with a search option
7961 (setq link search)))))
7963 ;; Check if we can/should use a relative path. If yes, simplify the link
7964 (when (string-match "^file:\\(.*\\)" link)
7965 (let* ((path (match-string 1 link))
7966 (origpath path)
7967 (case-fold-search nil))
7968 (cond
7969 ((or (eq org-link-file-path-type 'absolute)
7970 (equal complete-file '(16)))
7971 (setq path (abbreviate-file-name (expand-file-name path))))
7972 ((eq org-link-file-path-type 'noabbrev)
7973 (setq path (expand-file-name path)))
7974 ((eq org-link-file-path-type 'relative)
7975 (setq path (file-relative-name path)))
7977 (save-match-data
7978 (if (string-match (concat "^" (regexp-quote
7979 (file-name-as-directory
7980 (expand-file-name "."))))
7981 (expand-file-name path))
7982 ;; We are linking a file with relative path name.
7983 (setq path (substring (expand-file-name path)
7984 (match-end 0)))
7985 (setq path (abbreviate-file-name (expand-file-name path)))))))
7986 (setq link (concat "file:" path))
7987 (if (equal desc origpath)
7988 (setq desc path))))
7990 (if org-make-link-description-function
7991 (setq desc (funcall org-make-link-description-function link desc)))
7993 (setq desc (read-string "Description: " desc))
7994 (unless (string-match "\\S-" desc) (setq desc nil))
7995 (if remove (apply 'delete-region remove))
7996 (insert (org-make-link-string link desc))))
7998 (defun org-link-try-special-completion (type)
7999 "If there is completion support for link type TYPE, offer it."
8000 (let ((fun (intern (concat "org-" type "-complete-link"))))
8001 (if (functionp fun)
8002 (funcall fun)
8003 (read-string "Link (no completion support): " (concat type ":")))))
8005 (defun org-file-complete-link (&optional arg)
8006 "Create a file link using completion."
8007 (let (file link)
8008 (setq file (read-file-name "File: "))
8009 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8010 (pwd1 (file-name-as-directory (abbreviate-file-name
8011 (expand-file-name ".")))))
8012 (cond
8013 ((equal arg '(16))
8014 (setq link (org-make-link
8015 "file:"
8016 (abbreviate-file-name (expand-file-name file)))))
8017 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8018 (setq link (org-make-link "file:" (match-string 1 file))))
8019 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8020 (expand-file-name file))
8021 (setq link (org-make-link
8022 "file:" (match-string 1 (expand-file-name file)))))
8023 (t (setq link (org-make-link "file:" file)))))
8024 link))
8026 (defun org-completing-read (&rest args)
8027 "Completing-read with SPACE being a normal character."
8028 (let ((minibuffer-local-completion-map
8029 (copy-keymap minibuffer-local-completion-map)))
8030 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8031 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8032 (apply 'org-icompleting-read args)))
8034 (defun org-completing-read-no-i (&rest args)
8035 (let (org-completion-use-ido org-completion-use-iswitchb)
8036 (apply 'org-completing-read args)))
8038 (defun org-iswitchb-completing-read (prompt choices &rest args)
8039 "Use iswitch as a completing-read replacement to choose from choices.
8040 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8041 from."
8042 (let* ((iswitchb-use-virtual-buffers nil)
8043 (iswitchb-make-buflist-hook
8044 (lambda ()
8045 (setq iswitchb-temp-buflist choices))))
8046 (iswitchb-read-buffer prompt)))
8048 (defun org-icompleting-read (&rest args)
8049 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8050 (org-without-partial-completion
8051 (if (and org-completion-use-ido
8052 (fboundp 'ido-completing-read)
8053 (boundp 'ido-mode) ido-mode
8054 (listp (second args)))
8055 (let ((ido-enter-matching-directory nil))
8056 (apply 'ido-completing-read (concat (car args))
8057 (if (consp (car (nth 1 args)))
8058 (mapcar (lambda (x) (car x)) (nth 1 args))
8059 (nth 1 args))
8060 (cddr args)))
8061 (if (and org-completion-use-iswitchb
8062 (boundp 'iswitchb-mode) iswitchb-mode
8063 (listp (second args)))
8064 (apply 'org-iswitchb-completing-read (concat (car args))
8065 (if (consp (car (nth 1 args)))
8066 (mapcar (lambda (x) (car x)) (nth 1 args))
8067 (nth 1 args))
8068 (cddr args))
8069 (apply 'completing-read args)))))
8071 (defun org-extract-attributes (s)
8072 "Extract the attributes cookie from a string and set as text property."
8073 (let (a attr (start 0) key value)
8074 (save-match-data
8075 (when (string-match "{{\\([^}]+\\)}}$" s)
8076 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8077 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8078 (setq key (match-string 1 a) value (match-string 2 a)
8079 start (match-end 0)
8080 attr (plist-put attr (intern key) value))))
8081 (org-add-props s nil 'org-attr attr))
8084 (defun org-extract-attributes-from-string (tag)
8085 (let (key value attr)
8086 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8087 (setq key (match-string 1 tag) value (match-string 2 tag)
8088 tag (replace-match "" t t tag)
8089 attr (plist-put attr (intern key) value)))
8090 (cons tag attr)))
8092 (defun org-attributes-to-string (plist)
8093 "Format a property list into an HTML attribute list."
8094 (let ((s "") key value)
8095 (while plist
8096 (setq key (pop plist) value (pop plist))
8097 (and value
8098 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8101 ;;; Opening/following a link
8103 (defvar org-link-search-failed nil)
8105 (defun org-next-link ()
8106 "Move forward to the next link.
8107 If the link is in hidden text, expose it."
8108 (interactive)
8109 (when (and org-link-search-failed (eq this-command last-command))
8110 (goto-char (point-min))
8111 (message "Link search wrapped back to beginning of buffer"))
8112 (setq org-link-search-failed nil)
8113 (let* ((pos (point))
8114 (ct (org-context))
8115 (a (assoc :link ct)))
8116 (if a (goto-char (nth 2 a)))
8117 (if (re-search-forward org-any-link-re nil t)
8118 (progn
8119 (goto-char (match-beginning 0))
8120 (if (org-invisible-p) (org-show-context)))
8121 (goto-char pos)
8122 (setq org-link-search-failed t)
8123 (error "No further link found"))))
8125 (defun org-previous-link ()
8126 "Move backward to the previous link.
8127 If the link is in hidden text, expose it."
8128 (interactive)
8129 (when (and org-link-search-failed (eq this-command last-command))
8130 (goto-char (point-max))
8131 (message "Link search wrapped back to end of buffer"))
8132 (setq org-link-search-failed nil)
8133 (let* ((pos (point))
8134 (ct (org-context))
8135 (a (assoc :link ct)))
8136 (if a (goto-char (nth 1 a)))
8137 (if (re-search-backward org-any-link-re nil t)
8138 (progn
8139 (goto-char (match-beginning 0))
8140 (if (org-invisible-p) (org-show-context)))
8141 (goto-char pos)
8142 (setq org-link-search-failed t)
8143 (error "No further link found"))))
8145 (defun org-translate-link (s)
8146 "Translate a link string if a translation function has been defined."
8147 (if (and org-link-translation-function
8148 (fboundp org-link-translation-function)
8149 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8150 (progn
8151 (setq s (funcall org-link-translation-function
8152 (match-string 1) (match-string 2)))
8153 (concat (car s) ":" (cdr s)))
8156 (defun org-translate-link-from-planner (type path)
8157 "Translate a link from Emacs Planner syntax so that Org can follow it.
8158 This is still an experimental function, your mileage may vary."
8159 (cond
8160 ((member type '("http" "https" "news" "ftp"))
8161 ;; standard Internet links are the same.
8162 nil)
8163 ((and (equal type "irc") (string-match "^//" path))
8164 ;; Planner has two / at the beginning of an irc link, we have 1.
8165 ;; We should have zero, actually....
8166 (setq path (substring path 1)))
8167 ((and (equal type "lisp") (string-match "^/" path))
8168 ;; Planner has a slash, we do not.
8169 (setq type "elisp" path (substring path 1)))
8170 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8171 ;; A typical message link. Planner has the id after the final slash,
8172 ;; we separate it with a hash mark
8173 (setq path (concat (match-string 1 path) "#"
8174 (org-remove-angle-brackets (match-string 2 path)))))
8176 (cons type path))
8178 (defun org-find-file-at-mouse (ev)
8179 "Open file link or URL at mouse."
8180 (interactive "e")
8181 (mouse-set-point ev)
8182 (org-open-at-point 'in-emacs))
8184 (defun org-open-at-mouse (ev)
8185 "Open file link or URL at mouse."
8186 (interactive "e")
8187 (mouse-set-point ev)
8188 (if (eq major-mode 'org-agenda-mode)
8189 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8190 (org-open-at-point))
8192 (defvar org-window-config-before-follow-link nil
8193 "The window configuration before following a link.
8194 This is saved in case the need arises to restore it.")
8196 (defvar org-open-link-marker (make-marker)
8197 "Marker pointing to the location where `org-open-at-point; was called.")
8199 ;;;###autoload
8200 (defun org-open-at-point-global ()
8201 "Follow a link like Org-mode does.
8202 This command can be called in any mode to follow a link that has
8203 Org-mode syntax."
8204 (interactive)
8205 (org-run-like-in-org-mode 'org-open-at-point))
8207 ;;;###autoload
8208 (defun org-open-link-from-string (s &optional arg reference-buffer)
8209 "Open a link in the string S, as if it was in Org-mode."
8210 (interactive "sLink: \nP")
8211 (let ((reference-buffer (or reference-buffer (current-buffer))))
8212 (with-temp-buffer
8213 (let ((org-inhibit-startup t))
8214 (org-mode)
8215 (insert s)
8216 (goto-char (point-min))
8217 (org-open-at-point arg reference-buffer)))))
8219 (defun org-open-at-point (&optional in-emacs reference-buffer)
8220 "Open link at or after point.
8221 If there is no link at point, this function will search forward up to
8222 the end of the current line.
8223 Normally, files will be opened by an appropriate application. If the
8224 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8225 With a double prefix argument, try to open outside of Emacs, in the
8226 application the system uses for this file type."
8227 (interactive "P")
8228 (org-load-modules-maybe)
8229 (move-marker org-open-link-marker (point))
8230 (setq org-window-config-before-follow-link (current-window-configuration))
8231 (org-remove-occur-highlights nil nil t)
8232 (cond
8233 ((and (org-on-heading-p)
8234 (not (org-in-regexp
8235 (concat org-plain-link-re "\\|"
8236 org-bracket-link-regexp "\\|"
8237 org-angle-link-re "\\|"
8238 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8239 (or (org-offer-links-in-entry in-emacs)
8240 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8241 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8242 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8243 (org-footnote-action))
8245 (let (type path link line search (pos (point)))
8246 (catch 'match
8247 (save-excursion
8248 (skip-chars-forward "^]\n\r")
8249 (when (org-in-regexp org-bracket-link-regexp 1)
8250 (setq link (org-extract-attributes
8251 (org-link-unescape (org-match-string-no-properties 1))))
8252 (while (string-match " *\n *" link)
8253 (setq link (replace-match " " t t link)))
8254 (setq link (org-link-expand-abbrev link))
8255 (cond
8256 ((or (file-name-absolute-p link)
8257 (string-match "^\\.\\.?/" link))
8258 (setq type "file" path link))
8259 ((string-match org-link-re-with-space3 link)
8260 (setq type (match-string 1 link) path (match-string 2 link)))
8261 (t (setq type "thisfile" path link)))
8262 (throw 'match t)))
8264 (when (get-text-property (point) 'org-linked-text)
8265 (setq type "thisfile"
8266 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8267 (1+ (point)) (point))
8268 path (buffer-substring
8269 (previous-single-property-change pos 'org-linked-text)
8270 (next-single-property-change pos 'org-linked-text)))
8271 (throw 'match t))
8273 (save-excursion
8274 (when (or (org-in-regexp org-angle-link-re)
8275 (org-in-regexp org-plain-link-re))
8276 (setq type (match-string 1) path (match-string 2))
8277 (throw 'match t)))
8278 (save-excursion
8279 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8280 (setq type "tags"
8281 path (match-string 1))
8282 (while (string-match ":" path)
8283 (setq path (replace-match "+" t t path)))
8284 (throw 'match t)))
8285 (when (org-in-regexp "<\\([^><\n]+\\)>")
8286 (setq type "tree-match"
8287 path (match-string 1))
8288 (throw 'match t)))
8289 (unless path
8290 (error "No link found"))
8292 ;; switch back to reference buffer
8293 ;; needed when if called in a temporary buffer through
8294 ;; org-open-link-from-string
8295 (with-current-buffer (or reference-buffer (current-buffer))
8297 ;; Remove any trailing spaces in path
8298 (if (string-match " +\\'" path)
8299 (setq path (replace-match "" t t path)))
8300 (if (and org-link-translation-function
8301 (fboundp org-link-translation-function))
8302 ;; Check if we need to translate the link
8303 (let ((tmp (funcall org-link-translation-function type path)))
8304 (setq type (car tmp) path (cdr tmp))))
8306 (cond
8308 ((assoc type org-link-protocols)
8309 (funcall (nth 1 (assoc type org-link-protocols)) path))
8311 ((equal type "mailto")
8312 (let ((cmd (car org-link-mailto-program))
8313 (args (cdr org-link-mailto-program)) args1
8314 (address path) (subject "") a)
8315 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8316 (setq address (match-string 1 path)
8317 subject (org-link-escape (match-string 2 path))))
8318 (while args
8319 (cond
8320 ((not (stringp (car args))) (push (pop args) args1))
8321 (t (setq a (pop args))
8322 (if (string-match "%a" a)
8323 (setq a (replace-match address t t a)))
8324 (if (string-match "%s" a)
8325 (setq a (replace-match subject t t a)))
8326 (push a args1))))
8327 (apply cmd (nreverse args1))))
8329 ((member type '("http" "https" "ftp" "news"))
8330 (browse-url (concat type ":" (org-link-escape
8331 path org-link-escape-chars-browser))))
8333 ((member type '("message"))
8334 (browse-url (concat type ":" path)))
8336 ((string= type "tags")
8337 (org-tags-view in-emacs path))
8338 ((string= type "thisfile")
8339 (if in-emacs
8340 (switch-to-buffer-other-window
8341 (org-get-buffer-for-internal-link (current-buffer)))
8342 (org-mark-ring-push))
8343 (let ((cmd `(org-link-search
8344 ,path
8345 ,(cond ((equal in-emacs '(4)) 'occur)
8346 ((equal in-emacs '(16)) 'org-occur)
8347 (t nil))
8348 ,pos)))
8349 (condition-case nil (eval cmd)
8350 (error (progn (widen) (eval cmd))))))
8352 ((string= type "tree-match")
8353 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8355 ((string= type "file")
8356 (if (string-match "::\\([0-9]+\\)\\'" path)
8357 (setq line (string-to-number (match-string 1 path))
8358 path (substring path 0 (match-beginning 0)))
8359 (if (string-match "::\\(.+\\)\\'" path)
8360 (setq search (match-string 1 path)
8361 path (substring path 0 (match-beginning 0)))))
8362 (if (string-match "[*?{]" (file-name-nondirectory path))
8363 (dired path)
8364 (org-open-file path in-emacs line search)))
8366 ((string= type "news")
8367 (require 'org-gnus)
8368 (org-gnus-follow-link path))
8370 ((string= type "shell")
8371 (let ((cmd path))
8372 (if (or (not org-confirm-shell-link-function)
8373 (funcall org-confirm-shell-link-function
8374 (format "Execute \"%s\" in shell? "
8375 (org-add-props cmd nil
8376 'face 'org-warning))))
8377 (progn
8378 (message "Executing %s" cmd)
8379 (shell-command cmd))
8380 (error "Abort"))))
8382 ((string= type "elisp")
8383 (let ((cmd path))
8384 (if (or (not org-confirm-elisp-link-function)
8385 (funcall org-confirm-elisp-link-function
8386 (format "Execute \"%s\" as elisp? "
8387 (org-add-props cmd nil
8388 'face 'org-warning))))
8389 (message "%s => %s" cmd
8390 (if (equal (string-to-char cmd) ?\()
8391 (eval (read cmd))
8392 (call-interactively (read cmd))))
8393 (error "Abort"))))
8396 (browse-url-at-point)))))))
8397 (move-marker org-open-link-marker nil)
8398 (run-hook-with-args 'org-follow-link-hook))
8400 (defun org-offer-links-in-entry (&optional nth zero)
8401 "Offer links in the current entry and follow the selected link.
8402 If there is only one link, follow it immediately as well.
8403 If NTH is an integer, immediately pick the NTH link found.
8404 If ZERO is a string, check also this string for a link, and if
8405 there is one, offer it as link number zero."
8406 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8407 "\\(" org-angle-link-re "\\)\\|"
8408 "\\(" org-plain-link-re "\\)"))
8409 (cnt ?0)
8410 (in-emacs (if (integerp nth) nil nth))
8411 have-zero end links link c)
8412 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8413 (push (match-string 0 zero) links)
8414 (setq cnt (1- cnt) have-zero t))
8415 (save-excursion
8416 (org-back-to-heading t)
8417 (setq end (save-excursion (outline-next-heading) (point)))
8418 (while (re-search-forward re end t)
8419 (push (match-string 0) links))
8420 (setq links (org-uniquify (reverse links))))
8422 (cond
8423 ((null links)
8424 (message "No links"))
8425 ((equal (length links) 1)
8426 (setq link (car links)))
8427 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8428 (setq link (nth (if have-zero nth (1- nth)) links)))
8429 (t ; we have to select a link
8430 (save-excursion
8431 (save-window-excursion
8432 (delete-other-windows)
8433 (with-output-to-temp-buffer "*Select Link*"
8434 (mapc (lambda (l)
8435 (if (not (string-match org-bracket-link-regexp l))
8436 (princ (format "[%c] %s\n" (incf cnt)
8437 (org-remove-angle-brackets l)))
8438 (if (match-end 3)
8439 (princ (format "[%c] %s (%s)\n" (incf cnt)
8440 (match-string 3 l) (match-string 1 l)))
8441 (princ (format "[%c] %s\n" (incf cnt)
8442 (match-string 1 l))))))
8443 links))
8444 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8445 (message "Select link to open:")
8446 (setq c (read-char-exclusive))
8447 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8448 (when (equal c ?q) (error "Abort"))
8449 (setq nth (- c ?0))
8450 (if have-zero (setq nth (1+ nth)))
8451 (unless (and (integerp nth) (>= (length links) nth))
8452 (error "Invalid link selection"))
8453 (setq link (nth (1- nth) links))))
8454 (if link
8455 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8456 nil)))
8458 ;;;; Time estimates
8460 (defun org-get-effort (&optional pom)
8461 "Get the effort estimate for the current entry."
8462 (org-entry-get pom org-effort-property))
8464 ;;; File search
8466 (defvar org-create-file-search-functions nil
8467 "List of functions to construct the right search string for a file link.
8468 These functions are called in turn with point at the location to
8469 which the link should point.
8471 A function in the hook should first test if it would like to
8472 handle this file type, for example by checking the major-mode or
8473 the file extension. If it decides not to handle this file, it
8474 should just return nil to give other functions a chance. If it
8475 does handle the file, it must return the search string to be used
8476 when following the link. The search string will be part of the
8477 file link, given after a double colon, and `org-open-at-point'
8478 will automatically search for it. If special measures must be
8479 taken to make the search successful, another function should be
8480 added to the companion hook `org-execute-file-search-functions',
8481 which see.
8483 A function in this hook may also use `setq' to set the variable
8484 `description' to provide a suggestion for the descriptive text to
8485 be used for this link when it gets inserted into an Org-mode
8486 buffer with \\[org-insert-link].")
8488 (defvar org-execute-file-search-functions nil
8489 "List of functions to execute a file search triggered by a link.
8491 Functions added to this hook must accept a single argument, the
8492 search string that was part of the file link, the part after the
8493 double colon. The function must first check if it would like to
8494 handle this search, for example by checking the major-mode or the
8495 file extension. If it decides not to handle this search, it
8496 should just return nil to give other functions a chance. If it
8497 does handle the search, it must return a non-nil value to keep
8498 other functions from trying.
8500 Each function can access the current prefix argument through the
8501 variable `current-prefix-argument'. Note that a single prefix is
8502 used to force opening a link in Emacs, so it may be good to only
8503 use a numeric or double prefix to guide the search function.
8505 In case this is needed, a function in this hook can also restore
8506 the window configuration before `org-open-at-point' was called using:
8508 (set-window-configuration org-window-config-before-follow-link)")
8510 (defun org-link-search (s &optional type avoid-pos)
8511 "Search for a link search option.
8512 If S is surrounded by forward slashes, it is interpreted as a
8513 regular expression. In org-mode files, this will create an `org-occur'
8514 sparse tree. In ordinary files, `occur' will be used to list matches.
8515 If the current buffer is in `dired-mode', grep will be used to search
8516 in all files. If AVOID-POS is given, ignore matches near that position."
8517 (let ((case-fold-search t)
8518 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8519 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8520 (append '(("") (" ") ("\t") ("\n"))
8521 org-emphasis-alist)
8522 "\\|") "\\)"))
8523 (pos (point))
8524 (pre nil) (post nil)
8525 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8526 (cond
8527 ;; First check if there are any special
8528 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8529 ;; Now try the builtin stuff
8530 ((and (equal (string-to-char s0) ?#)
8531 (> (length s0) 1)
8532 (save-excursion
8533 (goto-char (point-min))
8534 (and
8535 (re-search-forward
8536 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8537 (setq type 'dedicated
8538 pos (match-beginning 0))))
8539 ;; There is an exact target for this
8540 (goto-char pos)
8541 (org-back-to-heading t)))
8542 ((save-excursion
8543 (goto-char (point-min))
8544 (and
8545 (re-search-forward
8546 (concat "<<" (regexp-quote s0) ">>") nil t)
8547 (setq type 'dedicated
8548 pos (match-beginning 0))))
8549 ;; There is an exact target for this
8550 (goto-char pos))
8551 ((and (string-match "^(\\(.*\\))$" s0)
8552 (save-excursion
8553 (goto-char (point-min))
8554 (and
8555 (re-search-forward
8556 (concat "[^[]" (regexp-quote
8557 (format org-coderef-label-format
8558 (match-string 1 s0))))
8559 nil t)
8560 (setq type 'dedicated
8561 pos (1+ (match-beginning 0))))))
8562 ;; There is a coderef target for this
8563 (goto-char pos))
8564 ((string-match "^/\\(.*\\)/$" s)
8565 ;; A regular expression
8566 (cond
8567 ((org-mode-p)
8568 (org-occur (match-string 1 s)))
8569 ;;((eq major-mode 'dired-mode)
8570 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8571 (t (org-do-occur (match-string 1 s)))))
8573 ;; A normal search strings
8574 (when (equal (string-to-char s) ?*)
8575 ;; Anchor on headlines, post may include tags.
8576 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8577 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8578 s (substring s 1)))
8579 (remove-text-properties
8580 0 (length s)
8581 '(face nil mouse-face nil keymap nil fontified nil) s)
8582 ;; Make a series of regular expressions to find a match
8583 (setq words (org-split-string s "[ \n\r\t]+")
8585 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8586 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8587 "\\)" markers)
8588 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8589 re2a (concat "[ \t\r\n]" re2a_)
8590 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8591 re4 (concat "[^a-zA-Z_]" re4_)
8593 re1 (concat pre re2 post)
8594 re3 (concat pre (if pre re4_ re4) post)
8595 re5 (concat pre ".*" re4)
8596 re2 (concat pre re2)
8597 re2a (concat pre (if pre re2a_ re2a))
8598 re4 (concat pre (if pre re4_ re4))
8599 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8600 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8601 re5 "\\)"
8603 (cond
8604 ((eq type 'org-occur) (org-occur reall))
8605 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8606 (t (goto-char (point-min))
8607 (setq type 'fuzzy)
8608 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8609 (org-search-not-self 1 re1 nil t)
8610 (org-search-not-self 1 re2 nil t)
8611 (org-search-not-self 1 re2a nil t)
8612 (org-search-not-self 1 re3 nil t)
8613 (org-search-not-self 1 re4 nil t)
8614 (org-search-not-self 1 re5 nil t)
8616 (goto-char (match-beginning 1))
8617 (goto-char pos)
8618 (error "No match")))))
8620 ;; Normal string-search
8621 (goto-char (point-min))
8622 (if (search-forward s nil t)
8623 (goto-char (match-beginning 0))
8624 (error "No match"))))
8625 (and (org-mode-p) (org-show-context 'link-search))
8626 type))
8628 (defun org-search-not-self (group &rest args)
8629 "Execute `re-search-forward', but only accept matches that do not
8630 enclose the position of `org-open-link-marker'."
8631 (let ((m org-open-link-marker))
8632 (catch 'exit
8633 (while (apply 're-search-forward args)
8634 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8635 (goto-char (match-end group))
8636 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8637 (> (match-beginning 0) (marker-position m))
8638 (< (match-end 0) (marker-position m)))
8639 (save-match-data
8640 (or (not (org-in-regexp
8641 org-bracket-link-analytic-regexp 1))
8642 (not (match-end 4)) ; no description
8643 (and (<= (match-beginning 4) (point))
8644 (>= (match-end 4) (point))))))
8645 (throw 'exit (point))))))))
8647 (defun org-get-buffer-for-internal-link (buffer)
8648 "Return a buffer to be used for displaying the link target of internal links."
8649 (cond
8650 ((not org-display-internal-link-with-indirect-buffer)
8651 buffer)
8652 ((string-match "(Clone)$" (buffer-name buffer))
8653 (message "Buffer is already a clone, not making another one")
8654 ;; we also do not modify visibility in this case
8655 buffer)
8656 (t ; make a new indirect buffer for displaying the link
8657 (let* ((bn (buffer-name buffer))
8658 (ibn (concat bn "(Clone)"))
8659 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8660 (with-current-buffer ib (org-overview))
8661 ib))))
8663 (defun org-do-occur (regexp &optional cleanup)
8664 "Call the Emacs command `occur'.
8665 If CLEANUP is non-nil, remove the printout of the regular expression
8666 in the *Occur* buffer. This is useful if the regex is long and not useful
8667 to read."
8668 (occur regexp)
8669 (when cleanup
8670 (let ((cwin (selected-window)) win beg end)
8671 (when (setq win (get-buffer-window "*Occur*"))
8672 (select-window win))
8673 (goto-char (point-min))
8674 (when (re-search-forward "match[a-z]+" nil t)
8675 (setq beg (match-end 0))
8676 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8677 (setq end (1- (match-beginning 0)))))
8678 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8679 (goto-char (point-min))
8680 (select-window cwin))))
8682 ;;; The mark ring for links jumps
8684 (defvar org-mark-ring nil
8685 "Mark ring for positions before jumps in Org-mode.")
8686 (defvar org-mark-ring-last-goto nil
8687 "Last position in the mark ring used to go back.")
8688 ;; Fill and close the ring
8689 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8690 (loop for i from 1 to org-mark-ring-length do
8691 (push (make-marker) org-mark-ring))
8692 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8693 org-mark-ring)
8695 (defun org-mark-ring-push (&optional pos buffer)
8696 "Put the current position or POS into the mark ring and rotate it."
8697 (interactive)
8698 (setq pos (or pos (point)))
8699 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8700 (move-marker (car org-mark-ring)
8701 (or pos (point))
8702 (or buffer (current-buffer)))
8703 (message "%s"
8704 (substitute-command-keys
8705 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8707 (defun org-mark-ring-goto (&optional n)
8708 "Jump to the previous position in the mark ring.
8709 With prefix arg N, jump back that many stored positions. When
8710 called several times in succession, walk through the entire ring.
8711 Org-mode commands jumping to a different position in the current file,
8712 or to another Org-mode file, automatically push the old position
8713 onto the ring."
8714 (interactive "p")
8715 (let (p m)
8716 (if (eq last-command this-command)
8717 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8718 (setq p org-mark-ring))
8719 (setq org-mark-ring-last-goto p)
8720 (setq m (car p))
8721 (switch-to-buffer (marker-buffer m))
8722 (goto-char m)
8723 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8725 (defun org-remove-angle-brackets (s)
8726 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8727 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8729 (defun org-add-angle-brackets (s)
8730 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8731 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8733 (defun org-remove-double-quotes (s)
8734 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8735 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8738 ;;; Following specific links
8740 (defun org-follow-timestamp-link ()
8741 (cond
8742 ((org-at-date-range-p t)
8743 (let ((org-agenda-start-on-weekday)
8744 (t1 (match-string 1))
8745 (t2 (match-string 2)))
8746 (setq t1 (time-to-days (org-time-string-to-time t1))
8747 t2 (time-to-days (org-time-string-to-time t2)))
8748 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8749 ((org-at-timestamp-p t)
8750 (org-agenda-list nil (time-to-days (org-time-string-to-time
8751 (substring (match-string 1) 0 10)))
8753 (t (error "This should not happen"))))
8756 ;;; Following file links
8757 (defvar org-wait nil)
8758 (defun org-open-file (path &optional in-emacs line search)
8759 "Open the file at PATH.
8760 First, this expands any special file name abbreviations. Then the
8761 configuration variable `org-file-apps' is checked if it contains an
8762 entry for this file type, and if yes, the corresponding command is launched.
8764 If no application is found, Emacs simply visits the file.
8766 With optional prefix argument IN-EMACS, Emacs will visit the file.
8767 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8768 and o use an external application to visit the file.
8770 Optional LINE specifies a line to go to, optional SEARCH a string to
8771 search for. If LINE or SEARCH is given, the file will always be
8772 opened in Emacs.
8773 If the file does not exist, an error is thrown."
8774 (setq in-emacs (or in-emacs line search))
8775 (let* ((file (if (equal path "")
8776 buffer-file-name
8777 (substitute-in-file-name (expand-file-name path))))
8778 (apps (append org-file-apps (org-default-apps)))
8779 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8780 (dirp (if remp nil (file-directory-p file)))
8781 (file (if (and dirp org-open-directory-means-index-dot-org)
8782 (concat (file-name-as-directory file) "index.org")
8783 file))
8784 (a-m-a-p (assq 'auto-mode apps))
8785 (dfile (downcase file))
8786 (old-buffer (current-buffer))
8787 (old-pos (point))
8788 (old-mode major-mode)
8789 ext cmd)
8790 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8791 (setq ext (match-string 1 dfile))
8792 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8793 (setq ext (match-string 1 dfile))))
8794 (cond
8795 ((equal in-emacs '(16))
8796 (setq cmd (cdr (assoc 'system apps))))
8797 (in-emacs (setq cmd 'emacs))
8799 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8800 (and dirp (cdr (assoc 'directory apps)))
8801 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8802 'string-match)
8803 (cdr (assoc ext apps))
8804 (cdr (assoc t apps))))))
8805 (when (eq cmd 'system)
8806 (setq cmd (cdr (assoc 'system apps))))
8807 (when (eq cmd 'default)
8808 (setq cmd (cdr (assoc t apps))))
8809 (when (eq cmd 'mailcap)
8810 (require 'mailcap)
8811 (mailcap-parse-mailcaps)
8812 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8813 (command (mailcap-mime-info mime-type)))
8814 (if (stringp command)
8815 (setq cmd command)
8816 (setq cmd 'emacs))))
8817 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8818 (not (file-exists-p file))
8819 (not org-open-non-existing-files))
8820 (error "No such file: %s" file))
8821 (cond
8822 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8823 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8824 (while (string-match "['\"]%s['\"]" cmd)
8825 (setq cmd (replace-match "%s" t t cmd)))
8826 (while (string-match "%s" cmd)
8827 (setq cmd (replace-match
8828 (save-match-data
8829 (shell-quote-argument
8830 (convert-standard-filename file)))
8831 t t cmd)))
8832 (save-window-excursion
8833 (start-process-shell-command cmd nil cmd)
8834 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8836 ((or (stringp cmd)
8837 (eq cmd 'emacs))
8838 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8839 (widen)
8840 (if line (org-goto-line line)
8841 (if search (org-link-search search))))
8842 ((consp cmd)
8843 (let ((file (convert-standard-filename file)))
8844 (eval cmd)))
8845 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8846 (and (org-mode-p) (eq old-mode 'org-mode)
8847 (or (not (equal old-buffer (current-buffer)))
8848 (not (equal old-pos (point))))
8849 (org-mark-ring-push old-pos old-buffer))))
8851 (defun org-default-apps ()
8852 "Return the default applications for this operating system."
8853 (cond
8854 ((eq system-type 'darwin)
8855 org-file-apps-defaults-macosx)
8856 ((eq system-type 'windows-nt)
8857 org-file-apps-defaults-windowsnt)
8858 (t org-file-apps-defaults-gnu)))
8860 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8861 "Convert extensions to regular expressions in the cars of LIST.
8862 Also, weed out any non-string entries, because the return value is used
8863 only for regexp matching.
8864 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8865 point to the symbol `emacs', indicating that the file should
8866 be opened in Emacs."
8867 (append
8868 (delq nil
8869 (mapcar (lambda (x)
8870 (if (not (stringp (car x)))
8872 (if (string-match "\\W" (car x))
8874 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8875 list))
8876 (if add-auto-mode
8877 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8879 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8880 (defun org-file-remote-p (file)
8881 "Test whether FILE specifies a location on a remote system.
8882 Return non-nil if the location is indeed remote.
8884 For example, the filename \"/user@host:/foo\" specifies a location
8885 on the system \"/user@host:\"."
8886 (cond ((fboundp 'file-remote-p)
8887 (file-remote-p file))
8888 ((fboundp 'tramp-handle-file-remote-p)
8889 (tramp-handle-file-remote-p file))
8890 ((and (boundp 'ange-ftp-name-format)
8891 (string-match (car ange-ftp-name-format) file))
8893 (t nil)))
8896 ;;;; Refiling
8898 (defun org-get-org-file ()
8899 "Read a filename, with default directory `org-directory'."
8900 (let ((default (or org-default-notes-file remember-data-file)))
8901 (read-file-name (format "File name [%s]: " default)
8902 (file-name-as-directory org-directory)
8903 default)))
8905 (defun org-notes-order-reversed-p ()
8906 "Check if the current file should receive notes in reversed order."
8907 (cond
8908 ((not org-reverse-note-order) nil)
8909 ((eq t org-reverse-note-order) t)
8910 ((not (listp org-reverse-note-order)) nil)
8911 (t (catch 'exit
8912 (let ((all org-reverse-note-order)
8913 entry)
8914 (while (setq entry (pop all))
8915 (if (string-match (car entry) buffer-file-name)
8916 (throw 'exit (cdr entry))))
8917 nil)))))
8919 (defvar org-refile-target-table nil
8920 "The list of refile targets, created by `org-refile'.")
8922 (defvar org-agenda-new-buffers nil
8923 "Buffers created to visit agenda files.")
8925 (defun org-get-refile-targets (&optional default-buffer)
8926 "Produce a table with refile targets."
8927 (let ((case-fold-search nil)
8928 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8929 (entries (or org-refile-targets '((nil . (:level . 1)))))
8930 targets txt re files f desc descre fast-path-p level pos0)
8931 (message "Getting targets...")
8932 (with-current-buffer (or default-buffer (current-buffer))
8933 (while (setq entry (pop entries))
8934 (setq files (car entry) desc (cdr entry))
8935 (setq fast-path-p nil)
8936 (cond
8937 ((null files) (setq files (list (current-buffer))))
8938 ((eq files 'org-agenda-files)
8939 (setq files (org-agenda-files 'unrestricted)))
8940 ((and (symbolp files) (fboundp files))
8941 (setq files (funcall files)))
8942 ((and (symbolp files) (boundp files))
8943 (setq files (symbol-value files))))
8944 (if (stringp files) (setq files (list files)))
8945 (cond
8946 ((eq (car desc) :tag)
8947 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8948 ((eq (car desc) :todo)
8949 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8950 ((eq (car desc) :regexp)
8951 (setq descre (cdr desc)))
8952 ((eq (car desc) :level)
8953 (setq descre (concat "^\\*\\{" (number-to-string
8954 (if org-odd-levels-only
8955 (1- (* 2 (cdr desc)))
8956 (cdr desc)))
8957 "\\}[ \t]")))
8958 ((eq (car desc) :maxlevel)
8959 (setq fast-path-p t)
8960 (setq descre (concat "^\\*\\{1," (number-to-string
8961 (if org-odd-levels-only
8962 (1- (* 2 (cdr desc)))
8963 (cdr desc)))
8964 "\\}[ \t]")))
8965 (t (error "Bad refiling target description %s" desc)))
8966 (while (setq f (pop files))
8967 (with-current-buffer
8968 (if (bufferp f) f (org-get-agenda-file-buffer f))
8969 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8970 (setq f (expand-file-name f))
8971 (if (eq org-refile-use-outline-path 'file)
8972 (push (list (file-name-nondirectory f) f nil nil) targets))
8973 (save-excursion
8974 (save-restriction
8975 (widen)
8976 (goto-char (point-min))
8977 (while (re-search-forward descre nil t)
8978 (goto-char (setq pos0 (point-at-bol)))
8979 (catch 'next
8980 (when org-refile-target-verify-function
8981 (save-match-data
8982 (or (funcall org-refile-target-verify-function)
8983 (throw 'next t))))
8984 (when (looking-at org-complex-heading-regexp)
8985 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8986 txt (org-link-display-format (match-string 4))
8987 re (concat "^" (regexp-quote
8988 (buffer-substring (match-beginning 1)
8989 (match-end 4)))))
8990 (if (match-end 5) (setq re (concat re "[ \t]+"
8991 (regexp-quote
8992 (match-string 5)))))
8993 (setq re (concat re "[ \t]*$"))
8994 (when org-refile-use-outline-path
8995 (setq txt (mapconcat 'org-protect-slash
8996 (append
8997 (if (eq org-refile-use-outline-path 'file)
8998 (list (file-name-nondirectory
8999 (buffer-file-name (buffer-base-buffer))))
9000 (if (eq org-refile-use-outline-path 'full-file-path)
9001 (list (buffer-file-name (buffer-base-buffer)))))
9002 (org-get-outline-path fast-path-p level txt)
9003 (list txt))
9004 "/")))
9005 (push (list txt f re (point)) targets)))
9006 (when (= (point) pos0)
9007 ;; verification function has not moved point
9008 (goto-char (point-at-eol))))))))))
9009 (message "Getting targets...done")
9010 (nreverse targets)))
9012 (defun org-protect-slash (s)
9013 (while (string-match "/" s)
9014 (setq s (replace-match "\\" t t s)))
9017 (defvar org-olpa (make-vector 20 nil))
9019 (defun org-get-outline-path (&optional fastp level heading)
9020 "Return the outline path to the current entry, as a list.
9021 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9022 routine which makes outline path derivations for an entire file,
9023 avoiding backtracing."
9024 (if fastp
9025 (progn
9026 (if (> level 19)
9027 (error "Outline path failure, more than 19 levels."))
9028 (loop for i from level upto 19 do
9029 (aset org-olpa i nil))
9030 (prog1
9031 (delq nil (append org-olpa nil))
9032 (aset org-olpa level heading)))
9033 (let (rtn)
9034 (save-excursion
9035 (save-restriction
9036 (widen)
9037 (while (org-up-heading-safe)
9038 (when (looking-at org-complex-heading-regexp)
9039 (push (org-match-string-no-properties 4) rtn)))
9040 rtn)))))
9042 (defun org-format-outline-path (path &optional width prefix)
9043 "Format the outlie path PATH for display.
9044 Width is the maximum number of characters that is available.
9045 Prefix is a prefix to be included in the returned string,
9046 such as the file name."
9047 (setq width (or width 79))
9048 (if prefix (setq width (- width (length prefix))))
9049 (if (not path)
9050 (or prefix "")
9051 (let* ((nsteps (length path))
9052 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9053 (maxwidth (if (<= total-width width)
9054 10000 ;; everything fits
9055 ;; we need to shorten the level headings
9056 (/ (- width nsteps) nsteps)))
9057 (org-odd-levels-only nil)
9058 (n 0)
9059 (total (1+ (length prefix))))
9060 (setq maxwidth (max maxwidth 10))
9061 (concat prefix
9062 (mapconcat
9063 (lambda (h)
9064 (setq n (1+ n))
9065 (if (and (= n nsteps) (< maxwidth 10000))
9066 (setq maxwidth (- total-width total)))
9067 (if (< (length h) maxwidth)
9068 (progn (setq total (+ total (length h) 1)) h)
9069 (setq h (substring h 0 (- maxwidth 2))
9070 total (+ total maxwidth 1))
9071 (if (string-match "[ \t]+\\'" h)
9072 (setq h (substring h 0 (match-beginning 0))))
9073 (setq h (concat h "..")))
9074 (org-add-props h nil 'face
9075 (nth (% (1- n) org-n-level-faces)
9076 org-level-faces))
9078 path "/")))))
9080 (defun org-display-outline-path (&optional file current)
9081 "Display the current outline path in the echo area."
9082 (interactive "P")
9083 (let ((bfn (buffer-file-name (buffer-base-buffer)))
9084 (path (and (org-mode-p) (org-get-outline-path))))
9085 (if current (setq path (append path
9086 (save-excursion
9087 (org-back-to-heading t)
9088 (if (looking-at org-complex-heading-regexp)
9089 (list (match-string 4)))))))
9090 (message "%s"
9091 (org-format-outline-path
9092 path
9093 (1- (frame-width))
9094 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9096 (defvar org-refile-history nil
9097 "History for refiling operations.")
9099 (defvar org-after-refile-insert-hook nil
9100 "Hook run after `org-refile' has inserted its stuff at the new location.
9101 Note that this is still *before* the stuff will be removed from
9102 the *old* location.")
9104 (defun org-refile (&optional goto default-buffer rfloc)
9105 "Move the entry at point to another heading.
9106 The list of target headings is compiled using the information in
9107 `org-refile-targets', which see. This list is created before each use
9108 and will therefore always be up-to-date.
9110 At the target location, the entry is filed as a subitem of the target heading.
9111 Depending on `org-reverse-note-order', the new subitem will either be the
9112 first or the last subitem.
9114 If there is an active region, all entries in that region will be moved.
9115 However, the region must fulfil the requirement that the first heading
9116 is the first one sets the top-level of the moved text - at most siblings
9117 below it are allowed.
9119 With prefix arg GOTO, the command will only visit the target location,
9120 not actually move anything.
9121 With a double prefix `C-u C-u', go to the location where the last refiling
9122 operation has put the subtree.
9123 With a prefix argument of `2', refile to the running clock.
9125 RFLOC can be a refile location obtained in a different way.
9127 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9128 (interactive "P")
9129 (let* ((cbuf (current-buffer))
9130 (regionp (org-region-active-p))
9131 (region-start (and regionp (region-beginning)))
9132 (region-end (and regionp (region-end)))
9133 (region-length (and regionp (- region-end region-start)))
9134 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9135 pos it nbuf file re level reversed)
9136 (setq last-command nil)
9137 (when regionp
9138 (goto-char region-start)
9139 (or (bolp) (goto-char (point-at-bol)))
9140 (setq region-start (point))
9141 (unless (org-kill-is-subtree-p
9142 (buffer-substring region-start region-end))
9143 (error "The region is not a (sequence of) subtree(s)")))
9144 (if (equal goto '(16))
9145 (org-refile-goto-last-stored)
9146 (when (or
9147 (and (equal goto 2)
9148 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9149 (prog1
9150 (setq it (list (or org-clock-heading "running clock")
9151 (buffer-file-name
9152 (marker-buffer org-clock-hd-marker))
9154 (marker-position org-clock-hd-marker)))
9155 (setq goto nil)))
9156 (setq it (or rfloc
9157 (save-excursion
9158 (org-refile-get-location
9159 (if goto "Goto: " "Refile to: ") default-buffer
9160 org-refile-allow-creating-parent-nodes)))))
9161 (setq file (nth 1 it)
9162 re (nth 2 it)
9163 pos (nth 3 it))
9164 (if (and (not goto)
9166 (equal (buffer-file-name) file)
9167 (if regionp
9168 (and (>= pos region-start)
9169 (<= pos region-end))
9170 (and (>= pos (point))
9171 (< pos (save-excursion
9172 (org-end-of-subtree t t))))))
9173 (error "Cannot refile to position inside the tree or region"))
9175 (setq nbuf (or (find-buffer-visiting file)
9176 (find-file-noselect file)))
9177 (if goto
9178 (progn
9179 (switch-to-buffer nbuf)
9180 (goto-char pos)
9181 (org-show-context 'org-goto))
9182 (if regionp
9183 (progn
9184 (org-kill-new (buffer-substring region-start region-end))
9185 (org-save-markers-in-region region-start region-end))
9186 (org-copy-subtree 1 nil t))
9187 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9188 (find-file-noselect file)))
9189 (setq reversed (org-notes-order-reversed-p))
9190 (save-excursion
9191 (save-restriction
9192 (widen)
9193 (if pos
9194 (progn
9195 (goto-char pos)
9196 (looking-at outline-regexp)
9197 (setq level (org-get-valid-level (funcall outline-level) 1))
9198 (goto-char
9199 (if reversed
9200 (or (outline-next-heading) (point-max))
9201 (or (save-excursion (org-get-next-sibling))
9202 (org-end-of-subtree t t)
9203 (point-max)))))
9204 (setq level 1)
9205 (if (not reversed)
9206 (goto-char (point-max))
9207 (goto-char (point-min))
9208 (or (outline-next-heading) (goto-char (point-max)))))
9209 (if (not (bolp)) (newline))
9210 (bookmark-set "org-refile-last-stored")
9211 (org-paste-subtree level)
9212 (if (fboundp 'deactivate-mark) (deactivate-mark))
9213 (run-hooks 'org-after-refile-insert-hook))))
9214 (if regionp
9215 (delete-region (point) (+ (point) region-length))
9216 (org-cut-subtree))
9217 (when (featurep 'org-inlinetask)
9218 (org-inlinetask-remove-END-maybe))
9219 (setq org-markers-to-move nil)
9220 (message "Refiled to \"%s\"" (car it))))))
9221 (org-reveal))
9223 (defun org-refile-goto-last-stored ()
9224 "Go to the location where the last refile was stored."
9225 (interactive)
9226 (bookmark-jump "org-refile-last-stored")
9227 (message "This is the location of the last refile"))
9229 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9230 "Prompt the user for a refile location, using PROMPT."
9231 (let ((org-refile-targets org-refile-targets)
9232 (org-refile-use-outline-path org-refile-use-outline-path))
9233 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9234 (unless org-refile-target-table
9235 (error "No refile targets"))
9236 (let* ((cbuf (current-buffer))
9237 (partial-completion-mode nil)
9238 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9239 (cfunc (if (and org-refile-use-outline-path
9240 org-outline-path-complete-in-steps)
9241 'org-olpath-completing-read
9242 'org-icompleting-read))
9243 (extra (if org-refile-use-outline-path "/" ""))
9244 (filename (and cfn (expand-file-name cfn)))
9245 (tbl (mapcar
9246 (lambda (x)
9247 (if (and (not (member org-refile-use-outline-path
9248 '(file full-file-path)))
9249 (not (equal filename (nth 1 x))))
9250 (cons (concat (car x) extra " ("
9251 (file-name-nondirectory (nth 1 x)) ")")
9252 (cdr x))
9253 (cons (concat (car x) extra) (cdr x))))
9254 org-refile-target-table))
9255 (completion-ignore-case t)
9256 pa answ parent-target child parent old-hist)
9257 (setq old-hist org-refile-history)
9258 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9259 nil 'org-refile-history))
9260 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9261 (if pa
9262 (progn
9263 (when (or (not org-refile-history)
9264 (not (eq old-hist org-refile-history))
9265 (not (equal (car pa) (car org-refile-history))))
9266 (setq org-refile-history
9267 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9268 org-refile-history
9269 (cdr org-refile-history))))
9270 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9271 (pop org-refile-history)))
9273 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9274 (setq parent (match-string 1 answ)
9275 child (match-string 2 answ))
9276 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9277 (when (and parent-target
9278 (or (eq new-nodes t)
9279 (and (eq new-nodes 'confirm)
9280 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9281 (org-refile-new-child parent-target child))))))
9283 (defun org-refile-new-child (parent-target child)
9284 "Use refile target PARENT-TARGET to add new CHILD below it."
9285 (unless parent-target
9286 (error "Cannot find parent for new node"))
9287 (let ((file (nth 1 parent-target))
9288 (pos (nth 3 parent-target))
9289 level)
9290 (with-current-buffer (or (find-buffer-visiting file)
9291 (find-file-noselect file))
9292 (save-excursion
9293 (save-restriction
9294 (widen)
9295 (if pos
9296 (goto-char pos)
9297 (goto-char (point-max))
9298 (if (not (bolp)) (newline)))
9299 (when (looking-at outline-regexp)
9300 (setq level (funcall outline-level))
9301 (org-end-of-subtree t t))
9302 (org-back-over-empty-lines)
9303 (insert "\n" (make-string
9304 (if pos (org-get-valid-level level 1) 1) ?*)
9305 " " child "\n")
9306 (beginning-of-line 0)
9307 (list (concat (car parent-target) "/" child) file "" (point)))))))
9309 (defun org-olpath-completing-read (prompt collection &rest args)
9310 "Read an outline path like a file name."
9311 (let ((thetable collection)
9312 (org-completion-use-ido nil) ; does not work with ido.
9313 (org-completion-use-iswitchb nil)) ; or iswitchb
9314 (apply
9315 'org-icompleting-read prompt
9316 (lambda (string predicate &optional flag)
9317 (let (rtn r f (l (length string)))
9318 (cond
9319 ((eq flag nil)
9320 ;; try completion
9321 (try-completion string thetable))
9322 ((eq flag t)
9323 ;; all-completions
9324 (setq rtn (all-completions string thetable predicate))
9325 (mapcar
9326 (lambda (x)
9327 (setq r (substring x l))
9328 (if (string-match " ([^)]*)$" x)
9329 (setq f (match-string 0 x))
9330 (setq f ""))
9331 (if (string-match "/" r)
9332 (concat string (substring r 0 (match-end 0)) f)
9334 rtn))
9335 ((eq flag 'lambda)
9336 ;; exact match?
9337 (assoc string thetable)))
9339 args)))
9341 ;;;; Dynamic blocks
9343 (defun org-find-dblock (name)
9344 "Find the first dynamic block with name NAME in the buffer.
9345 If not found, stay at current position and return nil."
9346 (let (pos)
9347 (save-excursion
9348 (goto-char (point-min))
9349 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9350 nil t)
9351 (match-beginning 0))))
9352 (if pos (goto-char pos))
9353 pos))
9355 (defconst org-dblock-start-re
9356 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9357 "Matches the start line of a dynamic block, with parameters.")
9359 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9360 "Matches the end of a dynamic block.")
9362 (defun org-create-dblock (plist)
9363 "Create a dynamic block section, with parameters taken from PLIST.
9364 PLIST must contain a :name entry which is used as name of the block."
9365 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9366 (end-of-line 1)
9367 (newline))
9368 (let ((col (current-column))
9369 (name (plist-get plist :name)))
9370 (insert "#+BEGIN: " name)
9371 (while plist
9372 (if (eq (car plist) :name)
9373 (setq plist (cddr plist))
9374 (insert " " (prin1-to-string (pop plist)))))
9375 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9376 (beginning-of-line -2)))
9378 (defun org-prepare-dblock ()
9379 "Prepare dynamic block for refresh.
9380 This empties the block, puts the cursor at the insert position and returns
9381 the property list including an extra property :name with the block name."
9382 (unless (looking-at org-dblock-start-re)
9383 (error "Not at a dynamic block"))
9384 (let* ((begdel (1+ (match-end 0)))
9385 (name (org-no-properties (match-string 1)))
9386 (params (append (list :name name)
9387 (read (concat "(" (match-string 3) ")")))))
9388 (save-excursion
9389 (beginning-of-line 1)
9390 (skip-chars-forward " \t")
9391 (setq params (plist-put params :indentation-column (current-column))))
9392 (unless (re-search-forward org-dblock-end-re nil t)
9393 (error "Dynamic block not terminated"))
9394 (setq params
9395 (append params
9396 (list :content (buffer-substring
9397 begdel (match-beginning 0)))))
9398 (delete-region begdel (match-beginning 0))
9399 (goto-char begdel)
9400 (open-line 1)
9401 params))
9403 (defun org-map-dblocks (&optional command)
9404 "Apply COMMAND to all dynamic blocks in the current buffer.
9405 If COMMAND is not given, use `org-update-dblock'."
9406 (let ((cmd (or command 'org-update-dblock))
9407 pos)
9408 (save-excursion
9409 (goto-char (point-min))
9410 (while (re-search-forward org-dblock-start-re nil t)
9411 (goto-char (setq pos (match-beginning 0)))
9412 (condition-case nil
9413 (funcall cmd)
9414 (error (message "Error during update of dynamic block")))
9415 (goto-char pos)
9416 (unless (re-search-forward org-dblock-end-re nil t)
9417 (error "Dynamic block not terminated"))))))
9419 (defun org-dblock-update (&optional arg)
9420 "User command for updating dynamic blocks.
9421 Update the dynamic block at point. With prefix ARG, update all dynamic
9422 blocks in the buffer."
9423 (interactive "P")
9424 (if arg
9425 (org-update-all-dblocks)
9426 (or (looking-at org-dblock-start-re)
9427 (org-beginning-of-dblock))
9428 (org-update-dblock)))
9430 (defun org-update-dblock ()
9431 "Update the dynamic block at point
9432 This means to empty the block, parse for parameters and then call
9433 the correct writing function."
9434 (save-window-excursion
9435 (let* ((pos (point))
9436 (line (org-current-line))
9437 (params (org-prepare-dblock))
9438 (name (plist-get params :name))
9439 (indent (plist-get params :indentation-column))
9440 (cmd (intern (concat "org-dblock-write:" name))))
9441 (message "Updating dynamic block `%s' at line %d..." name line)
9442 (funcall cmd params)
9443 (message "Updating dynamic block `%s' at line %d...done" name line)
9444 (goto-char pos)
9445 (when (and indent (> indent 0))
9446 (setq indent (make-string indent ?\ ))
9447 (save-excursion
9448 (org-beginning-of-dblock)
9449 (forward-line 1)
9450 (while (not (looking-at org-dblock-end-re))
9451 (insert indent)
9452 (beginning-of-line 2))
9453 (when (looking-at org-dblock-end-re)
9454 (and (looking-at "[ \t]+")
9455 (replace-match ""))
9456 (insert indent)))))))
9458 (defun org-beginning-of-dblock ()
9459 "Find the beginning of the dynamic block at point.
9460 Error if there is no such block at point."
9461 (let ((pos (point))
9462 beg)
9463 (end-of-line 1)
9464 (if (and (re-search-backward org-dblock-start-re nil t)
9465 (setq beg (match-beginning 0))
9466 (re-search-forward org-dblock-end-re nil t)
9467 (> (match-end 0) pos))
9468 (goto-char beg)
9469 (goto-char pos)
9470 (error "Not in a dynamic block"))))
9472 (defun org-update-all-dblocks ()
9473 "Update all dynamic blocks in the buffer.
9474 This function can be used in a hook."
9475 (when (org-mode-p)
9476 (org-map-dblocks 'org-update-dblock)))
9479 ;;;; Completion
9481 (defconst org-additional-option-like-keywords
9482 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9483 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9484 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9485 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9486 "BEGIN:" "END:"
9487 "ORGTBL" "TBLFM:" "TBLNAME:"
9488 "BEGIN_EXAMPLE" "END_EXAMPLE"
9489 "BEGIN_QUOTE" "END_QUOTE"
9490 "BEGIN_VERSE" "END_VERSE"
9491 "BEGIN_CENTER" "END_CENTER"
9492 "BEGIN_SRC" "END_SRC"
9493 "CATEGORY" "COLUMNS"
9494 "CAPTION" "LABEL"
9495 "SETUPFILE"
9496 "BIND"
9497 "MACRO"))
9499 (defcustom org-structure-template-alist
9501 ("s" "#+begin_src ?\n\n#+end_src"
9502 "<src lang=\"?\">\n\n</src>")
9503 ("e" "#+begin_example\n?\n#+end_example"
9504 "<example>\n?\n</example>")
9505 ("q" "#+begin_quote\n?\n#+end_quote"
9506 "<quote>\n?\n</quote>")
9507 ("v" "#+begin_verse\n?\n#+end_verse"
9508 "<verse>\n?\n/verse>")
9509 ("c" "#+begin_center\n?\n#+end_center"
9510 "<center>\n?\n/center>")
9511 ("l" "#+begin_latex\n?\n#+end_latex"
9512 "<literal style=\"latex\">\n?\n</literal>")
9513 ("L" "#+latex: "
9514 "<literal style=\"latex\">?</literal>")
9515 ("h" "#+begin_html\n?\n#+end_html"
9516 "<literal style=\"html\">\n?\n</literal>")
9517 ("H" "#+html: "
9518 "<literal style=\"html\">?</literal>")
9519 ("a" "#+begin_ascii\n?\n#+end_ascii")
9520 ("A" "#+ascii: ")
9521 ("i" "#+include %file ?"
9522 "<include file=%file markup=\"?\">")
9524 "Structure completion elements.
9525 This is a list of abbreviation keys and values. The value gets inserted
9526 it you type @samp{.} followed by the key and then the completion key,
9527 usually `M-TAB'. %file will be replaced by a file name after prompting
9528 for the file using completion.
9529 There are two templates for each key, the first uses the original Org syntax,
9530 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9531 the default when the /org-mtags.el/ module has been loaded. See also the
9532 variable `org-mtags-prefer-muse-templates'.
9533 This is an experimental feature, it is undecided if it is going to stay in."
9534 :group 'org-completion
9535 :type '(repeat
9536 (string :tag "Key")
9537 (string :tag "Template")
9538 (string :tag "Muse Template")))
9540 (defun org-try-structure-completion ()
9541 "Try to complete a structure template before point.
9542 This looks for strings like \"<e\" on an otherwise empty line and
9543 expands them."
9544 (let ((l (buffer-substring (point-at-bol) (point)))
9546 (when (and (looking-at "[ \t]*$")
9547 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9548 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9549 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9550 (match-beginning 1)) a)
9551 t)))
9553 (defun org-complete-expand-structure-template (start cell)
9554 "Expand a structure template."
9555 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9556 (rpl (nth (if musep 2 1) cell))
9557 (ind ""))
9558 (delete-region start (point))
9559 (when (string-match "\\`#\\+" rpl)
9560 (cond
9561 ((bolp))
9562 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9563 (setq ind (buffer-substring (point-at-bol) (point))))
9564 (t (newline))))
9565 (setq start (point))
9566 (if (string-match "%file" rpl)
9567 (setq rpl (replace-match
9568 (concat
9569 "\""
9570 (save-match-data
9571 (abbreviate-file-name (read-file-name "Include file: ")))
9572 "\"")
9573 t t rpl)))
9574 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9575 (concat "\n" ind)))
9576 (insert rpl)
9577 (if (re-search-backward "\\?" start t) (delete-char 1))))
9580 (defun org-complete (&optional arg)
9581 "Perform completion on word at point.
9582 At the beginning of a headline, this completes TODO keywords as given in
9583 `org-todo-keywords'.
9584 If the current word is preceded by a backslash, completes the TeX symbols
9585 that are supported for HTML support.
9586 If the current word is preceded by \"#+\", completes special words for
9587 setting file options.
9588 In the line after \"#+STARTUP:, complete valid keywords.\"
9589 At all other locations, this simply calls the value of
9590 `org-completion-fallback-command'."
9591 (interactive "P")
9592 (org-without-partial-completion
9593 (catch 'exit
9594 (let* ((a nil)
9595 (end (point))
9596 (beg1 (save-excursion
9597 (skip-chars-backward (org-re "[:alnum:]_@"))
9598 (point)))
9599 (beg (save-excursion
9600 (skip-chars-backward "a-zA-Z0-9_:$")
9601 (point)))
9602 (confirm (lambda (x) (stringp (car x))))
9603 (searchhead (equal (char-before beg) ?*))
9604 (struct
9605 (when (and (member (char-before beg1) '(?. ?<))
9606 (setq a (assoc (buffer-substring beg1 (point))
9607 org-structure-template-alist)))
9608 (org-complete-expand-structure-template (1- beg1) a)
9609 (throw 'exit t)))
9610 (tag (and (equal (char-before beg1) ?:)
9611 (equal (char-after (point-at-bol)) ?*)))
9612 (prop (and (equal (char-before beg1) ?:)
9613 (not (equal (char-after (point-at-bol)) ?*))))
9614 (texp (equal (char-before beg) ?\\))
9615 (link (equal (char-before beg) ?\[))
9616 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9617 beg)
9618 "#+"))
9619 (startup (string-match "^#\\+STARTUP:.*"
9620 (buffer-substring (point-at-bol) (point))))
9621 (completion-ignore-case opt)
9622 (type nil)
9623 (tbl nil)
9624 (table (cond
9625 (opt
9626 (setq type :opt)
9627 (require 'org-exp)
9628 (append
9629 (delq nil
9630 (mapcar
9631 (lambda (x)
9632 (if (string-match
9633 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9634 (cons (match-string 2 x)
9635 (match-string 1 x))))
9636 (org-split-string (org-get-current-options) "\n")))
9637 (mapcar 'list org-additional-option-like-keywords)))
9638 (startup
9639 (setq type :startup)
9640 org-startup-options)
9641 (link (append org-link-abbrev-alist-local
9642 org-link-abbrev-alist))
9643 (texp
9644 (setq type :tex)
9645 org-html-entities)
9646 ((string-match "\\`\\*+[ \t]+\\'"
9647 (buffer-substring (point-at-bol) beg))
9648 (setq type :todo)
9649 (mapcar 'list org-todo-keywords-1))
9650 (searchhead
9651 (setq type :searchhead)
9652 (save-excursion
9653 (goto-char (point-min))
9654 (while (re-search-forward org-todo-line-regexp nil t)
9655 (push (list
9656 (org-make-org-heading-search-string
9657 (match-string 3) t))
9658 tbl)))
9659 tbl)
9660 (tag (setq type :tag beg beg1)
9661 (or org-tag-alist (org-get-buffer-tags)))
9662 (prop (setq type :prop beg beg1)
9663 (mapcar 'list (org-buffer-property-keys nil t t)))
9664 (t (progn
9665 (call-interactively org-completion-fallback-command)
9666 (throw 'exit nil)))))
9667 (pattern (buffer-substring-no-properties beg end))
9668 (completion (try-completion pattern table confirm)))
9669 (cond ((eq completion t)
9670 (if (not (assoc (upcase pattern) table))
9671 (message "Already complete")
9672 (if (and (equal type :opt)
9673 (not (member (car (assoc (upcase pattern) table))
9674 org-additional-option-like-keywords)))
9675 (insert (substring (cdr (assoc (upcase pattern) table))
9676 (length pattern)))
9677 (if (memq type '(:tag :prop)) (insert ":")))))
9678 ((null completion)
9679 (message "Can't find completion for \"%s\"" pattern)
9680 (ding))
9681 ((not (string= pattern completion))
9682 (delete-region beg end)
9683 (if (string-match " +$" completion)
9684 (setq completion (replace-match "" t t completion)))
9685 (insert completion)
9686 (if (get-buffer-window "*Completions*")
9687 (delete-window (get-buffer-window "*Completions*")))
9688 (if (assoc completion table)
9689 (if (eq type :todo) (insert " ")
9690 (if (memq type '(:tag :prop)) (insert ":"))))
9691 (if (and (equal type :opt) (assoc completion table))
9692 (message "%s" (substitute-command-keys
9693 "Press \\[org-complete] again to insert example settings"))))
9695 (message "Making completion list...")
9696 (let ((list (sort (all-completions pattern table confirm)
9697 'string<)))
9698 (with-output-to-temp-buffer "*Completions*"
9699 (condition-case nil
9700 ;; Protection needed for XEmacs and emacs 21
9701 (display-completion-list list pattern)
9702 (error (display-completion-list list)))))
9703 (message "Making completion list...%s" "done")))))))
9705 ;;;; TODO, DEADLINE, Comments
9707 (defun org-toggle-comment ()
9708 "Change the COMMENT state of an entry."
9709 (interactive)
9710 (save-excursion
9711 (org-back-to-heading)
9712 (let (case-fold-search)
9713 (if (looking-at (concat outline-regexp
9714 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9715 (replace-match "" t t nil 1)
9716 (if (looking-at outline-regexp)
9717 (progn
9718 (goto-char (match-end 0))
9719 (insert org-comment-string " ")))))))
9721 (defvar org-last-todo-state-is-todo nil
9722 "This is non-nil when the last TODO state change led to a TODO state.
9723 If the last change removed the TODO tag or switched to DONE, then
9724 this is nil.")
9726 (defvar org-setting-tags nil) ; dynamically skipped
9728 (defun org-parse-local-options (string var)
9729 "Parse STRING for startup setting relevant for variable VAR."
9730 (let ((rtn (symbol-value var))
9731 e opts)
9732 (save-match-data
9733 (if (or (not string) (not (string-match "\\S-" string)))
9735 (setq opts (delq nil (mapcar (lambda (x)
9736 (setq e (assoc x org-startup-options))
9737 (if (eq (nth 1 e) var) e nil))
9738 (org-split-string string "[ \t]+"))))
9739 (if (not opts)
9741 (setq rtn nil)
9742 (while (setq e (pop opts))
9743 (if (not (nth 3 e))
9744 (setq rtn (nth 2 e))
9745 (if (not (listp rtn)) (setq rtn nil))
9746 (push (nth 2 e) rtn)))
9747 rtn)))))
9749 (defvar org-todo-setup-filter-hook nil
9750 "Hook for functions that pre-filter todo specs.
9752 Each function takes a todo spec and returns either `nil' or the spec
9753 transformed into canonical form." )
9755 (defvar org-todo-get-default-hook nil
9756 "Hook for functions that get a default item for todo.
9758 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9759 `nil' or a string to be used for the todo mark." )
9761 (defvar org-agenda-headline-snapshot-before-repeat)
9763 (defun org-todo (&optional arg)
9764 "Change the TODO state of an item.
9765 The state of an item is given by a keyword at the start of the heading,
9766 like
9767 *** TODO Write paper
9768 *** DONE Call mom
9770 The different keywords are specified in the variable `org-todo-keywords'.
9771 By default the available states are \"TODO\" and \"DONE\".
9772 So for this example: when the item starts with TODO, it is changed to DONE.
9773 When it starts with DONE, the DONE is removed. And when neither TODO nor
9774 DONE are present, add TODO at the beginning of the heading.
9776 With C-u prefix arg, use completion to determine the new state.
9777 With numeric prefix arg, switch to that state.
9778 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9779 With a triple C-u prefix, circumvent any state blocking.
9781 For calling through lisp, arg is also interpreted in the following way:
9782 'none -> empty state
9783 \"\"(empty string) -> switch to empty state
9784 'done -> switch to DONE
9785 'nextset -> switch to the next set of keywords
9786 'previousset -> switch to the previous set of keywords
9787 \"WAITING\" -> switch to the specified keyword, but only if it
9788 really is a member of `org-todo-keywords'."
9789 (interactive "P")
9790 (if (equal arg '(16)) (setq arg 'nextset))
9791 (let ((org-blocker-hook org-blocker-hook)
9792 (case-fold-search nil))
9793 (when (equal arg '(64))
9794 (setq arg nil org-blocker-hook nil))
9795 (when (and org-blocker-hook
9796 (or org-inhibit-blocking
9797 (org-entry-get nil "NOBLOCKING")))
9798 (setq org-blocker-hook nil))
9799 (save-excursion
9800 (catch 'exit
9801 (org-back-to-heading t)
9802 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9803 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9804 (looking-at " *"))
9805 (let* ((match-data (match-data))
9806 (startpos (point-at-bol))
9807 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9808 (org-log-done org-log-done)
9809 (org-log-repeat org-log-repeat)
9810 (org-todo-log-states org-todo-log-states)
9811 (this (match-string 1))
9812 (hl-pos (match-beginning 0))
9813 (head (org-get-todo-sequence-head this))
9814 (ass (assoc head org-todo-kwd-alist))
9815 (interpret (nth 1 ass))
9816 (done-word (nth 3 ass))
9817 (final-done-word (nth 4 ass))
9818 (last-state (or this ""))
9819 (completion-ignore-case t)
9820 (member (member this org-todo-keywords-1))
9821 (tail (cdr member))
9822 (state (cond
9823 ((and org-todo-key-trigger
9824 (or (and (equal arg '(4))
9825 (eq org-use-fast-todo-selection 'prefix))
9826 (and (not arg) org-use-fast-todo-selection
9827 (not (eq org-use-fast-todo-selection
9828 'prefix)))))
9829 ;; Use fast selection
9830 (org-fast-todo-selection))
9831 ((and (equal arg '(4))
9832 (or (not org-use-fast-todo-selection)
9833 (not org-todo-key-trigger)))
9834 ;; Read a state with completion
9835 (org-icompleting-read
9836 "State: " (mapcar (lambda(x) (list x))
9837 org-todo-keywords-1)
9838 nil t))
9839 ((eq arg 'right)
9840 (if this
9841 (if tail (car tail) nil)
9842 (car org-todo-keywords-1)))
9843 ((eq arg 'left)
9844 (if (equal member org-todo-keywords-1)
9846 (if this
9847 (nth (- (length org-todo-keywords-1)
9848 (length tail) 2)
9849 org-todo-keywords-1)
9850 (org-last org-todo-keywords-1))))
9851 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9852 (setq arg nil))) ; hack to fall back to cycling
9853 (arg
9854 ;; user or caller requests a specific state
9855 (cond
9856 ((equal arg "") nil)
9857 ((eq arg 'none) nil)
9858 ((eq arg 'done) (or done-word (car org-done-keywords)))
9859 ((eq arg 'nextset)
9860 (or (car (cdr (member head org-todo-heads)))
9861 (car org-todo-heads)))
9862 ((eq arg 'previousset)
9863 (let ((org-todo-heads (reverse org-todo-heads)))
9864 (or (car (cdr (member head org-todo-heads)))
9865 (car org-todo-heads))))
9866 ((car (member arg org-todo-keywords-1)))
9867 ((stringp arg)
9868 (error "State `%s' not valid in this file" arg))
9869 ((nth (1- (prefix-numeric-value arg))
9870 org-todo-keywords-1))))
9871 ((null member) (or head (car org-todo-keywords-1)))
9872 ((equal this final-done-word) nil) ;; -> make empty
9873 ((null tail) nil) ;; -> first entry
9874 ((memq interpret '(type priority))
9875 (if (eq this-command last-command)
9876 (car tail)
9877 (if (> (length tail) 0)
9878 (or done-word (car org-done-keywords))
9879 nil)))
9881 (car tail))))
9882 (state (or
9883 (run-hook-with-args-until-success
9884 'org-todo-get-default-hook state last-state)
9885 state))
9886 (next (if state (concat " " state " ") " "))
9887 (change-plist (list :type 'todo-state-change :from this :to state
9888 :position startpos))
9889 dolog now-done-p)
9890 (when org-blocker-hook
9891 (setq org-last-todo-state-is-todo
9892 (not (member this org-done-keywords)))
9893 (unless (save-excursion
9894 (save-match-data
9895 (run-hook-with-args-until-failure
9896 'org-blocker-hook change-plist)))
9897 (if (interactive-p)
9898 (error "TODO state change from %s to %s blocked" this state)
9899 ;; fail silently
9900 (message "TODO state change from %s to %s blocked" this state)
9901 (throw 'exit nil))))
9902 (store-match-data match-data)
9903 (replace-match next t t)
9904 (unless (pos-visible-in-window-p hl-pos)
9905 (message "TODO state changed to %s" (org-trim next)))
9906 (unless head
9907 (setq head (org-get-todo-sequence-head state)
9908 ass (assoc head org-todo-kwd-alist)
9909 interpret (nth 1 ass)
9910 done-word (nth 3 ass)
9911 final-done-word (nth 4 ass)))
9912 (when (memq arg '(nextset previousset))
9913 (message "Keyword-Set %d/%d: %s"
9914 (- (length org-todo-sets) -1
9915 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9916 (length org-todo-sets)
9917 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9918 (setq org-last-todo-state-is-todo
9919 (not (member state org-done-keywords)))
9920 (setq now-done-p (and (member state org-done-keywords)
9921 (not (member this org-done-keywords))))
9922 (and logging (org-local-logging logging))
9923 (when (and (or org-todo-log-states org-log-done)
9924 (not (eq org-inhibit-logging t))
9925 (not (memq arg '(nextset previousset))))
9926 ;; we need to look at recording a time and note
9927 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9928 (nth 2 (assoc this org-todo-log-states))))
9929 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9930 (setq dolog 'time))
9931 (when (and state
9932 (member state org-not-done-keywords)
9933 (not (member this org-not-done-keywords)))
9934 ;; This is now a todo state and was not one before
9935 ;; If there was a CLOSED time stamp, get rid of it.
9936 (org-add-planning-info nil nil 'closed))
9937 (when (and now-done-p org-log-done)
9938 ;; It is now done, and it was not done before
9939 (org-add-planning-info 'closed (org-current-time))
9940 (if (and (not dolog) (eq 'note org-log-done))
9941 (org-add-log-setup 'done state this 'findpos 'note)))
9942 (when (and state dolog)
9943 ;; This is a non-nil state, and we need to log it
9944 (org-add-log-setup 'state state this 'findpos dolog)))
9945 ;; Fixup tag positioning
9946 (org-todo-trigger-tag-changes state)
9947 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9948 (when org-provide-todo-statistics
9949 (org-update-parent-todo-statistics))
9950 (run-hooks 'org-after-todo-state-change-hook)
9951 (if (and arg (not (member state org-done-keywords)))
9952 (setq head (org-get-todo-sequence-head state)))
9953 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9954 ;; Do we need to trigger a repeat?
9955 (when now-done-p
9956 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9957 ;; This is for the agenda, take a snapshot of the headline.
9958 (save-match-data
9959 (setq org-agenda-headline-snapshot-before-repeat
9960 (org-get-heading))))
9961 (org-auto-repeat-maybe state))
9962 ;; Fixup cursor location if close to the keyword
9963 (if (and (outline-on-heading-p)
9964 (not (bolp))
9965 (save-excursion (beginning-of-line 1)
9966 (looking-at org-todo-line-regexp))
9967 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9968 (progn
9969 (goto-char (or (match-end 2) (match-end 1)))
9970 (and (looking-at " ") (just-one-space))))
9971 (when org-trigger-hook
9972 (save-excursion
9973 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9975 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9976 "Block turning an entry into a TODO, using the hierarchy.
9977 This checks whether the current task should be blocked from state
9978 changes. Such blocking occurs when:
9980 1. The task has children which are not all in a completed state.
9982 2. A task has a parent with the property :ORDERED:, and there
9983 are siblings prior to the current task with incomplete
9984 status.
9986 3. The parent of the task is blocked because it has siblings that should
9987 be done first, or is child of a block grandparent TODO entry."
9989 (catch 'dont-block
9990 ;; If this is not a todo state change, or if this entry is already DONE,
9991 ;; do not block
9992 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9993 (member (plist-get change-plist :from)
9994 (cons 'done org-done-keywords))
9995 (member (plist-get change-plist :to)
9996 (cons 'todo org-not-done-keywords))
9997 (not (plist-get change-plist :to)))
9998 (throw 'dont-block t))
9999 ;; If this task has children, and any are undone, it's blocked
10000 (save-excursion
10001 (org-back-to-heading t)
10002 (let ((this-level (funcall outline-level)))
10003 (outline-next-heading)
10004 (let ((child-level (funcall outline-level)))
10005 (while (and (not (eobp))
10006 (> child-level this-level))
10007 ;; this todo has children, check whether they are all
10008 ;; completed
10009 (if (and (not (org-entry-is-done-p))
10010 (org-entry-is-todo-p))
10011 (throw 'dont-block nil))
10012 (outline-next-heading)
10013 (setq child-level (funcall outline-level))))))
10014 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10015 ;; any previous siblings are undone, it's blocked
10016 (save-excursion
10017 (org-back-to-heading t)
10018 (let* ((pos (point))
10019 (parent-pos (and (org-up-heading-safe) (point))))
10020 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10021 (when (and (org-entry-get (point) "ORDERED")
10022 (forward-line 1)
10023 (re-search-forward org-not-done-heading-regexp pos t))
10024 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10025 ;; Search further up the hierarchy, to see if an anchestor is blocked
10026 (while t
10027 (goto-char parent-pos)
10028 (if (not (looking-at org-not-done-heading-regexp))
10029 (throw 'dont-block t)) ; do not block, parent is not a TODO
10030 (setq pos (point))
10031 (setq parent-pos (and (org-up-heading-safe) (point)))
10032 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10033 (when (and (org-entry-get (point) "ORDERED")
10034 (forward-line 1)
10035 (re-search-forward org-not-done-heading-regexp pos t))
10036 (throw 'dont-block nil))))))) ; block, older sibling not done.
10038 (defcustom org-track-ordered-property-with-tag nil
10039 "Should the ORDERED property also be shown as a tag?
10040 The ORDERED property decides if an entry should require subtasks to be
10041 completed in sequence. Since a property is not very visible, setting
10042 this option means that toggling the ORDERED property with the command
10043 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10044 not relevant for the behavior, but it makes things more visible.
10046 Note that toggling the tag with tags commands will not change the property
10047 and therefore not influence behavior!
10049 This can be t, meaning the tag ORDERED should be used, It can also be a
10050 string to select a different tag for this task."
10051 :group 'org-todo
10052 :type '(choice
10053 (const :tag "No tracking" nil)
10054 (const :tag "Track with ORDERED tag" t)
10055 (string :tag "Use other tag")))
10057 (defun org-toggle-ordered-property ()
10058 "Toggle the ORDERED property of the current entry.
10059 For better visibility, you can track the value of this property with a tag.
10060 See variable `org-track-ordered-property-with-tag'."
10061 (interactive)
10062 (let* ((t1 org-track-ordered-property-with-tag)
10063 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10064 (save-excursion
10065 (org-back-to-heading)
10066 (if (org-entry-get nil "ORDERED")
10067 (progn
10068 (org-delete-property "ORDERED")
10069 (and tag (org-toggle-tag tag 'off))
10070 (message "Subtasks can be completed in arbitrary order"))
10071 (org-entry-put nil "ORDERED" "t")
10072 (and tag (org-toggle-tag tag 'on))
10073 (message "Subtasks must be completed in sequence")))))
10075 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10076 (defun org-block-todo-from-checkboxes (change-plist)
10077 "Block turning an entry into a TODO, using checkboxes.
10078 This checks whether the current task should be blocked from state
10079 changes because there are unchecked boxes in this entry."
10080 (catch 'dont-block
10081 ;; If this is not a todo state change, or if this entry is already DONE,
10082 ;; do not block
10083 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10084 (member (plist-get change-plist :from)
10085 (cons 'done org-done-keywords))
10086 (member (plist-get change-plist :to)
10087 (cons 'todo org-not-done-keywords))
10088 (not (plist-get change-plist :to)))
10089 (throw 'dont-block t))
10090 ;; If this task has checkboxes that are not checked, it's blocked
10091 (save-excursion
10092 (org-back-to-heading t)
10093 (let ((beg (point)) end)
10094 (outline-next-heading)
10095 (setq end (point))
10096 (goto-char beg)
10097 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10098 end t)
10099 (progn
10100 (if (boundp 'org-blocked-by-checkboxes)
10101 (setq org-blocked-by-checkboxes t))
10102 (throw 'dont-block nil)))))
10103 t)) ; do not block
10105 (defun org-update-statistics-cookies (all)
10106 "Update the statistics cookie, either from TODO or from checkboxes.
10107 This should be called with the cursor in a line with a statistics cookie."
10108 (interactive "P")
10109 (if all
10110 (progn
10111 (org-update-checkbox-count 'all)
10112 (org-map-entries 'org-update-parent-todo-statistics))
10113 (if (not (org-on-heading-p))
10114 (org-update-checkbox-count)
10115 (let ((pos (move-marker (make-marker) (point)))
10116 end l1 l2)
10117 (ignore-errors (org-back-to-heading t))
10118 (if (not (org-on-heading-p))
10119 (org-update-checkbox-count)
10120 (setq l1 (org-outline-level))
10121 (setq end (save-excursion
10122 (outline-next-heading)
10123 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10124 (point)))
10125 (if (and (save-excursion (re-search-forward
10126 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10127 (not (save-excursion (re-search-forward
10128 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10129 (org-update-checkbox-count)
10130 (if (and l2 (> l2 l1))
10131 (progn
10132 (goto-char end)
10133 (org-update-parent-todo-statistics))
10134 (error "No data for statistics cookie"))))
10135 (goto-char pos)
10136 (move-marker pos nil)))))
10138 (defvar org-entry-property-inherited-from) ;; defined below
10139 (defun org-update-parent-todo-statistics ()
10140 "Update any statistics cookie in the parent of the current headline.
10141 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10142 the entire subtree and this will travel up the hierarchy and update
10143 statistics everywhere."
10144 (interactive)
10145 (let* ((lim 0) prop
10146 (recursive (or (not org-hierarchical-todo-statistics)
10147 (string-match
10148 "\\<recursive\\>"
10149 (or (setq prop (org-entry-get
10150 nil "COOKIE_DATA" 'inherit)) ""))))
10151 (lim (or (and prop (marker-position
10152 org-entry-property-inherited-from))
10153 lim))
10154 (first t)
10155 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10156 level ltoggle l1 new ndel
10157 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10158 (catch 'exit
10159 (save-excursion
10160 (beginning-of-line 1)
10161 (if (org-at-heading-p)
10162 (setq ltoggle (funcall outline-level))
10163 (error "This should not happen"))
10164 (while (and (setq level (org-up-heading-safe))
10165 (or recursive first)
10166 (>= (point) lim))
10167 (setq first nil cookie-present nil)
10168 (unless (and level
10169 (not (string-match
10170 "\\<checkbox\\>"
10171 (downcase
10172 (or (org-entry-get
10173 nil "COOKIE_DATA")
10174 "")))))
10175 (throw 'exit nil))
10176 (while (re-search-forward box-re (point-at-eol) t)
10177 (setq cnt-all 0 cnt-done 0 cookie-present t)
10178 (setq is-percent (match-end 2))
10179 (save-match-data
10180 (unless (outline-next-heading) (throw 'exit nil))
10181 (while (and (looking-at org-complex-heading-regexp)
10182 (> (setq l1 (length (match-string 1))) level))
10183 (setq kwd (and (or recursive (= l1 ltoggle))
10184 (match-string 2)))
10185 (if (or (eq org-provide-todo-statistics 'all-headlines)
10186 (and (listp org-provide-todo-statistics)
10187 (or (member kwd org-provide-todo-statistics)
10188 (member kwd org-done-keywords))))
10189 (setq cnt-all (1+ cnt-all))
10190 (if (eq org-provide-todo-statistics t)
10191 (and kwd (setq cnt-all (1+ cnt-all)))))
10192 (and (member kwd org-done-keywords)
10193 (setq cnt-done (1+ cnt-done)))
10194 (outline-next-heading)))
10195 (setq new
10196 (if is-percent
10197 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10198 (format "[%d/%d]" cnt-done cnt-all))
10199 ndel (- (match-end 0) (match-beginning 0)))
10200 (goto-char (match-beginning 0))
10201 (insert new)
10202 (delete-region (point) (+ (point) ndel)))
10203 (when cookie-present
10204 (run-hook-with-args 'org-after-todo-statistics-hook
10205 cnt-done (- cnt-all cnt-done))))))
10206 (run-hooks 'org-todo-statistics-hook)))
10208 (defvar org-after-todo-statistics-hook nil
10209 "Hook that is called after a TODO statistics cookie has been updated.
10210 Each function is called with two arguments: the number of not-done entries
10211 and the number of done entries.
10213 For example, the following function, when added to this hook, will switch
10214 an entry to DONE when all children are done, and back to TODO when new
10215 entries are set to a TODO status. Note that this hook is only called
10216 when there is a statistics cookie in the headline!
10218 (defun org-summary-todo (n-done n-not-done)
10219 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10220 (let (org-log-done org-log-states) ; turn off logging
10221 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10224 (defvar org-todo-statistics-hook nil
10225 "Hook that is run whenever Org thinks TODO statistics should be updated.
10226 This hook runs even if there is no statistics cookie present, in which case
10227 `org-after-todo-statistics-hook' would not run.")
10229 (defun org-todo-trigger-tag-changes (state)
10230 "Apply the changes defined in `org-todo-state-tags-triggers'."
10231 (let ((l org-todo-state-tags-triggers)
10232 changes)
10233 (when (or (not state) (equal state ""))
10234 (setq changes (append changes (cdr (assoc "" l)))))
10235 (when (and (stringp state) (> (length state) 0))
10236 (setq changes (append changes (cdr (assoc state l)))))
10237 (when (member state org-not-done-keywords)
10238 (setq changes (append changes (cdr (assoc 'todo l)))))
10239 (when (member state org-done-keywords)
10240 (setq changes (append changes (cdr (assoc 'done l)))))
10241 (dolist (c changes)
10242 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10244 (defun org-local-logging (value)
10245 "Get logging settings from a property VALUE."
10246 (let* (words w a)
10247 ;; directly set the variables, they are already local.
10248 (setq org-log-done nil
10249 org-log-repeat nil
10250 org-todo-log-states nil)
10251 (setq words (org-split-string value))
10252 (while (setq w (pop words))
10253 (cond
10254 ((setq a (assoc w org-startup-options))
10255 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10256 (set (nth 1 a) (nth 2 a))))
10257 ((setq a (org-extract-log-state-settings w))
10258 (and (member (car a) org-todo-keywords-1)
10259 (push a org-todo-log-states)))))))
10261 (defun org-get-todo-sequence-head (kwd)
10262 "Return the head of the TODO sequence to which KWD belongs.
10263 If KWD is not set, check if there is a text property remembering the
10264 right sequence."
10265 (let (p)
10266 (cond
10267 ((not kwd)
10268 (or (get-text-property (point-at-bol) 'org-todo-head)
10269 (progn
10270 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10271 nil (point-at-eol)))
10272 (get-text-property p 'org-todo-head))))
10273 ((not (member kwd org-todo-keywords-1))
10274 (car org-todo-keywords-1))
10275 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10277 (defun org-fast-todo-selection ()
10278 "Fast TODO keyword selection with single keys.
10279 Returns the new TODO keyword, or nil if no state change should occur."
10280 (let* ((fulltable org-todo-key-alist)
10281 (done-keywords org-done-keywords) ;; needed for the faces.
10282 (maxlen (apply 'max (mapcar
10283 (lambda (x)
10284 (if (stringp (car x)) (string-width (car x)) 0))
10285 fulltable)))
10286 (expert nil)
10287 (fwidth (+ maxlen 3 1 3))
10288 (ncol (/ (- (window-width) 4) fwidth))
10289 tg cnt e c tbl
10290 groups ingroup)
10291 (save-excursion
10292 (save-window-excursion
10293 (if expert
10294 (set-buffer (get-buffer-create " *Org todo*"))
10295 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10296 (erase-buffer)
10297 (org-set-local 'org-done-keywords done-keywords)
10298 (setq tbl fulltable cnt 0)
10299 (while (setq e (pop tbl))
10300 (cond
10301 ((equal e '(:startgroup))
10302 (push '() groups) (setq ingroup t)
10303 (when (not (= cnt 0))
10304 (setq cnt 0)
10305 (insert "\n"))
10306 (insert "{ "))
10307 ((equal e '(:endgroup))
10308 (setq ingroup nil cnt 0)
10309 (insert "}\n"))
10310 ((equal e '(:newline))
10311 (when (not (= cnt 0))
10312 (setq cnt 0)
10313 (insert "\n")
10314 (setq e (car tbl))
10315 (while (equal (car tbl) '(:newline))
10316 (insert "\n")
10317 (setq tbl (cdr tbl)))))
10319 (setq tg (car e) c (cdr e))
10320 (if ingroup (push tg (car groups)))
10321 (setq tg (org-add-props tg nil 'face
10322 (org-get-todo-face tg)))
10323 (if (and (= cnt 0) (not ingroup)) (insert " "))
10324 (insert "[" c "] " tg (make-string
10325 (- fwidth 4 (length tg)) ?\ ))
10326 (when (= (setq cnt (1+ cnt)) ncol)
10327 (insert "\n")
10328 (if ingroup (insert " "))
10329 (setq cnt 0)))))
10330 (insert "\n")
10331 (goto-char (point-min))
10332 (if (not expert) (org-fit-window-to-buffer))
10333 (message "[a-z..]:Set [SPC]:clear")
10334 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10335 (cond
10336 ((or (= c ?\C-g)
10337 (and (= c ?q) (not (rassoc c fulltable))))
10338 (setq quit-flag t))
10339 ((= c ?\ ) nil)
10340 ((setq e (rassoc c fulltable) tg (car e))
10342 (t (setq quit-flag t)))))))
10344 (defun org-entry-is-todo-p ()
10345 (member (org-get-todo-state) org-not-done-keywords))
10347 (defun org-entry-is-done-p ()
10348 (member (org-get-todo-state) org-done-keywords))
10350 (defun org-get-todo-state ()
10351 (save-excursion
10352 (org-back-to-heading t)
10353 (and (looking-at org-todo-line-regexp)
10354 (match-end 2)
10355 (match-string 2))))
10357 (defun org-at-date-range-p (&optional inactive-ok)
10358 "Is the cursor inside a date range?"
10359 (interactive)
10360 (save-excursion
10361 (catch 'exit
10362 (let ((pos (point)))
10363 (skip-chars-backward "^[<\r\n")
10364 (skip-chars-backward "<[")
10365 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10366 (>= (match-end 0) pos)
10367 (throw 'exit t))
10368 (skip-chars-backward "^<[\r\n")
10369 (skip-chars-backward "<[")
10370 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10371 (>= (match-end 0) pos)
10372 (throw 'exit t)))
10373 nil)))
10375 (defun org-get-repeat (&optional tagline)
10376 "Check if there is a deadline/schedule with repeater in this entry."
10377 (save-match-data
10378 (save-excursion
10379 (org-back-to-heading t)
10380 (and (re-search-forward (if tagline
10381 (concat tagline "\\s-*" org-repeat-re)
10382 org-repeat-re)
10383 (org-entry-end-position) t)
10384 (match-string-no-properties 1)))))
10386 (defvar org-last-changed-timestamp)
10387 (defvar org-last-inserted-timestamp)
10388 (defvar org-log-post-message)
10389 (defvar org-log-note-purpose)
10390 (defvar org-log-note-how)
10391 (defvar org-log-note-extra)
10392 (defun org-auto-repeat-maybe (done-word)
10393 "Check if the current headline contains a repeated deadline/schedule.
10394 If yes, set TODO state back to what it was and change the base date
10395 of repeating deadline/scheduled time stamps to new date.
10396 This function is run automatically after each state change to a DONE state."
10397 ;; last-state is dynamically scoped into this function
10398 (let* ((repeat (org-get-repeat))
10399 (aa (assoc last-state org-todo-kwd-alist))
10400 (interpret (nth 1 aa))
10401 (head (nth 2 aa))
10402 (whata '(("d" . day) ("m" . month) ("y" . year)))
10403 (msg "Entry repeats: ")
10404 (org-log-done nil)
10405 (org-todo-log-states nil)
10406 (nshiftmax 10) (nshift 0)
10407 re type n what ts time)
10408 (when repeat
10409 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10410 (org-todo (if (eq interpret 'type) last-state head))
10411 (org-entry-put nil "LAST_REPEAT" (format-time-string
10412 (org-time-stamp-format t t)))
10413 (when org-log-repeat
10414 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10415 (memq 'org-add-log-note post-command-hook))
10416 ;; OK, we are already setup for some record
10417 (if (eq org-log-repeat 'note)
10418 ;; make sure we take a note, not only a time stamp
10419 (setq org-log-note-how 'note))
10420 ;; Set up for taking a record
10421 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10422 last-state
10423 'findpos org-log-repeat)))
10424 (org-back-to-heading t)
10425 (org-add-planning-info nil nil 'closed)
10426 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10427 org-deadline-time-regexp "\\)\\|\\("
10428 org-ts-regexp "\\)"))
10429 (while (re-search-forward
10430 re (save-excursion (outline-next-heading) (point)) t)
10431 (setq type (if (match-end 1) org-scheduled-string
10432 (if (match-end 3) org-deadline-string "Plain:"))
10433 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10434 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10435 (setq n (string-to-number (match-string 2 ts))
10436 what (match-string 3 ts))
10437 (if (equal what "w") (setq n (* n 7) what "d"))
10438 ;; Preparation, see if we need to modify the start date for the change
10439 (when (match-end 1)
10440 (setq time (save-match-data (org-time-string-to-time ts)))
10441 (cond
10442 ((equal (match-string 1 ts) ".")
10443 ;; Shift starting date to today
10444 (org-timestamp-change
10445 (- (time-to-days (current-time)) (time-to-days time))
10446 'day))
10447 ((equal (match-string 1 ts) "+")
10448 (while (or (= nshift 0)
10449 (<= (time-to-days time) (time-to-days (current-time))))
10450 (when (= (incf nshift) nshiftmax)
10451 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10452 (error "Abort")))
10453 (org-timestamp-change n (cdr (assoc what whata)))
10454 (org-at-timestamp-p t)
10455 (setq ts (match-string 1))
10456 (setq time (save-match-data (org-time-string-to-time ts))))
10457 (org-timestamp-change (- n) (cdr (assoc what whata)))
10458 ;; rematch, so that we have everything in place for the real shift
10459 (org-at-timestamp-p t)
10460 (setq ts (match-string 1))
10461 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10462 (org-timestamp-change n (cdr (assoc what whata)))
10463 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10464 (setq org-log-post-message msg)
10465 (message "%s" msg))))
10467 (defun org-show-todo-tree (arg)
10468 "Make a compact tree which shows all headlines marked with TODO.
10469 The tree will show the lines where the regexp matches, and all higher
10470 headlines above the match.
10471 With a \\[universal-argument] prefix, prompt for a regexp to match.
10472 With a numeric prefix N, construct a sparse tree for the Nth element
10473 of `org-todo-keywords-1'."
10474 (interactive "P")
10475 (let ((case-fold-search nil)
10476 (kwd-re
10477 (cond ((null arg) org-not-done-regexp)
10478 ((equal arg '(4))
10479 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10480 (mapcar 'list org-todo-keywords-1))))
10481 (concat "\\("
10482 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10483 "\\)\\>")))
10484 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10485 (regexp-quote (nth (1- (prefix-numeric-value arg))
10486 org-todo-keywords-1)))
10487 (t (error "Invalid prefix argument: %s" arg)))))
10488 (message "%d TODO entries found"
10489 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10491 (defun org-deadline (&optional remove time)
10492 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10493 With argument REMOVE, remove any deadline from the item.
10494 When TIME is set, it should be an internal time specification, and the
10495 scheduling will use the corresponding date."
10496 (interactive "P")
10497 (let ((old-date (org-entry-get nil "DEADLINE")))
10498 (if remove
10499 (progn
10500 (org-remove-timestamp-with-keyword org-deadline-string)
10501 (message "Item no longer has a deadline."))
10502 (if (org-get-repeat)
10503 (error "Cannot change deadline on task with repeater, please do that by hand")
10504 (org-add-planning-info 'deadline time 'closed)
10505 (when (and old-date org-log-redeadline
10506 (not (equal old-date
10507 (substring org-last-inserted-timestamp 1 -1))))
10508 (org-add-log-setup 'redeadline nil old-date 'findpos
10509 org-log-redeadline))
10510 (message "Deadline on %s" org-last-inserted-timestamp)))))
10512 (defun org-schedule (&optional remove time)
10513 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10514 With argument REMOVE, remove any scheduling date from the item.
10515 When TIME is set, it should be an internal time specification, and the
10516 scheduling will use the corresponding date."
10517 (interactive "P")
10518 (let ((old-date (org-entry-get nil "SCHEDULED")))
10519 (if remove
10520 (progn
10521 (org-remove-timestamp-with-keyword org-scheduled-string)
10522 (message "Item is no longer scheduled."))
10523 (if (org-get-repeat)
10524 (error "Cannot reschedule task with repeater, please do that by hand")
10525 (org-add-planning-info 'scheduled time 'closed)
10526 (when (and old-date org-log-reschedule
10527 (not (equal old-date
10528 (substring org-last-inserted-timestamp 1 -1))))
10529 (org-add-log-setup 'reschedule nil old-date 'findpos
10530 org-log-reschedule))
10531 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10533 (defun org-get-scheduled-time (pom &optional inherit)
10534 "Get the scheduled time as a time tuple, of a format suitable
10535 for calling org-schedule with, or if there is no scheduling,
10536 returns nil."
10537 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10538 (when time
10539 (apply 'encode-time (org-parse-time-string time)))))
10541 (defun org-get-deadline-time (pom &optional inherit)
10542 "Get the deadine as a time tuple, of a format suitable for
10543 calling org-deadline with, or if there is no scheduling, returns
10544 nil."
10545 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10546 (when time
10547 (apply 'encode-time (org-parse-time-string time)))))
10549 (defun org-remove-timestamp-with-keyword (keyword)
10550 "Remove all time stamps with KEYWORD in the current entry."
10551 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10552 beg)
10553 (save-excursion
10554 (org-back-to-heading t)
10555 (setq beg (point))
10556 (outline-next-heading)
10557 (while (re-search-backward re beg t)
10558 (replace-match "")
10559 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10560 (equal (char-before) ?\ ))
10561 (backward-delete-char 1)
10562 (if (string-match "^[ \t]*$" (buffer-substring
10563 (point-at-bol) (point-at-eol)))
10564 (delete-region (point-at-bol)
10565 (min (point-max) (1+ (point-at-eol))))))))))
10567 (defun org-add-planning-info (what &optional time &rest remove)
10568 "Insert new timestamp with keyword in the line directly after the headline.
10569 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10570 If non is given, the user is prompted for a date.
10571 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10572 be removed."
10573 (interactive)
10574 (let (org-time-was-given org-end-time-was-given ts
10575 end default-time default-input)
10577 (catch 'exit
10578 (when (and (not time) (memq what '(scheduled deadline)))
10579 ;; Try to get a default date/time from existing timestamp
10580 (save-excursion
10581 (org-back-to-heading t)
10582 (setq end (save-excursion (outline-next-heading) (point)))
10583 (when (re-search-forward (if (eq what 'scheduled)
10584 org-scheduled-time-regexp
10585 org-deadline-time-regexp)
10586 end t)
10587 (setq ts (match-string 1)
10588 default-time
10589 (apply 'encode-time (org-parse-time-string ts))
10590 default-input (and ts (org-get-compact-tod ts))))))
10591 (when what
10592 ;; If necessary, get the time from the user
10593 (setq time (or time (org-read-date nil 'to-time nil nil
10594 default-time default-input))))
10596 (when (and org-insert-labeled-timestamps-at-point
10597 (member what '(scheduled deadline)))
10598 (insert
10599 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10600 (org-insert-time-stamp time org-time-was-given
10601 nil nil nil (list org-end-time-was-given))
10602 (setq what nil))
10603 (save-excursion
10604 (save-restriction
10605 (let (col list elt ts buffer-invisibility-spec)
10606 (org-back-to-heading t)
10607 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10608 (goto-char (match-end 1))
10609 (setq col (current-column))
10610 (goto-char (match-end 0))
10611 (if (eobp) (insert "\n") (forward-char 1))
10612 (when (and (not what)
10613 (not (looking-at
10614 (concat "[ \t]*"
10615 org-keyword-time-not-clock-regexp))))
10616 ;; Nothing to add, nothing to remove...... :-)
10617 (throw 'exit nil))
10618 (if (and (not (looking-at outline-regexp))
10619 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10620 "[^\r\n]*"))
10621 (not (equal (match-string 1) org-clock-string)))
10622 (narrow-to-region (match-beginning 0) (match-end 0))
10623 (insert-before-markers "\n")
10624 (backward-char 1)
10625 (narrow-to-region (point) (point))
10626 (and org-adapt-indentation (org-indent-to-column col)))
10627 ;; Check if we have to remove something.
10628 (setq list (cons what remove))
10629 (while list
10630 (setq elt (pop list))
10631 (goto-char (point-min))
10632 (when (or (and (eq elt 'scheduled)
10633 (re-search-forward org-scheduled-time-regexp nil t))
10634 (and (eq elt 'deadline)
10635 (re-search-forward org-deadline-time-regexp nil t))
10636 (and (eq elt 'closed)
10637 (re-search-forward org-closed-time-regexp nil t)))
10638 (replace-match "")
10639 (if (looking-at "--+<[^>]+>") (replace-match ""))
10640 (skip-chars-backward " ")
10641 (if (looking-at " +") (replace-match ""))))
10642 (goto-char (point-max))
10643 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10644 (when what
10645 (insert
10646 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10647 (cond ((eq what 'scheduled) org-scheduled-string)
10648 ((eq what 'deadline) org-deadline-string)
10649 ((eq what 'closed) org-closed-string))
10650 " ")
10651 (setq ts (org-insert-time-stamp
10652 time
10653 (or org-time-was-given
10654 (and (eq what 'closed) org-log-done-with-time))
10655 (eq what 'closed)
10656 nil nil (list org-end-time-was-given)))
10657 (end-of-line 1))
10658 (goto-char (point-min))
10659 (widen)
10660 (if (and (looking-at "[ \t]+\n")
10661 (equal (char-before) ?\n))
10662 (delete-region (1- (point)) (point-at-eol)))
10663 ts))))))
10665 (defvar org-log-note-marker (make-marker))
10666 (defvar org-log-note-purpose nil)
10667 (defvar org-log-note-state nil)
10668 (defvar org-log-note-previous-state nil)
10669 (defvar org-log-note-how nil)
10670 (defvar org-log-note-extra nil)
10671 (defvar org-log-note-window-configuration nil)
10672 (defvar org-log-note-return-to (make-marker))
10673 (defvar org-log-post-message nil
10674 "Message to be displayed after a log note has been stored.
10675 The auto-repeater uses this.")
10677 (defun org-add-note ()
10678 "Add a note to the current entry.
10679 This is done in the same way as adding a state change note."
10680 (interactive)
10681 (org-add-log-setup 'note nil nil 'findpos nil))
10683 (defvar org-property-end-re)
10684 (defun org-add-log-setup (&optional purpose state prev-state
10685 findpos how &optional extra)
10686 "Set up the post command hook to take a note.
10687 If this is about to TODO state change, the new state is expected in STATE.
10688 When FINDPOS is non-nil, find the correct position for the note in
10689 the current entry. If not, assume that it can be inserted at point.
10690 HOW is an indicator what kind of note should be created.
10691 EXTRA is additional text that will be inserted into the notes buffer."
10692 (let* ((org-log-into-drawer (org-log-into-drawer))
10693 (drawer (cond ((stringp org-log-into-drawer)
10694 org-log-into-drawer)
10695 (org-log-into-drawer "LOGBOOK")
10696 (t nil))))
10697 (save-restriction
10698 (save-excursion
10699 (when findpos
10700 (org-back-to-heading t)
10701 (narrow-to-region (point) (save-excursion
10702 (outline-next-heading) (point)))
10703 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10704 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10705 "[^\r\n]*\\)?"))
10706 (goto-char (match-end 0))
10707 (cond
10708 (drawer
10709 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10710 nil t)
10711 (progn
10712 (goto-char (match-end 0))
10713 (or org-log-states-order-reversed
10714 (and (re-search-forward org-property-end-re nil t)
10715 (goto-char (1- (match-beginning 0))))))
10716 (insert "\n:" drawer ":\n:END:")
10717 (beginning-of-line 0)
10718 (org-indent-line-function)
10719 (beginning-of-line 2)
10720 (org-indent-line-function)
10721 (end-of-line 0)))
10722 ((and org-log-state-notes-insert-after-drawers
10723 (save-excursion
10724 (forward-line) (looking-at org-drawer-regexp)))
10725 (forward-line)
10726 (while (looking-at org-drawer-regexp)
10727 (goto-char (match-end 0))
10728 (re-search-forward org-property-end-re (point-max) t)
10729 (forward-line))
10730 (forward-line -1)))
10731 (unless org-log-states-order-reversed
10732 (and (= (char-after) ?\n) (forward-char 1))
10733 (org-skip-over-state-notes)
10734 (skip-chars-backward " \t\n\r")))
10735 (move-marker org-log-note-marker (point))
10736 (setq org-log-note-purpose purpose
10737 org-log-note-state state
10738 org-log-note-previous-state prev-state
10739 org-log-note-how how
10740 org-log-note-extra extra)
10741 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10743 (defun org-skip-over-state-notes ()
10744 "Skip past the list of State notes in an entry."
10745 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10746 (while (looking-at "[ \t]*- State")
10747 (condition-case nil
10748 (org-next-item)
10749 (error (org-end-of-item)))))
10751 (defun org-add-log-note (&optional purpose)
10752 "Pop up a window for taking a note, and add this note later at point."
10753 (remove-hook 'post-command-hook 'org-add-log-note)
10754 (setq org-log-note-window-configuration (current-window-configuration))
10755 (delete-other-windows)
10756 (move-marker org-log-note-return-to (point))
10757 (switch-to-buffer (marker-buffer org-log-note-marker))
10758 (goto-char org-log-note-marker)
10759 (org-switch-to-buffer-other-window "*Org Note*")
10760 (erase-buffer)
10761 (if (memq org-log-note-how '(time state))
10762 (let (current-prefix-arg) (org-store-log-note))
10763 (let ((org-inhibit-startup t)) (org-mode))
10764 (insert (format "# Insert note for %s.
10765 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10766 (cond
10767 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10768 ((eq org-log-note-purpose 'done) "closed todo item")
10769 ((eq org-log-note-purpose 'state)
10770 (format "state change from \"%s\" to \"%s\""
10771 (or org-log-note-previous-state "")
10772 (or org-log-note-state "")))
10773 ((eq org-log-note-purpose 'reschedule)
10774 "rescheduling")
10775 ((eq org-log-note-purpose 'redeadline)
10776 "changing deadline")
10777 ((eq org-log-note-purpose 'note)
10778 "this entry")
10779 (t (error "This should not happen")))))
10780 (if org-log-note-extra (insert org-log-note-extra))
10781 (org-set-local 'org-finish-function 'org-store-log-note)))
10783 (defvar org-note-abort nil) ; dynamically scoped
10784 (defun org-store-log-note ()
10785 "Finish taking a log note, and insert it to where it belongs."
10786 (let ((txt (buffer-string))
10787 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10788 lines ind)
10789 (kill-buffer (current-buffer))
10790 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10791 (setq txt (replace-match "" t t txt)))
10792 (if (string-match "\\s-+\\'" txt)
10793 (setq txt (replace-match "" t t txt)))
10794 (setq lines (org-split-string txt "\n"))
10795 (when (and note (string-match "\\S-" note))
10796 (setq note
10797 (org-replace-escapes
10798 note
10799 (list (cons "%u" (user-login-name))
10800 (cons "%U" user-full-name)
10801 (cons "%t" (format-time-string
10802 (org-time-stamp-format 'long 'inactive)
10803 (current-time)))
10804 (cons "%s" (if org-log-note-state
10805 (concat "\"" org-log-note-state "\"")
10806 ""))
10807 (cons "%S" (if org-log-note-previous-state
10808 (concat "\"" org-log-note-previous-state "\"")
10809 "\"\"")))))
10810 (if lines (setq note (concat note " \\\\")))
10811 (push note lines))
10812 (when (or current-prefix-arg org-note-abort)
10813 (when org-log-into-drawer
10814 (org-remove-empty-drawer-at
10815 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10816 org-log-note-marker))
10817 (setq lines nil))
10818 (when lines
10819 (with-current-buffer (marker-buffer org-log-note-marker)
10820 (save-excursion
10821 (goto-char org-log-note-marker)
10822 (move-marker org-log-note-marker nil)
10823 (end-of-line 1)
10824 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10825 (insert "- " (pop lines))
10826 (org-indent-line-function)
10827 (beginning-of-line 1)
10828 (looking-at "[ \t]*")
10829 (setq ind (concat (match-string 0) " "))
10830 (end-of-line 1)
10831 (while lines (insert "\n" ind (pop lines)))
10832 (message "Note stored")
10833 (org-back-to-heading t)
10834 (org-cycle-hide-drawers 'children)))))
10835 (set-window-configuration org-log-note-window-configuration)
10836 (with-current-buffer (marker-buffer org-log-note-return-to)
10837 (goto-char org-log-note-return-to))
10838 (move-marker org-log-note-return-to nil)
10839 (and org-log-post-message (message "%s" org-log-post-message)))
10841 (defun org-remove-empty-drawer-at (drawer pos)
10842 "Remove an empty drawer DRAWER at position POS.
10843 POS may also be a marker."
10844 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10845 (save-excursion
10846 (save-restriction
10847 (widen)
10848 (goto-char pos)
10849 (if (org-in-regexp
10850 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10851 (replace-match ""))))))
10853 (defun org-sparse-tree (&optional arg)
10854 "Create a sparse tree, prompt for the details.
10855 This command can create sparse trees. You first need to select the type
10856 of match used to create the tree:
10858 t Show entries with a specific TODO keyword.
10859 m Show entries selected by a tags/property match.
10860 p Enter a property name and its value (both with completion on existing
10861 names/values) and show entries with that property.
10862 / Show entries matching a regular expression (`r' can be used as well)
10863 d Show deadlines due within `org-deadline-warning-days'.
10864 b Show deadlines and scheduled items before a date.
10865 a Show deadlines and scheduled items after a date."
10866 (interactive "P")
10867 (let (ans kwd value)
10868 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10869 (setq ans (read-char-exclusive))
10870 (cond
10871 ((equal ans ?d)
10872 (call-interactively 'org-check-deadlines))
10873 ((equal ans ?b)
10874 (call-interactively 'org-check-before-date))
10875 ((equal ans ?a)
10876 (call-interactively 'org-check-after-date))
10877 ((equal ans ?t)
10878 (org-show-todo-tree '(4)))
10879 ((member ans '(?T ?m))
10880 (call-interactively 'org-match-sparse-tree))
10881 ((member ans '(?p ?P))
10882 (setq kwd (org-icompleting-read "Property: "
10883 (mapcar 'list (org-buffer-property-keys))))
10884 (setq value (org-icompleting-read "Value: "
10885 (mapcar 'list (org-property-values kwd))))
10886 (unless (string-match "\\`{.*}\\'" value)
10887 (setq value (concat "\"" value "\"")))
10888 (org-match-sparse-tree arg (concat kwd "=" value)))
10889 ((member ans '(?r ?R ?/))
10890 (call-interactively 'org-occur))
10891 (t (error "No such sparse tree command \"%c\"" ans)))))
10893 (defvar org-occur-highlights nil
10894 "List of overlays used for occur matches.")
10895 (make-variable-buffer-local 'org-occur-highlights)
10896 (defvar org-occur-parameters nil
10897 "Parameters of the active org-occur calls.
10898 This is a list, each call to org-occur pushes as cons cell,
10899 containing the regular expression and the callback, onto the list.
10900 The list can contain several entries if `org-occur' has been called
10901 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10902 will only contain one set of parameters. When the highlights are
10903 removed (for example with `C-c C-c', or with the next edit (depending
10904 on `org-remove-highlights-with-change'), this variable is emptied
10905 as well.")
10906 (make-variable-buffer-local 'org-occur-parameters)
10908 (defun org-occur (regexp &optional keep-previous callback)
10909 "Make a compact tree which shows all matches of REGEXP.
10910 The tree will show the lines where the regexp matches, and all higher
10911 headlines above the match. It will also show the heading after the match,
10912 to make sure editing the matching entry is easy.
10913 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10914 call to `org-occur' will be kept, to allow stacking of calls to this
10915 command.
10916 If CALLBACK is non-nil, it is a function which is called to confirm
10917 that the match should indeed be shown."
10918 (interactive "sRegexp: \nP")
10919 (when (equal regexp "")
10920 (error "Regexp cannot be empty"))
10921 (unless keep-previous
10922 (org-remove-occur-highlights nil nil t))
10923 (push (cons regexp callback) org-occur-parameters)
10924 (let ((cnt 0))
10925 (save-excursion
10926 (goto-char (point-min))
10927 (if (or (not keep-previous) ; do not want to keep
10928 (not org-occur-highlights)) ; no previous matches
10929 ;; hide everything
10930 (org-overview))
10931 (while (re-search-forward regexp nil t)
10932 (when (or (not callback)
10933 (save-match-data (funcall callback)))
10934 (setq cnt (1+ cnt))
10935 (when org-highlight-sparse-tree-matches
10936 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10937 (org-show-context 'occur-tree))))
10938 (when org-remove-highlights-with-change
10939 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10940 nil 'local))
10941 (unless org-sparse-tree-open-archived-trees
10942 (org-hide-archived-subtrees (point-min) (point-max)))
10943 (run-hooks 'org-occur-hook)
10944 (if (interactive-p)
10945 (message "%d match(es) for regexp %s" cnt regexp))
10946 cnt))
10948 (defun org-show-context (&optional key)
10949 "Make sure point and context and visible.
10950 How much context is shown depends upon the variables
10951 `org-show-hierarchy-above', `org-show-following-heading'. and
10952 `org-show-siblings'."
10953 (let ((heading-p (org-on-heading-p t))
10954 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10955 (following-p (org-get-alist-option org-show-following-heading key))
10956 (entry-p (org-get-alist-option org-show-entry-below key))
10957 (siblings-p (org-get-alist-option org-show-siblings key)))
10958 (catch 'exit
10959 ;; Show heading or entry text
10960 (if (and heading-p (not entry-p))
10961 (org-flag-heading nil) ; only show the heading
10962 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10963 (org-show-hidden-entry))) ; show entire entry
10964 (when following-p
10965 ;; Show next sibling, or heading below text
10966 (save-excursion
10967 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10968 (org-flag-heading nil))))
10969 (when siblings-p (org-show-siblings))
10970 (when hierarchy-p
10971 ;; show all higher headings, possibly with siblings
10972 (save-excursion
10973 (while (and (condition-case nil
10974 (progn (org-up-heading-all 1) t)
10975 (error nil))
10976 (not (bobp)))
10977 (org-flag-heading nil)
10978 (when siblings-p (org-show-siblings))))))))
10980 (defun org-reveal (&optional siblings)
10981 "Show current entry, hierarchy above it, and the following headline.
10982 This can be used to show a consistent set of context around locations
10983 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10984 not t for the search context.
10986 With optional argument SIBLINGS, on each level of the hierarchy all
10987 siblings are shown. This repairs the tree structure to what it would
10988 look like when opened with hierarchical calls to `org-cycle'."
10989 (interactive "P")
10990 (let ((org-show-hierarchy-above t)
10991 (org-show-following-heading t)
10992 (org-show-siblings (if siblings t org-show-siblings)))
10993 (org-show-context nil)))
10995 (defun org-highlight-new-match (beg end)
10996 "Highlight from BEG to END and mark the highlight is an occur headline."
10997 (let ((ov (org-make-overlay beg end)))
10998 (org-overlay-put ov 'face 'secondary-selection)
10999 (push ov org-occur-highlights)))
11001 (defun org-remove-occur-highlights (&optional beg end noremove)
11002 "Remove the occur highlights from the buffer.
11003 BEG and END are ignored. If NOREMOVE is nil, remove this function
11004 from the `before-change-functions' in the current buffer."
11005 (interactive)
11006 (unless org-inhibit-highlight-removal
11007 (mapc 'org-delete-overlay org-occur-highlights)
11008 (setq org-occur-highlights nil)
11009 (setq org-occur-parameters nil)
11010 (unless noremove
11011 (remove-hook 'before-change-functions
11012 'org-remove-occur-highlights 'local))))
11014 ;;;; Priorities
11016 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11017 "Regular expression matching the priority indicator.")
11019 (defvar org-remove-priority-next-time nil)
11021 (defun org-priority-up ()
11022 "Increase the priority of the current item."
11023 (interactive)
11024 (org-priority 'up))
11026 (defun org-priority-down ()
11027 "Decrease the priority of the current item."
11028 (interactive)
11029 (org-priority 'down))
11031 (defun org-priority (&optional action)
11032 "Change the priority of an item by ARG.
11033 ACTION can be `set', `up', `down', or a character."
11034 (interactive)
11035 (unless org-enable-priority-commands
11036 (error "Priority commands are disabled"))
11037 (setq action (or action 'set))
11038 (let (current new news have remove)
11039 (save-excursion
11040 (org-back-to-heading t)
11041 (if (looking-at org-priority-regexp)
11042 (setq current (string-to-char (match-string 2))
11043 have t)
11044 (setq current org-default-priority))
11045 (cond
11046 ((eq action 'remove)
11047 (setq remove t new ?\ ))
11048 ((or (eq action 'set)
11049 (if (featurep 'xemacs) (characterp action) (integerp action)))
11050 (if (not (eq action 'set))
11051 (setq new action)
11052 (message "Priority %c-%c, SPC to remove: "
11053 org-highest-priority org-lowest-priority)
11054 (setq new (read-char-exclusive)))
11055 (if (and (= (upcase org-highest-priority) org-highest-priority)
11056 (= (upcase org-lowest-priority) org-lowest-priority))
11057 (setq new (upcase new)))
11058 (cond ((equal new ?\ ) (setq remove t))
11059 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11060 (error "Priority must be between `%c' and `%c'"
11061 org-highest-priority org-lowest-priority))))
11062 ((eq action 'up)
11063 (if (and (not have) (eq last-command this-command))
11064 (setq new org-lowest-priority)
11065 (setq new (if (and org-priority-start-cycle-with-default (not have))
11066 org-default-priority (1- current)))))
11067 ((eq action 'down)
11068 (if (and (not have) (eq last-command this-command))
11069 (setq new org-highest-priority)
11070 (setq new (if (and org-priority-start-cycle-with-default (not have))
11071 org-default-priority (1+ current)))))
11072 (t (error "Invalid action")))
11073 (if (or (< (upcase new) org-highest-priority)
11074 (> (upcase new) org-lowest-priority))
11075 (setq remove t))
11076 (setq news (format "%c" new))
11077 (if have
11078 (if remove
11079 (replace-match "" t t nil 1)
11080 (replace-match news t t nil 2))
11081 (if remove
11082 (error "No priority cookie found in line")
11083 (let ((case-fold-search nil))
11084 (looking-at org-todo-line-regexp))
11085 (if (match-end 2)
11086 (progn
11087 (goto-char (match-end 2))
11088 (insert " [#" news "]"))
11089 (goto-char (match-beginning 3))
11090 (insert "[#" news "] "))))
11091 (org-preserve-lc (org-set-tags nil 'align)))
11092 (if remove
11093 (message "Priority removed")
11094 (message "Priority of current item set to %s" news))))
11096 (defun org-get-priority (s)
11097 "Find priority cookie and return priority."
11098 (save-match-data
11099 (if (not (string-match org-priority-regexp s))
11100 (* 1000 (- org-lowest-priority org-default-priority))
11101 (* 1000 (- org-lowest-priority
11102 (string-to-char (match-string 2 s)))))))
11104 ;;;; Tags
11106 (defvar org-agenda-archives-mode)
11107 (defvar org-map-continue-from nil
11108 "Position from where mapping should continue.
11109 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11111 (defvar org-scanner-tags nil
11112 "The current tag list while the tags scanner is running.")
11113 (defvar org-trust-scanner-tags nil
11114 "Should `org-get-tags-at' use the tags fro the scanner.
11115 This is for internal dynamical scoping only.
11116 When this is non-nil, the function `org-get-tags-at' will return the value
11117 of `org-scanner-tags' instead of building the list by itself. This
11118 can lead to large speed-ups when the tags scanner is used in a file with
11119 many entries, and when the list of tags is retrieved, for example to
11120 obtain a list of properties. Building the tags list for each entry in such
11121 a file becomes an N^2 operation - but with this variable set, it scales
11122 as N.")
11124 (defun org-scan-tags (action matcher &optional todo-only)
11125 "Scan headline tags with inheritance and produce output ACTION.
11127 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11128 or `agenda' to produce an entry list for an agenda view. It can also be
11129 a Lisp form or a function that should be called at each matched headline, in
11130 this case the return value is a list of all return values from these calls.
11132 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11133 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11134 only lines with a TODO keyword are included in the output."
11135 (require 'org-agenda)
11136 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11137 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11138 (org-re
11139 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11140 (props (list 'face 'default
11141 'done-face 'org-agenda-done
11142 'undone-face 'default
11143 'mouse-face 'highlight
11144 'org-not-done-regexp org-not-done-regexp
11145 'org-todo-regexp org-todo-regexp
11146 'help-echo
11147 (format "mouse-2 or RET jump to org file %s"
11148 (abbreviate-file-name
11149 (or (buffer-file-name (buffer-base-buffer))
11150 (buffer-name (buffer-base-buffer)))))))
11151 (case-fold-search nil)
11152 (org-map-continue-from nil)
11153 lspos tags tags-list
11154 (tags-alist (list (cons 0 org-file-tags)))
11155 (llast 0) rtn rtn1 level category i txt
11156 todo marker entry priority)
11157 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11158 (setq action (list 'lambda nil action)))
11159 (save-excursion
11160 (goto-char (point-min))
11161 (when (eq action 'sparse-tree)
11162 (org-overview)
11163 (org-remove-occur-highlights))
11164 (while (re-search-forward re nil t)
11165 (catch :skip
11166 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11167 tags (if (match-end 4) (org-match-string-no-properties 4)))
11168 (goto-char (setq lspos (match-beginning 0)))
11169 (setq level (org-reduced-level (funcall outline-level))
11170 category (org-get-category))
11171 (setq i llast llast level)
11172 ;; remove tag lists from same and sublevels
11173 (while (>= i level)
11174 (when (setq entry (assoc i tags-alist))
11175 (setq tags-alist (delete entry tags-alist)))
11176 (setq i (1- i)))
11177 ;; add the next tags
11178 (when tags
11179 (setq tags (org-split-string tags ":")
11180 tags-alist
11181 (cons (cons level tags) tags-alist)))
11182 ;; compile tags for current headline
11183 (setq tags-list
11184 (if org-use-tag-inheritance
11185 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11186 tags)
11187 org-scanner-tags tags-list)
11188 (when org-use-tag-inheritance
11189 (setcdr (car tags-alist)
11190 (mapcar (lambda (x)
11191 (setq x (copy-sequence x))
11192 (org-add-prop-inherited x))
11193 (cdar tags-alist))))
11194 (when (and tags org-use-tag-inheritance
11195 (or (not (eq t org-use-tag-inheritance))
11196 org-tags-exclude-from-inheritance))
11197 ;; selective inheritance, remove uninherited ones
11198 (setcdr (car tags-alist)
11199 (org-remove-uniherited-tags (cdar tags-alist))))
11200 (when (and (or (not todo-only)
11201 (and (member todo org-not-done-keywords)
11202 (or (not org-agenda-tags-todo-honor-ignore-options)
11203 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11204 (let ((case-fold-search t)) (eval matcher))
11206 (not (member org-archive-tag tags-list))
11207 ;; we have an archive tag, should we use this anyway?
11208 (or (not org-agenda-skip-archived-trees)
11209 (and (eq action 'agenda) org-agenda-archives-mode))))
11210 (unless (eq action 'sparse-tree) (org-agenda-skip))
11212 ;; select this headline
11214 (cond
11215 ((eq action 'sparse-tree)
11216 (and org-highlight-sparse-tree-matches
11217 (org-get-heading) (match-end 0)
11218 (org-highlight-new-match
11219 (match-beginning 0) (match-beginning 1)))
11220 (org-show-context 'tags-tree))
11221 ((eq action 'agenda)
11222 (setq txt (org-format-agenda-item
11224 (concat
11225 (if (eq org-tags-match-list-sublevels 'indented)
11226 (make-string (1- level) ?.) "")
11227 (org-get-heading))
11228 category
11229 tags-list
11231 priority (org-get-priority txt))
11232 (goto-char lspos)
11233 (setq marker (org-agenda-new-marker))
11234 (org-add-props txt props
11235 'org-marker marker 'org-hd-marker marker 'org-category category
11236 'todo-state todo
11237 'priority priority 'type "tagsmatch")
11238 (push txt rtn))
11239 ((functionp action)
11240 (setq org-map-continue-from nil)
11241 (save-excursion
11242 (setq rtn1 (funcall action))
11243 (push rtn1 rtn)))
11244 (t (error "Invalid action")))
11246 ;; if we are to skip sublevels, jump to end of subtree
11247 (unless org-tags-match-list-sublevels
11248 (org-end-of-subtree t)
11249 (backward-char 1))))
11250 ;; Get the correct position from where to continue
11251 (if org-map-continue-from
11252 (goto-char org-map-continue-from)
11253 (and (= (point) lspos) (end-of-line 1)))))
11254 (when (and (eq action 'sparse-tree)
11255 (not org-sparse-tree-open-archived-trees))
11256 (org-hide-archived-subtrees (point-min) (point-max)))
11257 (nreverse rtn)))
11259 (defun org-remove-uniherited-tags (tags)
11260 "Remove all tags that are not inherited from the list TAGS."
11261 (cond
11262 ((eq org-use-tag-inheritance t)
11263 (if org-tags-exclude-from-inheritance
11264 (org-delete-all org-tags-exclude-from-inheritance tags)
11265 tags))
11266 ((not org-use-tag-inheritance) nil)
11267 ((stringp org-use-tag-inheritance)
11268 (delq nil (mapcar
11269 (lambda (x)
11270 (if (and (string-match org-use-tag-inheritance x)
11271 (not (member x org-tags-exclude-from-inheritance)))
11272 x nil))
11273 tags)))
11274 ((listp org-use-tag-inheritance)
11275 (delq nil (mapcar
11276 (lambda (x)
11277 (if (member x org-use-tag-inheritance) x nil))
11278 tags)))))
11280 (defvar todo-only) ;; dynamically scoped
11282 (defun org-match-sparse-tree (&optional todo-only match)
11283 "Create a sparse tree according to tags string MATCH.
11284 MATCH can contain positive and negative selection of tags, like
11285 \"+WORK+URGENT-WITHBOSS\".
11286 If optional argument TODO-ONLY is non-nil, only select lines that are
11287 also TODO lines."
11288 (interactive "P")
11289 (org-prepare-agenda-buffers (list (current-buffer)))
11290 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11292 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11294 (defvar org-cached-props nil)
11295 (defun org-cached-entry-get (pom property)
11296 (if (or (eq t org-use-property-inheritance)
11297 (and (stringp org-use-property-inheritance)
11298 (string-match org-use-property-inheritance property))
11299 (and (listp org-use-property-inheritance)
11300 (member property org-use-property-inheritance)))
11301 ;; Caching is not possible, check it directly
11302 (org-entry-get pom property 'inherit)
11303 ;; Get all properties, so that we can do complicated checks easily
11304 (cdr (assoc property (or org-cached-props
11305 (setq org-cached-props
11306 (org-entry-properties pom)))))))
11308 (defun org-global-tags-completion-table (&optional files)
11309 "Return the list of all tags in all agenda buffer/files."
11310 (save-excursion
11311 (org-uniquify
11312 (delq nil
11313 (apply 'append
11314 (mapcar
11315 (lambda (file)
11316 (set-buffer (find-file-noselect file))
11317 (append (org-get-buffer-tags)
11318 (mapcar (lambda (x) (if (stringp (car-safe x))
11319 (list (car-safe x)) nil))
11320 org-tag-alist)))
11321 (if (and files (car files))
11322 files
11323 (org-agenda-files))))))))
11325 (defun org-make-tags-matcher (match)
11326 "Create the TAGS//TODO matcher form for the selection string MATCH."
11327 ;; todo-only is scoped dynamically into this function, and the function
11328 ;; may change it if the matcher asks for it.
11329 (unless match
11330 ;; Get a new match request, with completion
11331 (let ((org-last-tags-completion-table
11332 (org-global-tags-completion-table)))
11333 (setq match (org-completing-read-no-i
11334 "Match: " 'org-tags-completion-function nil nil nil
11335 'org-tags-history))))
11337 ;; Parse the string and create a lisp form
11338 (let ((match0 match)
11339 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11340 minus tag mm
11341 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11342 orterms term orlist re-p str-p level-p level-op time-p
11343 prop-p pn pv po cat-p gv rest)
11344 (if (string-match "/+" match)
11345 ;; match contains also a todo-matching request
11346 (progn
11347 (setq tagsmatch (substring match 0 (match-beginning 0))
11348 todomatch (substring match (match-end 0)))
11349 (if (string-match "^!" todomatch)
11350 (setq todo-only t todomatch (substring todomatch 1)))
11351 (if (string-match "^\\s-*$" todomatch)
11352 (setq todomatch nil)))
11353 ;; only matching tags
11354 (setq tagsmatch match todomatch nil))
11356 ;; Make the tags matcher
11357 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11358 (setq tagsmatcher t)
11359 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11360 (while (setq term (pop orterms))
11361 (while (and (equal (substring term -1) "\\") orterms)
11362 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11363 (while (string-match re term)
11364 (setq rest (substring term (match-end 0))
11365 minus (and (match-end 1)
11366 (equal (match-string 1 term) "-"))
11367 tag (match-string 2 term)
11368 re-p (equal (string-to-char tag) ?{)
11369 level-p (match-end 4)
11370 prop-p (match-end 5)
11371 mm (cond
11372 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11373 (level-p
11374 (setq level-op (org-op-to-function (match-string 3 term)))
11375 `(,level-op level ,(string-to-number
11376 (match-string 4 term))))
11377 (prop-p
11378 (setq pn (match-string 5 term)
11379 po (match-string 6 term)
11380 pv (match-string 7 term)
11381 cat-p (equal pn "CATEGORY")
11382 re-p (equal (string-to-char pv) ?{)
11383 str-p (equal (string-to-char pv) ?\")
11384 time-p (save-match-data
11385 (string-match "^\"[[<].*[]>]\"$" pv))
11386 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11387 (if time-p (setq pv (org-matcher-time pv)))
11388 (setq po (org-op-to-function po (if time-p 'time str-p)))
11389 (cond
11390 ((equal pn "CATEGORY")
11391 (setq gv '(get-text-property (point) 'org-category)))
11392 ((equal pn "TODO")
11393 (setq gv 'todo))
11395 (setq gv `(org-cached-entry-get nil ,pn))))
11396 (if re-p
11397 (if (eq po 'org<>)
11398 `(not (string-match ,pv (or ,gv "")))
11399 `(string-match ,pv (or ,gv "")))
11400 (if str-p
11401 `(,po (or ,gv "") ,pv)
11402 `(,po (string-to-number (or ,gv ""))
11403 ,(string-to-number pv) ))))
11404 (t `(member ,tag tags-list)))
11405 mm (if minus (list 'not mm) mm)
11406 term rest)
11407 (push mm tagsmatcher))
11408 (push (if (> (length tagsmatcher) 1)
11409 (cons 'and tagsmatcher)
11410 (car tagsmatcher))
11411 orlist)
11412 (setq tagsmatcher nil))
11413 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11414 (setq tagsmatcher
11415 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11416 ;; Make the todo matcher
11417 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11418 (setq todomatcher t)
11419 (setq orterms (org-split-string todomatch "|") orlist nil)
11420 (while (setq term (pop orterms))
11421 (while (string-match re term)
11422 (setq minus (and (match-end 1)
11423 (equal (match-string 1 term) "-"))
11424 kwd (match-string 2 term)
11425 re-p (equal (string-to-char kwd) ?{)
11426 term (substring term (match-end 0))
11427 mm (if re-p
11428 `(string-match ,(substring kwd 1 -1) todo)
11429 (list 'equal 'todo kwd))
11430 mm (if minus (list 'not mm) mm))
11431 (push mm todomatcher))
11432 (push (if (> (length todomatcher) 1)
11433 (cons 'and todomatcher)
11434 (car todomatcher))
11435 orlist)
11436 (setq todomatcher nil))
11437 (setq todomatcher (if (> (length orlist) 1)
11438 (cons 'or orlist) (car orlist))))
11440 ;; Return the string and lisp forms of the matcher
11441 (setq matcher (if todomatcher
11442 (list 'and tagsmatcher todomatcher)
11443 tagsmatcher))
11444 (cons match0 matcher)))
11446 (defun org-op-to-function (op &optional stringp)
11447 "Turn an operator into the appropriate function."
11448 (setq op
11449 (cond
11450 ((equal op "<" ) '(< string< org-time<))
11451 ((equal op ">" ) '(> org-string> org-time>))
11452 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11453 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11454 ((member op '("=" "==")) '(= string= org-time=))
11455 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11456 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11458 (defun org<> (a b) (not (= a b)))
11459 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11460 (defun org-string>= (a b) (not (string< a b)))
11461 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11462 (defun org-string<> (a b) (not (string= a b)))
11463 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11464 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11465 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11466 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11467 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11468 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11469 (defun org-2ft (s)
11470 "Convert S to a floating point time.
11471 If S is already a number, just return it. If it is a string, parse
11472 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11473 (cond
11474 ((numberp s) s)
11475 ((stringp s)
11476 (condition-case nil
11477 (float-time (apply 'encode-time (org-parse-time-string s)))
11478 (error 0.)))
11479 (t 0.)))
11481 (defun org-time-today ()
11482 "Time in seconds today at 0:00.
11483 Returns the float number of seconds since the beginning of the
11484 epoch to the beginning of today (00:00)."
11485 (float-time (apply 'encode-time
11486 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11488 (defun org-matcher-time (s)
11489 "Interpret a time comparison value."
11490 (save-match-data
11491 (cond
11492 ((string= s "<now>") (float-time))
11493 ((string= s "<today>") (org-time-today))
11494 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11495 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11496 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11497 (+ (org-time-today)
11498 (* (string-to-number (match-string 1 s))
11499 (cdr (assoc (match-string 2 s)
11500 '(("d" . 86400.0) ("w" . 604800.0)
11501 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11502 (t (org-2ft s)))))
11504 (defun org-match-any-p (re list)
11505 "Does re match any element of list?"
11506 (setq list (mapcar (lambda (x) (string-match re x)) list))
11507 (delq nil list))
11509 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11510 (defvar org-tags-overlay (org-make-overlay 1 1))
11511 (org-detach-overlay org-tags-overlay)
11513 (defun org-get-local-tags-at (&optional pos)
11514 "Get a list of tags defined in the current headline."
11515 (org-get-tags-at pos 'local))
11517 (defun org-get-local-tags ()
11518 "Get a list of tags defined in the current headline."
11519 (org-get-tags-at nil 'local))
11521 (defun org-get-tags-at (&optional pos local)
11522 "Get a list of all headline tags applicable at POS.
11523 POS defaults to point. If tags are inherited, the list contains
11524 the targets in the same sequence as the headlines appear, i.e.
11525 the tags of the current headline come last.
11526 When LOCAL is non-nil, only return tags from the current headline,
11527 ignore inherited ones."
11528 (interactive)
11529 (if (and org-trust-scanner-tags
11530 (or (not pos) (equal pos (point)))
11531 (not local))
11532 org-scanner-tags
11533 (let (tags ltags lastpos parent)
11534 (save-excursion
11535 (save-restriction
11536 (widen)
11537 (goto-char (or pos (point)))
11538 (save-match-data
11539 (catch 'done
11540 (condition-case nil
11541 (progn
11542 (org-back-to-heading t)
11543 (while (not (equal lastpos (point)))
11544 (setq lastpos (point))
11545 (when (looking-at
11546 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11547 (setq ltags (org-split-string
11548 (org-match-string-no-properties 1) ":"))
11549 (when parent
11550 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11551 (setq tags (append
11552 (if parent
11553 (org-remove-uniherited-tags ltags)
11554 ltags)
11555 tags)))
11556 (or org-use-tag-inheritance (throw 'done t))
11557 (if local (throw 'done t))
11558 (or (org-up-heading-safe) (error nil))
11559 (setq parent t)))
11560 (error nil)))))
11561 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11563 (defun org-add-prop-inherited (s)
11564 (add-text-properties 0 (length s) '(inherited t) s)
11567 (defun org-toggle-tag (tag &optional onoff)
11568 "Toggle the tag TAG for the current line.
11569 If ONOFF is `on' or `off', don't toggle but set to this state."
11570 (let (res current)
11571 (save-excursion
11572 (org-back-to-heading t)
11573 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11574 (point-at-eol) t)
11575 (progn
11576 (setq current (match-string 1))
11577 (replace-match ""))
11578 (setq current ""))
11579 (setq current (nreverse (org-split-string current ":")))
11580 (cond
11581 ((eq onoff 'on)
11582 (setq res t)
11583 (or (member tag current) (push tag current)))
11584 ((eq onoff 'off)
11585 (or (not (member tag current)) (setq current (delete tag current))))
11586 (t (if (member tag current)
11587 (setq current (delete tag current))
11588 (setq res t)
11589 (push tag current))))
11590 (end-of-line 1)
11591 (if current
11592 (progn
11593 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11594 (org-set-tags nil t))
11595 (delete-horizontal-space))
11596 (run-hooks 'org-after-tags-change-hook))
11597 res))
11599 (defun org-align-tags-here (to-col)
11600 ;; Assumes that this is a headline
11601 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11602 (beginning-of-line 1)
11603 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11604 (< pos (match-beginning 2)))
11605 (progn
11606 (setq tags-l (- (match-end 2) (match-beginning 2)))
11607 (goto-char (match-beginning 1))
11608 (insert " ")
11609 (delete-region (point) (1+ (match-beginning 2)))
11610 (setq ncol (max (1+ (current-column))
11611 (1+ col)
11612 (if (> to-col 0)
11613 to-col
11614 (- (abs to-col) tags-l))))
11615 (setq p (point))
11616 (insert (make-string (- ncol (current-column)) ?\ ))
11617 (setq ncol (current-column))
11618 (when indent-tabs-mode (tabify p (point-at-eol)))
11619 (org-move-to-column (min ncol col) t))
11620 (goto-char pos))))
11622 (defun org-set-tags-command (&optional arg just-align)
11623 "Call the set-tags command for the current entry."
11624 (interactive "P")
11625 (if (org-on-heading-p)
11626 (org-set-tags arg just-align)
11627 (save-excursion
11628 (org-back-to-heading t)
11629 (org-set-tags arg just-align))))
11631 (defun org-set-tags-to (data)
11632 "Set the tags of the current entry to DATA, replacing the current tags.
11633 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11634 If DATA is nil or the empty string, any tags will be removed."
11635 (interactive "sTags: ")
11636 (setq data
11637 (cond
11638 ((eq data nil) "")
11639 ((equal data "") "")
11640 ((stringp data)
11641 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11642 ":"))
11643 ((listp data)
11644 (concat ":" (mapconcat 'identity data ":") ":"))
11645 (t nil)))
11646 (when data
11647 (save-excursion
11648 (org-back-to-heading t)
11649 (when (looking-at org-complex-heading-regexp)
11650 (if (match-end 5)
11651 (progn
11652 (goto-char (match-beginning 5))
11653 (insert data)
11654 (delete-region (point) (point-at-eol))
11655 (org-set-tags nil 'align))
11656 (goto-char (point-at-eol))
11657 (insert " " data)
11658 (org-set-tags nil 'align)))
11659 (beginning-of-line 1)
11660 (if (looking-at ".*?\\([ \t]+\\)$")
11661 (delete-region (match-beginning 1) (match-end 1))))))
11663 (defun org-set-tags (&optional arg just-align)
11664 "Set the tags for the current headline.
11665 With prefix ARG, realign all tags in headings in the current buffer."
11666 (interactive "P")
11667 (let* ((re (concat "^" outline-regexp))
11668 (current (org-get-tags-string))
11669 (col (current-column))
11670 (org-setting-tags t)
11671 table current-tags inherited-tags ; computed below when needed
11672 tags p0 c0 c1 rpl)
11673 (if arg
11674 (save-excursion
11675 (goto-char (point-min))
11676 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11677 (while (re-search-forward re nil t)
11678 (org-set-tags nil t)
11679 (end-of-line 1)))
11680 (message "All tags realigned to column %d" org-tags-column))
11681 (if just-align
11682 (setq tags current)
11683 ;; Get a new set of tags from the user
11684 (save-excursion
11685 (setq table (append org-tag-persistent-alist
11686 (or org-tag-alist (org-get-buffer-tags)))
11687 org-last-tags-completion-table table
11688 current-tags (org-split-string current ":")
11689 inherited-tags (nreverse
11690 (nthcdr (length current-tags)
11691 (nreverse (org-get-tags-at))))
11692 tags
11693 (if (or (eq t org-use-fast-tag-selection)
11694 (and org-use-fast-tag-selection
11695 (delq nil (mapcar 'cdr table))))
11696 (org-fast-tag-selection
11697 current-tags inherited-tags table
11698 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11699 (let ((org-add-colon-after-tag-completion t))
11700 (org-trim
11701 (org-without-partial-completion
11702 (org-icompleting-read "Tags: " 'org-tags-completion-function
11703 nil nil current 'org-tags-history)))))))
11704 (while (string-match "[-+&]+" tags)
11705 ;; No boolean logic, just a list
11706 (setq tags (replace-match ":" t t tags))))
11708 (if org-tags-sort-function
11709 (setq tags (mapconcat 'identity
11710 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11711 org-tags-sort-function) ":")))
11713 (if (string-match "\\`[\t ]*\\'" tags)
11714 (setq tags "")
11715 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11716 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11718 ;; Insert new tags at the correct column
11719 (beginning-of-line 1)
11720 (cond
11721 ((and (equal current "") (equal tags "")))
11722 ((re-search-forward
11723 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11724 (point-at-eol) t)
11725 (if (equal tags "")
11726 (setq rpl "")
11727 (goto-char (match-beginning 0))
11728 (setq c0 (current-column) p0 (point)
11729 c1 (max (1+ c0) (if (> org-tags-column 0)
11730 org-tags-column
11731 (- (- org-tags-column) (length tags))))
11732 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11733 (replace-match rpl t t)
11734 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11735 tags)
11736 (t (error "Tags alignment failed")))
11737 (org-move-to-column col)
11738 (unless just-align
11739 (run-hooks 'org-after-tags-change-hook)))))
11741 (defun org-change-tag-in-region (beg end tag off)
11742 "Add or remove TAG for each entry in the region.
11743 This works in the agenda, and also in an org-mode buffer."
11744 (interactive
11745 (list (region-beginning) (region-end)
11746 (let ((org-last-tags-completion-table
11747 (if (org-mode-p)
11748 (org-get-buffer-tags)
11749 (org-global-tags-completion-table))))
11750 (org-icompleting-read
11751 "Tag: " 'org-tags-completion-function nil nil nil
11752 'org-tags-history))
11753 (progn
11754 (message "[s]et or [r]emove? ")
11755 (equal (read-char-exclusive) ?r))))
11756 (if (fboundp 'deactivate-mark) (deactivate-mark))
11757 (let ((agendap (equal major-mode 'org-agenda-mode))
11758 l1 l2 m buf pos newhead (cnt 0))
11759 (goto-char end)
11760 (setq l2 (1- (org-current-line)))
11761 (goto-char beg)
11762 (setq l1 (org-current-line))
11763 (loop for l from l1 to l2 do
11764 (org-goto-line l)
11765 (setq m (get-text-property (point) 'org-hd-marker))
11766 (when (or (and (org-mode-p) (org-on-heading-p))
11767 (and agendap m))
11768 (setq buf (if agendap (marker-buffer m) (current-buffer))
11769 pos (if agendap m (point)))
11770 (with-current-buffer buf
11771 (save-excursion
11772 (save-restriction
11773 (goto-char pos)
11774 (setq cnt (1+ cnt))
11775 (org-toggle-tag tag (if off 'off 'on))
11776 (setq newhead (org-get-heading)))))
11777 (and agendap (org-agenda-change-all-lines newhead m))))
11778 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11780 (defun org-tags-completion-function (string predicate &optional flag)
11781 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11782 (confirm (lambda (x) (stringp (car x)))))
11783 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11784 (setq s1 (match-string 1 string)
11785 s2 (match-string 2 string))
11786 (setq s1 "" s2 string))
11787 (cond
11788 ((eq flag nil)
11789 ;; try completion
11790 (setq rtn (try-completion s2 ctable confirm))
11791 (if (stringp rtn)
11792 (setq rtn
11793 (concat s1 s2 (substring rtn (length s2))
11794 (if (and org-add-colon-after-tag-completion
11795 (assoc rtn ctable))
11796 ":" ""))))
11797 rtn)
11798 ((eq flag t)
11799 ;; all-completions
11800 (all-completions s2 ctable confirm)
11802 ((eq flag 'lambda)
11803 ;; exact match?
11804 (assoc s2 ctable)))
11807 (defun org-fast-tag-insert (kwd tags face &optional end)
11808 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11809 (insert (format "%-12s" (concat kwd ":"))
11810 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11811 (or end "")))
11813 (defun org-fast-tag-show-exit (flag)
11814 (save-excursion
11815 (org-goto-line 3)
11816 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11817 (replace-match ""))
11818 (when flag
11819 (end-of-line 1)
11820 (org-move-to-column (- (window-width) 19) t)
11821 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11823 (defun org-set-current-tags-overlay (current prefix)
11824 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11825 (if (featurep 'xemacs)
11826 (org-overlay-display org-tags-overlay (concat prefix s)
11827 'secondary-selection)
11828 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11829 (org-overlay-display org-tags-overlay (concat prefix s)))))
11831 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11832 "Fast tag selection with single keys.
11833 CURRENT is the current list of tags in the headline, INHERITED is the
11834 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11835 possibly with grouping information. TODO-TABLE is a similar table with
11836 TODO keywords, should these have keys assigned to them.
11837 If the keys are nil, a-z are automatically assigned.
11838 Returns the new tags string, or nil to not change the current settings."
11839 (let* ((fulltable (append table todo-table))
11840 (maxlen (apply 'max (mapcar
11841 (lambda (x)
11842 (if (stringp (car x)) (string-width (car x)) 0))
11843 fulltable)))
11844 (buf (current-buffer))
11845 (expert (eq org-fast-tag-selection-single-key 'expert))
11846 (buffer-tags nil)
11847 (fwidth (+ maxlen 3 1 3))
11848 (ncol (/ (- (window-width) 4) fwidth))
11849 (i-face 'org-done)
11850 (c-face 'org-todo)
11851 tg cnt e c char c1 c2 ntable tbl rtn
11852 ov-start ov-end ov-prefix
11853 (exit-after-next org-fast-tag-selection-single-key)
11854 (done-keywords org-done-keywords)
11855 groups ingroup)
11856 (save-excursion
11857 (beginning-of-line 1)
11858 (if (looking-at
11859 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11860 (setq ov-start (match-beginning 1)
11861 ov-end (match-end 1)
11862 ov-prefix "")
11863 (setq ov-start (1- (point-at-eol))
11864 ov-end (1+ ov-start))
11865 (skip-chars-forward "^\n\r")
11866 (setq ov-prefix
11867 (concat
11868 (buffer-substring (1- (point)) (point))
11869 (if (> (current-column) org-tags-column)
11871 (make-string (- org-tags-column (current-column)) ?\ ))))))
11872 (org-move-overlay org-tags-overlay ov-start ov-end)
11873 (save-window-excursion
11874 (if expert
11875 (set-buffer (get-buffer-create " *Org tags*"))
11876 (delete-other-windows)
11877 (split-window-vertically)
11878 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11879 (erase-buffer)
11880 (org-set-local 'org-done-keywords done-keywords)
11881 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11882 (org-fast-tag-insert "Current" current c-face "\n\n")
11883 (org-fast-tag-show-exit exit-after-next)
11884 (org-set-current-tags-overlay current ov-prefix)
11885 (setq tbl fulltable char ?a cnt 0)
11886 (while (setq e (pop tbl))
11887 (cond
11888 ((equal (car e) :startgroup)
11889 (push '() groups) (setq ingroup t)
11890 (when (not (= cnt 0))
11891 (setq cnt 0)
11892 (insert "\n"))
11893 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11894 ((equal (car e) :endgroup)
11895 (setq ingroup nil cnt 0)
11896 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11897 ((equal e '(:newline))
11898 (when (not (= cnt 0))
11899 (setq cnt 0)
11900 (insert "\n")
11901 (setq e (car tbl))
11902 (while (equal (car tbl) '(:newline))
11903 (insert "\n")
11904 (setq tbl (cdr tbl)))))
11906 (setq tg (copy-sequence (car e)) c2 nil)
11907 (if (cdr e)
11908 (setq c (cdr e))
11909 ;; automatically assign a character.
11910 (setq c1 (string-to-char
11911 (downcase (substring
11912 tg (if (= (string-to-char tg) ?@) 1 0)))))
11913 (if (or (rassoc c1 ntable) (rassoc c1 table))
11914 (while (or (rassoc char ntable) (rassoc char table))
11915 (setq char (1+ char)))
11916 (setq c2 c1))
11917 (setq c (or c2 char)))
11918 (if ingroup (push tg (car groups)))
11919 (setq tg (org-add-props tg nil 'face
11920 (cond
11921 ((not (assoc tg table))
11922 (org-get-todo-face tg))
11923 ((member tg current) c-face)
11924 ((member tg inherited) i-face)
11925 (t nil))))
11926 (if (and (= cnt 0) (not ingroup)) (insert " "))
11927 (insert "[" c "] " tg (make-string
11928 (- fwidth 4 (length tg)) ?\ ))
11929 (push (cons tg c) ntable)
11930 (when (= (setq cnt (1+ cnt)) ncol)
11931 (insert "\n")
11932 (if ingroup (insert " "))
11933 (setq cnt 0)))))
11934 (setq ntable (nreverse ntable))
11935 (insert "\n")
11936 (goto-char (point-min))
11937 (if (not expert) (org-fit-window-to-buffer))
11938 (setq rtn
11939 (catch 'exit
11940 (while t
11941 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11942 (if (not groups) "no " "")
11943 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11944 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11945 (cond
11946 ((= c ?\r) (throw 'exit t))
11947 ((= c ?!)
11948 (setq groups (not groups))
11949 (goto-char (point-min))
11950 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11951 ((= c ?\C-c)
11952 (if (not expert)
11953 (org-fast-tag-show-exit
11954 (setq exit-after-next (not exit-after-next)))
11955 (setq expert nil)
11956 (delete-other-windows)
11957 (split-window-vertically)
11958 (org-switch-to-buffer-other-window " *Org tags*")
11959 (org-fit-window-to-buffer)))
11960 ((or (= c ?\C-g)
11961 (and (= c ?q) (not (rassoc c ntable))))
11962 (org-detach-overlay org-tags-overlay)
11963 (setq quit-flag t))
11964 ((= c ?\ )
11965 (setq current nil)
11966 (if exit-after-next (setq exit-after-next 'now)))
11967 ((= c ?\t)
11968 (condition-case nil
11969 (setq tg (org-icompleting-read
11970 "Tag: "
11971 (or buffer-tags
11972 (with-current-buffer buf
11973 (org-get-buffer-tags)))))
11974 (quit (setq tg "")))
11975 (when (string-match "\\S-" tg)
11976 (add-to-list 'buffer-tags (list tg))
11977 (if (member tg current)
11978 (setq current (delete tg current))
11979 (push tg current)))
11980 (if exit-after-next (setq exit-after-next 'now)))
11981 ((setq e (rassoc c todo-table) tg (car e))
11982 (with-current-buffer buf
11983 (save-excursion (org-todo tg)))
11984 (if exit-after-next (setq exit-after-next 'now)))
11985 ((setq e (rassoc c ntable) tg (car e))
11986 (if (member tg current)
11987 (setq current (delete tg current))
11988 (loop for g in groups do
11989 (if (member tg g)
11990 (mapc (lambda (x)
11991 (setq current (delete x current)))
11992 g)))
11993 (push tg current))
11994 (if exit-after-next (setq exit-after-next 'now))))
11996 ;; Create a sorted list
11997 (setq current
11998 (sort current
11999 (lambda (a b)
12000 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12001 (if (eq exit-after-next 'now) (throw 'exit t))
12002 (goto-char (point-min))
12003 (beginning-of-line 2)
12004 (delete-region (point) (point-at-eol))
12005 (org-fast-tag-insert "Current" current c-face)
12006 (org-set-current-tags-overlay current ov-prefix)
12007 (while (re-search-forward
12008 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12009 (setq tg (match-string 1))
12010 (add-text-properties
12011 (match-beginning 1) (match-end 1)
12012 (list 'face
12013 (cond
12014 ((member tg current) c-face)
12015 ((member tg inherited) i-face)
12016 (t (get-text-property (match-beginning 1) 'face))))))
12017 (goto-char (point-min)))))
12018 (org-detach-overlay org-tags-overlay)
12019 (if rtn
12020 (mapconcat 'identity current ":")
12021 nil))))
12023 (defun org-get-tags-string ()
12024 "Get the TAGS string in the current headline."
12025 (unless (org-on-heading-p t)
12026 (error "Not on a heading"))
12027 (save-excursion
12028 (beginning-of-line 1)
12029 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12030 (org-match-string-no-properties 1)
12031 "")))
12033 (defun org-get-tags ()
12034 "Get the list of tags specified in the current headline."
12035 (org-split-string (org-get-tags-string) ":"))
12037 (defun org-get-buffer-tags ()
12038 "Get a table of all tags used in the buffer, for completion."
12039 (let (tags)
12040 (save-excursion
12041 (goto-char (point-min))
12042 (while (re-search-forward
12043 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12044 (when (equal (char-after (point-at-bol 0)) ?*)
12045 (mapc (lambda (x) (add-to-list 'tags x))
12046 (org-split-string (org-match-string-no-properties 1) ":")))))
12047 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12048 (mapcar 'list tags)))
12050 ;;;; The mapping API
12052 ;;;###autoload
12053 (defun org-map-entries (func &optional match scope &rest skip)
12054 "Call FUNC at each headline selected by MATCH in SCOPE.
12056 FUNC is a function or a lisp form. The function will be called without
12057 arguments, with the cursor positioned at the beginning of the headline.
12058 The return values of all calls to the function will be collected and
12059 returned as a list.
12061 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12062 does not need to preserve point. After evaluation, the cursor will be
12063 moved to the end of the line (presumably of the headline of the
12064 processed entry) and search continues from there. Under some
12065 circumstances, this may not produce the wanted results. For example,
12066 if you have removed (e.g. archived) the current (sub)tree it could
12067 mean that the next entry will be skipped entirely. In such cases, you
12068 can specify the position from where search should continue by making
12069 FUNC set the variable `org-map-continue-from' to the desired buffer
12070 position.
12072 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12073 Only headlines that are matched by this query will be considered during
12074 the iteration. When MATCH is nil or t, all headlines will be
12075 visited by the iteration.
12077 SCOPE determines the scope of this command. It can be any of:
12079 nil The current buffer, respecting the restriction if any
12080 tree The subtree started with the entry at point
12081 file The current buffer, without restriction
12082 file-with-archives
12083 The current buffer, and any archives associated with it
12084 agenda All agenda files
12085 agenda-with-archives
12086 All agenda files with any archive files associated with them
12087 \(file1 file2 ...)
12088 If this is a list, all files in the list will be scanned
12090 The remaining args are treated as settings for the skipping facilities of
12091 the scanner. The following items can be given here:
12093 archive skip trees with the archive tag.
12094 comment skip trees with the COMMENT keyword
12095 function or Emacs Lisp form:
12096 will be used as value for `org-agenda-skip-function', so whenever
12097 the function returns t, FUNC will not be called for that
12098 entry and search will continue from the point where the
12099 function leaves it.
12101 If your function needs to retrieve the tags including inherited tags
12102 at the *current* entry, you can use the value of the variable
12103 `org-scanner-tags' which will be much faster than getting the value
12104 with `org-get-tags-at'. If your function gets properties with
12105 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12106 to t around the call to `org-entry-properties' to get the same speedup.
12107 Note that if your function moves around to retrieve tags and properties at
12108 a *different* entry, you cannot use these techniques."
12109 (let* ((org-agenda-archives-mode nil) ; just to make sure
12110 (org-agenda-skip-archived-trees (memq 'archive skip))
12111 (org-agenda-skip-comment-trees (memq 'comment skip))
12112 (org-agenda-skip-function
12113 (car (org-delete-all '(comment archive) skip)))
12114 (org-tags-match-list-sublevels t)
12115 matcher file res
12116 org-todo-keywords-for-agenda
12117 org-done-keywords-for-agenda
12118 org-todo-keyword-alist-for-agenda
12119 org-drawers-for-agenda
12120 org-tag-alist-for-agenda)
12122 (cond
12123 ((eq match t) (setq matcher t))
12124 ((eq match nil) (setq matcher t))
12125 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12127 (save-excursion
12128 (save-restriction
12129 (when (eq scope 'tree)
12130 (org-back-to-heading t)
12131 (org-narrow-to-subtree)
12132 (setq scope nil))
12134 (if (not scope)
12135 (progn
12136 (org-prepare-agenda-buffers
12137 (list (buffer-file-name (current-buffer))))
12138 (setq res (org-scan-tags func matcher)))
12139 ;; Get the right scope
12140 (cond
12141 ((and scope (listp scope) (symbolp (car scope)))
12142 (setq scope (eval scope)))
12143 ((eq scope 'agenda)
12144 (setq scope (org-agenda-files t)))
12145 ((eq scope 'agenda-with-archives)
12146 (setq scope (org-agenda-files t))
12147 (setq scope (org-add-archive-files scope)))
12148 ((eq scope 'file)
12149 (setq scope (list (buffer-file-name))))
12150 ((eq scope 'file-with-archives)
12151 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12152 (org-prepare-agenda-buffers scope)
12153 (while (setq file (pop scope))
12154 (with-current-buffer (org-find-base-buffer-visiting file)
12155 (save-excursion
12156 (save-restriction
12157 (widen)
12158 (goto-char (point-min))
12159 (setq res (append res (org-scan-tags func matcher))))))))))
12160 res))
12162 ;;;; Properties
12164 ;;; Setting and retrieving properties
12166 (defconst org-special-properties
12167 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12168 "TIMESTAMP" "TIMESTAMP_IA")
12169 "The special properties valid in Org-mode.
12171 These are properties that are not defined in the property drawer,
12172 but in some other way.")
12174 (defconst org-default-properties
12175 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12176 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12177 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12178 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12179 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12180 "CLOCK_MODELINE_TOTAL" "STYLE")
12181 "Some properties that are used by Org-mode for various purposes.
12182 Being in this list makes sure that they are offered for completion.")
12184 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12185 "Regular expression matching the first line of a property drawer.")
12187 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12188 "Regular expression matching the first line of a property drawer.")
12190 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12191 "Regular expression matching the first line of a property drawer.")
12193 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12194 "Regular expression matching the first line of a property drawer.")
12196 (defconst org-property-drawer-re
12197 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12198 org-property-end-re "\\)\n?")
12199 "Matches an entire property drawer.")
12201 (defconst org-clock-drawer-re
12202 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12203 org-property-end-re "\\)\n?")
12204 "Matches an entire clock drawer.")
12206 (defun org-property-action ()
12207 "Do an action on properties."
12208 (interactive)
12209 (let (c)
12210 (org-at-property-p)
12211 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12212 (setq c (read-char-exclusive))
12213 (cond
12214 ((equal c ?s)
12215 (call-interactively 'org-set-property))
12216 ((equal c ?d)
12217 (call-interactively 'org-delete-property))
12218 ((equal c ?D)
12219 (call-interactively 'org-delete-property-globally))
12220 ((equal c ?c)
12221 (call-interactively 'org-compute-property-at-point))
12222 (t (error "No such property action %c" c)))))
12224 (defun org-set-effort (&optional value)
12225 "Set the effort property of the current entry.
12226 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12227 allowed value."
12228 (interactive "P")
12229 (if (equal value 0) (setq value 10))
12230 (let* ((completion-ignore-case t)
12231 (prop org-effort-property)
12232 (cur (org-entry-get nil prop))
12233 (allowed (org-property-get-allowed-values nil prop 'table))
12234 (existing (mapcar 'list (org-property-values prop)))
12236 (val (cond
12237 ((stringp value) value)
12238 ((and allowed (integerp value))
12239 (or (car (nth (1- value) allowed))
12240 (car (org-last allowed))))
12241 (allowed
12242 (message "Select 1-9,0, [RET%s]: %s"
12243 (if cur (concat "=" cur) "")
12244 (mapconcat 'car allowed " "))
12245 (setq rpl (read-char-exclusive))
12246 (if (equal rpl ?\r)
12248 (setq rpl (- rpl ?0))
12249 (if (equal rpl 0) (setq rpl 10))
12250 (if (and (> rpl 0) (<= rpl (length allowed)))
12251 (car (nth (1- rpl) allowed))
12252 (org-completing-read "Effort: " allowed nil))))
12254 (let (org-completion-use-ido org-completion-use-iswitchb)
12255 (org-completing-read
12256 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12257 (concat "[" cur "]") "")
12258 ": ")
12259 existing nil nil "" nil cur))))))
12260 (unless (equal (org-entry-get nil prop) val)
12261 (org-entry-put nil prop val))
12262 (message "%s is now %s" prop val)))
12264 (defun org-at-property-p ()
12265 "Is the cursor in a property line?"
12266 ;; FIXME: Does not check if we are actually in the drawer.
12267 ;; FIXME: also returns true on any drawers.....
12268 ;; This is used by C-c C-c for property action.
12269 (save-excursion
12270 (beginning-of-line 1)
12271 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12273 (defun org-get-property-block (&optional beg end force)
12274 "Return the (beg . end) range of the body of the property drawer.
12275 BEG and END can be beginning and end of subtree, if not given
12276 they will be found.
12277 If the drawer does not exist and FORCE is non-nil, create the drawer."
12278 (catch 'exit
12279 (save-excursion
12280 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12281 (end (or end (progn (outline-next-heading) (point)))))
12282 (goto-char beg)
12283 (if (re-search-forward org-property-start-re end t)
12284 (setq beg (1+ (match-end 0)))
12285 (if force
12286 (save-excursion
12287 (org-insert-property-drawer)
12288 (setq end (progn (outline-next-heading) (point))))
12289 (throw 'exit nil))
12290 (goto-char beg)
12291 (if (re-search-forward org-property-start-re end t)
12292 (setq beg (1+ (match-end 0)))))
12293 (if (re-search-forward org-property-end-re end t)
12294 (setq end (match-beginning 0))
12295 (or force (throw 'exit nil))
12296 (goto-char beg)
12297 (setq end beg)
12298 (org-indent-line-function)
12299 (insert ":END:\n"))
12300 (cons beg end)))))
12302 (defun org-entry-properties (&optional pom which)
12303 "Get all properties of the entry at point-or-marker POM.
12304 This includes the TODO keyword, the tags, time strings for deadline,
12305 scheduled, and clocking, and any additional properties defined in the
12306 entry. The return value is an alist, keys may occur multiple times
12307 if the property key was used several times.
12308 POM may also be nil, in which case the current entry is used.
12309 If WHICH is nil or `all', get all properties. If WHICH is
12310 `special' or `standard', only get that subclass."
12311 (setq which (or which 'all))
12312 (org-with-point-at pom
12313 (let ((clockstr (substring org-clock-string 0 -1))
12314 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12315 beg end range props sum-props key value string clocksum)
12316 (save-excursion
12317 (when (condition-case nil
12318 (and (org-mode-p) (org-back-to-heading t))
12319 (error nil))
12320 (setq beg (point))
12321 (setq sum-props (get-text-property (point) 'org-summaries))
12322 (setq clocksum (get-text-property (point) :org-clock-minutes))
12323 (outline-next-heading)
12324 (setq end (point))
12325 (when (memq which '(all special))
12326 ;; Get the special properties, like TODO and tags
12327 (goto-char beg)
12328 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12329 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12330 (when (looking-at org-priority-regexp)
12331 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12332 (when (and (setq value (org-get-tags-string))
12333 (string-match "\\S-" value))
12334 (push (cons "TAGS" value) props))
12335 (when (setq value (org-get-tags-at))
12336 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12337 props))
12338 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12339 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12340 string (if (equal key clockstr)
12341 (org-no-properties
12342 (org-trim
12343 (buffer-substring
12344 (match-beginning 3) (goto-char (point-at-eol)))))
12345 (substring (org-match-string-no-properties 3) 1 -1)))
12346 (unless key
12347 (if (= (char-after (match-beginning 3)) ?\[)
12348 (setq key "TIMESTAMP_IA")
12349 (setq key "TIMESTAMP")))
12350 (when (or (equal key clockstr) (not (assoc key props)))
12351 (push (cons key string) props)))
12355 (when (memq which '(all standard))
12356 ;; Get the standard properties, like :PROP: ...
12357 (setq range (org-get-property-block beg end))
12358 (when range
12359 (goto-char (car range))
12360 (while (re-search-forward
12361 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12362 (cdr range) t)
12363 (setq key (org-match-string-no-properties 1)
12364 value (org-trim (or (org-match-string-no-properties 2) "")))
12365 (unless (member key excluded)
12366 (push (cons key (or value "")) props)))))
12367 (if clocksum
12368 (push (cons "CLOCKSUM"
12369 (org-columns-number-to-string (/ (float clocksum) 60.)
12370 'add_times))
12371 props))
12372 (unless (assoc "CATEGORY" props)
12373 (setq value (or (org-get-category)
12374 (progn (org-refresh-category-properties)
12375 (org-get-category))))
12376 (push (cons "CATEGORY" value) props))
12377 (append sum-props (nreverse props)))))))
12379 (defun org-entry-get (pom property &optional inherit)
12380 "Get value of PROPERTY for entry at point-or-marker POM.
12381 If INHERIT is non-nil and the entry does not have the property,
12382 then also check higher levels of the hierarchy.
12383 If INHERIT is the symbol `selective', use inheritance only if the setting
12384 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12385 If the property is present but empty, the return value is the empty string.
12386 If the property is not present at all, nil is returned."
12387 (org-with-point-at pom
12388 (if (and inherit (if (eq inherit 'selective)
12389 (org-property-inherit-p property)
12391 (org-entry-get-with-inheritance property)
12392 (if (member property org-special-properties)
12393 ;; We need a special property. Use brute force, get all properties.
12394 (cdr (assoc property (org-entry-properties nil 'special)))
12395 (let ((range (org-get-property-block)))
12396 (if (and range
12397 (goto-char (car range))
12398 (re-search-forward
12399 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12400 (cdr range) t))
12401 ;; Found the property, return it.
12402 (if (match-end 1)
12403 (org-match-string-no-properties 1)
12404 "")))))))
12406 (defun org-property-or-variable-value (var &optional inherit)
12407 "Check if there is a property fixing the value of VAR.
12408 If yes, return this value. If not, return the current value of the variable."
12409 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12410 (if (and prop (stringp prop) (string-match "\\S-" prop))
12411 (read prop)
12412 (symbol-value var))))
12414 (defun org-entry-delete (pom property)
12415 "Delete the property PROPERTY from entry at point-or-marker POM."
12416 (org-with-point-at pom
12417 (if (member property org-special-properties)
12418 nil ; cannot delete these properties.
12419 (let ((range (org-get-property-block)))
12420 (if (and range
12421 (goto-char (car range))
12422 (re-search-forward
12423 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12424 (cdr range) t))
12425 (progn
12426 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12428 nil)))))
12430 ;; Multi-values properties are properties that contain multiple values
12431 ;; These values are assumed to be single words, separated by whitespace.
12432 (defun org-entry-add-to-multivalued-property (pom property value)
12433 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12434 (let* ((old (org-entry-get pom property))
12435 (values (and old (org-split-string old "[ \t]"))))
12436 (setq value (org-entry-protect-space value))
12437 (unless (member value values)
12438 (setq values (cons value values))
12439 (org-entry-put pom property
12440 (mapconcat 'identity values " ")))))
12442 (defun org-entry-remove-from-multivalued-property (pom property value)
12443 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12444 (let* ((old (org-entry-get pom property))
12445 (values (and old (org-split-string old "[ \t]"))))
12446 (setq value (org-entry-protect-space value))
12447 (when (member value values)
12448 (setq values (delete value values))
12449 (org-entry-put pom property
12450 (mapconcat 'identity values " ")))))
12452 (defun org-entry-member-in-multivalued-property (pom property value)
12453 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12454 (let* ((old (org-entry-get pom property))
12455 (values (and old (org-split-string old "[ \t]"))))
12456 (setq value (org-entry-protect-space value))
12457 (member value values)))
12459 (defun org-entry-get-multivalued-property (pom property)
12460 "Return a list of values in a multivalued property."
12461 (let* ((value (org-entry-get pom property))
12462 (values (and value (org-split-string value "[ \t]"))))
12463 (mapcar 'org-entry-restore-space values)))
12465 (defun org-entry-put-multivalued-property (pom property &rest values)
12466 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12467 VALUES should be a list of strings. Spaces will be protected."
12468 (org-entry-put pom property
12469 (mapconcat 'org-entry-protect-space values " "))
12470 (let* ((value (org-entry-get pom property))
12471 (values (and value (org-split-string value "[ \t]"))))
12472 (mapcar 'org-entry-restore-space values)))
12474 (defun org-entry-protect-space (s)
12475 "Protect spaces and newline in string S."
12476 (while (string-match " " s)
12477 (setq s (replace-match "%20" t t s)))
12478 (while (string-match "\n" s)
12479 (setq s (replace-match "%0A" t t s)))
12482 (defun org-entry-restore-space (s)
12483 "Restore spaces and newline in string S."
12484 (while (string-match "%20" s)
12485 (setq s (replace-match " " t t s)))
12486 (while (string-match "%0A" s)
12487 (setq s (replace-match "\n" t t s)))
12490 (defvar org-entry-property-inherited-from (make-marker)
12491 "Marker pointing to the entry from where a property was inherited.
12492 Each call to `org-entry-get-with-inheritance' will set this marker to the
12493 location of the entry where the inheritance search matched. If there was
12494 no match, the marker will point nowhere.
12495 Note that also `org-entry-get' calls this function, if the INHERIT flag
12496 is set.")
12498 (defun org-entry-get-with-inheritance (property)
12499 "Get entry property, and search higher levels if not present."
12500 (move-marker org-entry-property-inherited-from nil)
12501 (let (tmp)
12502 (save-excursion
12503 (save-restriction
12504 (widen)
12505 (catch 'ex
12506 (while t
12507 (when (setq tmp (org-entry-get nil property))
12508 (org-back-to-heading t)
12509 (move-marker org-entry-property-inherited-from (point))
12510 (throw 'ex tmp))
12511 (or (org-up-heading-safe) (throw 'ex nil)))))
12512 (or tmp
12513 (cdr (assoc property org-file-properties))
12514 (cdr (assoc property org-global-properties))
12515 (cdr (assoc property org-global-properties-fixed))))))
12517 (defun org-entry-put (pom property value)
12518 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12519 (org-with-point-at pom
12520 (org-back-to-heading t)
12521 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12522 range)
12523 (cond
12524 ((equal property "TODO")
12525 (when (and (stringp value) (string-match "\\S-" value)
12526 (not (member value org-todo-keywords-1)))
12527 (error "\"%s\" is not a valid TODO state" value))
12528 (if (or (not value)
12529 (not (string-match "\\S-" value)))
12530 (setq value 'none))
12531 (org-todo value)
12532 (org-set-tags nil 'align))
12533 ((equal property "PRIORITY")
12534 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12535 (string-to-char value) ?\ ))
12536 (org-set-tags nil 'align))
12537 ((equal property "SCHEDULED")
12538 (if (re-search-forward org-scheduled-time-regexp end t)
12539 (cond
12540 ((eq value 'earlier) (org-timestamp-change -1 'day))
12541 ((eq value 'later) (org-timestamp-change 1 'day))
12542 (t (call-interactively 'org-schedule)))
12543 (call-interactively 'org-schedule)))
12544 ((equal property "DEADLINE")
12545 (if (re-search-forward org-deadline-time-regexp end t)
12546 (cond
12547 ((eq value 'earlier) (org-timestamp-change -1 'day))
12548 ((eq value 'later) (org-timestamp-change 1 'day))
12549 (t (call-interactively 'org-deadline)))
12550 (call-interactively 'org-deadline)))
12551 ((member property org-special-properties)
12552 (error "The %s property can not yet be set with `org-entry-put'"
12553 property))
12554 (t ; a non-special property
12555 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12556 (setq range (org-get-property-block beg end 'force))
12557 (goto-char (car range))
12558 (if (re-search-forward
12559 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12560 (progn
12561 (delete-region (match-beginning 1) (match-end 1))
12562 (goto-char (match-beginning 1)))
12563 (goto-char (cdr range))
12564 (insert "\n")
12565 (backward-char 1)
12566 (org-indent-line-function)
12567 (insert ":" property ":"))
12568 (and value (insert " " value))
12569 (org-indent-line-function)))))))
12571 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12572 "Get all property keys in the current buffer.
12573 With INCLUDE-SPECIALS, also list the special properties that reflect things
12574 like tags and TODO state.
12575 With INCLUDE-DEFAULTS, also include properties that has special meaning
12576 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12577 With INCLUDE-COLUMNS, also include property names given in COLUMN
12578 formats in the current buffer."
12579 (let (rtn range cfmt s p)
12580 (save-excursion
12581 (save-restriction
12582 (widen)
12583 (goto-char (point-min))
12584 (while (re-search-forward org-property-start-re nil t)
12585 (setq range (org-get-property-block))
12586 (goto-char (car range))
12587 (while (re-search-forward
12588 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12589 (cdr range) t)
12590 (add-to-list 'rtn (org-match-string-no-properties 1)))
12591 (outline-next-heading))))
12593 (when include-specials
12594 (setq rtn (append org-special-properties rtn)))
12596 (when include-defaults
12597 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12598 (add-to-list 'rtn org-effort-property))
12600 (when include-columns
12601 (save-excursion
12602 (save-restriction
12603 (widen)
12604 (goto-char (point-min))
12605 (while (re-search-forward
12606 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12607 nil t)
12608 (setq cfmt (match-string 2) s 0)
12609 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12610 cfmt s)
12611 (setq s (match-end 0)
12612 p (match-string 1 cfmt))
12613 (unless (or (equal p "ITEM")
12614 (member p org-special-properties))
12615 (add-to-list 'rtn (match-string 1 cfmt))))))))
12617 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12619 (defun org-property-values (key)
12620 "Return a list of all values of property KEY."
12621 (save-excursion
12622 (save-restriction
12623 (widen)
12624 (goto-char (point-min))
12625 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12626 values)
12627 (while (re-search-forward re nil t)
12628 (add-to-list 'values (org-trim (match-string 1))))
12629 (delete "" values)))))
12631 (defun org-insert-property-drawer ()
12632 "Insert a property drawer into the current entry."
12633 (interactive)
12634 (org-back-to-heading t)
12635 (looking-at outline-regexp)
12636 (let ((indent (if org-adapt-indentation
12637 (- (match-end 0)(match-beginning 0))
12639 (beg (point))
12640 (re (concat "^[ \t]*" org-keyword-time-regexp))
12641 end hiddenp)
12642 (outline-next-heading)
12643 (setq end (point))
12644 (goto-char beg)
12645 (while (re-search-forward re end t))
12646 (setq hiddenp (org-invisible-p))
12647 (end-of-line 1)
12648 (and (equal (char-after) ?\n) (forward-char 1))
12649 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12650 (if (member (match-string 1) '("CLOCK:" ":END:"))
12651 ;; just skip this line
12652 (beginning-of-line 2)
12653 ;; Drawer start, find the end
12654 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12655 (beginning-of-line 1)))
12656 (org-skip-over-state-notes)
12657 (skip-chars-backward " \t\n\r")
12658 (if (eq (char-before) ?*) (forward-char 1))
12659 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12660 (beginning-of-line 0)
12661 (org-indent-to-column indent)
12662 (beginning-of-line 2)
12663 (org-indent-to-column indent)
12664 (beginning-of-line 0)
12665 (if hiddenp
12666 (save-excursion
12667 (org-back-to-heading t)
12668 (hide-entry))
12669 (org-flag-drawer t))))
12671 (defun org-set-property (property value)
12672 "In the current entry, set PROPERTY to VALUE.
12673 When called interactively, this will prompt for a property name, offering
12674 completion on existing and default properties. And then it will prompt
12675 for a value, offering completion either on allowed values (via an inherited
12676 xxx_ALL property) or on existing values in other instances of this property
12677 in the current file."
12678 (interactive
12679 (let* ((completion-ignore-case t)
12680 (keys (org-buffer-property-keys nil t t))
12681 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12682 (prop (if (member prop0 keys)
12683 prop0
12684 (or (cdr (assoc (downcase prop0)
12685 (mapcar (lambda (x) (cons (downcase x) x))
12686 keys)))
12687 prop0)))
12688 (cur (org-entry-get nil prop))
12689 (allowed (org-property-get-allowed-values nil prop 'table))
12690 (existing (mapcar 'list (org-property-values prop)))
12691 (val (if allowed
12692 (org-completing-read "Value: " allowed nil 'req-match)
12693 (let (org-completion-use-ido org-completion-use-iswitchb)
12694 (org-completing-read
12695 (concat "Value " (if (and cur (string-match "\\S-" cur))
12696 (concat "[" cur "]") "")
12697 ": ")
12698 existing nil nil "" nil cur)))))
12699 (list prop (if (equal val "") cur val))))
12700 (unless (equal (org-entry-get nil property) value)
12701 (org-entry-put nil property value)))
12703 (defun org-delete-property (property)
12704 "In the current entry, delete PROPERTY."
12705 (interactive
12706 (let* ((completion-ignore-case t)
12707 (prop (org-icompleting-read
12708 "Property: " (org-entry-properties nil 'standard))))
12709 (list prop)))
12710 (message "Property %s %s" property
12711 (if (org-entry-delete nil property)
12712 "deleted"
12713 "was not present in the entry")))
12715 (defun org-delete-property-globally (property)
12716 "Remove PROPERTY globally, from all entries."
12717 (interactive
12718 (let* ((completion-ignore-case t)
12719 (prop (org-icompleting-read
12720 "Globally remove property: "
12721 (mapcar 'list (org-buffer-property-keys)))))
12722 (list prop)))
12723 (save-excursion
12724 (save-restriction
12725 (widen)
12726 (goto-char (point-min))
12727 (let ((cnt 0))
12728 (while (re-search-forward
12729 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12730 nil t)
12731 (setq cnt (1+ cnt))
12732 (replace-match ""))
12733 (message "Property \"%s\" removed from %d entries" property cnt)))))
12735 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12737 (defun org-compute-property-at-point ()
12738 "Compute the property at point.
12739 This looks for an enclosing column format, extracts the operator and
12740 then applies it to the property in the column format's scope."
12741 (interactive)
12742 (unless (org-at-property-p)
12743 (error "Not at a property"))
12744 (let ((prop (org-match-string-no-properties 2)))
12745 (org-columns-get-format-and-top-level)
12746 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12747 (error "No operator defined for property %s" prop))
12748 (org-columns-compute prop)))
12750 (defun org-property-get-allowed-values (pom property &optional table)
12751 "Get allowed values for the property PROPERTY.
12752 When TABLE is non-nil, return an alist that can directly be used for
12753 completion."
12754 (let (vals)
12755 (cond
12756 ((equal property "TODO")
12757 (setq vals (org-with-point-at pom
12758 (append org-todo-keywords-1 '("")))))
12759 ((equal property "PRIORITY")
12760 (let ((n org-lowest-priority))
12761 (while (>= n org-highest-priority)
12762 (push (char-to-string n) vals)
12763 (setq n (1- n)))))
12764 ((member property org-special-properties))
12766 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12768 (when (and vals (string-match "\\S-" vals))
12769 (setq vals (car (read-from-string (concat "(" vals ")"))))
12770 (setq vals (mapcar (lambda (x)
12771 (cond ((stringp x) x)
12772 ((numberp x) (number-to-string x))
12773 ((symbolp x) (symbol-name x))
12774 (t "???")))
12775 vals)))))
12776 (if table (mapcar 'list vals) vals)))
12778 (defun org-property-previous-allowed-value (&optional previous)
12779 "Switch to the next allowed value for this property."
12780 (interactive)
12781 (org-property-next-allowed-value t))
12783 (defun org-property-next-allowed-value (&optional previous)
12784 "Switch to the next allowed value for this property."
12785 (interactive)
12786 (unless (org-at-property-p)
12787 (error "Not at a property"))
12788 (let* ((key (match-string 2))
12789 (value (match-string 3))
12790 (allowed (or (org-property-get-allowed-values (point) key)
12791 (and (member value '("[ ]" "[-]" "[X]"))
12792 '("[ ]" "[X]"))))
12793 nval)
12794 (unless allowed
12795 (error "Allowed values for this property have not been defined"))
12796 (if previous (setq allowed (reverse allowed)))
12797 (if (member value allowed)
12798 (setq nval (car (cdr (member value allowed)))))
12799 (setq nval (or nval (car allowed)))
12800 (if (equal nval value)
12801 (error "Only one allowed value for this property"))
12802 (org-at-property-p)
12803 (replace-match (concat " :" key ": " nval) t t)
12804 (org-indent-line-function)
12805 (beginning-of-line 1)
12806 (skip-chars-forward " \t")))
12808 (defun org-find-entry-with-id (ident)
12809 "Locate the entry that contains the ID property with exact value IDENT.
12810 IDENT can be a string, a symbol or a number, this function will search for
12811 the string representation of it.
12812 Return the position where this entry starts, or nil if there is no such entry."
12813 (interactive "sID: ")
12814 (let ((id (cond
12815 ((stringp ident) ident)
12816 ((symbol-name ident) (symbol-name ident))
12817 ((numberp ident) (number-to-string ident))
12818 (t (error "IDENT %s must be a string, symbol or number" ident))))
12819 (case-fold-search nil))
12820 (save-excursion
12821 (save-restriction
12822 (widen)
12823 (goto-char (point-min))
12824 (when (re-search-forward
12825 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12826 nil t)
12827 (org-back-to-heading t)
12828 (point))))))
12830 ;;;; Timestamps
12832 (defvar org-last-changed-timestamp nil)
12833 (defvar org-last-inserted-timestamp nil
12834 "The last time stamp inserted with `org-insert-time-stamp'.")
12835 (defvar org-time-was-given) ; dynamically scoped parameter
12836 (defvar org-end-time-was-given) ; dynamically scoped parameter
12837 (defvar org-ts-what) ; dynamically scoped parameter
12839 (defun org-time-stamp (arg &optional inactive)
12840 "Prompt for a date/time and insert a time stamp.
12841 If the user specifies a time like HH:MM, or if this command is called
12842 with a prefix argument, the time stamp will contain date and time.
12843 Otherwise, only the date will be included. All parts of a date not
12844 specified by the user will be filled in from the current date/time.
12845 So if you press just return without typing anything, the time stamp
12846 will represent the current date/time. If there is already a timestamp
12847 at the cursor, it will be modified."
12848 (interactive "P")
12849 (let* ((ts nil)
12850 (default-time
12851 ;; Default time is either today, or, when entering a range,
12852 ;; the range start.
12853 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12854 (save-excursion
12855 (re-search-backward
12856 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12857 (- (point) 20) t)))
12858 (apply 'encode-time (org-parse-time-string (match-string 1)))
12859 (current-time)))
12860 (default-input (and ts (org-get-compact-tod ts)))
12861 org-time-was-given org-end-time-was-given time)
12862 (cond
12863 ((and (org-at-timestamp-p t)
12864 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12865 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12866 (insert "--")
12867 (setq time (let ((this-command this-command))
12868 (org-read-date arg 'totime nil nil
12869 default-time default-input)))
12870 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12871 ((org-at-timestamp-p t)
12872 (setq time (let ((this-command this-command))
12873 (org-read-date arg 'totime nil nil default-time default-input)))
12874 (when (org-at-timestamp-p t) ; just to get the match data
12875 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12876 (replace-match "")
12877 (setq org-last-changed-timestamp
12878 (org-insert-time-stamp
12879 time (or org-time-was-given arg)
12880 inactive nil nil (list org-end-time-was-given))))
12881 (message "Timestamp updated"))
12883 (setq time (let ((this-command this-command))
12884 (org-read-date arg 'totime nil nil default-time default-input)))
12885 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12886 nil nil (list org-end-time-was-given))))))
12888 ;; FIXME: can we use this for something else, like computing time differences?
12889 (defun org-get-compact-tod (s)
12890 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12891 (let* ((t1 (match-string 1 s))
12892 (h1 (string-to-number (match-string 2 s)))
12893 (m1 (string-to-number (match-string 3 s)))
12894 (t2 (and (match-end 4) (match-string 5 s)))
12895 (h2 (and t2 (string-to-number (match-string 6 s))))
12896 (m2 (and t2 (string-to-number (match-string 7 s))))
12897 dh dm)
12898 (if (not t2)
12900 (setq dh (- h2 h1) dm (- m2 m1))
12901 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12902 (concat t1 "+" (number-to-string dh)
12903 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12905 (defun org-time-stamp-inactive (&optional arg)
12906 "Insert an inactive time stamp.
12907 An inactive time stamp is enclosed in square brackets instead of angle
12908 brackets. It is inactive in the sense that it does not trigger agenda entries,
12909 does not link to the calendar and cannot be changed with the S-cursor keys.
12910 So these are more for recording a certain time/date."
12911 (interactive "P")
12912 (org-time-stamp arg 'inactive))
12914 (defvar org-date-ovl (org-make-overlay 1 1))
12915 (org-overlay-put org-date-ovl 'face 'org-warning)
12916 (org-detach-overlay org-date-ovl)
12918 (defvar org-ans1) ; dynamically scoped parameter
12919 (defvar org-ans2) ; dynamically scoped parameter
12921 (defvar org-plain-time-of-day-regexp) ; defined below
12923 (defvar org-overriding-default-time nil) ; dynamically scoped
12924 (defvar org-read-date-overlay nil)
12925 (defvar org-dcst nil) ; dynamically scoped
12926 (defvar org-read-date-history nil)
12927 (defvar org-read-date-final-answer nil)
12929 (defun org-read-date (&optional with-time to-time from-string prompt
12930 default-time default-input)
12931 "Read a date, possibly a time, and make things smooth for the user.
12932 The prompt will suggest to enter an ISO date, but you can also enter anything
12933 which will at least partially be understood by `parse-time-string'.
12934 Unrecognized parts of the date will default to the current day, month, year,
12935 hour and minute. If this command is called to replace a timestamp at point,
12936 of to enter the second timestamp of a range, the default time is taken from the
12937 existing stamp. For example,
12938 3-2-5 --> 2003-02-05
12939 feb 15 --> currentyear-02-15
12940 sep 12 9 --> 2009-09-12
12941 12:45 --> today 12:45
12942 22 sept 0:34 --> currentyear-09-22 0:34
12943 12 --> currentyear-currentmonth-12
12944 Fri --> nearest Friday (today or later)
12945 etc.
12947 Furthermore you can specify a relative date by giving, as the *first* thing
12948 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12949 change in days weeks, months, years.
12950 With a single plus or minus, the date is relative to today. With a double
12951 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12952 +4d --> four days from today
12953 +4 --> same as above
12954 +2w --> two weeks from today
12955 ++5 --> five days from default date
12957 The function understands only English month and weekday abbreviations,
12958 but this can be configured with the variables `parse-time-months' and
12959 `parse-time-weekdays'.
12961 While prompting, a calendar is popped up - you can also select the
12962 date with the mouse (button 1). The calendar shows a period of three
12963 months. To scroll it to other months, use the keys `>' and `<'.
12964 If you don't like the calendar, turn it off with
12965 \(setq org-read-date-popup-calendar nil)
12967 With optional argument TO-TIME, the date will immediately be converted
12968 to an internal time.
12969 With an optional argument WITH-TIME, the prompt will suggest to also
12970 insert a time. Note that when WITH-TIME is not set, you can still
12971 enter a time, and this function will inform the calling routine about
12972 this change. The calling routine may then choose to change the format
12973 used to insert the time stamp into the buffer to include the time.
12974 With optional argument FROM-STRING, read from this string instead from
12975 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12976 the time/date that is used for everything that is not specified by the
12977 user."
12978 (require 'parse-time)
12979 (let* ((org-time-stamp-rounding-minutes
12980 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12981 (org-dcst org-display-custom-times)
12982 (ct (org-current-time))
12983 (def (or org-overriding-default-time default-time ct))
12984 (defdecode (decode-time def))
12985 (dummy (progn
12986 (when (< (nth 2 defdecode) org-extend-today-until)
12987 (setcar (nthcdr 2 defdecode) -1)
12988 (setcar (nthcdr 1 defdecode) 59)
12989 (setq def (apply 'encode-time defdecode)
12990 defdecode (decode-time def)))))
12991 (calendar-frame-setup nil)
12992 (calendar-move-hook nil)
12993 (calendar-view-diary-initially-flag nil)
12994 (view-diary-entries-initially nil)
12995 (calendar-view-holidays-initially-flag nil)
12996 (view-calendar-holidays-initially nil)
12997 (timestr (format-time-string
12998 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12999 (prompt (concat (if prompt (concat prompt " ") "")
13000 (format "Date+time [%s]: " timestr)))
13001 ans (org-ans0 "") org-ans1 org-ans2 final)
13003 (cond
13004 (from-string (setq ans from-string))
13005 (org-read-date-popup-calendar
13006 (save-excursion
13007 (save-window-excursion
13008 (calendar)
13009 (calendar-forward-day (- (time-to-days def)
13010 (calendar-absolute-from-gregorian
13011 (calendar-current-date))))
13012 (org-eval-in-calendar nil t)
13013 (let* ((old-map (current-local-map))
13014 (map (copy-keymap calendar-mode-map))
13015 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13016 (org-defkey map (kbd "RET") 'org-calendar-select)
13017 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13018 'org-calendar-select-mouse)
13019 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13020 'org-calendar-select-mouse)
13021 (org-defkey minibuffer-local-map [(meta shift left)]
13022 (lambda () (interactive)
13023 (org-eval-in-calendar '(calendar-backward-month 1))))
13024 (org-defkey minibuffer-local-map [(meta shift right)]
13025 (lambda () (interactive)
13026 (org-eval-in-calendar '(calendar-forward-month 1))))
13027 (org-defkey minibuffer-local-map [(meta shift up)]
13028 (lambda () (interactive)
13029 (org-eval-in-calendar '(calendar-backward-year 1))))
13030 (org-defkey minibuffer-local-map [(meta shift down)]
13031 (lambda () (interactive)
13032 (org-eval-in-calendar '(calendar-forward-year 1))))
13033 (org-defkey minibuffer-local-map [?\e (shift left)]
13034 (lambda () (interactive)
13035 (org-eval-in-calendar '(calendar-backward-month 1))))
13036 (org-defkey minibuffer-local-map [?\e (shift right)]
13037 (lambda () (interactive)
13038 (org-eval-in-calendar '(calendar-forward-month 1))))
13039 (org-defkey minibuffer-local-map [?\e (shift up)]
13040 (lambda () (interactive)
13041 (org-eval-in-calendar '(calendar-backward-year 1))))
13042 (org-defkey minibuffer-local-map [?\e (shift down)]
13043 (lambda () (interactive)
13044 (org-eval-in-calendar '(calendar-forward-year 1))))
13045 (org-defkey minibuffer-local-map [(shift up)]
13046 (lambda () (interactive)
13047 (org-eval-in-calendar '(calendar-backward-week 1))))
13048 (org-defkey minibuffer-local-map [(shift down)]
13049 (lambda () (interactive)
13050 (org-eval-in-calendar '(calendar-forward-week 1))))
13051 (org-defkey minibuffer-local-map [(shift left)]
13052 (lambda () (interactive)
13053 (org-eval-in-calendar '(calendar-backward-day 1))))
13054 (org-defkey minibuffer-local-map [(shift right)]
13055 (lambda () (interactive)
13056 (org-eval-in-calendar '(calendar-forward-day 1))))
13057 (org-defkey minibuffer-local-map ">"
13058 (lambda () (interactive)
13059 (org-eval-in-calendar '(scroll-calendar-left 1))))
13060 (org-defkey minibuffer-local-map "<"
13061 (lambda () (interactive)
13062 (org-eval-in-calendar '(scroll-calendar-right 1))))
13063 (run-hooks 'org-read-date-minibuffer-setup-hook)
13064 (unwind-protect
13065 (progn
13066 (use-local-map map)
13067 (add-hook 'post-command-hook 'org-read-date-display)
13068 (setq org-ans0 (read-string prompt default-input
13069 'org-read-date-history nil))
13070 ;; org-ans0: from prompt
13071 ;; org-ans1: from mouse click
13072 ;; org-ans2: from calendar motion
13073 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13074 (remove-hook 'post-command-hook 'org-read-date-display)
13075 (use-local-map old-map)
13076 (when org-read-date-overlay
13077 (org-delete-overlay org-read-date-overlay)
13078 (setq org-read-date-overlay nil)))))))
13080 (t ; Naked prompt only
13081 (unwind-protect
13082 (setq ans (read-string prompt default-input
13083 'org-read-date-history timestr))
13084 (when org-read-date-overlay
13085 (org-delete-overlay org-read-date-overlay)
13086 (setq org-read-date-overlay nil)))))
13088 (setq final (org-read-date-analyze ans def defdecode))
13089 (setq org-read-date-final-answer ans)
13091 (if to-time
13092 (apply 'encode-time final)
13093 (if (and (boundp 'org-time-was-given) org-time-was-given)
13094 (format "%04d-%02d-%02d %02d:%02d"
13095 (nth 5 final) (nth 4 final) (nth 3 final)
13096 (nth 2 final) (nth 1 final))
13097 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13099 (defvar def)
13100 (defvar defdecode)
13101 (defvar with-time)
13102 (defvar org-read-date-analyze-futurep nil)
13103 (defun org-read-date-display ()
13104 "Display the current date prompt interpretation in the minibuffer."
13105 (when org-read-date-display-live
13106 (when org-read-date-overlay
13107 (org-delete-overlay org-read-date-overlay))
13108 (let ((p (point)))
13109 (end-of-line 1)
13110 (while (not (equal (buffer-substring
13111 (max (point-min) (- (point) 4)) (point))
13112 " "))
13113 (insert " "))
13114 (goto-char p))
13115 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13116 " " (or org-ans1 org-ans2)))
13117 (org-end-time-was-given nil)
13118 (f (org-read-date-analyze ans def defdecode))
13119 (fmts (if org-dcst
13120 org-time-stamp-custom-formats
13121 org-time-stamp-formats))
13122 (fmt (if (or with-time
13123 (and (boundp 'org-time-was-given) org-time-was-given))
13124 (cdr fmts)
13125 (car fmts)))
13126 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13127 (when (and org-end-time-was-given
13128 (string-match org-plain-time-of-day-regexp txt))
13129 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13130 org-end-time-was-given
13131 (substring txt (match-end 0)))))
13132 (when org-read-date-analyze-futurep
13133 (setq txt (concat txt " (=>F)")))
13134 (setq org-read-date-overlay
13135 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13136 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13138 (defun org-read-date-analyze (ans def defdecode)
13139 "Analyse the combined answer of the date prompt."
13140 ;; FIXME: cleanup and comment
13141 (let (delta deltan deltaw deltadef year month day
13142 hour minute second wday pm h2 m2 tl wday1
13143 iso-year iso-weekday iso-week iso-year iso-date futurep)
13144 (setq org-read-date-analyze-futurep nil)
13145 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13146 (setq ans "+0"))
13148 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13149 (setq ans (replace-match "" t t ans)
13150 deltan (car delta)
13151 deltaw (nth 1 delta)
13152 deltadef (nth 2 delta)))
13154 ;; Check if there is an iso week date in there
13155 ;; If yes, store the info and postpone interpreting it until the rest
13156 ;; of the parsing is done
13157 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13158 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13159 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13160 iso-week (string-to-number (match-string 2 ans)))
13161 (setq ans (replace-match "" t t ans)))
13163 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13164 (when (string-match
13165 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13166 (setq year (if (match-end 2)
13167 (string-to-number (match-string 2 ans))
13168 (string-to-number (format-time-string "%Y")))
13169 month (string-to-number (match-string 3 ans))
13170 day (string-to-number (match-string 4 ans)))
13171 (if (< year 100) (setq year (+ 2000 year)))
13172 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13173 t nil ans)))
13174 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13175 ;; If there is a time with am/pm, and *no* time without it, we convert
13176 ;; so that matching will be successful.
13177 (loop for i from 1 to 2 do ; twice, for end time as well
13178 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13179 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13180 (setq hour (string-to-number (match-string 1 ans))
13181 minute (if (match-end 3)
13182 (string-to-number (match-string 3 ans))
13184 pm (equal ?p
13185 (string-to-char (downcase (match-string 4 ans)))))
13186 (if (and (= hour 12) (not pm))
13187 (setq hour 0)
13188 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13189 (setq ans (replace-match (format "%02d:%02d" hour minute)
13190 t t ans))))
13192 ;; Check if a time range is given as a duration
13193 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13194 (setq hour (string-to-number (match-string 1 ans))
13195 h2 (+ hour (string-to-number (match-string 3 ans)))
13196 minute (string-to-number (match-string 2 ans))
13197 m2 (+ minute (if (match-end 5) (string-to-number
13198 (match-string 5 ans))0)))
13199 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13200 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13201 t t ans)))
13203 ;; Check if there is a time range
13204 (when (boundp 'org-end-time-was-given)
13205 (setq org-time-was-given nil)
13206 (when (and (string-match org-plain-time-of-day-regexp ans)
13207 (match-end 8))
13208 (setq org-end-time-was-given (match-string 8 ans))
13209 (setq ans (concat (substring ans 0 (match-beginning 7))
13210 (substring ans (match-end 7))))))
13212 (setq tl (parse-time-string ans)
13213 day (or (nth 3 tl) (nth 3 defdecode))
13214 month (or (nth 4 tl)
13215 (if (and org-read-date-prefer-future
13216 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13217 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13218 (nth 4 defdecode)))
13219 year (or (nth 5 tl)
13220 (if (and org-read-date-prefer-future
13221 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13222 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13223 (nth 5 defdecode)))
13224 hour (or (nth 2 tl) (nth 2 defdecode))
13225 minute (or (nth 1 tl) (nth 1 defdecode))
13226 second (or (nth 0 tl) 0)
13227 wday (nth 6 tl))
13229 (when (and (eq org-read-date-prefer-future 'time)
13230 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13231 (equal day (nth 3 defdecode))
13232 (equal month (nth 4 defdecode))
13233 (equal year (nth 5 defdecode))
13234 (nth 2 tl)
13235 (or (< (nth 2 tl) (nth 2 defdecode))
13236 (and (= (nth 2 tl) (nth 2 defdecode))
13237 (nth 1 tl)
13238 (< (nth 1 tl) (nth 1 defdecode)))))
13239 (setq day (1+ day)
13240 futurep t))
13242 ;; Special date definitions below
13243 (cond
13244 (iso-week
13245 ;; There was an iso week
13246 (setq futurep nil)
13247 (setq year (or iso-year year)
13248 day (or iso-weekday wday 1)
13249 wday nil ; to make sure that the trigger below does not match
13250 iso-date (calendar-gregorian-from-absolute
13251 (calendar-absolute-from-iso
13252 (list iso-week day year))))
13253 ; FIXME: Should we also push ISO weeks into the future?
13254 ; (when (and org-read-date-prefer-future
13255 ; (not iso-year)
13256 ; (< (calendar-absolute-from-gregorian iso-date)
13257 ; (time-to-days (current-time))))
13258 ; (setq year (1+ year)
13259 ; iso-date (calendar-gregorian-from-absolute
13260 ; (calendar-absolute-from-iso
13261 ; (list iso-week day year)))))
13262 (setq month (car iso-date)
13263 year (nth 2 iso-date)
13264 day (nth 1 iso-date)))
13265 (deltan
13266 (setq futurep nil)
13267 (unless deltadef
13268 (let ((now (decode-time (current-time))))
13269 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13270 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13271 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13272 ((equal deltaw "m") (setq month (+ month deltan)))
13273 ((equal deltaw "y") (setq year (+ year deltan)))))
13274 ((and wday (not (nth 3 tl)))
13275 (setq futurep nil)
13276 ;; Weekday was given, but no day, so pick that day in the week
13277 ;; on or after the derived date.
13278 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13279 (unless (equal wday wday1)
13280 (setq day (+ day (% (- wday wday1 -7) 7))))))
13281 (if (and (boundp 'org-time-was-given)
13282 (nth 2 tl))
13283 (setq org-time-was-given t))
13284 (if (< year 100) (setq year (+ 2000 year)))
13285 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13286 (setq org-read-date-analyze-futurep futurep)
13287 (list second minute hour day month year)))
13289 (defvar parse-time-weekdays)
13291 (defun org-read-date-get-relative (s today default)
13292 "Check string S for special relative date string.
13293 TODAY and DEFAULT are internal times, for today and for a default.
13294 Return shift list (N what def-flag)
13295 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13296 N is the number of WHATs to shift.
13297 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13298 the DEFAULT date rather than TODAY."
13299 (when (and
13300 (string-match
13301 (concat
13302 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13303 "\\([0-9]+\\)?"
13304 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13305 "\\([ \t]\\|$\\)") s)
13306 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13307 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13308 (string-to-char (substring (match-string 1 s) -1))
13309 ?+))
13310 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13311 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13312 (what (if (match-end 3) (match-string 3 s) "d"))
13313 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13314 (date (if rel default today))
13315 (wday (nth 6 (decode-time date)))
13316 delta)
13317 (if wday1
13318 (progn
13319 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13320 (if (= dir ?-) (setq delta (- delta 7)))
13321 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13322 (list delta "d" rel))
13323 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13325 (defun org-eval-in-calendar (form &optional keepdate)
13326 "Eval FORM in the calendar window and return to current window.
13327 Also, store the cursor date in variable org-ans2."
13328 (let ((sf (selected-frame))
13329 (sw (selected-window)))
13330 (select-window (get-buffer-window "*Calendar*" t))
13331 (eval form)
13332 (when (and (not keepdate) (calendar-cursor-to-date))
13333 (let* ((date (calendar-cursor-to-date))
13334 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13335 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13336 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13337 (select-window sw)
13338 (org-select-frame-set-input-focus sf)))
13340 (defun org-calendar-select ()
13341 "Return to `org-read-date' with the date currently selected.
13342 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13343 (interactive)
13344 (when (calendar-cursor-to-date)
13345 (let* ((date (calendar-cursor-to-date))
13346 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13347 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13348 (if (active-minibuffer-window) (exit-minibuffer))))
13350 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13351 "Insert a date stamp for the date given by the internal TIME.
13352 WITH-HM means, use the stamp format that includes the time of the day.
13353 INACTIVE means use square brackets instead of angular ones, so that the
13354 stamp will not contribute to the agenda.
13355 PRE and POST are optional strings to be inserted before and after the
13356 stamp.
13357 The command returns the inserted time stamp."
13358 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13359 stamp)
13360 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13361 (insert-before-markers (or pre ""))
13362 (insert-before-markers (setq stamp (format-time-string fmt time)))
13363 (when (listp extra)
13364 (setq extra (car extra))
13365 (if (and (stringp extra)
13366 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13367 (setq extra (format "-%02d:%02d"
13368 (string-to-number (match-string 1 extra))
13369 (string-to-number (match-string 2 extra))))
13370 (setq extra nil)))
13371 (when extra
13372 (backward-char 1)
13373 (insert-before-markers extra)
13374 (forward-char 1))
13375 (insert-before-markers (or post ""))
13376 (setq org-last-inserted-timestamp stamp)))
13378 (defun org-toggle-time-stamp-overlays ()
13379 "Toggle the use of custom time stamp formats."
13380 (interactive)
13381 (setq org-display-custom-times (not org-display-custom-times))
13382 (unless org-display-custom-times
13383 (let ((p (point-min)) (bmp (buffer-modified-p)))
13384 (while (setq p (next-single-property-change p 'display))
13385 (if (and (get-text-property p 'display)
13386 (eq (get-text-property p 'face) 'org-date))
13387 (remove-text-properties
13388 p (setq p (next-single-property-change p 'display))
13389 '(display t))))
13390 (set-buffer-modified-p bmp)))
13391 (if (featurep 'xemacs)
13392 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13393 (org-restart-font-lock)
13394 (setq org-table-may-need-update t)
13395 (if org-display-custom-times
13396 (message "Time stamps are overlayed with custom format")
13397 (message "Time stamp overlays removed")))
13399 (defun org-display-custom-time (beg end)
13400 "Overlay modified time stamp format over timestamp between BEG and END."
13401 (let* ((ts (buffer-substring beg end))
13402 t1 w1 with-hm tf time str w2 (off 0))
13403 (save-match-data
13404 (setq t1 (org-parse-time-string ts t))
13405 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13406 (setq off (- (match-end 0) (match-beginning 0)))))
13407 (setq end (- end off))
13408 (setq w1 (- end beg)
13409 with-hm (and (nth 1 t1) (nth 2 t1))
13410 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13411 time (org-fix-decoded-time t1)
13412 str (org-add-props
13413 (format-time-string
13414 (substring tf 1 -1) (apply 'encode-time time))
13415 nil 'mouse-face 'highlight)
13416 w2 (length str))
13417 (if (not (= w2 w1))
13418 (add-text-properties (1+ beg) (+ 2 beg)
13419 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13420 (if (featurep 'xemacs)
13421 (progn
13422 (put-text-property beg end 'invisible t)
13423 (put-text-property beg end 'end-glyph (make-glyph str)))
13424 (put-text-property beg end 'display str))))
13426 (defun org-translate-time (string)
13427 "Translate all timestamps in STRING to custom format.
13428 But do this only if the variable `org-display-custom-times' is set."
13429 (when org-display-custom-times
13430 (save-match-data
13431 (let* ((start 0)
13432 (re org-ts-regexp-both)
13433 t1 with-hm inactive tf time str beg end)
13434 (while (setq start (string-match re string start))
13435 (setq beg (match-beginning 0)
13436 end (match-end 0)
13437 t1 (save-match-data
13438 (org-parse-time-string (substring string beg end) t))
13439 with-hm (and (nth 1 t1) (nth 2 t1))
13440 inactive (equal (substring string beg (1+ beg)) "[")
13441 tf (funcall (if with-hm 'cdr 'car)
13442 org-time-stamp-custom-formats)
13443 time (org-fix-decoded-time t1)
13444 str (format-time-string
13445 (concat
13446 (if inactive "[" "<") (substring tf 1 -1)
13447 (if inactive "]" ">"))
13448 (apply 'encode-time time))
13449 string (replace-match str t t string)
13450 start (+ start (length str)))))))
13451 string)
13453 (defun org-fix-decoded-time (time)
13454 "Set 0 instead of nil for the first 6 elements of time.
13455 Don't touch the rest."
13456 (let ((n 0))
13457 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13459 (defun org-days-to-time (timestamp-string)
13460 "Difference between TIMESTAMP-STRING and now in days."
13461 (- (time-to-days (org-time-string-to-time timestamp-string))
13462 (time-to-days (current-time))))
13464 (defun org-deadline-close (timestamp-string &optional ndays)
13465 "Is the time in TIMESTAMP-STRING close to the current date?"
13466 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13467 (and (< (org-days-to-time timestamp-string) ndays)
13468 (not (org-entry-is-done-p))))
13470 (defun org-get-wdays (ts)
13471 "Get the deadline lead time appropriate for timestring TS."
13472 (cond
13473 ((<= org-deadline-warning-days 0)
13474 ;; 0 or negative, enforce this value no matter what
13475 (- org-deadline-warning-days))
13476 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13477 ;; lead time is specified.
13478 (floor (* (string-to-number (match-string 1 ts))
13479 (cdr (assoc (match-string 2 ts)
13480 '(("d" . 1) ("w" . 7)
13481 ("m" . 30.4) ("y" . 365.25)))))))
13482 ;; go for the default.
13483 (t org-deadline-warning-days)))
13485 (defun org-calendar-select-mouse (ev)
13486 "Return to `org-read-date' with the date currently selected.
13487 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13488 (interactive "e")
13489 (mouse-set-point ev)
13490 (when (calendar-cursor-to-date)
13491 (let* ((date (calendar-cursor-to-date))
13492 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13493 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13494 (if (active-minibuffer-window) (exit-minibuffer))))
13496 (defun org-check-deadlines (ndays)
13497 "Check if there are any deadlines due or past due.
13498 A deadline is considered due if it happens within `org-deadline-warning-days'
13499 days from today's date. If the deadline appears in an entry marked DONE,
13500 it is not shown. The prefix arg NDAYS can be used to test that many
13501 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13502 (interactive "P")
13503 (let* ((org-warn-days
13504 (cond
13505 ((equal ndays '(4)) 100000)
13506 (ndays (prefix-numeric-value ndays))
13507 (t (abs org-deadline-warning-days))))
13508 (case-fold-search nil)
13509 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13510 (callback
13511 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13513 (message "%d deadlines past-due or due within %d days"
13514 (org-occur regexp nil callback)
13515 org-warn-days)))
13517 (defun org-check-before-date (date)
13518 "Check if there are deadlines or scheduled entries before DATE."
13519 (interactive (list (org-read-date)))
13520 (let ((case-fold-search nil)
13521 (regexp (concat "\\<\\(" org-deadline-string
13522 "\\|" org-scheduled-string
13523 "\\) *<\\([^>]+\\)>"))
13524 (callback
13525 (lambda () (time-less-p
13526 (org-time-string-to-time (match-string 2))
13527 (org-time-string-to-time date)))))
13528 (message "%d entries before %s"
13529 (org-occur regexp nil callback) date)))
13531 (defun org-check-after-date (date)
13532 "Check if there are deadlines or scheduled entries after DATE."
13533 (interactive (list (org-read-date)))
13534 (let ((case-fold-search nil)
13535 (regexp (concat "\\<\\(" org-deadline-string
13536 "\\|" org-scheduled-string
13537 "\\) *<\\([^>]+\\)>"))
13538 (callback
13539 (lambda () (not
13540 (time-less-p
13541 (org-time-string-to-time (match-string 2))
13542 (org-time-string-to-time date))))))
13543 (message "%d entries after %s"
13544 (org-occur regexp nil callback) date)))
13546 (defun org-evaluate-time-range (&optional to-buffer)
13547 "Evaluate a time range by computing the difference between start and end.
13548 Normally the result is just printed in the echo area, but with prefix arg
13549 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13550 If the time range is actually in a table, the result is inserted into the
13551 next column.
13552 For time difference computation, a year is assumed to be exactly 365
13553 days in order to avoid rounding problems."
13554 (interactive "P")
13556 (org-clock-update-time-maybe)
13557 (save-excursion
13558 (unless (org-at-date-range-p t)
13559 (goto-char (point-at-bol))
13560 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13561 (if (not (org-at-date-range-p t))
13562 (error "Not at a time-stamp range, and none found in current line")))
13563 (let* ((ts1 (match-string 1))
13564 (ts2 (match-string 2))
13565 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13566 (match-end (match-end 0))
13567 (time1 (org-time-string-to-time ts1))
13568 (time2 (org-time-string-to-time ts2))
13569 (t1 (org-float-time time1))
13570 (t2 (org-float-time time2))
13571 (diff (abs (- t2 t1)))
13572 (negative (< (- t2 t1) 0))
13573 ;; (ys (floor (* 365 24 60 60)))
13574 (ds (* 24 60 60))
13575 (hs (* 60 60))
13576 (fy "%dy %dd %02d:%02d")
13577 (fy1 "%dy %dd")
13578 (fd "%dd %02d:%02d")
13579 (fd1 "%dd")
13580 (fh "%02d:%02d")
13581 y d h m align)
13582 (if havetime
13583 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13585 d (floor (/ diff ds)) diff (mod diff ds)
13586 h (floor (/ diff hs)) diff (mod diff hs)
13587 m (floor (/ diff 60)))
13588 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13590 d (floor (+ (/ diff ds) 0.5))
13591 h 0 m 0))
13592 (if (not to-buffer)
13593 (message "%s" (org-make-tdiff-string y d h m))
13594 (if (org-at-table-p)
13595 (progn
13596 (goto-char match-end)
13597 (setq align t)
13598 (and (looking-at " *|") (goto-char (match-end 0))))
13599 (goto-char match-end))
13600 (if (looking-at
13601 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13602 (replace-match ""))
13603 (if negative (insert " -"))
13604 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13605 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13606 (insert " " (format fh h m))))
13607 (if align (org-table-align))
13608 (message "Time difference inserted")))))
13610 (defun org-make-tdiff-string (y d h m)
13611 (let ((fmt "")
13612 (l nil))
13613 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13614 l (push y l)))
13615 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13616 l (push d l)))
13617 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13618 l (push h l)))
13619 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13620 l (push m l)))
13621 (apply 'format fmt (nreverse l))))
13623 (defun org-time-string-to-time (s)
13624 (apply 'encode-time (org-parse-time-string s)))
13625 (defun org-time-string-to-seconds (s)
13626 (org-float-time (org-time-string-to-time s)))
13628 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13629 "Convert a time stamp to an absolute day number.
13630 If there is a specifyer for a cyclic time stamp, get the closest date to
13631 DAYNR.
13632 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13633 the variable date is bound by the calendar when this is called."
13634 (cond
13635 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13636 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13637 daynr
13638 (+ daynr 1000)))
13639 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13640 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13641 (time-to-days (current-time))) (match-string 0 s)
13642 prefer show-all))
13643 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13645 (defun org-days-to-iso-week (days)
13646 "Return the iso week number."
13647 (require 'cal-iso)
13648 (car (calendar-iso-from-absolute days)))
13650 (defun org-small-year-to-year (year)
13651 "Convert 2-digit years into 4-digit years.
13652 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13653 The year 2000 cannot be abbreviated. Any year larger than 99
13654 is returned unchanged."
13655 (if (< year 38)
13656 (setq year (+ 2000 year))
13657 (if (< year 100)
13658 (setq year (+ 1900 year))))
13659 year)
13661 (defun org-time-from-absolute (d)
13662 "Return the time corresponding to date D.
13663 D may be an absolute day number, or a calendar-type list (month day year)."
13664 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13665 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13667 (defun org-calendar-holiday ()
13668 "List of holidays, for Diary display in Org-mode."
13669 (require 'holidays)
13670 (let ((hl (funcall
13671 (if (fboundp 'calendar-check-holidays)
13672 'calendar-check-holidays 'check-calendar-holidays) date)))
13673 (if hl (mapconcat 'identity hl "; "))))
13675 (defun org-diary-sexp-entry (sexp entry date)
13676 "Process a SEXP diary ENTRY for DATE."
13677 (require 'diary-lib)
13678 (let ((result (if calendar-debug-sexp
13679 (let ((stack-trace-on-error t))
13680 (eval (car (read-from-string sexp))))
13681 (condition-case nil
13682 (eval (car (read-from-string sexp)))
13683 (error
13684 (beep)
13685 (message "Bad sexp at line %d in %s: %s"
13686 (org-current-line)
13687 (buffer-file-name) sexp)
13688 (sleep-for 2))))))
13689 (cond ((stringp result) result)
13690 ((and (consp result)
13691 (stringp (cdr result))) (cdr result))
13692 (result entry)
13693 (t nil))))
13695 (defun org-diary-to-ical-string (frombuf)
13696 "Get iCalendar entries from diary entries in buffer FROMBUF.
13697 This uses the icalendar.el library."
13698 (let* ((tmpdir (if (featurep 'xemacs)
13699 (temp-directory)
13700 temporary-file-directory))
13701 (tmpfile (make-temp-name
13702 (expand-file-name "orgics" tmpdir)))
13703 buf rtn b e)
13704 (with-current-buffer frombuf
13705 (icalendar-export-region (point-min) (point-max) tmpfile)
13706 (setq buf (find-buffer-visiting tmpfile))
13707 (set-buffer buf)
13708 (goto-char (point-min))
13709 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13710 (setq b (match-beginning 0)))
13711 (goto-char (point-max))
13712 (if (re-search-backward "^END:VEVENT" nil t)
13713 (setq e (match-end 0)))
13714 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13715 (kill-buffer buf)
13716 (delete-file tmpfile)
13717 rtn))
13719 (defun org-closest-date (start current change prefer show-all)
13720 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13721 When PREFER is `past' return a date that is either CURRENT or past.
13722 When PREFER is `future', return a date that is either CURRENT or future.
13723 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13724 ;; Make the proper lists from the dates
13725 (catch 'exit
13726 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13727 dn dw sday cday n1 n2 n0
13728 d m y y1 y2 date1 date2 nmonths nm ny m2)
13730 (setq start (org-date-to-gregorian start)
13731 current (org-date-to-gregorian
13732 (if show-all
13733 current
13734 (time-to-days (current-time))))
13735 sday (calendar-absolute-from-gregorian start)
13736 cday (calendar-absolute-from-gregorian current))
13738 (if (<= cday sday) (throw 'exit sday))
13740 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13741 (setq dn (string-to-number (match-string 1 change))
13742 dw (cdr (assoc (match-string 2 change) a1)))
13743 (error "Invalid change specifyer: %s" change))
13744 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13745 (cond
13746 ((eq dw 'day)
13747 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13748 n2 (+ n1 dn)))
13749 ((eq dw 'year)
13750 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13751 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13752 (setq date1 (list m d y1)
13753 n1 (calendar-absolute-from-gregorian date1)
13754 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13755 n2 (calendar-absolute-from-gregorian date2)))
13756 ((eq dw 'month)
13757 ;; approx number of month between the two dates
13758 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13759 ;; How often does dn fit in there?
13760 (setq d (nth 1 start) m (car start) y (nth 2 start)
13761 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13762 m (+ m nm)
13763 ny (floor (/ m 12))
13764 y (+ y ny)
13765 m (- m (* ny 12)))
13766 (while (> m 12) (setq m (- m 12) y (1+ y)))
13767 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13768 (setq m2 (+ m dn) y2 y)
13769 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13770 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13771 (while (<= n2 cday)
13772 (setq n1 n2 m m2 y y2)
13773 (setq m2 (+ m dn) y2 y)
13774 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13775 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13776 ;; Make sure n1 is the earlier date
13777 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13778 (if show-all
13779 (cond
13780 ((eq prefer 'past) (if (= cday n2) n2 n1))
13781 ((eq prefer 'future) (if (= cday n1) n1 n2))
13782 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13783 (cond
13784 ((eq prefer 'past) (if (= cday n2) n2 n1))
13785 ((eq prefer 'future) (if (= cday n1) n1 n2))
13786 (t (if (= cday n1) n1 n2)))))))
13788 (defun org-date-to-gregorian (date)
13789 "Turn any specification of DATE into a gregorian date for the calendar."
13790 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13791 ((and (listp date) (= (length date) 3)) date)
13792 ((stringp date)
13793 (setq date (org-parse-time-string date))
13794 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13795 ((listp date)
13796 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13798 (defun org-parse-time-string (s &optional nodefault)
13799 "Parse the standard Org-mode time string.
13800 This should be a lot faster than the normal `parse-time-string'.
13801 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13802 hour and minute fields will be nil if not given."
13803 (if (string-match org-ts-regexp0 s)
13804 (list 0
13805 (if (or (match-beginning 8) (not nodefault))
13806 (string-to-number (or (match-string 8 s) "0")))
13807 (if (or (match-beginning 7) (not nodefault))
13808 (string-to-number (or (match-string 7 s) "0")))
13809 (string-to-number (match-string 4 s))
13810 (string-to-number (match-string 3 s))
13811 (string-to-number (match-string 2 s))
13812 nil nil nil)
13813 (error "Not a standard Org-mode time string: %s" s)))
13815 (defun org-timestamp-up (&optional arg)
13816 "Increase the date item at the cursor by one.
13817 If the cursor is on the year, change the year. If it is on the month or
13818 the day, change that.
13819 With prefix ARG, change by that many units."
13820 (interactive "p")
13821 (org-timestamp-change (prefix-numeric-value arg)))
13823 (defun org-timestamp-down (&optional arg)
13824 "Decrease the date item at the cursor by one.
13825 If the cursor is on the year, change the year. If it is on the month or
13826 the day, change that.
13827 With prefix ARG, change by that many units."
13828 (interactive "p")
13829 (org-timestamp-change (- (prefix-numeric-value arg))))
13831 (defun org-timestamp-up-day (&optional arg)
13832 "Increase the date in the time stamp by one day.
13833 With prefix ARG, change that many days."
13834 (interactive "p")
13835 (if (and (not (org-at-timestamp-p t))
13836 (org-on-heading-p))
13837 (org-todo 'up)
13838 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13840 (defun org-timestamp-down-day (&optional arg)
13841 "Decrease the date in the time stamp by one day.
13842 With prefix ARG, change that many days."
13843 (interactive "p")
13844 (if (and (not (org-at-timestamp-p t))
13845 (org-on-heading-p))
13846 (org-todo 'down)
13847 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13849 (defun org-at-timestamp-p (&optional inactive-ok)
13850 "Determine if the cursor is in or at a timestamp."
13851 (interactive)
13852 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13853 (pos (point))
13854 (ans (or (looking-at tsr)
13855 (save-excursion
13856 (skip-chars-backward "^[<\n\r\t")
13857 (if (> (point) (point-min)) (backward-char 1))
13858 (and (looking-at tsr)
13859 (> (- (match-end 0) pos) -1))))))
13860 (and ans
13861 (boundp 'org-ts-what)
13862 (setq org-ts-what
13863 (cond
13864 ((= pos (match-beginning 0)) 'bracket)
13865 ((= pos (1- (match-end 0))) 'bracket)
13866 ((org-pos-in-match-range pos 2) 'year)
13867 ((org-pos-in-match-range pos 3) 'month)
13868 ((org-pos-in-match-range pos 7) 'hour)
13869 ((org-pos-in-match-range pos 8) 'minute)
13870 ((or (org-pos-in-match-range pos 4)
13871 (org-pos-in-match-range pos 5)) 'day)
13872 ((and (> pos (or (match-end 8) (match-end 5)))
13873 (< pos (match-end 0)))
13874 (- pos (or (match-end 8) (match-end 5))))
13875 (t 'day))))
13876 ans))
13878 (defun org-toggle-timestamp-type ()
13879 "Toggle the type (<active> or [inactive]) of a time stamp."
13880 (interactive)
13881 (when (org-at-timestamp-p t)
13882 (let ((beg (match-beginning 0)) (end (match-end 0))
13883 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13884 (save-excursion
13885 (goto-char beg)
13886 (while (re-search-forward "[][<>]" end t)
13887 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13888 t t)))
13889 (message "Timestamp is now %sactive"
13890 (if (equal (char-after beg) ?<) "" "in")))))
13892 (defun org-timestamp-change (n &optional what)
13893 "Change the date in the time stamp at point.
13894 The date will be changed by N times WHAT. WHAT can be `day', `month',
13895 `year', `minute', `second'. If WHAT is not given, the cursor position
13896 in the timestamp determines what will be changed."
13897 (let ((pos (point))
13898 with-hm inactive
13899 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13900 org-ts-what
13901 extra rem
13902 ts time time0)
13903 (if (not (org-at-timestamp-p t))
13904 (error "Not at a timestamp"))
13905 (if (and (not what) (eq org-ts-what 'bracket))
13906 (org-toggle-timestamp-type)
13907 (if (and (not what) (not (eq org-ts-what 'day))
13908 org-display-custom-times
13909 (get-text-property (point) 'display)
13910 (not (get-text-property (1- (point)) 'display)))
13911 (setq org-ts-what 'day))
13912 (setq org-ts-what (or what org-ts-what)
13913 inactive (= (char-after (match-beginning 0)) ?\[)
13914 ts (match-string 0))
13915 (replace-match "")
13916 (if (string-match
13917 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13919 (setq extra (match-string 1 ts)))
13920 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13921 (setq with-hm t))
13922 (setq time0 (org-parse-time-string ts))
13923 (when (and (eq org-ts-what 'minute)
13924 (eq current-prefix-arg nil))
13925 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13926 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13927 (setcar (cdr time0) (+ (nth 1 time0)
13928 (if (> n 0) (- rem) (- dm rem))))))
13929 (setq time
13930 (encode-time (or (car time0) 0)
13931 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13932 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13933 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13934 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13935 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13936 (nthcdr 6 time0)))
13937 (when (and (member org-ts-what '(hour minute))
13938 extra
13939 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13940 (setq extra (org-modify-ts-extra
13941 extra
13942 (if (eq org-ts-what 'hour) 2 5)
13943 n dm)))
13944 (when (integerp org-ts-what)
13945 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13946 (if (eq what 'calendar)
13947 (let ((cal-date (org-get-date-from-calendar)))
13948 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13949 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13950 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13951 (setcar time0 (or (car time0) 0))
13952 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13953 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13954 (setq time (apply 'encode-time time0))))
13955 (setq org-last-changed-timestamp
13956 (org-insert-time-stamp time with-hm inactive nil nil extra))
13957 (org-clock-update-time-maybe)
13958 (goto-char pos)
13959 ;; Try to recenter the calendar window, if any
13960 (if (and org-calendar-follow-timestamp-change
13961 (get-buffer-window "*Calendar*" t)
13962 (memq org-ts-what '(day month year)))
13963 (org-recenter-calendar (time-to-days time))))))
13965 (defun org-modify-ts-extra (s pos n dm)
13966 "Change the different parts of the lead-time and repeat fields in timestamp."
13967 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13968 ng h m new rem)
13969 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13970 (cond
13971 ((or (org-pos-in-match-range pos 2)
13972 (org-pos-in-match-range pos 3))
13973 (setq m (string-to-number (match-string 3 s))
13974 h (string-to-number (match-string 2 s)))
13975 (if (org-pos-in-match-range pos 2)
13976 (setq h (+ h n))
13977 (setq n (* dm (org-no-warnings (signum n))))
13978 (when (not (= 0 (setq rem (% m dm))))
13979 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13980 (setq m (+ m n)))
13981 (if (< m 0) (setq m (+ m 60) h (1- h)))
13982 (if (> m 59) (setq m (- m 60) h (1+ h)))
13983 (setq h (min 24 (max 0 h)))
13984 (setq ng 1 new (format "-%02d:%02d" h m)))
13985 ((org-pos-in-match-range pos 6)
13986 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13987 ((org-pos-in-match-range pos 5)
13988 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13990 ((org-pos-in-match-range pos 9)
13991 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13992 ((org-pos-in-match-range pos 8)
13993 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13995 (when ng
13996 (setq s (concat
13997 (substring s 0 (match-beginning ng))
13999 (substring s (match-end ng))))))
14002 (defun org-recenter-calendar (date)
14003 "If the calendar is visible, recenter it to DATE."
14004 (let* ((win (selected-window))
14005 (cwin (get-buffer-window "*Calendar*" t))
14006 (calendar-move-hook nil))
14007 (when cwin
14008 (select-window cwin)
14009 (calendar-goto-date (if (listp date) date
14010 (calendar-gregorian-from-absolute date)))
14011 (select-window win))))
14013 (defun org-goto-calendar (&optional arg)
14014 "Go to the Emacs calendar at the current date.
14015 If there is a time stamp in the current line, go to that date.
14016 A prefix ARG can be used to force the current date."
14017 (interactive "P")
14018 (let ((tsr org-ts-regexp) diff
14019 (calendar-move-hook nil)
14020 (calendar-view-holidays-initially-flag nil)
14021 (view-calendar-holidays-initially nil)
14022 (calendar-view-diary-initially-flag nil)
14023 (view-diary-entries-initially nil))
14024 (if (or (org-at-timestamp-p)
14025 (save-excursion
14026 (beginning-of-line 1)
14027 (looking-at (concat ".*" tsr))))
14028 (let ((d1 (time-to-days (current-time)))
14029 (d2 (time-to-days
14030 (org-time-string-to-time (match-string 1)))))
14031 (setq diff (- d2 d1))))
14032 (calendar)
14033 (calendar-goto-today)
14034 (if (and diff (not arg)) (calendar-forward-day diff))))
14036 (defun org-get-date-from-calendar ()
14037 "Return a list (month day year) of date at point in calendar."
14038 (with-current-buffer "*Calendar*"
14039 (save-match-data
14040 (calendar-cursor-to-date))))
14042 (defun org-date-from-calendar ()
14043 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14044 If there is already a time stamp at the cursor position, update it."
14045 (interactive)
14046 (if (org-at-timestamp-p t)
14047 (org-timestamp-change 0 'calendar)
14048 (let ((cal-date (org-get-date-from-calendar)))
14049 (org-insert-time-stamp
14050 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14052 (defun org-minutes-to-hh:mm-string (m)
14053 "Compute H:MM from a number of minutes."
14054 (let ((h (/ m 60)))
14055 (setq m (- m (* 60 h)))
14056 (format org-time-clocksum-format h m)))
14058 (defun org-hh:mm-string-to-minutes (s)
14059 "Convert a string H:MM to a number of minutes.
14060 If the string is just a number, interpret it as minutes.
14061 In fact, the first hh:mm or number in the string will be taken,
14062 there can be extra stuff in the string.
14063 If no number is found, the return value is 0."
14064 (cond
14065 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14066 (+ (* (string-to-number (match-string 1 s)) 60)
14067 (string-to-number (match-string 2 s))))
14068 ((string-match "\\([0-9]+\\)" s)
14069 (string-to-number (match-string 1 s)))
14070 (t 0)))
14072 ;;;; Files
14074 (defun org-save-all-org-buffers ()
14075 "Save all Org-mode buffers without user confirmation."
14076 (interactive)
14077 (message "Saving all Org-mode buffers...")
14078 (save-some-buffers t 'org-mode-p)
14079 (when (featurep 'org-id) (org-id-locations-save))
14080 (message "Saving all Org-mode buffers... done"))
14082 (defun org-revert-all-org-buffers ()
14083 "Revert all Org-mode buffers.
14084 Prompt for confirmation when there are unsaved changes.
14085 Be sure you know what you are doing before letting this function
14086 overwrite your changes.
14088 This function is useful in a setup where one tracks org files
14089 with a version control system, to revert on one machine after pulling
14090 changes from another. I believe the procedure must be like this:
14092 1. M-x org-save-all-org-buffers
14093 2. Pull changes from the other machine, resolve conflicts
14094 3. M-x org-revert-all-org-buffers"
14095 (interactive)
14096 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14097 (error "Abort"))
14098 (save-excursion
14099 (save-window-excursion
14100 (mapc
14101 (lambda (b)
14102 (when (and (with-current-buffer b (org-mode-p))
14103 (with-current-buffer b buffer-file-name))
14104 (switch-to-buffer b)
14105 (revert-buffer t 'no-confirm)))
14106 (buffer-list))
14107 (when (and (featurep 'org-id) org-id-track-globally)
14108 (org-id-locations-load)))))
14110 ;;;; Agenda files
14112 ;;;###autoload
14113 (defun org-iswitchb (&optional arg)
14114 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14115 With a prefix argument, restrict available to files.
14116 With two prefix arguments, restrict available buffers to agenda files."
14117 (interactive "P")
14118 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14119 ((equal arg '(16)) (org-buffer-list 'agenda))
14120 (t (org-buffer-list)))))
14121 (switch-to-buffer
14122 (org-icompleting-read "Org buffer: "
14123 (mapcar 'list (mapcar 'buffer-name blist))
14124 nil t))))
14126 ;;;###autoload
14127 (defalias 'org-ido-switchb 'org-iswitchb)
14129 (defun org-buffer-list (&optional predicate exclude-tmp)
14130 "Return a list of Org buffers.
14131 PREDICATE can be `export', `files' or `agenda'.
14133 export restrict the list to Export buffers.
14134 files restrict the list to buffers visiting Org files.
14135 agenda restrict the list to buffers visiting agenda files.
14137 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14138 (let* ((bfn nil)
14139 (agenda-files (and (eq predicate 'agenda)
14140 (mapcar 'file-truename (org-agenda-files t))))
14141 (filter
14142 (cond
14143 ((eq predicate 'files)
14144 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14145 ((eq predicate 'export)
14146 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14147 ((eq predicate 'agenda)
14148 (lambda (b)
14149 (with-current-buffer b
14150 (and (eq major-mode 'org-mode)
14151 (setq bfn (buffer-file-name b))
14152 (member (file-truename bfn) agenda-files)))))
14153 (t (lambda (b) (with-current-buffer b
14154 (or (eq major-mode 'org-mode)
14155 (string-match "\*Org .*Export"
14156 (buffer-name b)))))))))
14157 (delq nil
14158 (mapcar
14159 (lambda(b)
14160 (if (and (funcall filter b)
14161 (or (not exclude-tmp)
14162 (not (string-match "tmp" (buffer-name b)))))
14164 nil))
14165 (buffer-list)))))
14167 (defun org-agenda-files (&optional unrestricted archives)
14168 "Get the list of agenda files.
14169 Optional UNRESTRICTED means return the full list even if a restriction
14170 is currently in place.
14171 When ARCHIVES is t, include all archive files hat are really being
14172 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14173 `org-agenda-archives-mode' is t."
14174 (let ((files
14175 (cond
14176 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14177 ((stringp org-agenda-files) (org-read-agenda-file-list))
14178 ((listp org-agenda-files) org-agenda-files)
14179 (t (error "Invalid value of `org-agenda-files'")))))
14180 (setq files (apply 'append
14181 (mapcar (lambda (f)
14182 (if (file-directory-p f)
14183 (directory-files
14184 f t org-agenda-file-regexp)
14185 (list f)))
14186 files)))
14187 (when org-agenda-skip-unavailable-files
14188 (setq files (delq nil
14189 (mapcar (function
14190 (lambda (file)
14191 (and (file-readable-p file) file)))
14192 files))))
14193 (when (or (eq archives t)
14194 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14195 (setq files (org-add-archive-files files)))
14196 files))
14198 (defun org-edit-agenda-file-list ()
14199 "Edit the list of agenda files.
14200 Depending on setup, this either uses customize to edit the variable
14201 `org-agenda-files', or it visits the file that is holding the list. In the
14202 latter case, the buffer is set up in a way that saving it automatically kills
14203 the buffer and restores the previous window configuration."
14204 (interactive)
14205 (if (stringp org-agenda-files)
14206 (let ((cw (current-window-configuration)))
14207 (find-file org-agenda-files)
14208 (org-set-local 'org-window-configuration cw)
14209 (org-add-hook 'after-save-hook
14210 (lambda ()
14211 (set-window-configuration
14212 (prog1 org-window-configuration
14213 (kill-buffer (current-buffer))))
14214 (org-install-agenda-files-menu)
14215 (message "New agenda file list installed"))
14216 nil 'local)
14217 (message "%s" (substitute-command-keys
14218 "Edit list and finish with \\[save-buffer]")))
14219 (customize-variable 'org-agenda-files)))
14221 (defun org-store-new-agenda-file-list (list)
14222 "Set new value for the agenda file list and save it correctly."
14223 (if (stringp org-agenda-files)
14224 (let ((f org-agenda-files) b)
14225 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14226 (with-temp-file f
14227 (insert (mapconcat 'identity list "\n") "\n")))
14228 (let ((org-mode-hook nil) (org-inhibit-startup t)
14229 (org-insert-mode-line-in-empty-file nil))
14230 (setq org-agenda-files list)
14231 (customize-save-variable 'org-agenda-files org-agenda-files))))
14233 (defun org-read-agenda-file-list ()
14234 "Read the list of agenda files from a file."
14235 (when (file-directory-p org-agenda-files)
14236 (error "`org-agenda-files' cannot be a single directory"))
14237 (when (stringp org-agenda-files)
14238 (with-temp-buffer
14239 (insert-file-contents org-agenda-files)
14240 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14243 ;;;###autoload
14244 (defun org-cycle-agenda-files ()
14245 "Cycle through the files in `org-agenda-files'.
14246 If the current buffer visits an agenda file, find the next one in the list.
14247 If the current buffer does not, find the first agenda file."
14248 (interactive)
14249 (let* ((fs (org-agenda-files t))
14250 (files (append fs (list (car fs))))
14251 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14252 file)
14253 (unless files (error "No agenda files"))
14254 (catch 'exit
14255 (while (setq file (pop files))
14256 (if (equal (file-truename file) tcf)
14257 (when (car files)
14258 (find-file (car files))
14259 (throw 'exit t))))
14260 (find-file (car fs)))
14261 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14263 (defun org-agenda-file-to-front (&optional to-end)
14264 "Move/add the current file to the top of the agenda file list.
14265 If the file is not present in the list, it is added to the front. If it is
14266 present, it is moved there. With optional argument TO-END, add/move to the
14267 end of the list."
14268 (interactive "P")
14269 (let ((org-agenda-skip-unavailable-files nil)
14270 (file-alist (mapcar (lambda (x)
14271 (cons (file-truename x) x))
14272 (org-agenda-files t)))
14273 (ctf (file-truename buffer-file-name))
14274 x had)
14275 (setq x (assoc ctf file-alist) had x)
14277 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14278 (if to-end
14279 (setq file-alist (append (delq x file-alist) (list x)))
14280 (setq file-alist (cons x (delq x file-alist))))
14281 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14282 (org-install-agenda-files-menu)
14283 (message "File %s to %s of agenda file list"
14284 (if had "moved" "added") (if to-end "end" "front"))))
14286 (defun org-remove-file (&optional file)
14287 "Remove current file from the list of files in variable `org-agenda-files'.
14288 These are the files which are being checked for agenda entries.
14289 Optional argument FILE means, use this file instead of the current."
14290 (interactive)
14291 (let* ((org-agenda-skip-unavailable-files nil)
14292 (file (or file buffer-file-name))
14293 (true-file (file-truename file))
14294 (afile (abbreviate-file-name file))
14295 (files (delq nil (mapcar
14296 (lambda (x)
14297 (if (equal true-file
14298 (file-truename x))
14299 nil x))
14300 (org-agenda-files t)))))
14301 (if (not (= (length files) (length (org-agenda-files t))))
14302 (progn
14303 (org-store-new-agenda-file-list files)
14304 (org-install-agenda-files-menu)
14305 (message "Removed file: %s" afile))
14306 (message "File was not in list: %s (not removed)" afile))))
14308 (defun org-file-menu-entry (file)
14309 (vector file (list 'find-file file) t))
14311 (defun org-check-agenda-file (file)
14312 "Make sure FILE exists. If not, ask user what to do."
14313 (when (not (file-exists-p file))
14314 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14315 (abbreviate-file-name file))
14316 (let ((r (downcase (read-char-exclusive))))
14317 (cond
14318 ((equal r ?r)
14319 (org-remove-file file)
14320 (throw 'nextfile t))
14321 (t (error "Abort"))))))
14323 (defun org-get-agenda-file-buffer (file)
14324 "Get a buffer visiting FILE. If the buffer needs to be created, add
14325 it to the list of buffers which might be released later."
14326 (let ((buf (org-find-base-buffer-visiting file)))
14327 (if buf
14328 buf ; just return it
14329 ;; Make a new buffer and remember it
14330 (setq buf (find-file-noselect file))
14331 (if buf (push buf org-agenda-new-buffers))
14332 buf)))
14334 (defun org-release-buffers (blist)
14335 "Release all buffers in list, asking the user for confirmation when needed.
14336 When a buffer is unmodified, it is just killed. When modified, it is saved
14337 \(if the user agrees) and then killed."
14338 (let (buf file)
14339 (while (setq buf (pop blist))
14340 (setq file (buffer-file-name buf))
14341 (when (and (buffer-modified-p buf)
14342 file
14343 (y-or-n-p (format "Save file %s? " file)))
14344 (with-current-buffer buf (save-buffer)))
14345 (kill-buffer buf))))
14347 (defun org-prepare-agenda-buffers (files)
14348 "Create buffers for all agenda files, protect archived trees and comments."
14349 (interactive)
14350 (let ((pa '(:org-archived t))
14351 (pc '(:org-comment t))
14352 (pall '(:org-archived t :org-comment t))
14353 (inhibit-read-only t)
14354 (rea (concat ":" org-archive-tag ":"))
14355 bmp file re)
14356 (save-excursion
14357 (save-restriction
14358 (while (setq file (pop files))
14359 (catch 'nextfile
14360 (if (bufferp file)
14361 (set-buffer file)
14362 (org-check-agenda-file file)
14363 (set-buffer (org-get-agenda-file-buffer file)))
14364 (widen)
14365 (setq bmp (buffer-modified-p))
14366 (org-refresh-category-properties)
14367 (setq org-todo-keywords-for-agenda
14368 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14369 (setq org-done-keywords-for-agenda
14370 (append org-done-keywords-for-agenda org-done-keywords))
14371 (setq org-todo-keyword-alist-for-agenda
14372 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14373 (setq org-drawers-for-agenda
14374 (append org-drawers-for-agenda org-drawers))
14375 (setq org-tag-alist-for-agenda
14376 (append org-tag-alist-for-agenda org-tag-alist))
14378 (save-excursion
14379 (remove-text-properties (point-min) (point-max) pall)
14380 (when org-agenda-skip-archived-trees
14381 (goto-char (point-min))
14382 (while (re-search-forward rea nil t)
14383 (if (org-on-heading-p t)
14384 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14385 (goto-char (point-min))
14386 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14387 (while (re-search-forward re nil t)
14388 (add-text-properties
14389 (match-beginning 0) (org-end-of-subtree t) pc)))
14390 (set-buffer-modified-p bmp)))))
14391 (setq org-todo-keyword-alist-for-agenda
14392 (org-uniquify org-todo-keyword-alist-for-agenda)
14393 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14395 ;;;; Embedded LaTeX
14397 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14398 "Keymap for the minor `org-cdlatex-mode'.")
14400 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14401 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14402 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14403 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14404 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14406 (defvar org-cdlatex-texmathp-advice-is-done nil
14407 "Flag remembering if we have applied the advice to texmathp already.")
14409 (define-minor-mode org-cdlatex-mode
14410 "Toggle the minor `org-cdlatex-mode'.
14411 This mode supports entering LaTeX environment and math in LaTeX fragments
14412 in Org-mode.
14413 \\{org-cdlatex-mode-map}"
14414 nil " OCDL" nil
14415 (when org-cdlatex-mode (require 'cdlatex))
14416 (unless org-cdlatex-texmathp-advice-is-done
14417 (setq org-cdlatex-texmathp-advice-is-done t)
14418 (defadvice texmathp (around org-math-always-on activate)
14419 "Always return t in org-mode buffers.
14420 This is because we want to insert math symbols without dollars even outside
14421 the LaTeX math segments. If Orgmode thinks that point is actually inside
14422 an embedded LaTeX fragment, let texmathp do its job.
14423 \\[org-cdlatex-mode-map]"
14424 (interactive)
14425 (let (p)
14426 (cond
14427 ((not (org-mode-p)) ad-do-it)
14428 ((eq this-command 'cdlatex-math-symbol)
14429 (setq ad-return-value t
14430 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14432 (let ((p (org-inside-LaTeX-fragment-p)))
14433 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14434 (setq ad-return-value t
14435 texmathp-why '("Org-mode embedded math" . 0))
14436 (if p ad-do-it)))))))))
14438 (defun turn-on-org-cdlatex ()
14439 "Unconditionally turn on `org-cdlatex-mode'."
14440 (org-cdlatex-mode 1))
14442 (defun org-inside-LaTeX-fragment-p ()
14443 "Test if point is inside a LaTeX fragment.
14444 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14445 sequence appearing also before point.
14446 Even though the matchers for math are configurable, this function assumes
14447 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14448 delimiters are skipped when they have been removed by customization.
14449 The return value is nil, or a cons cell with the delimiter and
14450 and the position of this delimiter.
14452 This function does a reasonably good job, but can locally be fooled by
14453 for example currency specifications. For example it will assume being in
14454 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14455 fragments that are properly closed, but during editing, we have to live
14456 with the uncertainty caused by missing closing delimiters. This function
14457 looks only before point, not after."
14458 (catch 'exit
14459 (let ((pos (point))
14460 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14461 (lim (progn
14462 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14463 (point)))
14464 dd-on str (start 0) m re)
14465 (goto-char pos)
14466 (when dodollar
14467 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14468 re (nth 1 (assoc "$" org-latex-regexps)))
14469 (while (string-match re str start)
14470 (cond
14471 ((= (match-end 0) (length str))
14472 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14473 ((= (match-end 0) (- (length str) 5))
14474 (throw 'exit nil))
14475 (t (setq start (match-end 0))))))
14476 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14477 (goto-char pos)
14478 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14479 (and (match-beginning 2) (throw 'exit nil))
14480 ;; count $$
14481 (while (re-search-backward "\\$\\$" lim t)
14482 (setq dd-on (not dd-on)))
14483 (goto-char pos)
14484 (if dd-on (cons "$$" m))))))
14486 (defun org-inside-latex-macro-p ()
14487 "Is point inside a LaTeX macro or its arguments?"
14488 (org-in-regexp
14489 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?"))
14491 (defun org-try-cdlatex-tab ()
14492 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14493 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14494 - inside a LaTeX fragment, or
14495 - after the first word in a line, where an abbreviation expansion could
14496 insert a LaTeX environment."
14497 (when org-cdlatex-mode
14498 (cond
14499 ((save-excursion
14500 (skip-chars-backward "a-zA-Z0-9*")
14501 (skip-chars-backward " \t")
14502 (bolp))
14503 (cdlatex-tab) t)
14504 ((org-inside-LaTeX-fragment-p)
14505 (cdlatex-tab) t)
14506 (t nil))))
14508 (defun org-cdlatex-underscore-caret (&optional arg)
14509 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14510 Revert to the normal definition outside of these fragments."
14511 (interactive "P")
14512 (if (org-inside-LaTeX-fragment-p)
14513 (call-interactively 'cdlatex-sub-superscript)
14514 (let (org-cdlatex-mode)
14515 (call-interactively (key-binding (vector last-input-event))))))
14517 (defun org-cdlatex-math-modify (&optional arg)
14518 "Execute `cdlatex-math-modify' in LaTeX fragments.
14519 Revert to the normal definition outside of these fragments."
14520 (interactive "P")
14521 (if (org-inside-LaTeX-fragment-p)
14522 (call-interactively 'cdlatex-math-modify)
14523 (let (org-cdlatex-mode)
14524 (call-interactively (key-binding (vector last-input-event))))))
14526 (defvar org-latex-fragment-image-overlays nil
14527 "List of overlays carrying the images of latex fragments.")
14528 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14530 (defun org-remove-latex-fragment-image-overlays ()
14531 "Remove all overlays with LaTeX fragment images in current buffer."
14532 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14533 (setq org-latex-fragment-image-overlays nil))
14535 (defun org-preview-latex-fragment (&optional subtree)
14536 "Preview the LaTeX fragment at point, or all locally or globally.
14537 If the cursor is in a LaTeX fragment, create the image and overlay
14538 it over the source code. If there is no fragment at point, display
14539 all fragments in the current text, from one headline to the next. With
14540 prefix SUBTREE, display all fragments in the current subtree. With a
14541 double prefix `C-u C-u', or when the cursor is before the first headline,
14542 display all fragments in the buffer.
14543 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14544 (interactive "P")
14545 (org-remove-latex-fragment-image-overlays)
14546 (save-excursion
14547 (save-restriction
14548 (let (beg end at msg)
14549 (cond
14550 ((or (equal subtree '(16))
14551 (not (save-excursion
14552 (re-search-backward (concat "^" outline-regexp) nil t))))
14553 (setq beg (point-min) end (point-max)
14554 msg "Creating images for buffer...%s"))
14555 ((equal subtree '(4))
14556 (org-back-to-heading)
14557 (setq beg (point) end (org-end-of-subtree t)
14558 msg "Creating images for subtree...%s"))
14560 (if (setq at (org-inside-LaTeX-fragment-p))
14561 (goto-char (max (point-min) (- (cdr at) 2)))
14562 (org-back-to-heading))
14563 (setq beg (point) end (progn (outline-next-heading) (point))
14564 msg (if at "Creating image...%s"
14565 "Creating images for entry...%s"))))
14566 (message msg "")
14567 (narrow-to-region beg end)
14568 (goto-char beg)
14569 (org-format-latex
14570 (concat "ltxpng/" (file-name-sans-extension
14571 (file-name-nondirectory
14572 buffer-file-name)))
14573 default-directory 'overlays msg at 'forbuffer)
14574 (message msg "done. Use `C-c C-c' to remove images.")))))
14576 (defvar org-latex-regexps
14577 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14578 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14579 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14580 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14581 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14582 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14583 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14584 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14585 "Regular expressions for matching embedded LaTeX.")
14587 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14588 "Replace LaTeX fragments with links to an image, and produce images.
14589 Some of the options can be changed using the variable
14590 `org-format-latex-options'."
14591 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14592 (let* ((prefixnodir (file-name-nondirectory prefix))
14593 (absprefix (expand-file-name prefix dir))
14594 (todir (file-name-directory absprefix))
14595 (opt org-format-latex-options)
14596 (matchers (plist-get opt :matchers))
14597 (re-list org-latex-regexps)
14598 (cnt 0) txt hash link beg end re e checkdir
14599 executables-checked
14600 m n block linkfile movefile ov)
14601 ;; Check the different regular expressions
14602 (while (setq e (pop re-list))
14603 (setq m (car e) re (nth 1 e) n (nth 2 e)
14604 block (if (nth 3 e) "\n\n" ""))
14605 (when (member m matchers)
14606 (goto-char (point-min))
14607 (while (re-search-forward re nil t)
14608 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14609 (not (get-text-property (match-beginning n)
14610 'org-protected))
14611 (or (not overlays)
14612 (not (eq (get-char-property (match-beginning n)
14613 'org-overlay-type)
14614 'org-latex-overlay))))
14615 (setq txt (match-string n)
14616 beg (match-beginning n) end (match-end n)
14617 cnt (1+ cnt)
14618 link (concat block "[[file:" linkfile "]]" block))
14619 (let (print-length print-level) ; make sure full list is printed
14620 (setq hash (sha1 (prin1-to-string
14621 (list org-format-latex-header
14622 org-export-latex-packages-alist
14623 org-format-latex-options
14624 forbuffer txt)))
14625 linkfile (format "%s_%s.png" prefix hash)
14626 movefile (format "%s_%s.png" absprefix hash)))
14627 (if msg (message msg cnt))
14628 (goto-char beg)
14629 (unless checkdir ; make sure the directory exists
14630 (setq checkdir t)
14631 (or (file-directory-p todir) (make-directory todir)))
14633 (unless executables-checked
14634 (org-check-external-command
14635 "latex" "needed to convert LaTeX fragments to images")
14636 (org-check-external-command
14637 "dvipng" "needed to convert LaTeX fragments to images")
14638 (setq executables-checked t))
14640 (unless (file-exists-p movefile)
14641 (org-create-formula-image
14642 txt movefile opt forbuffer))
14643 (if overlays
14644 (progn
14645 (mapc (lambda (o)
14646 (if (eq (org-overlay-get o 'org-overlay-type)
14647 'org-latex-overlay)
14648 (org-delete-overlay o)))
14649 (org-overlays-in beg end))
14650 (setq ov (org-make-overlay beg end))
14651 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14652 (if (featurep 'xemacs)
14653 (progn
14654 (org-overlay-put ov 'invisible t)
14655 (org-overlay-put
14656 ov 'end-glyph
14657 (make-glyph (vector 'png :file movefile))))
14658 (org-overlay-put
14659 ov 'display
14660 (list 'image :type 'png :file movefile :ascent 'center)))
14661 (push ov org-latex-fragment-image-overlays)
14662 (goto-char end))
14663 (delete-region beg end)
14664 (insert link))))))))
14666 ;; This function borrows from Ganesh Swami's latex2png.el
14667 (defun org-create-formula-image (string tofile options buffer)
14668 "This calls dvipng."
14669 (require 'org-latex)
14670 (let* ((tmpdir (if (featurep 'xemacs)
14671 (temp-directory)
14672 temporary-file-directory))
14673 (texfilebase (make-temp-name
14674 (expand-file-name "orgtex" tmpdir)))
14675 (texfile (concat texfilebase ".tex"))
14676 (dvifile (concat texfilebase ".dvi"))
14677 (pngfile (concat texfilebase ".png"))
14678 (fnh (if (featurep 'xemacs)
14679 (font-height (get-face-font 'default))
14680 (face-attribute 'default :height nil)))
14681 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14682 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14683 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14684 "Black"))
14685 (bg (or (plist-get options (if buffer :background :html-background))
14686 "Transparent")))
14687 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14688 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14689 (with-temp-file texfile
14690 (insert org-format-latex-header
14691 (if org-export-latex-packages-alist
14692 (concat "\n"
14693 (mapconcat (lambda(p)
14694 (if (equal "" (car p))
14695 (format "\\usepackage{%s}" (cadr p))
14696 (format "\\usepackage[%s]{%s}"
14697 (car p) (cadr p))))
14698 org-export-latex-packages-alist "\n"))
14700 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14701 (let ((dir default-directory))
14702 (condition-case nil
14703 (progn
14704 (cd tmpdir)
14705 (call-process "latex" nil nil nil texfile))
14706 (error nil))
14707 (cd dir))
14708 (if (not (file-exists-p dvifile))
14709 (progn (message "Failed to create dvi file from %s" texfile) nil)
14710 (condition-case nil
14711 (call-process "dvipng" nil nil nil
14712 "-fg" fg "-bg" bg
14713 "-D" dpi
14714 ;;"-x" scale "-y" scale
14715 "-T" "tight"
14716 "-o" pngfile
14717 dvifile)
14718 (error nil))
14719 (if (not (file-exists-p pngfile))
14720 (progn (message "Failed to create png file from %s" texfile) nil)
14721 ;; Use the requested file name and clean up
14722 (copy-file pngfile tofile 'replace)
14723 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14724 (delete-file (concat texfilebase e)))
14725 pngfile))))
14727 (defun org-dvipng-color (attr)
14728 "Return an rgb color specification for dvipng."
14729 (apply 'format "rgb %s %s %s"
14730 (mapcar 'org-normalize-color
14731 (color-values (face-attribute 'default attr nil)))))
14733 (defun org-normalize-color (value)
14734 "Return string to be used as color value for an RGB component."
14735 (format "%g" (/ value 65535.0)))
14737 ;;;; Key bindings
14739 ;; Make `C-c C-x' a prefix key
14740 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14742 ;; TAB key with modifiers
14743 (org-defkey org-mode-map "\C-i" 'org-cycle)
14744 (org-defkey org-mode-map [(tab)] 'org-cycle)
14745 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14746 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14747 (org-defkey org-mode-map "\M-\t" 'org-complete)
14748 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14749 ;; The following line is necessary under Suse GNU/Linux
14750 (unless (featurep 'xemacs)
14751 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14752 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14753 (define-key org-mode-map [backtab] 'org-shifttab)
14755 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14756 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14757 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14759 ;; Cursor keys with modifiers
14760 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14761 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14762 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14763 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14765 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14766 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14767 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14768 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14770 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14771 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14772 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14773 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14775 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14776 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14778 ;;; Extra keys for tty access.
14779 ;; We only set them when really needed because otherwise the
14780 ;; menus don't show the simple keys
14782 (when (or org-use-extra-keys
14783 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14784 (not window-system))
14785 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14786 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14787 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14788 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14789 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14790 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14791 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14792 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14793 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14794 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14795 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14796 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14797 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14798 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14799 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14800 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14801 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14802 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14803 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14804 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14805 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14806 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14807 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14808 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14809 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14810 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14811 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14812 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14814 ;; All the other keys
14816 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14817 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14818 (if (boundp 'narrow-map)
14819 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14820 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14821 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14822 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14823 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14824 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14825 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14826 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14827 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14828 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14829 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14830 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14831 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14832 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14833 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14834 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14835 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14836 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14837 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14838 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14839 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14840 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14841 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14842 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14843 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14844 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14845 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14846 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14847 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14848 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14849 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14850 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14851 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14852 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14853 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14854 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14855 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14856 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14857 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14858 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14859 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14860 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14861 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14862 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14863 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14864 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14865 (org-defkey org-mode-map "\C-c^" 'org-sort)
14866 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14867 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14868 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14869 (org-defkey org-mode-map "\C-m" 'org-return)
14870 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14871 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14872 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14873 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14874 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14875 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14876 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14877 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14878 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14879 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14880 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14881 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14882 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14883 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14884 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14885 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14886 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14887 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14888 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14889 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14890 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14892 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14893 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14894 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14895 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14897 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14898 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14899 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14900 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14901 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14902 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14903 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14904 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14905 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14906 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14907 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14908 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14909 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14910 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14911 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14913 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14914 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14915 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14916 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14918 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14920 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14922 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14923 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14925 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14928 (when (featurep 'xemacs)
14929 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14932 (defconst org-speed-commands-default
14934 ("Outline Navigation")
14935 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
14936 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
14937 ("f" . (org-speed-move-safe 'org-forward-same-level))
14938 ("b" . (org-speed-move-safe 'org-backward-same-level))
14939 ("u" . (org-speed-move-safe 'outline-up-heading))
14940 ("j" . org-goto)
14941 ("g" . (org-refile t))
14942 ("Outline Visibility")
14943 ("c" . org-cycle)
14944 ("C" . org-shifttab)
14945 (" " . org-display-outline-path)
14946 ("Outline Structure Editing")
14947 ("U" . org-shiftmetaup)
14948 ("D" . org-shiftmetadown)
14949 ("r" . org-metaright)
14950 ("l" . org-metaleft)
14951 ("R" . org-shiftmetaright)
14952 ("L" . org-shiftmetaleft)
14953 ("i" . (progn (forward-char 1) (call-interactively
14954 'org-insert-heading-respect-content)))
14955 ("^" . org-sort)
14956 ("w" . org-refile)
14957 ("a" . org-archive-subtree-default-with-confirmation)
14958 ("." . outline-mark-subtree)
14959 ("Clock Commands")
14960 ("I" . org-clock-in)
14961 ("O" . org-clock-out)
14962 ("Meta Data Editing")
14963 ("t" . org-todo)
14964 ("0" . (org-priority ?\ ))
14965 ("1" . (org-priority ?A))
14966 ("2" . (org-priority ?B))
14967 ("3" . (org-priority ?C))
14968 (";" . org-set-tags-command)
14969 ("e" . org-set-effort)
14970 ("Agenda Views etc")
14971 ("v" . org-agenda)
14972 ("/" . org-sparse-tree)
14973 ("Misc")
14974 ("o" . org-open-at-point)
14975 ("?" . org-speed-command-help)
14977 "The default speed commands.")
14979 (defun org-print-speed-command (e)
14980 (if (> (length (car e)) 1)
14981 (progn
14982 (princ "\n")
14983 (princ (car e))
14984 (princ "\n")
14985 (princ (make-string (length (car e)) ?-))
14986 (princ "\n"))
14987 (princ (car e))
14988 (princ " ")
14989 (if (symbolp (cdr e))
14990 (princ (symbol-name (cdr e)))
14991 (prin1 (cdr e)))
14992 (princ "\n")))
14994 (defun org-speed-command-help ()
14995 "Show the available speed commands."
14996 (interactive)
14997 (if (not org-use-speed-commands)
14998 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14999 (with-output-to-temp-buffer "*Help*"
15000 (princ "User-defined Speed commands\n===========================\n")
15001 (mapc 'org-print-speed-command org-speed-commands-user)
15002 (princ "\n")
15003 (princ "Built-in Speed commands\n=======================\n")
15004 (mapc 'org-print-speed-command org-speed-commands-default))
15005 (with-current-buffer "*Help*"
15006 (setq truncate-lines t))))
15008 (defun org-speed-move-safe (cmd)
15009 "Execute CMD, but make sure that the cursor always ends up in a headline.
15010 If not, return to the original position and throw an error."
15011 (interactive)
15012 (let ((pos (point)))
15013 (call-interactively cmd)
15014 (unless (and (bolp) (org-on-heading-p))
15015 (goto-char pos)
15016 (error "Boundary reached while executing %s" cmd))))
15018 (defvar org-self-insert-command-undo-counter 0)
15020 (defvar org-table-auto-blank-field) ; defined in org-table.el
15021 (defvar org-speed-command nil)
15022 (defun org-self-insert-command (N)
15023 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15024 If the cursor is in a table looking at whitespace, the whitespace is
15025 overwritten, and the table is not marked as requiring realignment."
15026 (interactive "p")
15027 (cond
15028 ((and org-use-speed-commands
15029 (or (and (bolp) (looking-at outline-regexp))
15030 (and (functionp org-use-speed-commands)
15031 (funcall org-use-speed-commands)))
15032 (setq
15033 org-speed-command
15034 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15035 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15036 (cond
15037 ((commandp org-speed-command)
15038 (setq this-command org-speed-command)
15039 (call-interactively org-speed-command))
15040 ((functionp org-speed-command)
15041 (funcall org-speed-command))
15042 ((and org-speed-command (listp org-speed-command))
15043 (eval org-speed-command))
15044 (t (let (org-use-speed-commands)
15045 (call-interactively 'org-self-insert-command)))))
15046 ((and
15047 (org-table-p)
15048 (progn
15049 ;; check if we blank the field, and if that triggers align
15050 (and (featurep 'org-table) org-table-auto-blank-field
15051 (member last-command
15052 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15053 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15054 ;; got extra space, this field does not determine column width
15055 (let (org-table-may-need-update) (org-table-blank-field))
15056 ;; no extra space, this field may determine column width
15057 (org-table-blank-field)))
15059 (eq N 1)
15060 (looking-at "[^|\n]* |"))
15061 (let (org-table-may-need-update)
15062 (goto-char (1- (match-end 0)))
15063 (delete-backward-char 1)
15064 (goto-char (match-beginning 0))
15065 (self-insert-command N)))
15067 (setq org-table-may-need-update t)
15068 (self-insert-command N)
15069 (org-fix-tags-on-the-fly)
15070 (if org-self-insert-cluster-for-undo
15071 (if (not (eq last-command 'org-self-insert-command))
15072 (setq org-self-insert-command-undo-counter 1)
15073 (if (>= org-self-insert-command-undo-counter 20)
15074 (setq org-self-insert-command-undo-counter 1)
15075 (and (> org-self-insert-command-undo-counter 0)
15076 buffer-undo-list
15077 (not (cadr buffer-undo-list)) ; remove nil entry
15078 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15079 (setq org-self-insert-command-undo-counter
15080 (1+ org-self-insert-command-undo-counter))))))))
15082 (defun org-fix-tags-on-the-fly ()
15083 (when (and (equal (char-after (point-at-bol)) ?*)
15084 (org-on-heading-p))
15085 (org-align-tags-here org-tags-column)))
15087 (defun org-delete-backward-char (N)
15088 "Like `delete-backward-char', insert whitespace at field end in tables.
15089 When deleting backwards, in tables this function will insert whitespace in
15090 front of the next \"|\" separator, to keep the table aligned. The table will
15091 still be marked for re-alignment if the field did fill the entire column,
15092 because, in this case the deletion might narrow the column."
15093 (interactive "p")
15094 (if (and (org-table-p)
15095 (eq N 1)
15096 (string-match "|" (buffer-substring (point-at-bol) (point)))
15097 (looking-at ".*?|"))
15098 (let ((pos (point))
15099 (noalign (looking-at "[^|\n\r]* |"))
15100 (c org-table-may-need-update))
15101 (backward-delete-char N)
15102 (skip-chars-forward "^|")
15103 (insert " ")
15104 (goto-char (1- pos))
15105 ;; noalign: if there were two spaces at the end, this field
15106 ;; does not determine the width of the column.
15107 (if noalign (setq org-table-may-need-update c)))
15108 (backward-delete-char N)
15109 (org-fix-tags-on-the-fly)))
15111 (defun org-delete-char (N)
15112 "Like `delete-char', but insert whitespace at field end in tables.
15113 When deleting characters, in tables this function will insert whitespace in
15114 front of the next \"|\" separator, to keep the table aligned. The table will
15115 still be marked for re-alignment if the field did fill the entire column,
15116 because, in this case the deletion might narrow the column."
15117 (interactive "p")
15118 (if (and (org-table-p)
15119 (not (bolp))
15120 (not (= (char-after) ?|))
15121 (eq N 1))
15122 (if (looking-at ".*?|")
15123 (let ((pos (point))
15124 (noalign (looking-at "[^|\n\r]* |"))
15125 (c org-table-may-need-update))
15126 (replace-match (concat
15127 (substring (match-string 0) 1 -1)
15128 " |"))
15129 (goto-char pos)
15130 ;; noalign: if there were two spaces at the end, this field
15131 ;; does not determine the width of the column.
15132 (if noalign (setq org-table-may-need-update c)))
15133 (delete-char N))
15134 (delete-char N)
15135 (org-fix-tags-on-the-fly)))
15137 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15138 (put 'org-self-insert-command 'delete-selection t)
15139 (put 'orgtbl-self-insert-command 'delete-selection t)
15140 (put 'org-delete-char 'delete-selection 'supersede)
15141 (put 'org-delete-backward-char 'delete-selection 'supersede)
15142 (put 'org-yank 'delete-selection 'yank)
15144 ;; Make `flyspell-mode' delay after some commands
15145 (put 'org-self-insert-command 'flyspell-delayed t)
15146 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15147 (put 'org-delete-char 'flyspell-delayed t)
15148 (put 'org-delete-backward-char 'flyspell-delayed t)
15150 ;; Make pabbrev-mode expand after org-mode commands
15151 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15152 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15154 ;; How to do this: Measure non-white length of current string
15155 ;; If equal to column width, we should realign.
15157 (defun org-remap (map &rest commands)
15158 "In MAP, remap the functions given in COMMANDS.
15159 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15160 (let (new old)
15161 (while commands
15162 (setq old (pop commands) new (pop commands))
15163 (if (fboundp 'command-remapping)
15164 (org-defkey map (vector 'remap old) new)
15165 (substitute-key-definition old new map global-map)))))
15167 (when (eq org-enable-table-editor 'optimized)
15168 ;; If the user wants maximum table support, we need to hijack
15169 ;; some standard editing functions
15170 (org-remap org-mode-map
15171 'self-insert-command 'org-self-insert-command
15172 'delete-char 'org-delete-char
15173 'delete-backward-char 'org-delete-backward-char)
15174 (org-defkey org-mode-map "|" 'org-force-self-insert))
15176 (defvar org-ctrl-c-ctrl-c-hook nil
15177 "Hook for functions attaching themselves to `C-c C-c'.
15178 This can be used to add additional functionality to the C-c C-c key which
15179 executes context-dependent commands.
15180 Each function will be called with no arguments. The function must check
15181 if the context is appropriate for it to act. If yes, it should do its
15182 thing and then return a non-nil value. If the context is wrong,
15183 just do nothing and return nil.")
15185 (defvar org-tab-first-hook nil
15186 "Hook for functions to attach themselves to TAB.
15187 See `org-ctrl-c-ctrl-c-hook' for more information.
15188 This hook runs as the first action when TAB is pressed, even before
15189 `org-cycle' messes around with the `outline-regexp' to cater for
15190 inline tasks and plain list item folding.
15191 If any function in this hook returns t, not other actions like table
15192 field motion visibility cycling will be done.")
15194 (defvar org-tab-after-check-for-table-hook nil
15195 "Hook for functions to attach themselves to TAB.
15196 See `org-ctrl-c-ctrl-c-hook' for more information.
15197 This hook runs after it has been established that the cursor is not in a
15198 table, but before checking if the cursor is in a headline or if global cycling
15199 should be done.
15200 If any function in this hook returns t, not other actions like visibility
15201 cycling will be done.")
15203 (defvar org-tab-after-check-for-cycling-hook nil
15204 "Hook for functions to attach themselves to TAB.
15205 See `org-ctrl-c-ctrl-c-hook' for more information.
15206 This hook runs after it has been established that not table field motion and
15207 not visibility should be done because of current context. This is probably
15208 the place where a package like yasnippets can hook in.")
15210 (defvar org-tab-before-tab-emulation-hook nil
15211 "Hook for functions to attach themselves to TAB.
15212 See `org-ctrl-c-ctrl-c-hook' for more information.
15213 This hook runs after every other options for TAB have been exhausted, but
15214 before indentation and \t insertion takes place.")
15216 (defvar org-metaleft-hook nil
15217 "Hook for functions attaching themselves to `M-left'.
15218 See `org-ctrl-c-ctrl-c-hook' for more information.")
15219 (defvar org-metaright-hook nil
15220 "Hook for functions attaching themselves to `M-right'.
15221 See `org-ctrl-c-ctrl-c-hook' for more information.")
15222 (defvar org-metaup-hook nil
15223 "Hook for functions attaching themselves to `M-up'.
15224 See `org-ctrl-c-ctrl-c-hook' for more information.")
15225 (defvar org-metadown-hook nil
15226 "Hook for functions attaching themselves to `M-down'.
15227 See `org-ctrl-c-ctrl-c-hook' for more information.")
15228 (defvar org-shiftmetaleft-hook nil
15229 "Hook for functions attaching themselves to `M-S-left'.
15230 See `org-ctrl-c-ctrl-c-hook' for more information.")
15231 (defvar org-shiftmetaright-hook nil
15232 "Hook for functions attaching themselves to `M-S-right'.
15233 See `org-ctrl-c-ctrl-c-hook' for more information.")
15234 (defvar org-shiftmetaup-hook nil
15235 "Hook for functions attaching themselves to `M-S-up'.
15236 See `org-ctrl-c-ctrl-c-hook' for more information.")
15237 (defvar org-shiftmetadown-hook nil
15238 "Hook for functions attaching themselves to `M-S-down'.
15239 See `org-ctrl-c-ctrl-c-hook' for more information.")
15240 (defvar org-metareturn-hook nil
15241 "Hook for functions attaching themselves to `M-RET'.
15242 See `org-ctrl-c-ctrl-c-hook' for more information.")
15244 (defun org-modifier-cursor-error ()
15245 "Throw an error, a modified cursor command was applied in wrong context."
15246 (error "This command is active in special context like tables, headlines or items"))
15248 (defun org-shiftselect-error ()
15249 "Throw an error because Shift-Cursor command was applied in wrong context."
15250 (if (and (boundp 'shift-select-mode) shift-select-mode)
15251 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15252 (error "This command works only in special context like headlines or timestamps")))
15254 (defun org-call-for-shift-select (cmd)
15255 (let ((this-command-keys-shift-translated t))
15256 (call-interactively cmd)))
15258 (defun org-shifttab (&optional arg)
15259 "Global visibility cycling or move to previous table field.
15260 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15261 on context.
15262 See the individual commands for more information."
15263 (interactive "P")
15264 (cond
15265 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15266 ((integerp arg)
15267 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15268 (message "Content view to level: %d" arg)
15269 (org-content (prefix-numeric-value arg2))
15270 (setq org-cycle-global-status 'overview)))
15271 (t (call-interactively 'org-global-cycle))))
15273 (defun org-shiftmetaleft ()
15274 "Promote subtree or delete table column.
15275 Calls `org-promote-subtree', `org-outdent-item',
15276 or `org-table-delete-column', depending on context.
15277 See the individual commands for more information."
15278 (interactive)
15279 (cond
15280 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15281 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15282 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15283 ((org-at-item-p) (call-interactively 'org-outdent-item))
15284 (t (org-modifier-cursor-error))))
15286 (defun org-shiftmetaright ()
15287 "Demote subtree or insert table column.
15288 Calls `org-demote-subtree', `org-indent-item',
15289 or `org-table-insert-column', depending on context.
15290 See the individual commands for more information."
15291 (interactive)
15292 (cond
15293 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15294 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15295 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15296 ((org-at-item-p) (call-interactively 'org-indent-item))
15297 (t (org-modifier-cursor-error))))
15299 (defun org-shiftmetaup (&optional arg)
15300 "Move subtree up or kill table row.
15301 Calls `org-move-subtree-up' or `org-table-kill-row' or
15302 `org-move-item-up' depending on context. See the individual commands
15303 for more information."
15304 (interactive "P")
15305 (cond
15306 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15307 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15308 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15309 ((org-at-item-p) (call-interactively 'org-move-item-up))
15310 (t (org-modifier-cursor-error))))
15312 (defun org-shiftmetadown (&optional arg)
15313 "Move subtree down or insert table row.
15314 Calls `org-move-subtree-down' or `org-table-insert-row' or
15315 `org-move-item-down', depending on context. See the individual
15316 commands for more information."
15317 (interactive "P")
15318 (cond
15319 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15320 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15321 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15322 ((org-at-item-p) (call-interactively 'org-move-item-down))
15323 (t (org-modifier-cursor-error))))
15325 (defun org-metaleft (&optional arg)
15326 "Promote heading or move table column to left.
15327 Calls `org-do-promote' or `org-table-move-column', depending on context.
15328 With no specific context, calls the Emacs default `backward-word'.
15329 See the individual commands for more information."
15330 (interactive "P")
15331 (cond
15332 ((run-hook-with-args-until-success 'org-metaleft-hook))
15333 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15334 ((or (org-on-heading-p)
15335 (and (org-region-active-p)
15336 (save-excursion
15337 (goto-char (region-beginning))
15338 (org-on-heading-p))))
15339 (call-interactively 'org-do-promote))
15340 ((or (org-at-item-p)
15341 (and (org-region-active-p)
15342 (save-excursion
15343 (goto-char (region-beginning))
15344 (org-at-item-p))))
15345 (call-interactively 'org-outdent-item))
15346 (t (call-interactively 'backward-word))))
15348 (defun org-metaright (&optional arg)
15349 "Demote subtree or move table column to right.
15350 Calls `org-do-demote' or `org-table-move-column', depending on context.
15351 With no specific context, calls the Emacs default `forward-word'.
15352 See the individual commands for more information."
15353 (interactive "P")
15354 (cond
15355 ((run-hook-with-args-until-success 'org-metaright-hook))
15356 ((org-at-table-p) (call-interactively 'org-table-move-column))
15357 ((or (org-on-heading-p)
15358 (and (org-region-active-p)
15359 (save-excursion
15360 (goto-char (region-beginning))
15361 (org-on-heading-p))))
15362 (call-interactively 'org-do-demote))
15363 ((or (org-at-item-p)
15364 (and (org-region-active-p)
15365 (save-excursion
15366 (goto-char (region-beginning))
15367 (org-at-item-p))))
15368 (call-interactively 'org-indent-item))
15369 (t (call-interactively 'forward-word))))
15371 (defun org-metaup (&optional arg)
15372 "Move subtree up or move table row up.
15373 Calls `org-move-subtree-up' or `org-table-move-row' or
15374 `org-move-item-up', depending on context. See the individual commands
15375 for more information."
15376 (interactive "P")
15377 (cond
15378 ((run-hook-with-args-until-success 'org-metaup-hook))
15379 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15380 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15381 ((org-at-item-p) (call-interactively 'org-move-item-up))
15382 (t (transpose-lines 1) (beginning-of-line -1))))
15384 (defun org-metadown (&optional arg)
15385 "Move subtree down or move table row down.
15386 Calls `org-move-subtree-down' or `org-table-move-row' or
15387 `org-move-item-down', depending on context. See the individual
15388 commands for more information."
15389 (interactive "P")
15390 (cond
15391 ((run-hook-with-args-until-success 'org-metadown-hook))
15392 ((org-at-table-p) (call-interactively 'org-table-move-row))
15393 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15394 ((org-at-item-p) (call-interactively 'org-move-item-down))
15395 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15397 (defun org-shiftup (&optional arg)
15398 "Increase item in timestamp or increase priority of current headline.
15399 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15400 depending on context. See the individual commands for more information."
15401 (interactive "P")
15402 (cond
15403 ((and org-support-shift-select (org-region-active-p))
15404 (org-call-for-shift-select 'previous-line))
15405 ((org-at-timestamp-p t)
15406 (call-interactively (if org-edit-timestamp-down-means-later
15407 'org-timestamp-down 'org-timestamp-up)))
15408 ((and (not (eq org-support-shift-select 'always))
15409 org-enable-priority-commands
15410 (org-on-heading-p))
15411 (call-interactively 'org-priority-up))
15412 ((and (not org-support-shift-select) (org-at-item-p))
15413 (call-interactively 'org-previous-item))
15414 ((org-clocktable-try-shift 'up arg))
15415 (org-support-shift-select
15416 (org-call-for-shift-select 'previous-line))
15417 (t (org-shiftselect-error))))
15419 (defun org-shiftdown (&optional arg)
15420 "Decrease item in timestamp or decrease priority of current headline.
15421 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15422 depending on context. See the individual commands for more information."
15423 (interactive "P")
15424 (cond
15425 ((and org-support-shift-select (org-region-active-p))
15426 (org-call-for-shift-select 'next-line))
15427 ((org-at-timestamp-p t)
15428 (call-interactively (if org-edit-timestamp-down-means-later
15429 'org-timestamp-up 'org-timestamp-down)))
15430 ((and (not (eq org-support-shift-select 'always))
15431 org-enable-priority-commands
15432 (org-on-heading-p))
15433 (call-interactively 'org-priority-down))
15434 ((and (not org-support-shift-select) (org-at-item-p))
15435 (call-interactively 'org-next-item))
15436 ((org-clocktable-try-shift 'down arg))
15437 (org-support-shift-select
15438 (org-call-for-shift-select 'next-line))
15439 (t (org-shiftselect-error))))
15441 (defun org-shiftright (&optional arg)
15442 "Cycle the thing at point or in the current line, depending on context.
15443 Depending on context, this does one of the following:
15445 - switch a timestamp at point one day into the future
15446 - on a headline, switch to the next TODO keyword.
15447 - on an item, switch entire list to the next bullet type
15448 - on a property line, switch to the next allowed value
15449 - on a clocktable definition line, move time block into the future"
15450 (interactive "P")
15451 (cond
15452 ((and org-support-shift-select (org-region-active-p))
15453 (org-call-for-shift-select 'forward-char))
15454 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15455 ((and (not (eq org-support-shift-select 'always))
15456 (org-on-heading-p))
15457 (let ((org-inhibit-logging
15458 (not org-treat-S-cursor-todo-selection-as-state-change))
15459 (org-inhibit-blocking
15460 (not org-treat-S-cursor-todo-selection-as-state-change)))
15461 (org-call-with-arg 'org-todo 'right)))
15462 ((or (and org-support-shift-select
15463 (not (eq org-support-shift-select 'always))
15464 (org-at-item-bullet-p))
15465 (and (not org-support-shift-select) (org-at-item-p)))
15466 (org-call-with-arg 'org-cycle-list-bullet nil))
15467 ((and (not (eq org-support-shift-select 'always))
15468 (org-at-property-p))
15469 (call-interactively 'org-property-next-allowed-value))
15470 ((org-clocktable-try-shift 'right arg))
15471 (org-support-shift-select
15472 (org-call-for-shift-select 'forward-char))
15473 (t (org-shiftselect-error))))
15475 (defun org-shiftleft (&optional arg)
15476 "Cycle the thing at point or in the current line, depending on context.
15477 Depending on context, this does one of the following:
15479 - switch a timestamp at point one day into the past
15480 - on a headline, switch to the previous TODO keyword.
15481 - on an item, switch entire list to the previous bullet type
15482 - on a property line, switch to the previous allowed value
15483 - on a clocktable definition line, move time block into the past"
15484 (interactive "P")
15485 (cond
15486 ((and org-support-shift-select (org-region-active-p))
15487 (org-call-for-shift-select 'backward-char))
15488 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15489 ((and (not (eq org-support-shift-select 'always))
15490 (org-on-heading-p))
15491 (let ((org-inhibit-logging
15492 (not org-treat-S-cursor-todo-selection-as-state-change))
15493 (org-inhibit-blocking
15494 (not org-treat-S-cursor-todo-selection-as-state-change)))
15495 (org-call-with-arg 'org-todo 'left)))
15496 ((or (and org-support-shift-select
15497 (not (eq org-support-shift-select 'always))
15498 (org-at-item-bullet-p))
15499 (and (not org-support-shift-select) (org-at-item-p)))
15500 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15501 ((and (not (eq org-support-shift-select 'always))
15502 (org-at-property-p))
15503 (call-interactively 'org-property-previous-allowed-value))
15504 ((org-clocktable-try-shift 'left arg))
15505 (org-support-shift-select
15506 (org-call-for-shift-select 'backward-char))
15507 (t (org-shiftselect-error))))
15509 (defun org-shiftcontrolright ()
15510 "Switch to next TODO set."
15511 (interactive)
15512 (cond
15513 ((and org-support-shift-select (org-region-active-p))
15514 (org-call-for-shift-select 'forward-word))
15515 ((and (not (eq org-support-shift-select 'always))
15516 (org-on-heading-p))
15517 (org-call-with-arg 'org-todo 'nextset))
15518 (org-support-shift-select
15519 (org-call-for-shift-select 'forward-word))
15520 (t (org-shiftselect-error))))
15522 (defun org-shiftcontrolleft ()
15523 "Switch to previous TODO set."
15524 (interactive)
15525 (cond
15526 ((and org-support-shift-select (org-region-active-p))
15527 (org-call-for-shift-select 'backward-word))
15528 ((and (not (eq org-support-shift-select 'always))
15529 (org-on-heading-p))
15530 (org-call-with-arg 'org-todo 'previousset))
15531 (org-support-shift-select
15532 (org-call-for-shift-select 'backward-word))
15533 (t (org-shiftselect-error))))
15535 (defun org-ctrl-c-ret ()
15536 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15537 (interactive)
15538 (cond
15539 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15540 (t (call-interactively 'org-insert-heading))))
15542 (defun org-copy-special ()
15543 "Copy region in table or copy current subtree.
15544 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15545 See the individual commands for more information."
15546 (interactive)
15547 (call-interactively
15548 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15550 (defun org-cut-special ()
15551 "Cut region in table or cut current subtree.
15552 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15553 See the individual commands for more information."
15554 (interactive)
15555 (call-interactively
15556 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15558 (defun org-paste-special (arg)
15559 "Paste rectangular region into table, or past subtree relative to level.
15560 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15561 See the individual commands for more information."
15562 (interactive "P")
15563 (if (org-at-table-p)
15564 (org-table-paste-rectangle)
15565 (org-paste-subtree arg)))
15567 (defun org-edit-special ()
15568 "Call a special editor for the stuff at point.
15569 When at a table, call the formula editor with `org-table-edit-formulas'.
15570 When at the first line of an src example, call `org-edit-src-code'.
15571 When in an #+include line, visit the include file. Otherwise call
15572 `ffap' to visit the file at point."
15573 (interactive)
15574 (cond
15575 ((org-at-table-p)
15576 (call-interactively 'org-table-edit-formulas))
15577 ((save-excursion
15578 (beginning-of-line 1)
15579 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15580 (find-file (org-trim (match-string 1))))
15581 ((org-edit-src-code))
15582 ((org-edit-fixed-width-region))
15583 (t (call-interactively 'ffap))))
15586 (defun org-ctrl-c-ctrl-c (&optional arg)
15587 "Set tags in headline, or update according to changed information at point.
15589 This command does many different things, depending on context:
15591 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15592 this is what we do.
15594 - If the cursor is on a statistics cookie, update it.
15596 - If the cursor is in a headline, prompt for tags and insert them
15597 into the current line, aligned to `org-tags-column'. When called
15598 with prefix arg, realign all tags in the current buffer.
15600 - If the cursor is in one of the special #+KEYWORD lines, this
15601 triggers scanning the buffer for these lines and updating the
15602 information.
15604 - If the cursor is inside a table, realign the table. This command
15605 works even if the automatic table editor has been turned off.
15607 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15608 the entire table.
15610 - If the cursor is at a footnote reference or definition, jump to
15611 the corresponding definition or references, respectively.
15613 - If the cursor is a the beginning of a dynamic block, update it.
15615 - If the cursor is inside a table created by the table.el package,
15616 activate that table.
15618 - If the current buffer is a remember buffer, close note and file
15619 it. A prefix argument of 1 files to the default location
15620 without further interaction. A prefix argument of 2 files to
15621 the currently clocking task.
15623 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15624 links in this buffer.
15626 - If the cursor is on a numbered item in a plain list, renumber the
15627 ordered list.
15629 - If the cursor is on a checkbox, toggle it."
15630 (interactive "P")
15631 (let ((org-enable-table-editor t))
15632 (cond
15633 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15634 org-occur-highlights
15635 org-latex-fragment-image-overlays)
15636 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15637 (org-remove-occur-highlights)
15638 (org-remove-latex-fragment-image-overlays)
15639 (message "Temporary highlights/overlays removed from current buffer"))
15640 ((and (local-variable-p 'org-finish-function (current-buffer))
15641 (fboundp org-finish-function))
15642 (funcall org-finish-function))
15643 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15644 ((org-at-property-p)
15645 (call-interactively 'org-property-action))
15646 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15647 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15648 (or (org-on-heading-p) (org-at-item-p)))
15649 (call-interactively 'org-update-statistics-cookies))
15650 ((org-on-heading-p) (call-interactively 'org-set-tags))
15651 ((org-at-table.el-p)
15652 (require 'table)
15653 (beginning-of-line 1)
15654 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15655 (call-interactively 'table-recognize-table))
15656 ((org-at-table-p)
15657 (org-table-maybe-eval-formula)
15658 (if arg
15659 (call-interactively 'org-table-recalculate)
15660 (org-table-maybe-recalculate-line))
15661 (call-interactively 'org-table-align))
15662 ((or (org-footnote-at-reference-p)
15663 (org-footnote-at-definition-p))
15664 (call-interactively 'org-footnote-action))
15665 ((org-at-item-checkbox-p)
15666 (call-interactively 'org-toggle-checkbox))
15667 ((org-at-item-p)
15668 (if arg
15669 (call-interactively 'org-toggle-checkbox)
15670 (call-interactively 'org-maybe-renumber-ordered-list)))
15671 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15672 ;; Dynamic block
15673 (beginning-of-line 1)
15674 (save-excursion (org-update-dblock)))
15675 ((save-excursion
15676 (beginning-of-line 1)
15677 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15678 (cond
15679 ((equal (match-string 1) "TBLFM")
15680 ;; Recalculate the table before this line
15681 (save-excursion
15682 (beginning-of-line 1)
15683 (skip-chars-backward " \r\n\t")
15684 (if (org-at-table-p)
15685 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15687 ; (org-set-regexps-and-options)
15688 ; (org-restart-font-lock)
15689 (let ((org-inhibit-startup t)) (org-mode-restart))
15690 (message "Local setup has been refreshed"))))
15691 ((org-clock-update-time-maybe))
15692 (t (error "C-c C-c can do nothing useful at this location")))))
15694 (defun org-mode-restart ()
15695 "Restart Org-mode, to scan again for special lines.
15696 Also updates the keyword regular expressions."
15697 (interactive)
15698 (org-mode)
15699 (message "Org-mode restarted"))
15701 (defun org-kill-note-or-show-branches ()
15702 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15703 (interactive)
15704 (if (not org-finish-function)
15705 (call-interactively 'show-branches)
15706 (let ((org-note-abort t))
15707 (funcall org-finish-function))))
15709 (defun org-return (&optional indent)
15710 "Goto next table row or insert a newline.
15711 Calls `org-table-next-row' or `newline', depending on context.
15712 See the individual commands for more information."
15713 (interactive)
15714 (cond
15715 ((bobp) (if indent (newline-and-indent) (newline)))
15716 ((org-at-table-p)
15717 (org-table-justify-field-maybe)
15718 (call-interactively 'org-table-next-row))
15719 ((and org-return-follows-link
15720 (eq (get-text-property (point) 'face) 'org-link))
15721 (call-interactively 'org-open-at-point))
15722 ((and (org-at-heading-p)
15723 (looking-at
15724 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15725 (org-show-entry)
15726 (end-of-line 1)
15727 (newline))
15728 (t (if indent (newline-and-indent) (newline)))))
15730 (defun org-return-indent ()
15731 "Goto next table row or insert a newline and indent.
15732 Calls `org-table-next-row' or `newline-and-indent', depending on
15733 context. See the individual commands for more information."
15734 (interactive)
15735 (org-return t))
15737 (defun org-ctrl-c-star ()
15738 "Compute table, or change heading status of lines.
15739 Calls `org-table-recalculate' or `org-toggle-heading',
15740 depending on context."
15741 (interactive)
15742 (cond
15743 ((org-at-table-p)
15744 (call-interactively 'org-table-recalculate))
15746 ;; Convert all lines in region to list items
15747 (call-interactively 'org-toggle-heading))))
15749 (defun org-ctrl-c-minus ()
15750 "Insert separator line in table or modify bullet status of line.
15751 Also turns a plain line or a region of lines into list items.
15752 Calls `org-table-insert-hline', `org-toggle-item', or
15753 `org-cycle-list-bullet', depending on context."
15754 (interactive)
15755 (cond
15756 ((org-at-table-p)
15757 (call-interactively 'org-table-insert-hline))
15758 ((org-region-active-p)
15759 (call-interactively 'org-toggle-item))
15760 ((org-in-item-p)
15761 (call-interactively 'org-cycle-list-bullet))
15763 (call-interactively 'org-toggle-item))))
15765 (defun org-toggle-item ()
15766 "Convert headings or normal lines to items, items to normal lines.
15767 If there is no active region, only the current line is considered.
15769 If the first line in the region is a headline, convert all headlines to items.
15771 If the first line in the region is an item, convert all items to normal lines.
15773 If the first line is normal text, add an item bullet to each line."
15774 (interactive)
15775 (let (l2 l beg end)
15776 (if (org-region-active-p)
15777 (setq beg (region-beginning) end (region-end))
15778 (setq beg (point-at-bol)
15779 end (min (1+ (point-at-eol)) (point-max))))
15780 (save-excursion
15781 (goto-char end)
15782 (setq l2 (org-current-line))
15783 (goto-char beg)
15784 (beginning-of-line 1)
15785 (setq l (1- (org-current-line)))
15786 (if (org-at-item-p)
15787 ;; We already have items, de-itemize
15788 (while (< (setq l (1+ l)) l2)
15789 (when (org-at-item-p)
15790 (goto-char (match-beginning 2))
15791 (delete-region (match-beginning 2) (match-end 2))
15792 (and (looking-at "[ \t]+") (replace-match "")))
15793 (beginning-of-line 2))
15794 (if (org-on-heading-p)
15795 ;; Headings, convert to items
15796 (while (< (setq l (1+ l)) l2)
15797 (if (looking-at org-outline-regexp)
15798 (replace-match "- " t t))
15799 (beginning-of-line 2))
15800 ;; normal lines, turn them into items
15801 (while (< (setq l (1+ l)) l2)
15802 (unless (org-at-item-p)
15803 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15804 (replace-match "\\1- \\2")))
15805 (beginning-of-line 2)))))))
15807 (defun org-toggle-heading (&optional nstars)
15808 "Convert headings to normal text, or items or text to headings.
15809 If there is no active region, only the current line is considered.
15811 If the first line is a heading, remove the stars from all headlines
15812 in the region.
15814 If the first line is a plain list item, turn all plain list items
15815 into headings.
15817 If the first line is a normal line, turn each and every line in the
15818 region into a heading.
15820 When converting a line into a heading, the number of stars is chosen
15821 such that the lines become children of the current entry. However,
15822 when a prefix argument is given, its value determines the number of
15823 stars to add."
15824 (interactive "P")
15825 (let (l2 l itemp beg end)
15826 (if (org-region-active-p)
15827 (setq beg (region-beginning) end (region-end))
15828 (setq beg (point-at-bol)
15829 end (min (1+ (point-at-eol)) (point-max))))
15830 (save-excursion
15831 (goto-char end)
15832 (setq l2 (org-current-line))
15833 (goto-char beg)
15834 (beginning-of-line 1)
15835 (setq l (1- (org-current-line)))
15836 (if (org-on-heading-p)
15837 ;; We already have headlines, de-star them
15838 (while (< (setq l (1+ l)) l2)
15839 (when (org-on-heading-p t)
15840 (and (looking-at outline-regexp) (replace-match "")))
15841 (beginning-of-line 2))
15842 (setq itemp (org-at-item-p))
15843 (let* ((stars
15844 (if nstars
15845 (make-string (prefix-numeric-value current-prefix-arg)
15847 (save-excursion
15848 (if (re-search-backward org-complex-heading-regexp nil t)
15849 (match-string 1) ""))))
15850 (add-stars (cond (nstars "")
15851 ((equal stars "") "*")
15852 (org-odd-levels-only "**")
15853 (t "*")))
15854 (rpl (concat stars add-stars " ")))
15855 (while (< (setq l (1+ l)) l2)
15856 (if itemp
15857 (and (org-at-item-p) (replace-match rpl t t))
15858 (unless (org-on-heading-p)
15859 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15860 (replace-match (concat rpl (match-string 2))))))
15861 (beginning-of-line 2)))))))
15863 (defun org-meta-return (&optional arg)
15864 "Insert a new heading or wrap a region in a table.
15865 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15866 See the individual commands for more information."
15867 (interactive "P")
15868 (cond
15869 ((run-hook-with-args-until-success 'org-metareturn-hook))
15870 ((org-at-table-p)
15871 (call-interactively 'org-table-wrap-region))
15872 (t (call-interactively 'org-insert-heading))))
15874 ;;; Menu entries
15876 ;; Define the Org-mode menus
15877 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15878 '("Tbl"
15879 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15880 ["Next Field" org-cycle (org-at-table-p)]
15881 ["Previous Field" org-shifttab (org-at-table-p)]
15882 ["Next Row" org-return (org-at-table-p)]
15883 "--"
15884 ["Blank Field" org-table-blank-field (org-at-table-p)]
15885 ["Edit Field" org-table-edit-field (org-at-table-p)]
15886 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15887 "--"
15888 ("Column"
15889 ["Move Column Left" org-metaleft (org-at-table-p)]
15890 ["Move Column Right" org-metaright (org-at-table-p)]
15891 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15892 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15893 ("Row"
15894 ["Move Row Up" org-metaup (org-at-table-p)]
15895 ["Move Row Down" org-metadown (org-at-table-p)]
15896 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15897 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15898 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15899 "--"
15900 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15901 ("Rectangle"
15902 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15903 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15904 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15905 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15906 "--"
15907 ("Calculate"
15908 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15909 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15910 ["Edit Formulas" org-edit-special (org-at-table-p)]
15911 "--"
15912 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15913 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15914 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15915 "--"
15916 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15917 "--"
15918 ["Sum Column/Rectangle" org-table-sum
15919 (or (org-at-table-p) (org-region-active-p))]
15920 ["Which Column?" org-table-current-column (org-at-table-p)])
15921 ["Debug Formulas"
15922 org-table-toggle-formula-debugger
15923 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15924 ["Show Col/Row Numbers"
15925 org-table-toggle-coordinate-overlays
15926 :style toggle
15927 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15928 "--"
15929 ["Create" org-table-create (and (not (org-at-table-p))
15930 org-enable-table-editor)]
15931 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15932 ["Import from File" org-table-import (not (org-at-table-p))]
15933 ["Export to File" org-table-export (org-at-table-p)]
15934 "--"
15935 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15937 (easy-menu-define org-org-menu org-mode-map "Org menu"
15938 '("Org"
15939 ("Show/Hide"
15940 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15941 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15942 ["Sparse Tree..." org-sparse-tree t]
15943 ["Reveal Context" org-reveal t]
15944 ["Show All" show-all t]
15945 "--"
15946 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15947 "--"
15948 ["New Heading" org-insert-heading t]
15949 ("Navigate Headings"
15950 ["Up" outline-up-heading t]
15951 ["Next" outline-next-visible-heading t]
15952 ["Previous" outline-previous-visible-heading t]
15953 ["Next Same Level" outline-forward-same-level t]
15954 ["Previous Same Level" outline-backward-same-level t]
15955 "--"
15956 ["Jump" org-goto t])
15957 ("Edit Structure"
15958 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15959 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15960 "--"
15961 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15962 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15963 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15964 "--"
15965 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15966 "--"
15967 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15968 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15969 ["Demote Heading" org-metaright (not (org-at-table-p))]
15970 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15971 "--"
15972 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15973 "--"
15974 ["Convert to odd levels" org-convert-to-odd-levels t]
15975 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15976 ("Editing"
15977 ["Emphasis..." org-emphasize t]
15978 ["Edit Source Example" org-edit-special t]
15979 "--"
15980 ["Footnote new/jump" org-footnote-action t]
15981 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15982 ("Archive"
15983 ["Archive (default method)" org-archive-subtree-default t]
15984 "--"
15985 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15986 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15987 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15989 "--"
15990 ("Hyperlinks"
15991 ["Store Link (Global)" org-store-link t]
15992 ["Find existing link to here" org-occur-link-in-agenda-files t]
15993 ["Insert Link" org-insert-link t]
15994 ["Follow Link" org-open-at-point t]
15995 "--"
15996 ["Next link" org-next-link t]
15997 ["Previous link" org-previous-link t]
15998 "--"
15999 ["Descriptive Links"
16000 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16001 :style radio
16002 :selected (member '(org-link) buffer-invisibility-spec)]
16003 ["Literal Links"
16004 (progn
16005 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16006 :style radio
16007 :selected (not (member '(org-link) buffer-invisibility-spec))])
16008 "--"
16009 ("TODO Lists"
16010 ["TODO/DONE/-" org-todo t]
16011 ("Select keyword"
16012 ["Next keyword" org-shiftright (org-on-heading-p)]
16013 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16014 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16015 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16016 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16017 ["Show TODO Tree" org-show-todo-tree t]
16018 ["Global TODO list" org-todo-list t]
16019 "--"
16020 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16021 :selected org-enforce-todo-dependencies :style toggle :active t]
16022 "Settings for tree at point"
16023 ["Do Children sequentially" org-toggle-ordered-property :style radio
16024 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16025 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16026 ["Do Children parallel" org-toggle-ordered-property :style radio
16027 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16028 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16029 "--"
16030 ["Set Priority" org-priority t]
16031 ["Priority Up" org-shiftup t]
16032 ["Priority Down" org-shiftdown t]
16033 "--"
16034 ["Get news from all feeds" org-feed-update-all t]
16035 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16036 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16037 ("TAGS and Properties"
16038 ["Set Tags" org-set-tags-command t]
16039 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16040 "--"
16041 ["Set property" org-set-property t]
16042 ["Column view of properties" org-columns t]
16043 ["Insert Column View DBlock" org-insert-columns-dblock t])
16044 ("Dates and Scheduling"
16045 ["Timestamp" org-time-stamp t]
16046 ["Timestamp (inactive)" org-time-stamp-inactive t]
16047 ("Change Date"
16048 ["1 Day Later" org-shiftright t]
16049 ["1 Day Earlier" org-shiftleft t]
16050 ["1 ... Later" org-shiftup t]
16051 ["1 ... Earlier" org-shiftdown t])
16052 ["Compute Time Range" org-evaluate-time-range t]
16053 ["Schedule Item" org-schedule t]
16054 ["Deadline" org-deadline t]
16055 "--"
16056 ["Custom time format" org-toggle-time-stamp-overlays
16057 :style radio :selected org-display-custom-times]
16058 "--"
16059 ["Goto Calendar" org-goto-calendar t]
16060 ["Date from Calendar" org-date-from-calendar t]
16061 "--"
16062 ["Start/Restart Timer" org-timer-start t]
16063 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16064 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16065 ["Insert Timer String" org-timer t]
16066 ["Insert Timer Item" org-timer-item t])
16067 ("Logging work"
16068 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16069 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16070 ["Clock out" org-clock-out t]
16071 ["Clock cancel" org-clock-cancel t]
16072 "--"
16073 ["Mark as default task" org-clock-mark-default-task t]
16074 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16075 ["Goto running clock" org-clock-goto t]
16076 "--"
16077 ["Display times" org-clock-display t]
16078 ["Create clock table" org-clock-report t]
16079 "--"
16080 ["Record DONE time"
16081 (progn (setq org-log-done (not org-log-done))
16082 (message "Switching to %s will %s record a timestamp"
16083 (car org-done-keywords)
16084 (if org-log-done "automatically" "not")))
16085 :style toggle :selected org-log-done])
16086 "--"
16087 ["Agenda Command..." org-agenda t]
16088 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16089 ("File List for Agenda")
16090 ("Special views current file"
16091 ["TODO Tree" org-show-todo-tree t]
16092 ["Check Deadlines" org-check-deadlines t]
16093 ["Timeline" org-timeline t]
16094 ["Tags/Property tree" org-match-sparse-tree t])
16095 "--"
16096 ["Export/Publish..." org-export t]
16097 ("LaTeX"
16098 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16099 :selected org-cdlatex-mode]
16100 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16101 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16102 ["Modify math symbol" org-cdlatex-math-modify
16103 (org-inside-LaTeX-fragment-p)]
16104 ["Insert citation" org-reftex-citation t]
16105 "--"
16106 ["Export LaTeX fragments as images"
16107 (if (featurep 'org-exp)
16108 (setq org-export-with-LaTeX-fragments
16109 (not org-export-with-LaTeX-fragments))
16110 (require 'org-exp))
16111 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16112 org-export-with-LaTeX-fragments)])
16113 "--"
16114 ("MobileOrg"
16115 ["Push Files and Views" org-mobile-push t]
16116 ["Get Captured and Flagged" org-mobile-pull t]
16117 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16118 "--"
16119 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16120 "--"
16121 ("Documentation"
16122 ["Show Version" org-version t]
16123 ["Info Documentation" org-info t])
16124 ("Customize"
16125 ["Browse Org Group" org-customize t]
16126 "--"
16127 ["Expand This Menu" org-create-customize-menu
16128 (fboundp 'customize-menu-create)])
16129 ["Send bug report" org-submit-bug-report t]
16130 "--"
16131 ("Refresh/Reload"
16132 ["Refresh setup current buffer" org-mode-restart t]
16133 ["Reload Org (after update)" org-reload t]
16134 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16137 (defun org-info (&optional node)
16138 "Read documentation for Org-mode in the info system.
16139 With optional NODE, go directly to that node."
16140 (interactive)
16141 (info (format "(org)%s" (or node ""))))
16143 ;;;###autoload
16144 (defun org-submit-bug-report ()
16145 "Submit a bug report on Org-mode via mail.
16147 Don't hesitate to report any problems or inaccurate documentation.
16149 If you don't have setup sending mail from (X)Emacs, please copy the
16150 output buffer into your mail program, as it gives us important
16151 information about your Org-mode version and configuration."
16152 (interactive)
16153 (require 'reporter)
16154 (org-load-modules-maybe)
16155 (org-require-autoloaded-modules)
16156 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16157 (reporter-submit-bug-report
16158 "emacs-orgmode@gnu.org"
16159 (org-version)
16160 (let (list)
16161 (save-window-excursion
16162 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16163 (delete-other-windows)
16164 (erase-buffer)
16165 (insert "You are about to submit a bug report to the Org-mode mailing list.
16167 We would like to add your full Org-mode and Outline configuration to the
16168 bug report. This greatly simplifies the work of the maintainer and
16169 other experts on the mailing list.
16171 HOWEVER, some variables you have customized may contain private
16172 information. The names of customers, colleagues, or friends, might
16173 appear in the form of file names, tags, todo states, or search strings.
16174 If you answer yes to the prompt, you might want to check and remove
16175 such private information before sending the email.")
16176 (add-text-properties (point-min) (point-max) '(face org-warning))
16177 (when (yes-or-no-p "Include your Org-mode configuration ")
16178 (mapatoms
16179 (lambda (v)
16180 (and (boundp v)
16181 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16182 (or (and (symbol-value v)
16183 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16184 (and
16185 (get v 'custom-type) (get v 'standard-value)
16186 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16187 (push v list)))))
16188 (kill-buffer (get-buffer "*Warn about privacy*"))
16189 list))
16190 nil nil
16191 "Remember to cover the basics, that is, what you expected to happen and
16192 what in fact did happen. You don't know how to make a good report? See
16194 http://orgmode.org/manual/Feedback.html#Feedback
16196 Your bug report will be posted to the Org-mode mailing list.
16197 ------------------------------------------------------------------------")
16198 (save-excursion
16199 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16200 (replace-match "\\1Bug: \\3 [\\2]")))))
16203 (defun org-install-agenda-files-menu ()
16204 (let ((bl (buffer-list)))
16205 (save-excursion
16206 (while bl
16207 (set-buffer (pop bl))
16208 (if (org-mode-p) (setq bl nil)))
16209 (when (org-mode-p)
16210 (easy-menu-change
16211 '("Org") "File List for Agenda"
16212 (append
16213 (list
16214 ["Edit File List" (org-edit-agenda-file-list) t]
16215 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16216 ["Remove Current File from List" org-remove-file t]
16217 ["Cycle through agenda files" org-cycle-agenda-files t]
16218 ["Occur in all agenda files" org-occur-in-agenda-files t]
16219 "--")
16220 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16222 ;;;; Documentation
16224 ;;;###autoload
16225 (defun org-require-autoloaded-modules ()
16226 (interactive)
16227 (mapc 'require
16228 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16229 org-docbook org-exp org-html org-icalendar
16230 org-id org-latex
16231 org-publish org-remember org-table
16232 org-timer org-xoxo)))
16234 ;;;###autoload
16235 (defun org-reload (&optional uncompiled)
16236 "Reload all org lisp files.
16237 With prefix arg UNCOMPILED, load the uncompiled versions."
16238 (interactive "P")
16239 (require 'find-func)
16240 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16241 (dir-org (file-name-directory (org-find-library-name "org")))
16242 (dir-org-contrib (ignore-errors
16243 (file-name-directory
16244 (org-find-library-name "org-contribdir"))))
16245 (files
16246 (append (directory-files dir-org t file-re)
16247 (and dir-org-contrib
16248 (directory-files dir-org-contrib t file-re))))
16249 (remove-re (concat (if (featurep 'xemacs)
16250 "org-colview" "org-colview-xemacs")
16251 "\\'")))
16252 (setq files (mapcar 'file-name-sans-extension files))
16253 (setq files (mapcar
16254 (lambda (x) (if (string-match remove-re x) nil x))
16255 files))
16256 (setq files (delq nil files))
16257 (mapc
16258 (lambda (f)
16259 (when (featurep (intern (file-name-nondirectory f)))
16260 (if (and (not uncompiled)
16261 (file-exists-p (concat f ".elc")))
16262 (load (concat f ".elc") nil nil t)
16263 (load (concat f ".el") nil nil t))))
16264 files))
16265 (org-version))
16267 ;;;###autoload
16268 (defun org-customize ()
16269 "Call the customize function with org as argument."
16270 (interactive)
16271 (org-load-modules-maybe)
16272 (org-require-autoloaded-modules)
16273 (customize-browse 'org))
16275 (defun org-create-customize-menu ()
16276 "Create a full customization menu for Org-mode, insert it into the menu."
16277 (interactive)
16278 (org-load-modules-maybe)
16279 (org-require-autoloaded-modules)
16280 (if (fboundp 'customize-menu-create)
16281 (progn
16282 (easy-menu-change
16283 '("Org") "Customize"
16284 `(["Browse Org group" org-customize t]
16285 "--"
16286 ,(customize-menu-create 'org)
16287 ["Set" Custom-set t]
16288 ["Save" Custom-save t]
16289 ["Reset to Current" Custom-reset-current t]
16290 ["Reset to Saved" Custom-reset-saved t]
16291 ["Reset to Standard Settings" Custom-reset-standard t]))
16292 (message "\"Org\"-menu now contains full customization menu"))
16293 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16295 ;;;; Miscellaneous stuff
16297 ;;; Generally useful functions
16299 (defun org-get-at-bol (property)
16300 "Get text property PROPERTY at beginning of line."
16301 (get-text-property (point-at-bol) property))
16303 (defun org-find-text-property-in-string (prop s)
16304 "Return the first non-nil value of property PROP in string S."
16305 (or (get-text-property 0 prop s)
16306 (get-text-property (or (next-single-property-change 0 prop s) 0)
16307 prop s)))
16309 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16310 "Display the given MESSAGE as a warning."
16311 (if (fboundp 'display-warning)
16312 (display-warning 'org message
16313 (if (featurep 'xemacs)
16314 'warning
16315 :warning))
16316 (let ((buf (get-buffer-create "*Org warnings*")))
16317 (with-current-buffer buf
16318 (goto-char (point-max))
16319 (insert "Warning (Org): " message)
16320 (unless (bolp)
16321 (newline)))
16322 (display-buffer buf)
16323 (sit-for 0))))
16325 (defun org-in-commented-line ()
16326 "Is point in a line starting with `#'?"
16327 (equal (char-after (point-at-bol)) ?#))
16329 (defun org-in-verbatim-emphasis ()
16330 (save-match-data
16331 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16333 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16334 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16335 (if (and marker (marker-buffer marker)
16336 (buffer-live-p (marker-buffer marker)))
16337 (progn
16338 (switch-to-buffer (marker-buffer marker))
16339 (if (or (> marker (point-max)) (< marker (point-min)))
16340 (widen))
16341 (goto-char marker)
16342 (org-show-context 'org-goto))
16343 (if bookmark
16344 (bookmark-jump bookmark)
16345 (error "Cannot find location"))))
16347 (defun org-quote-csv-field (s)
16348 "Quote field for inclusion in CSV material."
16349 (if (string-match "[\",]" s)
16350 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16353 (defun org-plist-delete (plist property)
16354 "Delete PROPERTY from PLIST.
16355 This is in contrast to merely setting it to 0."
16356 (let (p)
16357 (while plist
16358 (if (not (eq property (car plist)))
16359 (setq p (plist-put p (car plist) (nth 1 plist))))
16360 (setq plist (cddr plist)))
16363 (defun org-force-self-insert (N)
16364 "Needed to enforce self-insert under remapping."
16365 (interactive "p")
16366 (self-insert-command N))
16368 (defun org-string-width (s)
16369 "Compute width of string, ignoring invisible characters.
16370 This ignores character with invisibility property `org-link', and also
16371 characters with property `org-cwidth', because these will become invisible
16372 upon the next fontification round."
16373 (let (b l)
16374 (when (or (eq t buffer-invisibility-spec)
16375 (assq 'org-link buffer-invisibility-spec))
16376 (while (setq b (text-property-any 0 (length s)
16377 'invisible 'org-link s))
16378 (setq s (concat (substring s 0 b)
16379 (substring s (or (next-single-property-change
16380 b 'invisible s) (length s)))))))
16381 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16382 (setq s (concat (substring s 0 b)
16383 (substring s (or (next-single-property-change
16384 b 'org-cwidth s) (length s))))))
16385 (setq l (string-width s) b -1)
16386 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16387 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16390 (defun org-get-indentation (&optional line)
16391 "Get the indentation of the current line, interpreting tabs.
16392 When LINE is given, assume it represents a line and compute its indentation."
16393 (if line
16394 (if (string-match "^ *" (org-remove-tabs line))
16395 (match-end 0))
16396 (save-excursion
16397 (beginning-of-line 1)
16398 (skip-chars-forward " \t")
16399 (current-column))))
16401 (defun org-remove-tabs (s &optional width)
16402 "Replace tabulators in S with spaces.
16403 Assumes that s is a single line, starting in column 0."
16404 (setq width (or width tab-width))
16405 (while (string-match "\t" s)
16406 (setq s (replace-match
16407 (make-string
16408 (- (* width (/ (+ (match-beginning 0) width) width))
16409 (match-beginning 0)) ?\ )
16410 t t s)))
16413 (defun org-fix-indentation (line ind)
16414 "Fix indentation in LINE.
16415 IND is a cons cell with target and minimum indentation.
16416 If the current indentation in LINE is smaller than the minimum,
16417 leave it alone. If it is larger than ind, set it to the target."
16418 (let* ((l (org-remove-tabs line))
16419 (i (org-get-indentation l))
16420 (i1 (car ind)) (i2 (cdr ind)))
16421 (if (>= i i2) (setq l (substring line i2)))
16422 (if (> i1 0)
16423 (concat (make-string i1 ?\ ) l)
16424 l)))
16426 (defun org-remove-indentation (code &optional n)
16427 "Remove the maximum common indentation from the lines in CODE.
16428 N may optionally be the number of spaces to remove."
16429 (with-temp-buffer
16430 (insert code)
16431 (org-do-remove-indentation n)
16432 (buffer-string)))
16434 (defun org-do-remove-indentation (&optional n)
16435 "Remove the maximum common indentation from the buffer."
16436 (untabify (point-min) (point-max))
16437 (let ((min 10000) re)
16438 (if n
16439 (setq min n)
16440 (goto-char (point-min))
16441 (while (re-search-forward "^ *[^ \n]" nil t)
16442 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16443 (unless (or (= min 0) (= min 10000))
16444 (setq re (format "^ \\{%d\\}" min))
16445 (goto-char (point-min))
16446 (while (re-search-forward re nil t)
16447 (replace-match "")
16448 (end-of-line 1))
16449 min)))
16451 (defun org-fill-template (template alist)
16452 "Find each %key of ALIST in TEMPLATE and replace it."
16453 (let (entry key value)
16454 (setq alist (sort (copy-sequence alist)
16455 (lambda (a b) (< (length (car a)) (length (car b))))))
16456 (while (setq entry (pop alist))
16457 (setq template
16458 (replace-regexp-in-string
16459 (concat "%" (regexp-quote (car entry)))
16460 (cdr entry) template t t)))
16461 template))
16463 (defun org-base-buffer (buffer)
16464 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16465 (if (not buffer)
16466 buffer
16467 (or (buffer-base-buffer buffer)
16468 buffer)))
16470 (defun org-trim (s)
16471 "Remove whitespace at beginning and end of string."
16472 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16473 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16476 (defun org-wrap (string &optional width lines)
16477 "Wrap string to either a number of lines, or a width in characters.
16478 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16479 that costs. If there is a word longer than WIDTH, the text is actually
16480 wrapped to the length of that word.
16481 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16482 many lines, whatever width that takes.
16483 The return value is a list of lines, without newlines at the end."
16484 (let* ((words (org-split-string string "[ \t\n]+"))
16485 (maxword (apply 'max (mapcar 'org-string-width words)))
16486 w ll)
16487 (cond (width
16488 (org-do-wrap words (max maxword width)))
16489 (lines
16490 (setq w maxword)
16491 (setq ll (org-do-wrap words maxword))
16492 (if (<= (length ll) lines)
16494 (setq ll words)
16495 (while (> (length ll) lines)
16496 (setq w (1+ w))
16497 (setq ll (org-do-wrap words w)))
16498 ll))
16499 (t (error "Cannot wrap this")))))
16501 (defun org-do-wrap (words width)
16502 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16503 (let (lines line)
16504 (while words
16505 (setq line (pop words))
16506 (while (and words (< (+ (length line) (length (car words))) width))
16507 (setq line (concat line " " (pop words))))
16508 (setq lines (push line lines)))
16509 (nreverse lines)))
16511 (defun org-split-string (string &optional separators)
16512 "Splits STRING into substrings at SEPARATORS.
16513 No empty strings are returned if there are matches at the beginning
16514 and end of string."
16515 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16516 (start 0)
16517 notfirst
16518 (list nil))
16519 (while (and (string-match rexp string
16520 (if (and notfirst
16521 (= start (match-beginning 0))
16522 (< start (length string)))
16523 (1+ start) start))
16524 (< (match-beginning 0) (length string)))
16525 (setq notfirst t)
16526 (or (eq (match-beginning 0) 0)
16527 (and (eq (match-beginning 0) (match-end 0))
16528 (eq (match-beginning 0) start))
16529 (setq list
16530 (cons (substring string start (match-beginning 0))
16531 list)))
16532 (setq start (match-end 0)))
16533 (or (eq start (length string))
16534 (setq list
16535 (cons (substring string start)
16536 list)))
16537 (nreverse list)))
16539 (defun org-quote-vert (s)
16540 "Replace \"|\" with \"\\vert\"."
16541 (while (string-match "|" s)
16542 (setq s (replace-match "\\vert" t t s)))
16545 (defun org-uuidgen-p (s)
16546 "Is S an ID created by UUIDGEN?"
16547 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16549 (defun org-context ()
16550 "Return a list of contexts of the current cursor position.
16551 If several contexts apply, all are returned.
16552 Each context entry is a list with a symbol naming the context, and
16553 two positions indicating start and end of the context. Possible
16554 contexts are:
16556 :headline anywhere in a headline
16557 :headline-stars on the leading stars in a headline
16558 :todo-keyword on a TODO keyword (including DONE) in a headline
16559 :tags on the TAGS in a headline
16560 :priority on the priority cookie in a headline
16561 :item on the first line of a plain list item
16562 :item-bullet on the bullet/number of a plain list item
16563 :checkbox on the checkbox in a plain list item
16564 :table in an org-mode table
16565 :table-special on a special filed in a table
16566 :table-table in a table.el table
16567 :link on a hyperlink
16568 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16569 :target on a <<target>>
16570 :radio-target on a <<<radio-target>>>
16571 :latex-fragment on a LaTeX fragment
16572 :latex-preview on a LaTeX fragment with overlayed preview image
16574 This function expects the position to be visible because it uses font-lock
16575 faces as a help to recognize the following contexts: :table-special, :link,
16576 and :keyword."
16577 (let* ((f (get-text-property (point) 'face))
16578 (faces (if (listp f) f (list f)))
16579 (p (point)) clist o)
16580 ;; First the large context
16581 (cond
16582 ((org-on-heading-p t)
16583 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16584 (when (progn
16585 (beginning-of-line 1)
16586 (looking-at org-todo-line-tags-regexp))
16587 (push (org-point-in-group p 1 :headline-stars) clist)
16588 (push (org-point-in-group p 2 :todo-keyword) clist)
16589 (push (org-point-in-group p 4 :tags) clist))
16590 (goto-char p)
16591 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16592 (if (looking-at "\\[#[A-Z0-9]\\]")
16593 (push (org-point-in-group p 0 :priority) clist)))
16595 ((org-at-item-p)
16596 (push (org-point-in-group p 2 :item-bullet) clist)
16597 (push (list :item (point-at-bol)
16598 (save-excursion (org-end-of-item) (point)))
16599 clist)
16600 (and (org-at-item-checkbox-p)
16601 (push (org-point-in-group p 0 :checkbox) clist)))
16603 ((org-at-table-p)
16604 (push (list :table (org-table-begin) (org-table-end)) clist)
16605 (if (memq 'org-formula faces)
16606 (push (list :table-special
16607 (previous-single-property-change p 'face)
16608 (next-single-property-change p 'face)) clist)))
16609 ((org-at-table-p 'any)
16610 (push (list :table-table) clist)))
16611 (goto-char p)
16613 ;; Now the small context
16614 (cond
16615 ((org-at-timestamp-p)
16616 (push (org-point-in-group p 0 :timestamp) clist))
16617 ((memq 'org-link faces)
16618 (push (list :link
16619 (previous-single-property-change p 'face)
16620 (next-single-property-change p 'face)) clist))
16621 ((memq 'org-special-keyword faces)
16622 (push (list :keyword
16623 (previous-single-property-change p 'face)
16624 (next-single-property-change p 'face)) clist))
16625 ((org-on-target-p)
16626 (push (org-point-in-group p 0 :target) clist)
16627 (goto-char (1- (match-beginning 0)))
16628 (if (looking-at org-radio-target-regexp)
16629 (push (org-point-in-group p 0 :radio-target) clist))
16630 (goto-char p))
16631 ((setq o (car (delq nil
16632 (mapcar
16633 (lambda (x)
16634 (if (memq x org-latex-fragment-image-overlays) x))
16635 (org-overlays-at (point))))))
16636 (push (list :latex-fragment
16637 (org-overlay-start o) (org-overlay-end o)) clist)
16638 (push (list :latex-preview
16639 (org-overlay-start o) (org-overlay-end o)) clist))
16640 ((org-inside-LaTeX-fragment-p)
16641 ;; FIXME: positions wrong.
16642 (push (list :latex-fragment (point) (point)) clist)))
16644 (setq clist (nreverse (delq nil clist)))
16645 clist))
16647 ;; FIXME: Compare with at-regexp-p Do we need both?
16648 (defun org-in-regexp (re &optional nlines visually)
16649 "Check if point is inside a match of regexp.
16650 Normally only the current line is checked, but you can include NLINES extra
16651 lines both before and after point into the search.
16652 If VISUALLY is set, require that the cursor is not after the match but
16653 really on, so that the block visually is on the match."
16654 (catch 'exit
16655 (let ((pos (point))
16656 (eol (point-at-eol (+ 1 (or nlines 0))))
16657 (inc (if visually 1 0)))
16658 (save-excursion
16659 (beginning-of-line (- 1 (or nlines 0)))
16660 (while (re-search-forward re eol t)
16661 (if (and (<= (match-beginning 0) pos)
16662 (>= (+ inc (match-end 0)) pos))
16663 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16665 (defun org-at-regexp-p (regexp)
16666 "Is point inside a match of REGEXP in the current line?"
16667 (catch 'exit
16668 (save-excursion
16669 (let ((pos (point)) (end (point-at-eol)))
16670 (beginning-of-line 1)
16671 (while (re-search-forward regexp end t)
16672 (if (and (<= (match-beginning 0) pos)
16673 (>= (match-end 0) pos))
16674 (throw 'exit t)))
16675 nil))))
16677 (defun org-occur-in-agenda-files (regexp &optional nlines)
16678 "Call `multi-occur' with buffers for all agenda files."
16679 (interactive "sOrg-files matching: \np")
16680 (let* ((files (org-agenda-files))
16681 (tnames (mapcar 'file-truename files))
16682 (extra org-agenda-text-search-extra-files)
16684 (when (eq (car extra) 'agenda-archives)
16685 (setq extra (cdr extra))
16686 (setq files (org-add-archive-files files)))
16687 (while (setq f (pop extra))
16688 (unless (member (file-truename f) tnames)
16689 (add-to-list 'files f 'append)
16690 (add-to-list 'tnames (file-truename f) 'append)))
16691 (multi-occur
16692 (mapcar (lambda (x)
16693 (with-current-buffer
16694 (or (get-file-buffer x) (find-file-noselect x))
16695 (widen)
16696 (current-buffer)))
16697 files)
16698 regexp)))
16700 (if (boundp 'occur-mode-find-occurrence-hook)
16701 ;; Emacs 23
16702 (add-hook 'occur-mode-find-occurrence-hook
16703 (lambda ()
16704 (when (org-mode-p)
16705 (org-reveal))))
16706 ;; Emacs 22
16707 (defadvice occur-mode-goto-occurrence
16708 (after org-occur-reveal activate)
16709 (and (org-mode-p) (org-reveal)))
16710 (defadvice occur-mode-goto-occurrence-other-window
16711 (after org-occur-reveal activate)
16712 (and (org-mode-p) (org-reveal)))
16713 (defadvice occur-mode-display-occurrence
16714 (after org-occur-reveal activate)
16715 (when (org-mode-p)
16716 (let ((pos (occur-mode-find-occurrence)))
16717 (with-current-buffer (marker-buffer pos)
16718 (save-excursion
16719 (goto-char pos)
16720 (org-reveal)))))))
16722 (defun org-occur-link-in-agenda-files ()
16723 "Create a link and search for it in the agendas.
16724 The link is not stored in `org-stored-links', it is just created
16725 for the search purpose."
16726 (interactive)
16727 (let ((link (condition-case nil
16728 (org-store-link nil)
16729 (error "Unable to create a link to here"))))
16730 (org-occur-in-agenda-files (regexp-quote link))))
16732 (defun org-uniquify (list)
16733 "Remove duplicate elements from LIST."
16734 (let (res)
16735 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16736 res))
16738 (defun org-delete-all (elts list)
16739 "Remove all elements in ELTS from LIST."
16740 (while elts
16741 (setq list (delete (pop elts) list)))
16742 list)
16744 (defun org-back-over-empty-lines ()
16745 "Move backwards over whitespace, to the beginning of the first empty line.
16746 Returns the number of empty lines passed."
16747 (let ((pos (point)))
16748 (skip-chars-backward " \t\n\r")
16749 (beginning-of-line 2)
16750 (goto-char (min (point) pos))
16751 (count-lines (point) pos)))
16753 (defun org-skip-whitespace ()
16754 (skip-chars-forward " \t\n\r"))
16756 (defun org-point-in-group (point group &optional context)
16757 "Check if POINT is in match-group GROUP.
16758 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16759 match. If the match group does ot exist or point is not inside it,
16760 return nil."
16761 (and (match-beginning group)
16762 (>= point (match-beginning group))
16763 (<= point (match-end group))
16764 (if context
16765 (list context (match-beginning group) (match-end group))
16766 t)))
16768 (defun org-switch-to-buffer-other-window (&rest args)
16769 "Switch to buffer in a second window on the current frame.
16770 In particular, do not allow pop-up frames."
16771 (let (pop-up-frames special-display-buffer-names special-display-regexps
16772 special-display-function)
16773 (apply 'switch-to-buffer-other-window args)))
16775 (defun org-combine-plists (&rest plists)
16776 "Create a single property list from all plists in PLISTS.
16777 The process starts by copying the first list, and then setting properties
16778 from the other lists. Settings in the last list are the most significant
16779 ones and overrule settings in the other lists."
16780 (let ((rtn (copy-sequence (pop plists)))
16781 p v ls)
16782 (while plists
16783 (setq ls (pop plists))
16784 (while ls
16785 (setq p (pop ls) v (pop ls))
16786 (setq rtn (plist-put rtn p v))))
16787 rtn))
16789 (defun org-move-line-down (arg)
16790 "Move the current line down. With prefix argument, move it past ARG lines."
16791 (interactive "p")
16792 (let ((col (current-column))
16793 beg end pos)
16794 (beginning-of-line 1) (setq beg (point))
16795 (beginning-of-line 2) (setq end (point))
16796 (beginning-of-line (+ 1 arg))
16797 (setq pos (move-marker (make-marker) (point)))
16798 (insert (delete-and-extract-region beg end))
16799 (goto-char pos)
16800 (org-move-to-column col)))
16802 (defun org-move-line-up (arg)
16803 "Move the current line up. With prefix argument, move it past ARG lines."
16804 (interactive "p")
16805 (let ((col (current-column))
16806 beg end pos)
16807 (beginning-of-line 1) (setq beg (point))
16808 (beginning-of-line 2) (setq end (point))
16809 (beginning-of-line (- arg))
16810 (setq pos (move-marker (make-marker) (point)))
16811 (insert (delete-and-extract-region beg end))
16812 (goto-char pos)
16813 (org-move-to-column col)))
16815 (defun org-replace-escapes (string table)
16816 "Replace %-escapes in STRING with values in TABLE.
16817 TABLE is an association list with keys like \"%a\" and string values.
16818 The sequences in STRING may contain normal field width and padding information,
16819 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16820 so values can contain further %-escapes if they are define later in TABLE."
16821 (let ((case-fold-search nil)
16822 e re rpl)
16823 (while (setq e (pop table))
16824 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16825 (while (string-match re string)
16826 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16827 (cdr e)))
16828 (setq string (replace-match rpl t t string))))
16829 string))
16832 (defun org-sublist (list start end)
16833 "Return a section of LIST, from START to END.
16834 Counting starts at 1."
16835 (let (rtn (c start))
16836 (setq list (nthcdr (1- start) list))
16837 (while (and list (<= c end))
16838 (push (pop list) rtn)
16839 (setq c (1+ c)))
16840 (nreverse rtn)))
16842 (defun org-find-base-buffer-visiting (file)
16843 "Like `find-buffer-visiting' but always return the base buffer and
16844 not an indirect buffer."
16845 (let ((buf (or (get-file-buffer file)
16846 (find-buffer-visiting file))))
16847 (if buf
16848 (or (buffer-base-buffer buf) buf)
16849 nil)))
16851 (defun org-image-file-name-regexp (&optional extensions)
16852 "Return regexp matching the file names of images.
16853 If EXTENSIONS is given, only match these."
16854 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16855 (image-file-name-regexp)
16856 (let ((image-file-name-extensions
16857 (or extensions
16858 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16859 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16860 (concat "\\."
16861 (regexp-opt (nconc (mapcar 'upcase
16862 image-file-name-extensions)
16863 image-file-name-extensions)
16865 "\\'"))))
16867 (defun org-file-image-p (file &optional extensions)
16868 "Return non-nil if FILE is an image."
16869 (save-match-data
16870 (string-match (org-image-file-name-regexp extensions) file)))
16872 (defun org-get-cursor-date ()
16873 "Return the date at cursor in as a time.
16874 This works in the calendar and in the agenda, anywhere else it just
16875 returns the current time."
16876 (let (date day defd)
16877 (cond
16878 ((eq major-mode 'calendar-mode)
16879 (setq date (calendar-cursor-to-date)
16880 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16881 ((eq major-mode 'org-agenda-mode)
16882 (setq day (get-text-property (point) 'day))
16883 (if day
16884 (setq date (calendar-gregorian-from-absolute day)
16885 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16886 (nth 2 date))))))
16887 (or defd (current-time))))
16889 (defvar org-agenda-action-marker (make-marker)
16890 "Marker pointing to the entry for the next agenda action.")
16892 (defun org-mark-entry-for-agenda-action ()
16893 "Mark the current entry as target of an agenda action.
16894 Agenda actions are actions executed from the agenda with the key `k',
16895 which make use of the date at the cursor."
16896 (interactive)
16897 (move-marker org-agenda-action-marker
16898 (save-excursion (org-back-to-heading t) (point))
16899 (current-buffer))
16900 (message
16901 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16903 ;;; Paragraph filling stuff.
16904 ;; We want this to be just right, so use the full arsenal.
16906 (defun org-indent-line-function ()
16907 "Indent line like previous, but further if previous was headline or item."
16908 (interactive)
16909 (let* ((pos (point))
16910 (itemp (org-at-item-p))
16911 (case-fold-search t)
16912 (org-drawer-regexp (or org-drawer-regexp "\000"))
16913 column bpos bcol tpos tcol bullet btype bullet-type)
16914 ;; Find the previous relevant line
16915 (beginning-of-line 1)
16916 (cond
16917 ((looking-at "#") (setq column 0))
16918 ((looking-at "\\*+ ") (setq column 0))
16919 ((and (looking-at "[ \t]*:END:")
16920 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16921 (save-excursion
16922 (goto-char (1- (match-beginning 1)))
16923 (setq column (current-column))))
16924 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16925 (save-excursion
16926 (re-search-backward
16927 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16928 (setq column (org-get-indentation (match-string 0))))
16930 (beginning-of-line 0)
16931 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16932 (not (looking-at "[ \t]*:END:"))
16933 (not (looking-at org-drawer-regexp)))
16934 (beginning-of-line 0))
16935 (cond
16936 ((looking-at "\\*+[ \t]+")
16937 (if (not org-adapt-indentation)
16938 (setq column 0)
16939 (goto-char (match-end 0))
16940 (setq column (current-column))))
16941 ((looking-at org-drawer-regexp)
16942 (goto-char (1- (match-beginning 1)))
16943 (setq column (current-column)))
16944 ((looking-at "\\([ \t]*\\):END:")
16945 (goto-char (match-end 1))
16946 (setq column (current-column)))
16947 ((org-in-item-p)
16948 (org-beginning-of-item)
16949 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16950 (setq bpos (match-beginning 1) tpos (match-end 0)
16951 bcol (progn (goto-char bpos) (current-column))
16952 tcol (progn (goto-char tpos) (current-column))
16953 bullet (match-string 1)
16954 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16955 (if (> tcol (+ bcol org-description-max-indent))
16956 (setq tcol (+ bcol 5)))
16957 (if (not itemp)
16958 (setq column tcol)
16959 (goto-char pos)
16960 (beginning-of-line 1)
16961 (if (looking-at "\\S-")
16962 (progn
16963 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16964 (setq bullet (match-string 1)
16965 btype (if (string-match "[0-9]" bullet) "n" bullet))
16966 (setq column (if (equal btype bullet-type) bcol tcol)))
16967 (setq column (org-get-indentation)))))
16968 (t (setq column (org-get-indentation))))))
16969 (goto-char pos)
16970 (if (<= (current-column) (current-indentation))
16971 (org-indent-line-to column)
16972 (save-excursion (org-indent-line-to column)))
16973 (setq column (current-column))
16974 (beginning-of-line 1)
16975 (if (looking-at
16976 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16977 (replace-match (concat (match-string 1)
16978 (format org-property-format
16979 (match-string 2) (match-string 3)))
16980 t t))
16981 (org-move-to-column column)))
16983 (defun org-set-autofill-regexps ()
16984 (interactive)
16985 ;; In the paragraph separator we include headlines, because filling
16986 ;; text in a line directly attached to a headline would otherwise
16987 ;; fill the headline as well.
16988 (org-set-local 'comment-start-skip "^#+[ \t]*")
16989 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16990 ;; The paragraph starter includes hand-formatted lists.
16991 (org-set-local
16992 'paragraph-start
16993 (concat
16994 "\f" "\\|"
16995 "[ ]*$" "\\|"
16996 "\\*+ " "\\|"
16997 "[ \t]*#" "\\|"
16998 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16999 "[ \t]*[:|]" "\\|"
17000 "\\$\\$" "\\|"
17001 "\\\\\\(begin\\|end\\|[][]\\)"))
17002 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17003 ;; But only if the user has not turned off tables or fixed-width regions
17004 (org-set-local
17005 'auto-fill-inhibit-regexp
17006 (concat "\\*+ \\|#\\+"
17007 "\\|[ \t]*" org-keyword-time-regexp
17008 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17009 (concat
17010 "\\|[ \t]*["
17011 (if org-enable-table-editor "|" "")
17012 (if org-enable-fixed-width-editor ":" "")
17013 "]"))))
17014 ;; We use our own fill-paragraph function, to make sure that tables
17015 ;; and fixed-width regions are not wrapped. That function will pass
17016 ;; through to `fill-paragraph' when appropriate.
17017 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17018 ; Adaptive filling: To get full control, first make sure that
17019 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17020 (org-set-local 'adaptive-fill-regexp "\000")
17021 (org-set-local 'adaptive-fill-function
17022 'org-adaptive-fill-function)
17023 (org-set-local
17024 'align-mode-rules-list
17025 '((org-in-buffer-settings
17026 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17027 (modes . '(org-mode))))))
17029 (defun org-fill-paragraph (&optional justify)
17030 "Re-align a table, pass through to fill-paragraph if no table."
17031 (let ((table-p (org-at-table-p))
17032 (table.el-p (org-at-table.el-p)))
17033 (cond ((and (equal (char-after (point-at-bol)) ?*)
17034 (save-excursion (goto-char (point-at-bol))
17035 (looking-at outline-regexp)))
17036 t) ; skip headlines
17037 (table.el-p t) ; skip table.el tables
17038 (table-p (org-table-align) t) ; align org-mode tables
17039 (t nil)))) ; call paragraph-fill
17041 ;; For reference, this is the default value of adaptive-fill-regexp
17042 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17044 (defun org-adaptive-fill-function ()
17045 "Return a fill prefix for org-mode files.
17046 In particular, this makes sure hanging paragraphs for hand-formatted lists
17047 work correctly."
17048 (cond ((looking-at "#[ \t]+")
17049 (match-string 0))
17050 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17051 (save-excursion
17052 (if (> (match-end 1) (+ (match-beginning 1)
17053 org-description-max-indent))
17054 (goto-char (+ (match-beginning 1) 5))
17055 (goto-char (match-end 0)))
17056 (make-string (current-column) ?\ )))
17057 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17058 (save-excursion
17059 (goto-char (match-end 0))
17060 (make-string (current-column) ?\ )))
17061 (t nil)))
17063 ;;; Other stuff.
17065 (defun org-toggle-fixed-width-section (arg)
17066 "Toggle the fixed-width export.
17067 If there is no active region, the QUOTE keyword at the current headline is
17068 inserted or removed. When present, it causes the text between this headline
17069 and the next to be exported as fixed-width text, and unmodified.
17070 If there is an active region, this command adds or removes a colon as the
17071 first character of this line. If the first character of a line is a colon,
17072 this line is also exported in fixed-width font."
17073 (interactive "P")
17074 (let* ((cc 0)
17075 (regionp (org-region-active-p))
17076 (beg (if regionp (region-beginning) (point)))
17077 (end (if regionp (region-end)))
17078 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17079 (case-fold-search nil)
17080 (re "[ \t]*\\(: \\)")
17081 off)
17082 (if regionp
17083 (save-excursion
17084 (goto-char beg)
17085 (setq cc (current-column))
17086 (beginning-of-line 1)
17087 (setq off (looking-at re))
17088 (while (> nlines 0)
17089 (setq nlines (1- nlines))
17090 (beginning-of-line 1)
17091 (cond
17092 (arg
17093 (org-move-to-column cc t)
17094 (insert ": \n")
17095 (forward-line -1))
17096 ((and off (looking-at re))
17097 (replace-match "" t t nil 1))
17098 ((not off) (org-move-to-column cc t) (insert ": ")))
17099 (forward-line 1)))
17100 (save-excursion
17101 (org-back-to-heading)
17102 (if (looking-at (concat outline-regexp
17103 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17104 (replace-match "" t t nil 1)
17105 (if (looking-at outline-regexp)
17106 (progn
17107 (goto-char (match-end 0))
17108 (insert org-quote-string " "))))))))
17110 (defun org-reftex-citation ()
17111 "Use reftex-citation to insert a citation into the buffer.
17112 This looks for a line like
17114 #+BIBLIOGRAPHY: foo plain option:-d
17116 and derives from it that foo.bib is the bibliography file relevant
17117 for this document. It then installs the necessary environment for RefTeX
17118 to work in this buffer and calls `reftex-citation' to insert a citation
17119 into the buffer.
17121 Export of such citations to both LaTeX and HTML is handled by the contributed
17122 package org-exp-bibtex by Taru Karttunen."
17123 (interactive)
17124 (let ((reftex-docstruct-symbol 'rds)
17125 (reftex-cite-format "\\cite{%l}")
17126 rds bib)
17127 (save-excursion
17128 (save-restriction
17129 (widen)
17130 (let ((case-fold-search t)
17131 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17132 (if (not (save-excursion
17133 (or (re-search-forward re nil t)
17134 (re-search-backward re nil t))))
17135 (error "No bibliography defined in file")
17136 (setq bib (concat (match-string 1) ".bib")
17137 rds (list (list 'bib bib)))))))
17138 (call-interactively 'reftex-citation)))
17140 ;;;; Functions extending outline functionality
17142 (defun org-beginning-of-line (&optional arg)
17143 "Go to the beginning of the current line. If that is invisible, continue
17144 to a visible line beginning. This makes the function of C-a more intuitive.
17145 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17146 first attempt, and only move to after the tags when the cursor is already
17147 beyond the end of the headline."
17148 (interactive "P")
17149 (let ((pos (point))
17150 (special (if (consp org-special-ctrl-a/e)
17151 (car org-special-ctrl-a/e)
17152 org-special-ctrl-a/e))
17153 refpos)
17154 (if (org-bound-and-true-p line-move-visual)
17155 (beginning-of-visual-line 1)
17156 (beginning-of-line 1))
17157 (if (and arg (fboundp 'move-beginning-of-line))
17158 (call-interactively 'move-beginning-of-line)
17159 (if (bobp)
17161 (backward-char 1)
17162 (if (org-invisible-p)
17163 (while (and (not (bobp)) (org-invisible-p))
17164 (backward-char 1)
17165 (beginning-of-line 1))
17166 (forward-char 1))))
17167 (when special
17168 (cond
17169 ((and (looking-at org-complex-heading-regexp)
17170 (= (char-after (match-end 1)) ?\ ))
17171 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17172 (point-at-eol)))
17173 (goto-char
17174 (if (eq special t)
17175 (cond ((> pos refpos) refpos)
17176 ((= pos (point)) refpos)
17177 (t (point)))
17178 (cond ((> pos (point)) (point))
17179 ((not (eq last-command this-command)) (point))
17180 (t refpos)))))
17181 ((org-at-item-p)
17182 (goto-char
17183 (if (eq special t)
17184 (cond ((> pos (match-end 4)) (match-end 4))
17185 ((= pos (point)) (match-end 4))
17186 (t (point)))
17187 (cond ((> pos (point)) (point))
17188 ((not (eq last-command this-command)) (point))
17189 (t (match-end 4))))))))
17190 (org-no-warnings
17191 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17193 (defun org-end-of-line (&optional arg)
17194 "Go to the end of the line.
17195 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17196 first attempt, and only move to after the tags when the cursor is already
17197 beyond the end of the headline."
17198 (interactive "P")
17199 (let ((special (if (consp org-special-ctrl-a/e)
17200 (cdr org-special-ctrl-a/e)
17201 org-special-ctrl-a/e)))
17202 (if (or (not special)
17203 (not (org-on-heading-p))
17204 arg)
17205 (call-interactively
17206 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17207 ((fboundp 'move-end-of-line) 'move-end-of-line)
17208 (t 'end-of-line)))
17209 (let ((pos (point)))
17210 (beginning-of-line 1)
17211 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17212 (if (eq special t)
17213 (if (or (< pos (match-beginning 1))
17214 (= pos (match-end 0)))
17215 (goto-char (match-beginning 1))
17216 (goto-char (match-end 0)))
17217 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17218 (goto-char (match-end 0))
17219 (goto-char (match-beginning 1))))
17220 (call-interactively (if (fboundp 'move-end-of-line)
17221 'move-end-of-line
17222 'end-of-line)))))
17223 (org-no-warnings
17224 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17226 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17227 (define-key org-mode-map "\C-e" 'org-end-of-line)
17228 (define-key org-mode-map [home] 'org-beginning-of-line)
17229 (define-key org-mode-map [end] 'org-end-of-line)
17231 (defun org-backward-sentence (&optional arg)
17232 "Go to beginning of sentence, or beginning of table field.
17233 This will call `backward-sentence' or `org-table-beginning-of-field',
17234 depending on context."
17235 (interactive "P")
17236 (cond
17237 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17238 (t (call-interactively 'backward-sentence))))
17240 (defun org-forward-sentence (&optional arg)
17241 "Go to end of sentence, or end of table field.
17242 This will call `forward-sentence' or `org-table-end-of-field',
17243 depending on context."
17244 (interactive "P")
17245 (cond
17246 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17247 (t (call-interactively 'forward-sentence))))
17249 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17250 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17252 (defun org-kill-line (&optional arg)
17253 "Kill line, to tags or end of line."
17254 (interactive "P")
17255 (cond
17256 ((or (not org-special-ctrl-k)
17257 (bolp)
17258 (not (org-on-heading-p)))
17259 (call-interactively 'kill-line))
17260 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17261 (kill-region (point) (match-beginning 1))
17262 (org-set-tags nil t))
17263 (t (kill-region (point) (point-at-eol)))))
17265 (define-key org-mode-map "\C-k" 'org-kill-line)
17267 (defun org-yank (&optional arg)
17268 "Yank. If the kill is a subtree, treat it specially.
17269 This command will look at the current kill and check if is a single
17270 subtree, or a series of subtrees[1]. If it passes the test, and if the
17271 cursor is at the beginning of a line or after the stars of a currently
17272 empty headline, then the yank is handled specially. How exactly depends
17273 on the value of the following variables, both set by default.
17275 org-yank-folded-subtrees
17276 When set, the subtree(s) will be folded after insertion, but only
17277 if doing so would now swallow text after the yanked text.
17279 org-yank-adjusted-subtrees
17280 When set, the subtree will be promoted or demoted in order to
17281 fit into the local outline tree structure, which means that the level
17282 will be adjusted so that it becomes the smaller one of the two
17283 *visible* surrounding headings.
17285 Any prefix to this command will cause `yank' to be called directly with
17286 no special treatment. In particular, a simple `C-u' prefix will just
17287 plainly yank the text as it is.
17289 \[1] The test checks if the first non-white line is a heading
17290 and if there are no other headings with fewer stars."
17291 (interactive "P")
17292 (org-yank-generic 'yank arg))
17294 (defun org-yank-generic (command arg)
17295 "Perform some yank-like command.
17297 This function implements the behavior described in the `org-yank'
17298 documentation. However, it has been generalized to work for any
17299 interactive command with similar behavior."
17301 ;; pretend to be command COMMAND
17302 (setq this-command command)
17304 (if arg
17305 (call-interactively command)
17307 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17308 (and (org-kill-is-subtree-p)
17309 (or (bolp)
17310 (and (looking-at "[ \t]*$")
17311 (string-match
17312 "\\`\\*+\\'"
17313 (buffer-substring (point-at-bol) (point)))))))
17314 swallowp)
17315 (cond
17316 ((and subtreep org-yank-folded-subtrees)
17317 (let ((beg (point))
17318 end)
17319 (if (and subtreep org-yank-adjusted-subtrees)
17320 (org-paste-subtree nil nil 'for-yank)
17321 (call-interactively command))
17323 (setq end (point))
17324 (goto-char beg)
17325 (when (and (bolp) subtreep
17326 (not (setq swallowp
17327 (org-yank-folding-would-swallow-text beg end))))
17328 (or (looking-at outline-regexp)
17329 (re-search-forward (concat "^" outline-regexp) end t))
17330 (while (and (< (point) end) (looking-at outline-regexp))
17331 (hide-subtree)
17332 (org-cycle-show-empty-lines 'folded)
17333 (condition-case nil
17334 (outline-forward-same-level 1)
17335 (error (goto-char end)))))
17336 (when swallowp
17337 (message
17338 "Inserted text not folded because that would swallow text"))
17340 (goto-char end)
17341 (skip-chars-forward " \t\n\r")
17342 (beginning-of-line 1)
17343 (push-mark beg 'nomsg)))
17344 ((and subtreep org-yank-adjusted-subtrees)
17345 (let ((beg (point-at-bol)))
17346 (org-paste-subtree nil nil 'for-yank)
17347 (push-mark beg 'nomsg)))
17349 (call-interactively command))))))
17351 (defun org-yank-folding-would-swallow-text (beg end)
17352 "Would hide-subtree at BEG swallow any text after END?"
17353 (let (level)
17354 (save-excursion
17355 (goto-char beg)
17356 (when (or (looking-at outline-regexp)
17357 (re-search-forward (concat "^" outline-regexp) end t))
17358 (setq level (org-outline-level)))
17359 (goto-char end)
17360 (skip-chars-forward " \t\r\n\v\f")
17361 (if (or (eobp)
17362 (and (bolp) (looking-at org-outline-regexp)
17363 (<= (org-outline-level) level)))
17364 nil ; Nothing would be swallowed
17365 t)))) ; something would swallow
17367 (define-key org-mode-map "\C-y" 'org-yank)
17369 (defun org-invisible-p ()
17370 "Check if point is at a character currently not visible."
17371 ;; Early versions of noutline don't have `outline-invisible-p'.
17372 (if (fboundp 'outline-invisible-p)
17373 (outline-invisible-p)
17374 (get-char-property (point) 'invisible)))
17376 (defun org-invisible-p2 ()
17377 "Check if point is at a character currently not visible."
17378 (save-excursion
17379 (if (and (eolp) (not (bobp))) (backward-char 1))
17380 ;; Early versions of noutline don't have `outline-invisible-p'.
17381 (if (fboundp 'outline-invisible-p)
17382 (outline-invisible-p)
17383 (get-char-property (point) 'invisible))))
17385 (defun org-back-to-heading (&optional invisible-ok)
17386 "Call `outline-back-to-heading', but provide a better error message."
17387 (condition-case nil
17388 (outline-back-to-heading invisible-ok)
17389 (error (error "Before first headline at position %d in buffer %s"
17390 (point) (current-buffer)))))
17392 (defun org-before-first-heading-p ()
17393 "Before first heading?"
17394 (save-excursion
17395 (null (re-search-backward "^\\*+ " nil t))))
17397 (defun org-on-heading-p (&optional ignored)
17398 (outline-on-heading-p t))
17399 (defun org-at-heading-p (&optional ignored)
17400 (outline-on-heading-p t))
17402 (defun org-at-heading-or-item-p ()
17403 (or (org-on-heading-p) (org-at-item-p)))
17405 (defun org-on-target-p ()
17406 (or (org-in-regexp org-radio-target-regexp)
17407 (org-in-regexp org-target-regexp)))
17409 (defun org-up-heading-all (arg)
17410 "Move to the heading line of which the present line is a subheading.
17411 This function considers both visible and invisible heading lines.
17412 With argument, move up ARG levels."
17413 (if (fboundp 'outline-up-heading-all)
17414 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17415 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17417 (defun org-up-heading-safe ()
17418 "Move to the heading line of which the present line is a subheading.
17419 This version will not throw an error. It will return the level of the
17420 headline found, or nil if no higher level is found.
17422 Also, this function will be a lot faster than `outline-up-heading',
17423 because it relies on stars being the outline starters. This can really
17424 make a significant difference in outlines with very many siblings."
17425 (let (start-level re)
17426 (org-back-to-heading t)
17427 (setq start-level (funcall outline-level))
17428 (if (equal start-level 1)
17430 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17431 (if (re-search-backward re nil t)
17432 (funcall outline-level)))))
17434 (defun org-first-sibling-p ()
17435 "Is this heading the first child of its parents?"
17436 (interactive)
17437 (let ((re (concat "^" outline-regexp))
17438 level l)
17439 (unless (org-at-heading-p t)
17440 (error "Not at a heading"))
17441 (setq level (funcall outline-level))
17442 (save-excursion
17443 (if (not (re-search-backward re nil t))
17445 (setq l (funcall outline-level))
17446 (< l level)))))
17448 (defun org-goto-sibling (&optional previous)
17449 "Goto the next sibling, even if it is invisible.
17450 When PREVIOUS is set, go to the previous sibling instead. Returns t
17451 when a sibling was found. When none is found, return nil and don't
17452 move point."
17453 (let ((fun (if previous 're-search-backward 're-search-forward))
17454 (pos (point))
17455 (re (concat "^" outline-regexp))
17456 level l)
17457 (when (condition-case nil (org-back-to-heading t) (error nil))
17458 (setq level (funcall outline-level))
17459 (catch 'exit
17460 (or previous (forward-char 1))
17461 (while (funcall fun re nil t)
17462 (setq l (funcall outline-level))
17463 (when (< l level) (goto-char pos) (throw 'exit nil))
17464 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17465 (goto-char pos)
17466 nil))))
17468 (defun org-show-siblings ()
17469 "Show all siblings of the current headline."
17470 (save-excursion
17471 (while (org-goto-sibling) (org-flag-heading nil)))
17472 (save-excursion
17473 (while (org-goto-sibling 'previous)
17474 (org-flag-heading nil))))
17476 (defun org-show-hidden-entry ()
17477 "Show an entry where even the heading is hidden."
17478 (save-excursion
17479 (org-show-entry)))
17481 (defun org-flag-heading (flag &optional entry)
17482 "Flag the current heading. FLAG non-nil means make invisible.
17483 When ENTRY is non-nil, show the entire entry."
17484 (save-excursion
17485 (org-back-to-heading t)
17486 ;; Check if we should show the entire entry
17487 (if entry
17488 (progn
17489 (org-show-entry)
17490 (save-excursion
17491 (and (outline-next-heading)
17492 (org-flag-heading nil))))
17493 (outline-flag-region (max (point-min) (1- (point)))
17494 (save-excursion (outline-end-of-heading) (point))
17495 flag))))
17497 (defun org-get-next-sibling ()
17498 "Move to next heading of the same level, and return point.
17499 If there is no such heading, return nil.
17500 This is like outline-next-sibling, but invisible headings are ok."
17501 (let ((level (funcall outline-level)))
17502 (outline-next-heading)
17503 (while (and (not (eobp)) (> (funcall outline-level) level))
17504 (outline-next-heading))
17505 (if (or (eobp) (< (funcall outline-level) level))
17507 (point))))
17509 (defun org-get-last-sibling ()
17510 "Move to previous heading of the same level, and return point.
17511 If there is no such heading, return nil."
17512 (let ((opoint (point))
17513 (level (funcall outline-level)))
17514 (outline-previous-heading)
17515 (when (and (/= (point) opoint) (outline-on-heading-p t))
17516 (while (and (> (funcall outline-level) level)
17517 (not (bobp)))
17518 (outline-previous-heading))
17519 (if (< (funcall outline-level) level)
17521 (point)))))
17523 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17524 ;; This contains an exact copy of the original function, but it uses
17525 ;; `org-back-to-heading', to make it work also in invisible
17526 ;; trees. And is uses an invisible-OK argument.
17527 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17528 ;; Furthermore, when used inside Org, finding the end of a large subtree
17529 ;; with many children and grandchildren etc, this can be much faster
17530 ;; than the outline version.
17531 (org-back-to-heading invisible-OK)
17532 (let ((first t)
17533 (level (funcall outline-level)))
17534 (if (and (org-mode-p) (< level 1000))
17535 ;; A true heading (not a plain list item), in Org-mode
17536 ;; This means we can easily find the end by looking
17537 ;; only for the right number of stars. Using a regexp to do
17538 ;; this is so much faster than using a Lisp loop.
17539 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17540 (forward-char 1)
17541 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17542 ;; something else, do it the slow way
17543 (while (and (not (eobp))
17544 (or first (> (funcall outline-level) level)))
17545 (setq first nil)
17546 (outline-next-heading)))
17547 (unless to-heading
17548 (if (memq (preceding-char) '(?\n ?\^M))
17549 (progn
17550 ;; Go to end of line before heading
17551 (forward-char -1)
17552 (if (memq (preceding-char) '(?\n ?\^M))
17553 ;; leave blank line before heading
17554 (forward-char -1))))))
17555 (point))
17557 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17558 "Use Org version in org-mode, for dramatic speed-up."
17559 (if (eq major-mode 'org-mode)
17560 (progn
17561 (org-end-of-subtree nil t)
17562 (unless (eobp) (backward-char 1)))
17563 ad-do-it))
17565 (defun org-forward-same-level (arg &optional invisible-ok)
17566 "Move forward to the arg'th subheading at same level as this one.
17567 Stop at the first and last subheadings of a superior heading."
17568 (interactive "p")
17569 (org-back-to-heading invisible-ok)
17570 (org-on-heading-p)
17571 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17572 (re (format "^\\*\\{1,%d\\} " level))
17574 (forward-char 1)
17575 (while (> arg 0)
17576 (while (and (re-search-forward re nil 'move)
17577 (setq l (- (match-end 0) (match-beginning 0) 1))
17578 (= l level)
17579 (not invisible-ok)
17580 (progn (backward-char 1) (org-invisible-p)))
17581 (if (< l level) (setq arg 1)))
17582 (setq arg (1- arg)))
17583 (beginning-of-line 1)))
17585 (defun org-backward-same-level (arg &optional invisible-ok)
17586 "Move backward to the arg'th subheading at same level as this one.
17587 Stop at the first and last subheadings of a superior heading."
17588 (interactive "p")
17589 (org-back-to-heading)
17590 (org-on-heading-p)
17591 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17592 (re (format "^\\*\\{1,%d\\} " level))
17594 (while (> arg 0)
17595 (while (and (re-search-backward re nil 'move)
17596 (setq l (- (match-end 0) (match-beginning 0) 1))
17597 (= l level)
17598 (not invisible-ok)
17599 (org-invisible-p))
17600 (if (< l level) (setq arg 1)))
17601 (setq arg (1- arg)))))
17603 (defun org-show-subtree ()
17604 "Show everything after this heading at deeper levels."
17605 (outline-flag-region
17606 (point)
17607 (save-excursion
17608 (org-end-of-subtree t t))
17609 nil))
17611 (defun org-show-entry ()
17612 "Show the body directly following this heading.
17613 Show the heading too, if it is currently invisible."
17614 (interactive)
17615 (save-excursion
17616 (condition-case nil
17617 (progn
17618 (org-back-to-heading t)
17619 (outline-flag-region
17620 (max (point-min) (1- (point)))
17621 (save-excursion
17622 (if (re-search-forward
17623 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17624 (match-beginning 1)
17625 (point-max)))
17626 nil)
17627 (org-cycle-hide-drawers 'children))
17628 (error nil))))
17630 (defun org-make-options-regexp (kwds &optional extra)
17631 "Make a regular expression for keyword lines."
17632 (concat
17634 "#?[ \t]*\\+\\("
17635 (mapconcat 'regexp-quote kwds "\\|")
17636 (if extra (concat "\\|" extra))
17637 "\\):[ \t]*"
17638 "\\(.*\\)"))
17640 ;; Make isearch reveal the necessary context
17641 (defun org-isearch-end ()
17642 "Reveal context after isearch exits."
17643 (when isearch-success ; only if search was successful
17644 (if (featurep 'xemacs)
17645 ;; Under XEmacs, the hook is run in the correct place,
17646 ;; we directly show the context.
17647 (org-show-context 'isearch)
17648 ;; In Emacs the hook runs *before* restoring the overlays.
17649 ;; So we have to use a one-time post-command-hook to do this.
17650 ;; (Emacs 22 has a special variable, see function `org-mode')
17651 (unless (and (boundp 'isearch-mode-end-hook-quit)
17652 isearch-mode-end-hook-quit)
17653 ;; Only when the isearch was not quitted.
17654 (org-add-hook 'post-command-hook 'org-isearch-post-command
17655 'append 'local)))))
17657 (defun org-isearch-post-command ()
17658 "Remove self from hook, and show context."
17659 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17660 (org-show-context 'isearch))
17663 ;;;; Integration with and fixes for other packages
17665 ;;; Imenu support
17667 (defvar org-imenu-markers nil
17668 "All markers currently used by Imenu.")
17669 (make-variable-buffer-local 'org-imenu-markers)
17671 (defun org-imenu-new-marker (&optional pos)
17672 "Return a new marker for use by Imenu, and remember the marker."
17673 (let ((m (make-marker)))
17674 (move-marker m (or pos (point)))
17675 (push m org-imenu-markers)
17678 (defun org-imenu-get-tree ()
17679 "Produce the index for Imenu."
17680 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17681 (setq org-imenu-markers nil)
17682 (let* ((n org-imenu-depth)
17683 (re (concat "^" outline-regexp))
17684 (subs (make-vector (1+ n) nil))
17685 (last-level 0)
17686 m level head)
17687 (save-excursion
17688 (save-restriction
17689 (widen)
17690 (goto-char (point-max))
17691 (while (re-search-backward re nil t)
17692 (setq level (org-reduced-level (funcall outline-level)))
17693 (when (<= level n)
17694 (looking-at org-complex-heading-regexp)
17695 (setq head (org-link-display-format
17696 (org-match-string-no-properties 4))
17697 m (org-imenu-new-marker))
17698 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17699 (if (>= level last-level)
17700 (push (cons head m) (aref subs level))
17701 (push (cons head (aref subs (1+ level))) (aref subs level))
17702 (loop for i from (1+ level) to n do (aset subs i nil)))
17703 (setq last-level level)))))
17704 (aref subs 1)))
17706 (eval-after-load "imenu"
17707 '(progn
17708 (add-hook 'imenu-after-jump-hook
17709 (lambda ()
17710 (if (eq major-mode 'org-mode)
17711 (org-show-context 'org-goto))))))
17713 (defun org-link-display-format (link)
17714 "Replace a link with either the description, or the link target
17715 if no description is present"
17716 (save-match-data
17717 (if (string-match org-bracket-link-analytic-regexp link)
17718 (replace-match (if (match-end 5)
17719 (match-string 5 link)
17720 (concat (match-string 1 link)
17721 (match-string 3 link)))
17722 nil t link)
17723 link)))
17725 ;; Speedbar support
17727 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17728 "Overlay marking the agenda restriction line in speedbar.")
17729 (org-overlay-put org-speedbar-restriction-lock-overlay
17730 'face 'org-agenda-restriction-lock)
17731 (org-overlay-put org-speedbar-restriction-lock-overlay
17732 'help-echo "Agendas are currently limited to this item.")
17733 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17735 (defun org-speedbar-set-agenda-restriction ()
17736 "Restrict future agenda commands to the location at point in speedbar.
17737 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17738 (interactive)
17739 (require 'org-agenda)
17740 (let (p m tp np dir txt)
17741 (cond
17742 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17743 'org-imenu t))
17744 (setq m (get-text-property p 'org-imenu-marker))
17745 (with-current-buffer (marker-buffer m)
17746 (goto-char m)
17747 (org-agenda-set-restriction-lock 'subtree)))
17748 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17749 'speedbar-function 'speedbar-find-file))
17750 (setq tp (previous-single-property-change
17751 (1+ p) 'speedbar-function)
17752 np (next-single-property-change
17753 tp 'speedbar-function)
17754 dir (speedbar-line-directory)
17755 txt (buffer-substring-no-properties (or tp (point-min))
17756 (or np (point-max))))
17757 (with-current-buffer (find-file-noselect
17758 (let ((default-directory dir))
17759 (expand-file-name txt)))
17760 (unless (org-mode-p)
17761 (error "Cannot restrict to non-Org-mode file"))
17762 (org-agenda-set-restriction-lock 'file)))
17763 (t (error "Don't know how to restrict Org-mode's agenda")))
17764 (org-move-overlay org-speedbar-restriction-lock-overlay
17765 (point-at-bol) (point-at-eol))
17766 (setq current-prefix-arg nil)
17767 (org-agenda-maybe-redo)))
17769 (eval-after-load "speedbar"
17770 '(progn
17771 (speedbar-add-supported-extension ".org")
17772 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17773 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17774 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17775 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17776 (add-hook 'speedbar-visiting-tag-hook
17777 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17780 ;;; Fixes and Hacks for problems with other packages
17782 ;; Make flyspell not check words in links, to not mess up our keymap
17783 (defun org-mode-flyspell-verify ()
17784 "Don't let flyspell put overlays at active buttons."
17785 (and (not (get-text-property (point) 'keymap))
17786 (not (get-text-property (point) 'org-no-flyspell))))
17788 (defun org-remove-flyspell-overlays-in (beg end)
17789 "Remove flyspell overlays in region."
17790 (and (org-bound-and-true-p flyspell-mode)
17791 (fboundp 'flyspell-delete-region-overlays)
17792 (flyspell-delete-region-overlays beg end))
17793 (add-text-properties beg end '(org-no-flyspell t)))
17795 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17796 (eval-after-load "bookmark"
17797 '(if (boundp 'bookmark-after-jump-hook)
17798 ;; We can use the hook
17799 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17800 ;; Hook not available, use advice
17801 (defadvice bookmark-jump (after org-make-visible activate)
17802 "Make the position visible."
17803 (org-bookmark-jump-unhide))))
17805 ;; Make sure saveplace shows the location if it was hidden
17806 (eval-after-load "saveplace"
17807 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17808 "Make the position visible."
17809 (org-bookmark-jump-unhide)))
17811 ;; Make sure ecb shows the location if it was hidden
17812 (eval-after-load "ecb"
17813 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17814 "Make hierarchy visible when jumping into location from ECB tree buffer."
17815 (if (eq major-mode 'org-mode)
17816 (org-show-context))))
17818 (defun org-bookmark-jump-unhide ()
17819 "Unhide the current position, to show the bookmark location."
17820 (and (org-mode-p)
17821 (or (org-invisible-p)
17822 (save-excursion (goto-char (max (point-min) (1- (point))))
17823 (org-invisible-p)))
17824 (org-show-context 'bookmark-jump)))
17826 ;; Make session.el ignore our circular variable
17827 (eval-after-load "session"
17828 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17830 ;;;; Experimental code
17832 (defun org-closed-in-range ()
17833 "Sparse tree of items closed in a certain time range.
17834 Still experimental, may disappear in the future."
17835 (interactive)
17836 ;; Get the time interval from the user.
17837 (let* ((time1 (org-float-time
17838 (org-read-date nil 'to-time nil "Starting date: ")))
17839 (time2 (org-float-time
17840 (org-read-date nil 'to-time nil "End date:")))
17841 ;; callback function
17842 (callback (lambda ()
17843 (let ((time
17844 (org-float-time
17845 (apply 'encode-time
17846 (org-parse-time-string
17847 (match-string 1))))))
17848 ;; check if time in interval
17849 (and (>= time time1) (<= time time2))))))
17850 ;; make tree, check each match with the callback
17851 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17853 ;;;; Finish up
17855 (provide 'org)
17857 (run-hooks 'org-load-hook)
17859 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17861 ;;; org.el ends here