Capture link path into a group
[org-mode.git] / lisp / org.el
blob1e82be3acd89e0951d266c854e9d70b6b27f8d63
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-docview 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 " docview: Links to doc-view buffers" org-docview)
193 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
194 (const :tag " id: Global IDs for identifying entries" org-id)
195 (const :tag " info: Links to Info nodes" org-info)
196 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
197 (const :tag " habit: Track your consistency with habits" org-habit)
198 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
199 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
200 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
201 (const :tag " mew Links to Mew folders/messages" org-mew)
202 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
203 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
204 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
205 (const :tag " vm: Links to VM folders/messages" org-vm)
206 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
207 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
208 (const :tag " mouse: Additional mouse support" org-mouse)
210 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
211 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
212 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
213 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
214 (const :tag "C collector: Collect properties into tables" org-collector)
215 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
216 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
217 (const :tag "C eval: Include command output as text" org-eval)
218 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
219 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
220 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
221 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
222 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
224 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
226 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
227 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
228 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
229 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
230 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
231 (const :tag "C mtags: Support for muse-like tags" org-mtags)
232 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
233 (const :tag "C R: Computation using the R language" org-R)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
238 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
239 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
240 (const :tag "C track: Keep up with Org-mode development" org-track)
241 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
243 (defcustom org-support-shift-select nil
244 "Non-nil means, make shift-cursor commands select text when possible.
246 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
247 selecting a region, or enlarge thusly regions started in this way.
248 In Org-mode, in special contexts, these same keys are used for other
249 purposes, important enough to compete with shift selection. Org tries
250 to balance these needs by supporting `shift-select-mode' outside these
251 special contexts, under control of this variable.
253 The default of this variable is nil, to avoid confusing behavior. Shifted
254 cursor keys will then execute Org commands in the following contexts:
255 - on a headline, changing TODO state (left/right) and priority (up/down)
256 - on a time stamp, changing the time
257 - in a plain list item, changing the bullet type
258 - in a property definition line, switching between allowed values
259 - in the BEGIN line of a clock table (changing the time block).
260 Outside these contexts, the commands will throw an error.
262 When this variable is t and the cursor is not in a special context,
263 Org-mode will support shift-selection for making and enlarging regions.
264 To make this more effective, the bullet cycling will no longer happen
265 anywhere in an item line, but only if the cursor is exactly on the bullet.
267 If you set this variable to the symbol `always', then the keys
268 will not be special in headlines, property lines, and item lines, to make
269 shift selection work there as well. If this is what you want, you can
270 use the following alternative commands: `C-c C-t' and `C-c ,' to
271 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
272 TODO sets, `C-c -' to cycle item bullet types, and properties can be
273 edited by hand or in column view.
275 However, when the cursor is on a timestamp, shift-cursor commands
276 will still edit the time stamp - this is just too good to give up.
278 XEmacs user should have this variable set to nil, because shift-select-mode
279 is Emacs 23 only."
280 :group 'org
281 :type '(choice
282 (const :tag "Never" nil)
283 (const :tag "When outside special context" t)
284 (const :tag "Everywhere except timestamps" always)))
286 (defgroup org-startup nil
287 "Options concerning startup of Org-mode."
288 :tag "Org Startup"
289 :group 'org)
291 (defcustom org-startup-folded t
292 "Non-nil means, entering Org-mode will switch to OVERVIEW.
293 This can also be configured on a per-file basis by adding one of
294 the following lines anywhere in the buffer:
296 #+STARTUP: fold (or `overview', this is equivalent)
297 #+STARTUP: nofold (or `showall', this is equivalent)
298 #+STARTUP: content
299 #+STARTUP: showeverything"
300 :group 'org-startup
301 :type '(choice
302 (const :tag "nofold: show all" nil)
303 (const :tag "fold: overview" t)
304 (const :tag "content: all headlines" content)
305 (const :tag "show everything, even drawers" showeverything)))
307 (defcustom org-startup-truncated t
308 "Non-nil means, entering Org-mode will set `truncate-lines'.
309 This is useful since some lines containing links can be very long and
310 uninteresting. Also tables look terrible when wrapped."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-startup-indented nil
315 "Non-nil means, turn on `org-indent-mode' on startup.
316 This can also be configured on a per-file basis by adding one of
317 the following lines anywhere in the buffer:
319 #+STARTUP: indent
320 #+STARTUP: noindent"
321 :group 'org-structure
322 :type '(choice
323 (const :tag "Not" nil)
324 (const :tag "Globally (slow on startup in large files)" t)))
326 (defcustom org-startup-with-beamer-mode nil
327 "Non-nil means, turn on `org-beamer-mode' on startup.
328 This can also be configured on a per-file basis by adding one of
329 the following lines anywhere in the buffer:
331 #+STARTUP: beamer"
332 :group 'org-startup
333 :type 'boolean)
335 (defcustom org-startup-align-all-tables nil
336 "Non-nil means, align all tables when visiting a file.
337 This is useful when the column width in tables is forced with <N> cookies
338 in table fields. Such tables will look correct only after the first re-align.
339 This can also be configured on a per-file basis by adding one of
340 the following lines anywhere in the buffer:
341 #+STARTUP: align
342 #+STARTUP: noalign"
343 :group 'org-startup
344 :type 'boolean)
346 (defcustom org-insert-mode-line-in-empty-file nil
347 "Non-nil means insert the first line setting Org-mode in empty files.
348 When the function `org-mode' is called interactively in an empty file, this
349 normally means that the file name does not automatically trigger Org-mode.
350 To ensure that the file will always be in Org-mode in the future, a
351 line enforcing Org-mode will be inserted into the buffer, if this option
352 has been set."
353 :group 'org-startup
354 :type 'boolean)
356 (defcustom org-replace-disputed-keys nil
357 "Non-nil means use alternative key bindings for some keys.
358 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
359 These keys are also used by other packages like shift-selection-mode'
360 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
361 If you want to use Org-mode together with one of these other modes,
362 or more generally if you would like to move some Org-mode commands to
363 other keys, set this variable and configure the keys with the variable
364 `org-disputed-keys'.
366 This option is only relevant at load-time of Org-mode, and must be set
367 *before* org.el is loaded. Changing it requires a restart of Emacs to
368 become effective."
369 :group 'org-startup
370 :type 'boolean)
372 (defcustom org-use-extra-keys nil
373 "Non-nil means use extra key sequence definitions for certain
374 commands. This happens automatically if you run XEmacs or if
375 window-system is nil. This variable lets you do the same
376 manually. You must set it before loading org.
378 Example: on Carbon Emacs 22 running graphically, with an external
379 keyboard on a Powerbook, the default way of setting M-left might
380 not work for either Alt or ESC. Setting this variable will make
381 it work for ESC."
382 :group 'org-startup
383 :type 'boolean)
385 (if (fboundp 'defvaralias)
386 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
388 (defcustom org-disputed-keys
389 '(([(shift up)] . [(meta p)])
390 ([(shift down)] . [(meta n)])
391 ([(shift left)] . [(meta -)])
392 ([(shift right)] . [(meta +)])
393 ([(control shift right)] . [(meta shift +)])
394 ([(control shift left)] . [(meta shift -)]))
395 "Keys for which Org-mode and other modes compete.
396 This is an alist, cars are the default keys, second element specifies
397 the alternative to use when `org-replace-disputed-keys' is t.
399 Keys can be specified in any syntax supported by `define-key'.
400 The value of this option takes effect only at Org-mode's startup,
401 therefore you'll have to restart Emacs to apply it after changing."
402 :group 'org-startup
403 :type 'alist)
405 (defun org-key (key)
406 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
407 Or return the original if not disputed."
408 (if org-replace-disputed-keys
409 (let* ((nkey (key-description key))
410 (x (org-find-if (lambda (x)
411 (equal (key-description (car x)) nkey))
412 org-disputed-keys)))
413 (if x (cdr x) key))
414 key))
416 (defun org-find-if (predicate seq)
417 (catch 'exit
418 (while seq
419 (if (funcall predicate (car seq))
420 (throw 'exit (car seq))
421 (pop seq)))))
423 (defun org-defkey (keymap key def)
424 "Define a key, possibly translated, as returned by `org-key'."
425 (define-key keymap (org-key key) def))
427 (defcustom org-ellipsis nil
428 "The ellipsis to use in the Org-mode outline.
429 When nil, just use the standard three dots. When a string, use that instead,
430 When a face, use the standard 3 dots, but with the specified face.
431 The change affects only Org-mode (which will then use its own display table).
432 Changing this requires executing `M-x org-mode' in a buffer to become
433 effective."
434 :group 'org-startup
435 :type '(choice (const :tag "Default" nil)
436 (face :tag "Face" :value org-warning)
437 (string :tag "String" :value "...#")))
439 (defvar org-display-table nil
440 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
442 (defgroup org-keywords nil
443 "Keywords in Org-mode."
444 :tag "Org Keywords"
445 :group 'org)
447 (defcustom org-deadline-string "DEADLINE:"
448 "String to mark deadline entries.
449 A deadline is this string, followed by a time stamp. Should be a word,
450 terminated by a colon. You can insert a schedule keyword and
451 a timestamp with \\[org-deadline].
452 Changes become only effective after restarting Emacs."
453 :group 'org-keywords
454 :type 'string)
456 (defcustom org-scheduled-string "SCHEDULED:"
457 "String to mark scheduled TODO entries.
458 A schedule is this string, followed by a time stamp. Should be a word,
459 terminated by a colon. You can insert a schedule keyword and
460 a timestamp with \\[org-schedule].
461 Changes become only effective after restarting Emacs."
462 :group 'org-keywords
463 :type 'string)
465 (defcustom org-closed-string "CLOSED:"
466 "String used as the prefix for timestamps logging closing a TODO entry."
467 :group 'org-keywords
468 :type 'string)
470 (defcustom org-clock-string "CLOCK:"
471 "String used as prefix for timestamps clocking work hours on an item."
472 :group 'org-keywords
473 :type 'string)
475 (defcustom org-comment-string "COMMENT"
476 "Entries starting with this keyword will never be exported.
477 An entry can be toggled between COMMENT and normal with
478 \\[org-toggle-comment].
479 Changes become only effective after restarting Emacs."
480 :group 'org-keywords
481 :type 'string)
483 (defcustom org-quote-string "QUOTE"
484 "Entries starting with this keyword will be exported in fixed-width font.
485 Quoting applies only to the text in the entry following the headline, and does
486 not extend beyond the next headline, even if that is lower level.
487 An entry can be toggled between QUOTE and normal with
488 \\[org-toggle-fixed-width-section]."
489 :group 'org-keywords
490 :type 'string)
492 (defconst org-repeat-re
493 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
494 "Regular expression for specifying repeated events.
495 After a match, group 1 contains the repeat expression.")
497 (defgroup org-structure nil
498 "Options concerning the general structure of Org-mode files."
499 :tag "Org Structure"
500 :group 'org)
502 (defgroup org-reveal-location nil
503 "Options about how to make context of a location visible."
504 :tag "Org Reveal Location"
505 :group 'org-structure)
507 (defconst org-context-choice
508 '(choice
509 (const :tag "Always" t)
510 (const :tag "Never" nil)
511 (repeat :greedy t :tag "Individual contexts"
512 (cons
513 (choice :tag "Context"
514 (const agenda)
515 (const org-goto)
516 (const occur-tree)
517 (const tags-tree)
518 (const link-search)
519 (const mark-goto)
520 (const bookmark-jump)
521 (const isearch)
522 (const default))
523 (boolean))))
524 "Contexts for the reveal options.")
526 (defcustom org-show-hierarchy-above '((default . t))
527 "Non-nil means, show full hierarchy when revealing a location.
528 Org-mode often shows locations in an org-mode file which might have
529 been invisible before. When this is set, the hierarchy of headings
530 above the exposed location is shown.
531 Turning this off for example for sparse trees makes them very compact.
532 Instead of t, this can also be an alist specifying this option for different
533 contexts. Valid contexts are
534 agenda when exposing an entry from the agenda
535 org-goto when using the command `org-goto' on key C-c C-j
536 occur-tree when using the command `org-occur' on key C-c /
537 tags-tree when constructing a sparse tree based on tags matches
538 link-search when exposing search matches associated with a link
539 mark-goto when exposing the jump goal of a mark
540 bookmark-jump when exposing a bookmark location
541 isearch when exiting from an incremental search
542 default default for all contexts not set explicitly"
543 :group 'org-reveal-location
544 :type org-context-choice)
546 (defcustom org-show-following-heading '((default . nil))
547 "Non-nil means, show following heading when revealing a location.
548 Org-mode often shows locations in an org-mode file which might have
549 been invisible before. When this is set, the heading following the
550 match is shown.
551 Turning this off for example for sparse trees makes them very compact,
552 but makes it harder to edit the location of the match. In such a case,
553 use the command \\[org-reveal] to show more context.
554 Instead of t, this can also be an alist specifying this option for different
555 contexts. See `org-show-hierarchy-above' for valid contexts."
556 :group 'org-reveal-location
557 :type org-context-choice)
559 (defcustom org-show-siblings '((default . nil) (isearch t))
560 "Non-nil means, show all sibling heading when revealing a location.
561 Org-mode often shows locations in an org-mode file which might have
562 been invisible before. When this is set, the sibling of the current entry
563 heading are all made visible. If `org-show-hierarchy-above' is t,
564 the same happens on each level of the hierarchy above the current entry.
566 By default this is on for the isearch context, off for all other contexts.
567 Turning this off for example for sparse trees makes them very compact,
568 but makes it harder to edit the location of the match. In such a case,
569 use the command \\[org-reveal] to show more context.
570 Instead of t, this can also be an alist specifying this option for different
571 contexts. See `org-show-hierarchy-above' for valid contexts."
572 :group 'org-reveal-location
573 :type org-context-choice)
575 (defcustom org-show-entry-below '((default . nil))
576 "Non-nil means, show the entry below a headline when revealing a location.
577 Org-mode often shows locations in an org-mode file which might have
578 been invisible before. When this is set, the text below the headline that is
579 exposed is also shown.
581 By default this is off for all contexts.
582 Instead of t, this can also be an alist specifying this option for different
583 contexts. See `org-show-hierarchy-above' for valid contexts."
584 :group 'org-reveal-location
585 :type org-context-choice)
587 (defcustom org-indirect-buffer-display 'other-window
588 "How should indirect tree buffers be displayed?
589 This applies to indirect buffers created with the commands
590 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
591 Valid values are:
592 current-window Display in the current window
593 other-window Just display in another window.
594 dedicated-frame Create one new frame, and re-use it each time.
595 new-frame Make a new frame each time. Note that in this case
596 previously-made indirect buffers are kept, and you need to
597 kill these buffers yourself."
598 :group 'org-structure
599 :group 'org-agenda-windows
600 :type '(choice
601 (const :tag "In current window" current-window)
602 (const :tag "In current frame, other window" other-window)
603 (const :tag "Each time a new frame" new-frame)
604 (const :tag "One dedicated frame" dedicated-frame)))
606 (defcustom org-use-speed-commands nil
607 "Non-nil means, activate single letter commands at beginning of a headline.
608 This may also be a function to test for appropriate locations where speed
609 commands should be active."
610 :group 'org-structure
611 :type '(choice
612 (const :tag "Never" nil)
613 (const :tag "At beginning of headline stars" t)
614 (function)))
616 (defcustom org-speed-commands-user nil
617 "Alist of additional speed commands.
618 This list will be checked before `org-speed-commands-default'
619 when the variable `org-use-speed-commands' is non-nil
620 and when the cursor is at the beginning of a headline.
621 The car if each entry is a string with a single letter, which must
622 be assigned to `self-insert-command' in the global map.
623 The cdr is either a command to be called interactively, a function
624 to be called, or a form to be evaluated.
625 An entry that is just a list with a single string will be interpreted
626 as a descriptive headline that will be added when listing the speed
627 copmmands in the Help buffer using the `?' speed command."
628 :group 'org-structure
629 :type '(repeat :value ("k" . ignore)
630 (choice :value ("k" . ignore)
631 (list :tag "Descriptive Headline" (string :tag "Headline"))
632 (cons :tag "Letter and Command"
633 (string :tag "Command letter")
634 (choice
635 (function)
636 (sexp))))))
638 (defgroup org-cycle nil
639 "Options concerning visibility cycling in Org-mode."
640 :tag "Org Cycle"
641 :group 'org-structure)
643 (defcustom org-cycle-skip-children-state-if-no-children t
644 "Non-nil means, skip CHILDREN state in entries that don't have any."
645 :group 'org-cycle
646 :type 'boolean)
648 (defcustom org-cycle-max-level nil
649 "Maximum level which should still be subject to visibility cycling.
650 Levels higher than this will, for cycling, be treated as text, not a headline.
651 When `org-odd-levels-only' is set, a value of N in this variable actually
652 means 2N-1 stars as the limiting headline.
653 When nil, cycle all levels.
654 Note that the limiting level of cycling is also influenced by
655 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
656 `org-inlinetask-min-level' is, cycling will be limited to levels one less
657 than its value."
658 :group 'org-cycle
659 :type '(choice
660 (const :tag "No limit" nil)
661 (integer :tag "Maximum level")))
663 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
664 "Names of drawers. Drawers are not opened by cycling on the headline above.
665 Drawers only open with a TAB on the drawer line itself. A drawer looks like
666 this:
667 :DRAWERNAME:
668 .....
669 :END:
670 The drawer \"PROPERTIES\" is special for capturing properties through
671 the property API.
673 Drawers can be defined on the per-file basis with a line like:
675 #+DRAWERS: HIDDEN STATE PROPERTIES"
676 :group 'org-structure
677 :group 'org-cycle
678 :type '(repeat (string :tag "Drawer Name")))
680 (defcustom org-hide-block-startup nil
681 "Non-nil means, , entering Org-mode will fold all blocks.
682 This can also be set in on a per-file basis with
684 #+STARTUP: hideblocks
685 #+STARTUP: showblocks"
686 :group 'org-startup
687 :group 'org-cycle
688 :type 'boolean)
690 (defcustom org-cycle-global-at-bob nil
691 "Cycle globally if cursor is at beginning of buffer and not at a headline.
692 This makes it possible to do global cycling without having to use S-TAB or
693 C-u TAB. For this special case to work, the first line of the buffer
694 must not be a headline - it may be empty or some other text. When used in
695 this way, `org-cycle-hook' is disables temporarily, to make sure the
696 cursor stays at the beginning of the buffer.
697 When this option is nil, don't do anything special at the beginning
698 of the buffer."
699 :group 'org-cycle
700 :type 'boolean)
702 (defcustom org-cycle-level-after-item/entry-creation t
703 "Non-nil means, cycle entry level or item indentation in new empty entries.
705 When the cursor is at the end of an empty headline, i.e with only stars
706 and maybe a TODO keyword, TAB will then switch the entry to become a child,
707 and then all possible anchestor states, before returning to the original state.
708 This makes data entry extremely fast: M-RET to create a new headline,
709 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
711 When the cursor is at the end of an empty plain list item, one TAB will
712 make it a subitem, two or more tabs will back up to make this an item
713 higher up in the item hierarchy."
714 :group 'org-cycle
715 :type 'boolean)
717 (defcustom org-cycle-emulate-tab t
718 "Where should `org-cycle' emulate TAB.
719 nil Never
720 white Only in completely white lines
721 whitestart Only at the beginning of lines, before the first non-white char
722 t Everywhere except in headlines
723 exc-hl-bol Everywhere except at the start of a headline
724 If TAB is used in a place where it does not emulate TAB, the current subtree
725 visibility is cycled."
726 :group 'org-cycle
727 :type '(choice (const :tag "Never" nil)
728 (const :tag "Only in completely white lines" white)
729 (const :tag "Before first char in a line" whitestart)
730 (const :tag "Everywhere except in headlines" t)
731 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
734 (defcustom org-cycle-separator-lines 2
735 "Number of empty lines needed to keep an empty line between collapsed trees.
736 If you leave an empty line between the end of a subtree and the following
737 headline, this empty line is hidden when the subtree is folded.
738 Org-mode will leave (exactly) one empty line visible if the number of
739 empty lines is equal or larger to the number given in this variable.
740 So the default 2 means, at least 2 empty lines after the end of a subtree
741 are needed to produce free space between a collapsed subtree and the
742 following headline.
744 If the number is negative, and the number of empty lines is at least -N,
745 all empty lines are shown.
747 Special case: when 0, never leave empty lines in collapsed view."
748 :group 'org-cycle
749 :type 'integer)
750 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
752 (defcustom org-pre-cycle-hook nil
753 "Hook that is run before visibility cycling is happening.
754 The function(s) in this hook must accept a single argument which indicates
755 the new state that will be set right after running this hook. The
756 argument is a symbol. Before a global state change, it can have the values
757 `overview', `content', or `all'. Before a local state change, it can have
758 the values `folded', `children', or `subtree'."
759 :group 'org-cycle
760 :type 'hook)
762 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
763 org-cycle-hide-drawers
764 org-cycle-show-empty-lines
765 org-optimize-window-after-visibility-change)
766 "Hook that is run after `org-cycle' has changed the buffer visibility.
767 The function(s) in this hook must accept a single argument which indicates
768 the new state that was set by the most recent `org-cycle' command. The
769 argument is a symbol. After a global state change, it can have the values
770 `overview', `content', or `all'. After a local state change, it can have
771 the values `folded', `children', or `subtree'."
772 :group 'org-cycle
773 :type 'hook)
775 (defgroup org-edit-structure nil
776 "Options concerning structure editing in Org-mode."
777 :tag "Org Edit Structure"
778 :group 'org-structure)
780 (defcustom org-odd-levels-only nil
781 "Non-nil means, skip even levels and only use odd levels for the outline.
782 This has the effect that two stars are being added/taken away in
783 promotion/demotion commands. It also influences how levels are
784 handled by the exporters.
785 Changing it requires restart of `font-lock-mode' to become effective
786 for fontification also in regions already fontified.
787 You may also set this on a per-file basis by adding one of the following
788 lines to the buffer:
790 #+STARTUP: odd
791 #+STARTUP: oddeven"
792 :group 'org-edit-structure
793 :group 'org-font-lock
794 :type 'boolean)
796 (defcustom org-adapt-indentation t
797 "Non-nil means, adapt indentation to outline node level.
799 When this variable is set, Org assumes that you write outlines by
800 indenting text in each node to align with the headline (after the stars).
801 The following issues are influenced by this variable:
803 - When this is set and the *entire* text in an entry is indented, the
804 indentation is increased by one space in a demotion command, and
805 decreased by one in a promotion command. If any line in the entry
806 body starts with text at column 0, indentation is not changed at all.
808 - Property drawers and planning information is inserted indented when
809 this variable s set. When nil, they will not be indented.
811 - TAB indents a line relative to context. The lines below a headline
812 will be indented when this variable is set.
814 Note that this is all about true indentation, by adding and removing
815 space characters. See also `org-indent.el' which does level-dependent
816 indentation in a virtual way, i.e. at display time in Emacs."
817 :group 'org-edit-structure
818 :type 'boolean)
820 (defcustom org-special-ctrl-a/e nil
821 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
823 When t, `C-a' will bring back the cursor to the beginning of the
824 headline text, i.e. after the stars and after a possible TODO keyword.
825 In an item, this will be the position after the bullet.
826 When the cursor is already at that position, another `C-a' will bring
827 it to the beginning of the line.
829 `C-e' will jump to the end of the headline, ignoring the presence of tags
830 in the headline. A second `C-e' will then jump to the true end of the
831 line, after any tags. This also means that, when this variable is
832 non-nil, `C-e' also will never jump beyond the end of the heading of a
833 folded section, i.e. not after the ellipses.
835 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
836 going to the true line boundary first. Only a directly following, identical
837 keypress will bring the cursor to the special positions.
839 This may also be a cons cell where the behavior for `C-a' and `C-e' is
840 set separately."
841 :group 'org-edit-structure
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on: after stars/bullet and before tags first" t)
845 (const :tag "reversed: true line boundary first" reversed)
846 (cons :tag "Set C-a and C-e separately"
847 (choice :tag "Special C-a"
848 (const :tag "off" nil)
849 (const :tag "on: after stars/bullet first" t)
850 (const :tag "reversed: before stars/bullet first" reversed))
851 (choice :tag "Special C-e"
852 (const :tag "off" nil)
853 (const :tag "on: before tags first" t)
854 (const :tag "reversed: after tags first" reversed)))))
855 (if (fboundp 'defvaralias)
856 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
858 (defcustom org-special-ctrl-k nil
859 "Non-nil means `C-k' will behave specially in headlines.
860 When nil, `C-k' will call the default `kill-line' command.
861 When t, the following will happen while the cursor is in the headline:
863 - When the cursor is at the beginning of a headline, kill the entire
864 line and possible the folded subtree below the line.
865 - When in the middle of the headline text, kill the headline up to the tags.
866 - When after the headline text, kill the tags."
867 :group 'org-edit-structure
868 :type 'boolean)
870 (defcustom org-yank-folded-subtrees t
871 "Non-nil means, when yanking subtrees, fold them.
872 If the kill is a single subtree, or a sequence of subtrees, i.e. if
873 it starts with a heading and all other headings in it are either children
874 or siblings, then fold all the subtrees. However, do this only if no
875 text after the yank would be swallowed into a folded tree by this action."
876 :group 'org-edit-structure
877 :type 'boolean)
879 (defcustom org-yank-adjusted-subtrees nil
880 "Non-nil means, when yanking subtrees, adjust the level.
881 With this setting, `org-paste-subtree' is used to insert the subtree, see
882 this function for details."
883 :group 'org-edit-structure
884 :type 'boolean)
886 (defcustom org-M-RET-may-split-line '((default . t))
887 "Non-nil means, M-RET will split the line at the cursor position.
888 When nil, it will go to the end of the line before making a
889 new line.
890 You may also set this option in a different way for different
891 contexts. Valid contexts are:
893 headline when creating a new headline
894 item when creating a new item
895 table in a table field
896 default the value to be used for all contexts not explicitly
897 customized"
898 :group 'org-structure
899 :group 'org-table
900 :type '(choice
901 (const :tag "Always" t)
902 (const :tag "Never" nil)
903 (repeat :greedy t :tag "Individual contexts"
904 (cons
905 (choice :tag "Context"
906 (const headline)
907 (const item)
908 (const table)
909 (const default))
910 (boolean)))))
913 (defcustom org-insert-heading-respect-content nil
914 "Non-nil means, insert new headings after the current subtree.
915 When nil, the new heading is created directly after the current line.
916 The commands \\[org-insert-heading-respect-content] and
917 \\[org-insert-todo-heading-respect-content] turn this variable on
918 for the duration of the command."
919 :group 'org-structure
920 :type 'boolean)
922 (defcustom org-blank-before-new-entry '((heading . auto)
923 (plain-list-item . auto))
924 "Should `org-insert-heading' leave a blank line before new heading/item?
925 The value is an alist, with `heading' and `plain-list-item' as car,
926 and a boolean flag as cdr. For plain lists, if the variable
927 `org-empty-line-terminates-plain-lists' is set, the setting here
928 is ignored and no empty line is inserted, to keep the list in tact."
929 :group 'org-edit-structure
930 :type '(list
931 (cons (const heading)
932 (choice (const :tag "Never" nil)
933 (const :tag "Always" t)
934 (const :tag "Auto" auto)))
935 (cons (const plain-list-item)
936 (choice (const :tag "Never" nil)
937 (const :tag "Always" t)
938 (const :tag "Auto" auto)))))
940 (defcustom org-insert-heading-hook nil
941 "Hook being run after inserting a new heading."
942 :group 'org-edit-structure
943 :type 'hook)
945 (defcustom org-enable-fixed-width-editor t
946 "Non-nil means, lines starting with \":\" are treated as fixed-width.
947 This currently only means, they are never auto-wrapped.
948 When nil, such lines will be treated like ordinary lines.
949 See also the QUOTE keyword."
950 :group 'org-edit-structure
951 :type 'boolean)
954 (defcustom org-goto-auto-isearch t
955 "Non-nil means, typing characters in org-goto starts incremental search."
956 :group 'org-edit-structure
957 :type 'boolean)
959 (defgroup org-sparse-trees nil
960 "Options concerning sparse trees in Org-mode."
961 :tag "Org Sparse Trees"
962 :group 'org-structure)
964 (defcustom org-highlight-sparse-tree-matches t
965 "Non-nil means, highlight all matches that define a sparse tree.
966 The highlights will automatically disappear the next time the buffer is
967 changed by an edit command."
968 :group 'org-sparse-trees
969 :type 'boolean)
971 (defcustom org-remove-highlights-with-change t
972 "Non-nil means, any change to the buffer will remove temporary highlights.
973 Such highlights are created by `org-occur' and `org-clock-display'.
974 When nil, `C-c C-c needs to be used to get rid of the highlights.
975 The highlights created by `org-preview-latex-fragment' always need
976 `C-c C-c' to be removed."
977 :group 'org-sparse-trees
978 :group 'org-time
979 :type 'boolean)
982 (defcustom org-occur-hook '(org-first-headline-recenter)
983 "Hook that is run after `org-occur' has constructed a sparse tree.
984 This can be used to recenter the window to show as much of the structure
985 as possible."
986 :group 'org-sparse-trees
987 :type 'hook)
989 (defgroup org-imenu-and-speedbar nil
990 "Options concerning imenu and speedbar in Org-mode."
991 :tag "Org Imenu and Speedbar"
992 :group 'org-structure)
994 (defcustom org-imenu-depth 2
995 "The maximum level for Imenu access to Org-mode headlines.
996 This also applied for speedbar access."
997 :group 'org-imenu-and-speedbar
998 :type 'integer)
1000 (defgroup org-table nil
1001 "Options concerning tables in Org-mode."
1002 :tag "Org Table"
1003 :group 'org)
1005 (defcustom org-enable-table-editor 'optimized
1006 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1007 When nil, such lines will be treated like ordinary lines.
1009 When equal to the symbol `optimized', the table editor will be optimized to
1010 do the following:
1011 - Automatic overwrite mode in front of whitespace in table fields.
1012 This makes the structure of the table stay in tact as long as the edited
1013 field does not exceed the column width.
1014 - Minimize the number of realigns. Normally, the table is aligned each time
1015 TAB or RET are pressed to move to another field. With optimization this
1016 happens only if changes to a field might have changed the column width.
1017 Optimization requires replacing the functions `self-insert-command',
1018 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1019 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1020 very good at guessing when a re-align will be necessary, but you can always
1021 force one with \\[org-ctrl-c-ctrl-c].
1023 If you would like to use the optimized version in Org-mode, but the
1024 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1026 This variable can be used to turn on and off the table editor during a session,
1027 but in order to toggle optimization, a restart is required.
1029 See also the variable `org-table-auto-blank-field'."
1030 :group 'org-table
1031 :type '(choice
1032 (const :tag "off" nil)
1033 (const :tag "on" t)
1034 (const :tag "on, optimized" optimized)))
1036 (defcustom org-self-insert-cluster-for-undo t
1037 "Non-nil means cluster self-insert commands for undo when possible.
1038 If this is set, then, like in the Emacs command loop, 20 consecutive
1039 characters will be undone together.
1040 This is configurable, because there is some impact on typing performance."
1041 :group 'org-table
1042 :type 'boolean)
1044 (defcustom org-table-tab-recognizes-table.el t
1045 "Non-nil means, TAB will automatically notice a table.el table.
1046 When it sees such a table, it moves point into it and - if necessary -
1047 calls `table-recognize-table'."
1048 :group 'org-table-editing
1049 :type 'boolean)
1051 (defgroup org-link nil
1052 "Options concerning links in Org-mode."
1053 :tag "Org Link"
1054 :group 'org)
1056 (defvar org-link-abbrev-alist-local nil
1057 "Buffer-local version of `org-link-abbrev-alist', which see.
1058 The value of this is taken from the #+LINK lines.")
1059 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1061 (defcustom org-link-abbrev-alist nil
1062 "Alist of link abbreviations.
1063 The car of each element is a string, to be replaced at the start of a link.
1064 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1065 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1067 [[linkkey:tag][description]]
1069 The 'linkkey' must be a word word, starting with a letter, followed
1070 by letters, numbers, '-' or '_'.
1072 If REPLACE is a string, the tag will simply be appended to create the link.
1073 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1074 the placeholder \"%h\" will cause a url-encoded version of the tag to
1075 be inserted at that point (see the function `url-hexify-string').
1077 REPLACE may also be a function that will be called with the tag as the
1078 only argument to create the link, which should be returned as a string.
1080 See the manual for examples."
1081 :group 'org-link
1082 :type '(repeat
1083 (cons
1084 (string :tag "Protocol")
1085 (choice
1086 (string :tag "Format")
1087 (function)))))
1089 (defcustom org-descriptive-links t
1090 "Non-nil means, hide link part and only show description of bracket links.
1091 Bracket links are like [[link][description]]. This variable sets the initial
1092 state in new org-mode buffers. The setting can then be toggled on a
1093 per-buffer basis from the Org->Hyperlinks menu."
1094 :group 'org-link
1095 :type 'boolean)
1097 (defcustom org-link-file-path-type 'adaptive
1098 "How the path name in file links should be stored.
1099 Valid values are:
1101 relative Relative to the current directory, i.e. the directory of the file
1102 into which the link is being inserted.
1103 absolute Absolute path, if possible with ~ for home directory.
1104 noabbrev Absolute path, no abbreviation of home directory.
1105 adaptive Use relative path for files in the current directory and sub-
1106 directories of it. For other files, use an absolute path."
1107 :group 'org-link
1108 :type '(choice
1109 (const relative)
1110 (const absolute)
1111 (const noabbrev)
1112 (const adaptive)))
1114 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1115 "Types of links that should be activated in Org-mode files.
1116 This is a list of symbols, each leading to the activation of a certain link
1117 type. In principle, it does not hurt to turn on most link types - there may
1118 be a small gain when turning off unused link types. The types are:
1120 bracket The recommended [[link][description]] or [[link]] links with hiding.
1121 angular Links in angular brackets that may contain whitespace like
1122 <bbdb:Carsten Dominik>.
1123 plain Plain links in normal text, no whitespace, like http://google.com.
1124 radio Text that is matched by a radio target, see manual for details.
1125 tag Tag settings in a headline (link to tag search).
1126 date Time stamps (link to calendar).
1127 footnote Footnote labels.
1129 Changing this variable requires a restart of Emacs to become effective."
1130 :group 'org-link
1131 :type '(set :greedy t
1132 (const :tag "Double bracket links (new style)" bracket)
1133 (const :tag "Angular bracket links (old style)" angular)
1134 (const :tag "Plain text links" plain)
1135 (const :tag "Radio target matches" radio)
1136 (const :tag "Tags" tag)
1137 (const :tag "Timestamps" date)
1138 (const :tag "Footnotes" footnote)))
1140 (defcustom org-make-link-description-function nil
1141 "Function to use to generate link descriptions from links. If
1142 nil the link location will be used. This function must take two
1143 parameters; the first is the link and the second the description
1144 org-insert-link has generated, and should return the description
1145 to use."
1146 :group 'org-link
1147 :type 'function)
1149 (defgroup org-link-store nil
1150 "Options concerning storing links in Org-mode."
1151 :tag "Org Store Link"
1152 :group 'org-link)
1154 (defcustom org-email-link-description-format "Email %c: %.30s"
1155 "Format of the description part of a link to an email or usenet message.
1156 The following %-escapes will be replaced by corresponding information:
1158 %F full \"From\" field
1159 %f name, taken from \"From\" field, address if no name
1160 %T full \"To\" field
1161 %t first name in \"To\" field, address if no name
1162 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1163 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1164 %s subject
1165 %m message-id.
1167 You may use normal field width specification between the % and the letter.
1168 This is for example useful to limit the length of the subject.
1170 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1171 :group 'org-link-store
1172 :type 'string)
1174 (defcustom org-from-is-user-regexp
1175 (let (r1 r2)
1176 (when (and user-mail-address (not (string= user-mail-address "")))
1177 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1178 (when (and user-full-name (not (string= user-full-name "")))
1179 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1180 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1181 "Regexp matched against the \"From:\" header of an email or usenet message.
1182 It should match if the message is from the user him/herself."
1183 :group 'org-link-store
1184 :type 'regexp)
1186 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1187 "Non-nil means, storing a link to an Org file will use entry IDs.
1189 Note that before this variable is even considered, org-id must be loaded,
1190 so please customize `org-modules' and turn it on.
1192 The variable can have the following values:
1194 t Create an ID if needed to make a link to the current entry.
1196 create-if-interactive
1197 If `org-store-link' is called directly (interactively, as a user
1198 command), do create an ID to support the link. But when doing the
1199 job for remember, only use the ID if it already exists. The
1200 purpose of this setting is to avoid proliferation of unwanted
1201 IDs, just because you happen to be in an Org file when you
1202 call `org-remember' that automatically and preemptively
1203 creates a link. If you do want to get an ID link in a remember
1204 template to an entry not having an ID, create it first by
1205 explicitly creating a link to it, using `C-c C-l' first.
1207 create-if-interactive-and-no-custom-id
1208 Like create-if-interactive, but do not create an ID if there is
1209 a CUSTOM_ID property defined in the entry. This is the default.
1211 use-existing
1212 Use existing ID, do not create one.
1214 nil Never use an ID to make a link, instead link using a text search for
1215 the headline text."
1216 :group 'org-link-store
1217 :type '(choice
1218 (const :tag "Create ID to make link" t)
1219 (const :tag "Create if storing link interactively"
1220 create-if-interactive)
1221 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1222 create-if-interactive-and-no-custom-id)
1223 (const :tag "Only use existing" use-existing)
1224 (const :tag "Do not use ID to create link" nil)))
1226 (defcustom org-context-in-file-links t
1227 "Non-nil means, file links from `org-store-link' contain context.
1228 A search string will be added to the file name with :: as separator and
1229 used to find the context when the link is activated by the command
1230 `org-open-at-point'.
1231 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1232 negates this setting for the duration of the command."
1233 :group 'org-link-store
1234 :type 'boolean)
1236 (defcustom org-keep-stored-link-after-insertion nil
1237 "Non-nil means, keep link in list for entire session.
1239 The command `org-store-link' adds a link pointing to the current
1240 location to an internal list. These links accumulate during a session.
1241 The command `org-insert-link' can be used to insert links into any
1242 Org-mode file (offering completion for all stored links). When this
1243 option is nil, every link which has been inserted once using \\[org-insert-link]
1244 will be removed from the list, to make completing the unused links
1245 more efficient."
1246 :group 'org-link-store
1247 :type 'boolean)
1249 (defgroup org-link-follow nil
1250 "Options concerning following links in Org-mode."
1251 :tag "Org Follow Link"
1252 :group 'org-link)
1254 (defcustom org-link-translation-function nil
1255 "Function to translate links with different syntax to Org syntax.
1256 This can be used to translate links created for example by the Planner
1257 or emacs-wiki packages to Org syntax.
1258 The function must accept two parameters, a TYPE containing the link
1259 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1260 which is everything after the link protocol. It should return a cons
1261 with possibly modified values of type and path.
1262 Org contains a function for this, so if you set this variable to
1263 `org-translate-link-from-planner', you should be able follow many
1264 links created by planner."
1265 :group 'org-link-follow
1266 :type 'function)
1268 (defcustom org-follow-link-hook nil
1269 "Hook that is run after a link has been followed."
1270 :group 'org-link-follow
1271 :type 'hook)
1273 (defcustom org-tab-follows-link nil
1274 "Non-nil means, on links TAB will follow the link.
1275 Needs to be set before org.el is loaded.
1276 This really should not be used, it does not make sense, and the
1277 implementation is bad."
1278 :group 'org-link-follow
1279 :type 'boolean)
1281 (defcustom org-return-follows-link nil
1282 "Non-nil means, on links RET will follow the link.
1283 Needs to be set before org.el is loaded."
1284 :group 'org-link-follow
1285 :type 'boolean)
1287 (defcustom org-mouse-1-follows-link
1288 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1289 "Non-nil means, mouse-1 on a link will follow the link.
1290 A longer mouse click will still set point. Does not work on XEmacs.
1291 Needs to be set before org.el is loaded."
1292 :group 'org-link-follow
1293 :type 'boolean)
1295 (defcustom org-mark-ring-length 4
1296 "Number of different positions to be recorded in the ring
1297 Changing this requires a restart of Emacs to work correctly."
1298 :group 'org-link-follow
1299 :type 'integer)
1301 (defcustom org-link-frame-setup
1302 '((vm . vm-visit-folder-other-frame)
1303 (gnus . gnus-other-frame)
1304 (file . find-file-other-window))
1305 "Setup the frame configuration for following links.
1306 When following a link with Emacs, it may often be useful to display
1307 this link in another window or frame. This variable can be used to
1308 set this up for the different types of links.
1309 For VM, use any of
1310 `vm-visit-folder'
1311 `vm-visit-folder-other-frame'
1312 For Gnus, use any of
1313 `gnus'
1314 `gnus-other-frame'
1315 `org-gnus-no-new-news'
1316 For FILE, use any of
1317 `find-file'
1318 `find-file-other-window'
1319 `find-file-other-frame'
1320 For the calendar, use the variable `calendar-setup'.
1321 For BBDB, it is currently only possible to display the matches in
1322 another window."
1323 :group 'org-link-follow
1324 :type '(list
1325 (cons (const vm)
1326 (choice
1327 (const vm-visit-folder)
1328 (const vm-visit-folder-other-window)
1329 (const vm-visit-folder-other-frame)))
1330 (cons (const gnus)
1331 (choice
1332 (const gnus)
1333 (const gnus-other-frame)
1334 (const org-gnus-no-new-news)))
1335 (cons (const file)
1336 (choice
1337 (const find-file)
1338 (const find-file-other-window)
1339 (const find-file-other-frame)))))
1341 (defcustom org-display-internal-link-with-indirect-buffer nil
1342 "Non-nil means, use indirect buffer to display infile links.
1343 Activating internal links (from one location in a file to another location
1344 in the same file) normally just jumps to the location. When the link is
1345 activated with a C-u prefix (or with mouse-3), the link is displayed in
1346 another window. When this option is set, the other window actually displays
1347 an indirect buffer clone of the current buffer, to avoid any visibility
1348 changes to the current buffer."
1349 :group 'org-link-follow
1350 :type 'boolean)
1352 (defcustom org-open-non-existing-files nil
1353 "Non-nil means, `org-open-file' will open non-existing files.
1354 When nil, an error will be generated.
1355 This variable applies only to external applications because they
1356 might choke on non-existing files. If the link is to a file that
1357 will be opened in Emacs, the variable is ignored."
1358 :group 'org-link-follow
1359 :type 'boolean)
1361 (defcustom org-open-directory-means-index-dot-org nil
1362 "Non-nil means, a link to a directory really means to index.org.
1363 When nil, following a directory link will run dired or open a finder/explorer
1364 window on that directory."
1365 :group 'org-link-follow
1366 :type 'boolean)
1368 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1369 "Function and arguments to call for following mailto links.
1370 This is a list with the first element being a lisp function, and the
1371 remaining elements being arguments to the function. In string arguments,
1372 %a will be replaced by the address, and %s will be replaced by the subject
1373 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1374 :group 'org-link-follow
1375 :type '(choice
1376 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1377 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1378 (const :tag "message-mail" (message-mail "%a" "%s"))
1379 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1381 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1382 "Non-nil means, ask for confirmation before executing shell links.
1383 Shell links can be dangerous: just think about a link
1385 [[shell:rm -rf ~/*][Google Search]]
1387 This link would show up in your Org-mode document as \"Google Search\",
1388 but really it would remove your entire home directory.
1389 Therefore we advise against setting this variable to nil.
1390 Just change it to `y-or-n-p' if you want to confirm with a
1391 single keystroke rather than having to type \"yes\"."
1392 :group 'org-link-follow
1393 :type '(choice
1394 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1395 (const :tag "with y-or-n (faster)" y-or-n-p)
1396 (const :tag "no confirmation (dangerous)" nil)))
1398 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1399 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1400 Elisp links can be dangerous: just think about a link
1402 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1404 This link would show up in your Org-mode document as \"Google Search\",
1405 but really it would remove your entire home directory.
1406 Therefore we advise against setting this variable to nil.
1407 Just change it to `y-or-n-p' if you want to confirm with a
1408 single keystroke rather than having to type \"yes\"."
1409 :group 'org-link-follow
1410 :type '(choice
1411 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1412 (const :tag "with y-or-n (faster)" y-or-n-p)
1413 (const :tag "no confirmation (dangerous)" nil)))
1415 (defconst org-file-apps-defaults-gnu
1416 '((remote . emacs)
1417 (system . mailcap)
1418 (t . mailcap))
1419 "Default file applications on a UNIX or GNU/Linux system.
1420 See `org-file-apps'.")
1422 (defconst org-file-apps-defaults-macosx
1423 '((remote . emacs)
1424 (t . "open %s")
1425 (system . "open %s")
1426 ("ps.gz" . "gv %s")
1427 ("eps.gz" . "gv %s")
1428 ("dvi" . "xdvi %s")
1429 ("fig" . "xfig %s"))
1430 "Default file applications on a MacOS X system.
1431 The system \"open\" is known as a default, but we use X11 applications
1432 for some files for which the OS does not have a good default.
1433 See `org-file-apps'.")
1435 (defconst org-file-apps-defaults-windowsnt
1436 (list
1437 '(remote . emacs)
1438 (cons t
1439 (list (if (featurep 'xemacs)
1440 'mswindows-shell-execute
1441 'w32-shell-execute)
1442 "open" 'file))
1443 (cons 'system
1444 (list (if (featurep 'xemacs)
1445 'mswindows-shell-execute
1446 'w32-shell-execute)
1447 "open" 'file)))
1448 "Default file applications on a Windows NT system.
1449 The system \"open\" is used for most files.
1450 See `org-file-apps'.")
1452 (defcustom org-file-apps
1454 (auto-mode . emacs)
1455 ("\\.mm\\'" . default)
1456 ("\\.x?html?\\'" . default)
1457 ("\\.pdf\\'" . default)
1459 "External applications for opening `file:path' items in a document.
1460 Org-mode uses system defaults for different file types, but
1461 you can use this variable to set the application for a given file
1462 extension. The entries in this list are cons cells where the car identifies
1463 files and the cdr the corresponding command. Possible values for the
1464 file identifier are
1465 \"regex\" Regular expression matched against the file name. For backward
1466 compatibility, this can also be a string with only alphanumeric
1467 characters, which is then interpreted as an extension.
1468 `directory' Matches a directory
1469 `remote' Matches a remote file, accessible through tramp or efs.
1470 Remote files most likely should be visited through Emacs
1471 because external applications cannot handle such paths.
1472 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1473 so all files Emacs knows how to handle. Using this with
1474 command `emacs' will open most files in Emacs. Beware that this
1475 will also open html files inside Emacs, unless you add
1476 (\"html\" . default) to the list as well.
1477 t Default for files not matched by any of the other options.
1478 `system' The system command to open files, like `open' on Windows
1479 and Mac OS X, and mailcap under GNU/Linux. This is the command
1480 that will be selected if you call `C-c C-o' with a double
1481 `C-u C-u' prefix.
1483 Possible values for the command are:
1484 `emacs' The file will be visited by the current Emacs process.
1485 `default' Use the default application for this file type, which is the
1486 association for t in the list, most likely in the system-specific
1487 part.
1488 This can be used to overrule an unwanted setting in the
1489 system-specific variable.
1490 `system' Use the system command for opening files, like \"open\".
1491 This command is specified by the entry whose car is `system'.
1492 Most likely, the system-specific version of this variable
1493 does define this command, but you can overrule/replace it
1494 here.
1495 string A command to be executed by a shell; %s will be replaced
1496 by the path to the file.
1497 sexp A Lisp form which will be evaluated. The file path will
1498 be available in the Lisp variable `file'.
1499 For more examples, see the system specific constants
1500 `org-file-apps-defaults-macosx'
1501 `org-file-apps-defaults-windowsnt'
1502 `org-file-apps-defaults-gnu'."
1503 :group 'org-link-follow
1504 :type '(repeat
1505 (cons (choice :value ""
1506 (string :tag "Extension")
1507 (const :tag "System command to open files" system)
1508 (const :tag "Default for unrecognized files" t)
1509 (const :tag "Remote file" remote)
1510 (const :tag "Links to a directory" directory)
1511 (const :tag "Any files that have Emacs modes"
1512 auto-mode))
1513 (choice :value ""
1514 (const :tag "Visit with Emacs" emacs)
1515 (const :tag "Use default" default)
1516 (const :tag "Use the system command" system)
1517 (string :tag "Command")
1518 (sexp :tag "Lisp form")))))
1520 (defgroup org-refile nil
1521 "Options concerning refiling entries in Org-mode."
1522 :tag "Org Refile"
1523 :group 'org)
1525 (defcustom org-directory "~/org"
1526 "Directory with org files.
1527 This is just a default location to look for Org files. There is no need
1528 at all to put your files into this directory. It is only used in the
1529 following situations:
1531 1. When a remember template specifies a target file that is not an
1532 absolute path. The path will then be interpreted relative to
1533 `org-directory'
1534 2. When a remember note is filed away in an interactive way (when exiting the
1535 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1536 with `org-directory' as the default path."
1537 :group 'org-refile
1538 :group 'org-remember
1539 :type 'directory)
1541 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1542 "Default target for storing notes.
1543 Used by the hooks for remember.el. This can be a string, or nil to mean
1544 the value of `remember-data-file'.
1545 You can set this on a per-template basis with the variable
1546 `org-remember-templates'."
1547 :group 'org-refile
1548 :group 'org-remember
1549 :type '(choice
1550 (const :tag "Default from remember-data-file" nil)
1551 file))
1553 (defcustom org-goto-interface 'outline
1554 "The default interface to be used for `org-goto'.
1555 Allowed values are:
1556 outline The interface shows an outline of the relevant file
1557 and the correct heading is found by moving through
1558 the outline or by searching with incremental search.
1559 outline-path-completion Headlines in the current buffer are offered via
1560 completion. This is the interface also used by
1561 the refile command."
1562 :group 'org-refile
1563 :type '(choice
1564 (const :tag "Outline" outline)
1565 (const :tag "Outline-path-completion" outline-path-completion)))
1567 (defcustom org-goto-max-level 5
1568 "Maximum level to be considered when running org-goto with refile interface."
1569 :group 'org-refile
1570 :type 'integer)
1572 (defcustom org-reverse-note-order nil
1573 "Non-nil means, store new notes at the beginning of a file or entry.
1574 When nil, new notes will be filed to the end of a file or entry.
1575 This can also be a list with cons cells of regular expressions that
1576 are matched against file names, and values."
1577 :group 'org-remember
1578 :group 'org-refile
1579 :type '(choice
1580 (const :tag "Reverse always" t)
1581 (const :tag "Reverse never" nil)
1582 (repeat :tag "By file name regexp"
1583 (cons regexp boolean))))
1585 (defcustom org-refile-targets nil
1586 "Targets for refiling entries with \\[org-refile].
1587 This is list of cons cells. Each cell contains:
1588 - a specification of the files to be considered, either a list of files,
1589 or a symbol whose function or variable value will be used to retrieve
1590 a file name or a list of file names. If you use `org-agenda-files' for
1591 that, all agenda files will be scanned for targets. Nil means, consider
1592 headings in the current buffer.
1593 - A specification of how to find candidate refile targets. This may be
1594 any of:
1595 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1596 This tag has to be present in all target headlines, inheritance will
1597 not be considered.
1598 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1599 todo keyword.
1600 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1601 headlines that are refiling targets.
1602 - a cons cell (:level . N). Any headline of level N is considered a target.
1603 Note that, when `org-odd-levels-only' is set, level corresponds to
1604 order in hierarchy, not to the number of stars.
1605 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1606 Note that, when `org-odd-levels-only' is set, level corresponds to
1607 order in hierarchy, not to the number of stars.
1609 You can set the variable `org-refile-target-verify-function' to a function
1610 to verify each headline found by the simple critery above.
1612 When this variable is nil, all top-level headlines in the current buffer
1613 are used, equivalent to the value `((nil . (:level . 1))'."
1614 :group 'org-refile
1615 :type '(repeat
1616 (cons
1617 (choice :value org-agenda-files
1618 (const :tag "All agenda files" org-agenda-files)
1619 (const :tag "Current buffer" nil)
1620 (function) (variable) (file))
1621 (choice :tag "Identify target headline by"
1622 (cons :tag "Specific tag" (const :value :tag) (string))
1623 (cons :tag "TODO keyword" (const :value :todo) (string))
1624 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1625 (cons :tag "Level number" (const :value :level) (integer))
1626 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1628 (defcustom org-refile-target-verify-function nil
1629 "Function to verify if the headline at point should be a refile target.
1630 The function will be called without arguments, with point at the
1631 beginning of the headline. It should return t and leave point
1632 where it is if the headline is a valid target for refiling.
1634 If the target should not be selected, the function must return nil.
1635 In addition to this, it may move point to a place from where the search
1636 should be continued. For example, the function may decide that the entire
1637 subtree of the current entry should be excluded and move point to the end
1638 of the subtree."
1639 :group 'org-refile
1640 :type 'function)
1642 (defcustom org-refile-use-outline-path nil
1643 "Non-nil means, provide refile targets as paths.
1644 So a level 3 headline will be available as level1/level2/level3.
1646 When the value is `file', also include the file name (without directory)
1647 into the path. In this case, you can also stop the completion after
1648 the file name, to get entries inserted as top level in the file.
1650 When `full-file-path', include the full file path."
1651 :group 'org-refile
1652 :type '(choice
1653 (const :tag "Not" nil)
1654 (const :tag "Yes" t)
1655 (const :tag "Start with file name" file)
1656 (const :tag "Start with full file path" full-file-path)))
1658 (defcustom org-outline-path-complete-in-steps t
1659 "Non-nil means, complete the outline path in hierarchical steps.
1660 When Org-mode uses the refile interface to select an outline path
1661 \(see variable `org-refile-use-outline-path'), the completion of
1662 the path can be done is a single go, or if can be done in steps down
1663 the headline hierarchy. Going in steps is probably the best if you
1664 do not use a special completion package like `ido' or `icicles'.
1665 However, when using these packages, going in one step can be very
1666 fast, while still showing the whole path to the entry."
1667 :group 'org-refile
1668 :type 'boolean)
1670 (defcustom org-refile-allow-creating-parent-nodes nil
1671 "Non-nil means, allow to create new nodes as refile targets.
1672 New nodes are then created by adding \"/new node name\" to the completion
1673 of an existing node. When the value of this variable is `confirm',
1674 new node creation must be confirmed by the user (recommended)
1675 When nil, the completion must match an existing entry.
1677 Note that, if the new heading is not seen by the criteria
1678 listed in `org-refile-targets', multiple instances of the same
1679 heading would be created by trying again to file under the new
1680 heading."
1681 :group 'org-refile
1682 :type '(choice
1683 (const :tag "Never" nil)
1684 (const :tag "Always" t)
1685 (const :tag "Prompt for confirmation" confirm)))
1687 (defgroup org-todo nil
1688 "Options concerning TODO items in Org-mode."
1689 :tag "Org TODO"
1690 :group 'org)
1692 (defgroup org-progress nil
1693 "Options concerning Progress logging in Org-mode."
1694 :tag "Org Progress"
1695 :group 'org-time)
1697 (defvar org-todo-interpretation-widgets
1699 (:tag "Sequence (cycling hits every state)" sequence)
1700 (:tag "Type (cycling directly to DONE)" type))
1701 "The available interpretation symbols for customizing
1702 `org-todo-keywords'.
1703 Interested libraries should add to this list.")
1705 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1706 "List of TODO entry keyword sequences and their interpretation.
1707 \\<org-mode-map>This is a list of sequences.
1709 Each sequence starts with a symbol, either `sequence' or `type',
1710 indicating if the keywords should be interpreted as a sequence of
1711 action steps, or as different types of TODO items. The first
1712 keywords are states requiring action - these states will select a headline
1713 for inclusion into the global TODO list Org-mode produces. If one of
1714 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1715 signify that no further action is necessary. If \"|\" is not found,
1716 the last keyword is treated as the only DONE state of the sequence.
1718 The command \\[org-todo] cycles an entry through these states, and one
1719 additional state where no keyword is present. For details about this
1720 cycling, see the manual.
1722 TODO keywords and interpretation can also be set on a per-file basis with
1723 the special #+SEQ_TODO and #+TYP_TODO lines.
1725 Each keyword can optionally specify a character for fast state selection
1726 \(in combination with the variable `org-use-fast-todo-selection')
1727 and specifiers for state change logging, using the same syntax
1728 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1729 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1730 indicates to record a time stamp each time this state is selected.
1732 Each keyword may also specify if a timestamp or a note should be
1733 recorded when entering or leaving the state, by adding additional
1734 characters in the parenthesis after the keyword. This looks like this:
1735 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1736 record only the time of the state change. With X and Y being either
1737 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1738 Y when leaving the state if and only if the *target* state does not
1739 define X. You may omit any of the fast-selection key or X or /Y,
1740 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1742 For backward compatibility, this variable may also be just a list
1743 of keywords - in this case the interpretation (sequence or type) will be
1744 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1745 :group 'org-todo
1746 :group 'org-keywords
1747 :type '(choice
1748 (repeat :tag "Old syntax, just keywords"
1749 (string :tag "Keyword"))
1750 (repeat :tag "New syntax"
1751 (cons
1752 (choice
1753 :tag "Interpretation"
1754 ;;Quick and dirty way to see
1755 ;;`org-todo-interpretations'. This takes the
1756 ;;place of item arguments
1757 :convert-widget
1758 (lambda (widget)
1759 (widget-put widget
1760 :args (mapcar
1761 #'(lambda (x)
1762 (widget-convert
1763 (cons 'const x)))
1764 org-todo-interpretation-widgets))
1765 widget))
1766 (repeat
1767 (string :tag "Keyword"))))))
1769 (defvar org-todo-keywords-1 nil
1770 "All TODO and DONE keywords active in a buffer.")
1771 (make-variable-buffer-local 'org-todo-keywords-1)
1772 (defvar org-todo-keywords-for-agenda nil)
1773 (defvar org-done-keywords-for-agenda nil)
1774 (defvar org-drawers-for-agenda nil)
1775 (defvar org-todo-keyword-alist-for-agenda nil)
1776 (defvar org-tag-alist-for-agenda nil)
1777 (defvar org-agenda-contributing-files nil)
1778 (defvar org-not-done-keywords nil)
1779 (make-variable-buffer-local 'org-not-done-keywords)
1780 (defvar org-done-keywords nil)
1781 (make-variable-buffer-local 'org-done-keywords)
1782 (defvar org-todo-heads nil)
1783 (make-variable-buffer-local 'org-todo-heads)
1784 (defvar org-todo-sets nil)
1785 (make-variable-buffer-local 'org-todo-sets)
1786 (defvar org-todo-log-states nil)
1787 (make-variable-buffer-local 'org-todo-log-states)
1788 (defvar org-todo-kwd-alist nil)
1789 (make-variable-buffer-local 'org-todo-kwd-alist)
1790 (defvar org-todo-key-alist nil)
1791 (make-variable-buffer-local 'org-todo-key-alist)
1792 (defvar org-todo-key-trigger nil)
1793 (make-variable-buffer-local 'org-todo-key-trigger)
1795 (defcustom org-todo-interpretation 'sequence
1796 "Controls how TODO keywords are interpreted.
1797 This variable is in principle obsolete and is only used for
1798 backward compatibility, if the interpretation of todo keywords is
1799 not given already in `org-todo-keywords'. See that variable for
1800 more information."
1801 :group 'org-todo
1802 :group 'org-keywords
1803 :type '(choice (const sequence)
1804 (const type)))
1806 (defcustom org-use-fast-todo-selection t
1807 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1808 This variable describes if and under what circumstances the cycling
1809 mechanism for TODO keywords will be replaced by a single-key, direct
1810 selection scheme.
1812 When nil, fast selection is never used.
1814 When the symbol `prefix', it will be used when `org-todo' is called with
1815 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1816 in an agenda buffer.
1818 When t, fast selection is used by default. In this case, the prefix
1819 argument forces cycling instead.
1821 In all cases, the special interface is only used if access keys have actually
1822 been assigned by the user, i.e. if keywords in the configuration are followed
1823 by a letter in parenthesis, like TODO(t)."
1824 :group 'org-todo
1825 :type '(choice
1826 (const :tag "Never" nil)
1827 (const :tag "By default" t)
1828 (const :tag "Only with C-u C-c C-t" prefix)))
1830 (defcustom org-provide-todo-statistics t
1831 "Non-nil means, update todo statistics after insert and toggle.
1832 ALL-HEADLINES means update todo statistics by including headlines
1833 with no TODO keyword as well, counting them as not done.
1834 A list of TODO keywords means the same, but skip keywords that are
1835 not in this list.
1837 When this is set, todo statistics is updated in the parent of the
1838 current entry each time a todo state is changed."
1839 :group 'org-todo
1840 :type '(choice
1841 (const :tag "Yes, only for TODO entries" t)
1842 (const :tag "Yes, including all entries" 'all-headlines)
1843 (repeat :tag "Yes, for TODOs in this list"
1844 (string :tag "TODO keyword"))
1845 (other :tag "No TODO statistics" nil)))
1847 (defcustom org-hierarchical-todo-statistics t
1848 "Non-nil means, TODO statistics covers just direct children.
1849 When nil, all entries in the subtree are considered.
1850 This has only an effect if `org-provide-todo-statistics' is set.
1851 To set this to nil for only a single subtree, use a COOKIE_DATA
1852 property and include the word \"recursive\" into the value."
1853 :group 'org-todo
1854 :type 'boolean)
1856 (defcustom org-after-todo-state-change-hook nil
1857 "Hook which is run after the state of a TODO item was changed.
1858 The new state (a string with a TODO keyword, or nil) is available in the
1859 Lisp variable `state'."
1860 :group 'org-todo
1861 :type 'hook)
1863 (defvar org-blocker-hook nil
1864 "Hook for functions that are allowed to block a state change.
1866 Each function gets as its single argument a property list, see
1867 `org-trigger-hook' for more information about this list.
1869 If any of the functions in this hook returns nil, the state change
1870 is blocked.")
1872 (defvar org-trigger-hook nil
1873 "Hook for functions that are triggered by a state change.
1875 Each function gets as its single argument a property list with at least
1876 the following elements:
1878 (:type type-of-change :position pos-at-entry-start
1879 :from old-state :to new-state)
1881 Depending on the type, more properties may be present.
1883 This mechanism is currently implemented for:
1885 TODO state changes
1886 ------------------
1887 :type todo-state-change
1888 :from previous state (keyword as a string), or nil, or a symbol
1889 'todo' or 'done', to indicate the general type of state.
1890 :to new state, like in :from")
1892 (defcustom org-enforce-todo-dependencies nil
1893 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1894 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1895 be blocked if any prior sibling is not yet done.
1896 Finally, if the parent is blocked because of ordered siblings of its own,
1897 the child will also be blocked.
1898 This variable needs to be set before org.el is loaded, and you need to
1899 restart Emacs after a change to make the change effective. The only way
1900 to change is while Emacs is running is through the customize interface."
1901 :set (lambda (var val)
1902 (set var val)
1903 (if val
1904 (add-hook 'org-blocker-hook
1905 'org-block-todo-from-children-or-siblings-or-parent)
1906 (remove-hook 'org-blocker-hook
1907 'org-block-todo-from-children-or-siblings-or-parent)))
1908 :group 'org-todo
1909 :type 'boolean)
1911 (defcustom org-enforce-todo-checkbox-dependencies nil
1912 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1913 When this is nil, checkboxes have no influence on switching TODO states.
1914 When non-nil, you first need to check off all check boxes before the TODO
1915 entry can be switched to DONE.
1916 This variable needs to be set before org.el is loaded, and you need to
1917 restart Emacs after a change to make the change effective. The only way
1918 to change is while Emacs is running is through the customize interface."
1919 :set (lambda (var val)
1920 (set var val)
1921 (if val
1922 (add-hook 'org-blocker-hook
1923 'org-block-todo-from-checkboxes)
1924 (remove-hook 'org-blocker-hook
1925 'org-block-todo-from-checkboxes)))
1926 :group 'org-todo
1927 :type 'boolean)
1929 (defcustom org-treat-insert-todo-heading-as-state-change nil
1930 "Non-nil means, inserting a TODO heading is treated as state change.
1931 So when the command \\[org-insert-todo-heading] is used, state change
1932 logging will apply if appropriate. When nil, the new TODO item will
1933 be inserted directly, and no logging will take place."
1934 :group 'org-todo
1935 :type 'boolean)
1937 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1938 "Non-nil means, switching TODO states with S-cursor counts as state change.
1939 This is the default behavior. However, setting this to nil allows a
1940 convenient way to select a TODO state and bypass any logging associated
1941 with that."
1942 :group 'org-todo
1943 :type 'boolean)
1945 (defcustom org-todo-state-tags-triggers nil
1946 "Tag changes that should be triggered by TODO state changes.
1947 This is a list. Each entry is
1949 (state-change (tag . flag) .......)
1951 State-change can be a string with a state, and empty string to indicate the
1952 state that has no TODO keyword, or it can be one of the symbols `todo'
1953 or `done', meaning any not-done or done state, respectively."
1954 :group 'org-todo
1955 :group 'org-tags
1956 :type '(repeat
1957 (cons (choice :tag "When changing to"
1958 (const :tag "Not-done state" todo)
1959 (const :tag "Done state" done)
1960 (string :tag "State"))
1961 (repeat
1962 (cons :tag "Tag action"
1963 (string :tag "Tag")
1964 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1966 (defcustom org-log-done nil
1967 "Information to record when a task moves to the DONE state.
1969 Possible values are:
1971 nil Don't add anything, just change the keyword
1972 time Add a time stamp to the task
1973 note Prompt for a note and add it with template `org-log-note-headings'
1975 This option can also be set with on a per-file-basis with
1977 #+STARTUP: nologdone
1978 #+STARTUP: logdone
1979 #+STARTUP: lognotedone
1981 You can have local logging settings for a subtree by setting the LOGGING
1982 property to one or more of these keywords."
1983 :group 'org-todo
1984 :group 'org-progress
1985 :type '(choice
1986 (const :tag "No logging" nil)
1987 (const :tag "Record CLOSED timestamp" time)
1988 (const :tag "Record CLOSED timestamp with note." note)))
1990 ;; Normalize old uses of org-log-done.
1991 (cond
1992 ((eq org-log-done t) (setq org-log-done 'time))
1993 ((and (listp org-log-done) (memq 'done org-log-done))
1994 (setq org-log-done 'note)))
1996 (defcustom org-log-reschedule nil
1997 "Information to record when the scheduling date of a tasks is modified.
1999 Possible values are:
2001 nil Don't add anything, just change the date
2002 time Add a time stamp to the task
2003 note Prompt for a note and add it with template `org-log-note-headings'
2005 This option can also be set with on a per-file-basis with
2007 #+STARTUP: nologreschedule
2008 #+STARTUP: logreschedule
2009 #+STARTUP: lognotereschedule"
2010 :group 'org-todo
2011 :group 'org-progress
2012 :type '(choice
2013 (const :tag "No logging" nil)
2014 (const :tag "Record timestamp" time)
2015 (const :tag "Record timestamp with note." note)))
2017 (defcustom org-log-redeadline nil
2018 "Information to record when the deadline date of a tasks is modified.
2020 Possible values are:
2022 nil Don't add anything, just change the date
2023 time Add a time stamp to the task
2024 note Prompt for a note and add it with template `org-log-note-headings'
2026 This option can also be set with on a per-file-basis with
2028 #+STARTUP: nologredeadline
2029 #+STARTUP: logredeadline
2030 #+STARTUP: lognoteredeadline
2032 You can have local logging settings for a subtree by setting the LOGGING
2033 property to one or more of these keywords."
2034 :group 'org-todo
2035 :group 'org-progress
2036 :type '(choice
2037 (const :tag "No logging" nil)
2038 (const :tag "Record timestamp" time)
2039 (const :tag "Record timestamp with note." note)))
2041 (defcustom org-log-note-clock-out nil
2042 "Non-nil means, record a note when clocking out of an item.
2043 This can also be configured on a per-file basis by adding one of
2044 the following lines anywhere in the buffer:
2046 #+STARTUP: lognoteclock-out
2047 #+STARTUP: nolognoteclock-out"
2048 :group 'org-todo
2049 :group 'org-progress
2050 :type 'boolean)
2052 (defcustom org-log-done-with-time t
2053 "Non-nil means, the CLOSED time stamp will contain date and time.
2054 When nil, only the date will be recorded."
2055 :group 'org-progress
2056 :type 'boolean)
2058 (defcustom org-log-note-headings
2059 '((done . "CLOSING NOTE %t")
2060 (state . "State %-12s from %-12S %t")
2061 (note . "Note taken on %t")
2062 (reschedule . "Rescheduled from %S on %t")
2063 (redeadline . "New deadline from %S on %t")
2064 (clock-out . ""))
2065 "Headings for notes added to entries.
2066 The value is an alist, with the car being a symbol indicating the note
2067 context, and the cdr is the heading to be used. The heading may also be the
2068 empty string.
2069 %t in the heading will be replaced by a time stamp.
2070 %s will be replaced by the new TODO state, in double quotes.
2071 %S will be replaced by the old TODO state, in double quotes.
2072 %u will be replaced by the user name.
2073 %U will be replaced by the full user name."
2074 :group 'org-todo
2075 :group 'org-progress
2076 :type '(list :greedy t
2077 (cons (const :tag "Heading when closing an item" done) string)
2078 (cons (const :tag
2079 "Heading when changing todo state (todo sequence only)"
2080 state) string)
2081 (cons (const :tag "Heading when just taking a note" note) string)
2082 (cons (const :tag "Heading when clocking out" clock-out) string)
2083 (cons (const :tag "Heading when rescheduling" reschedule) string)
2084 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2086 (unless (assq 'note org-log-note-headings)
2087 (push '(note . "%t") org-log-note-headings))
2089 (defcustom org-log-into-drawer nil
2090 "Non-nil means, insert state change notes and time stamps into a drawer.
2091 When nil, state changes notes will be inserted after the headline and
2092 any scheduling and clock lines, but not inside a drawer.
2094 The value of this variable should be the name of the drawer to use.
2095 LOGBOOK is proposed at the default drawer for this purpose, you can
2096 also set this to a string to define the drawer of your choice.
2098 A value of t is also allowed, representing \"LOGBOOK\".
2100 If this variable is set, `org-log-state-notes-insert-after-drawers'
2101 will be ignored.
2103 You can set the property LOG_INTO_DRAWER to overrule this setting for
2104 a subtree."
2105 :group 'org-todo
2106 :group 'org-progress
2107 :type '(choice
2108 (const :tag "Not into a drawer" nil)
2109 (const :tag "LOGBOOK" t)
2110 (string :tag "Other")))
2112 (if (fboundp 'defvaralias)
2113 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2115 (defun org-log-into-drawer ()
2116 "Return the value of `org-log-into-drawer', but let properties overrule.
2117 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2118 used instead of the default value."
2119 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2120 (cond
2121 ((or (not p) (equal p "nil")) org-log-into-drawer)
2122 ((equal p "t") "LOGBOOK")
2123 (t p))))
2125 (defcustom org-log-state-notes-insert-after-drawers nil
2126 "Non-nil means, insert state change notes after any drawers in entry.
2127 Only the drawers that *immediately* follow the headline and the
2128 deadline/scheduled line are skipped.
2129 When nil, insert notes right after the heading and perhaps the line
2130 with deadline/scheduling if present.
2132 This variable will have no effect if `org-log-into-drawer' is
2133 set."
2134 :group 'org-todo
2135 :group 'org-progress
2136 :type 'boolean)
2138 (defcustom org-log-states-order-reversed t
2139 "Non-nil means, the latest state change note will be directly after heading.
2140 When nil, the notes will be orderer according to time."
2141 :group 'org-todo
2142 :group 'org-progress
2143 :type 'boolean)
2145 (defcustom org-log-repeat 'time
2146 "Non-nil means, record moving through the DONE state when triggering repeat.
2147 An auto-repeating task is immediately switched back to TODO when
2148 marked DONE. If you are not logging state changes (by adding \"@\"
2149 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2150 record a closing note, there will be no record of the task moving
2151 through DONE. This variable forces taking a note anyway.
2153 nil Don't force a record
2154 time Record a time stamp
2155 note Record a note
2157 This option can also be set with on a per-file-basis with
2159 #+STARTUP: logrepeat
2160 #+STARTUP: lognoterepeat
2161 #+STARTUP: nologrepeat
2163 You can have local logging settings for a subtree by setting the LOGGING
2164 property to one or more of these keywords."
2165 :group 'org-todo
2166 :group 'org-progress
2167 :type '(choice
2168 (const :tag "Don't force a record" nil)
2169 (const :tag "Force recording the DONE state" time)
2170 (const :tag "Force recording a note with the DONE state" note)))
2173 (defgroup org-priorities nil
2174 "Priorities in Org-mode."
2175 :tag "Org Priorities"
2176 :group 'org-todo)
2178 (defcustom org-enable-priority-commands t
2179 "Non-nil means, priority commands are active.
2180 When nil, these commands will be disabled, so that you never accidentally
2181 set a priority."
2182 :group 'org-priorities
2183 :type 'boolean)
2185 (defcustom org-highest-priority ?A
2186 "The highest priority of TODO items. A character like ?A, ?B etc.
2187 Must have a smaller ASCII number than `org-lowest-priority'."
2188 :group 'org-priorities
2189 :type 'character)
2191 (defcustom org-lowest-priority ?C
2192 "The lowest priority of TODO items. A character like ?A, ?B etc.
2193 Must have a larger ASCII number than `org-highest-priority'."
2194 :group 'org-priorities
2195 :type 'character)
2197 (defcustom org-default-priority ?B
2198 "The default priority of TODO items.
2199 This is the priority an item get if no explicit priority is given."
2200 :group 'org-priorities
2201 :type 'character)
2203 (defcustom org-priority-start-cycle-with-default t
2204 "Non-nil means, start with default priority when starting to cycle.
2205 When this is nil, the first step in the cycle will be (depending on the
2206 command used) one higher or lower that the default priority."
2207 :group 'org-priorities
2208 :type 'boolean)
2210 (defgroup org-time nil
2211 "Options concerning time stamps and deadlines in Org-mode."
2212 :tag "Org Time"
2213 :group 'org)
2215 (defcustom org-insert-labeled-timestamps-at-point nil
2216 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2217 When nil, these labeled time stamps are forces into the second line of an
2218 entry, just after the headline. When scheduling from the global TODO list,
2219 the time stamp will always be forced into the second line."
2220 :group 'org-time
2221 :type 'boolean)
2223 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2224 "Formats for `format-time-string' which are used for time stamps.
2225 It is not recommended to change this constant.")
2227 (defcustom org-time-stamp-rounding-minutes '(0 5)
2228 "Number of minutes to round time stamps to.
2229 These are two values, the first applies when first creating a time stamp.
2230 The second applies when changing it with the commands `S-up' and `S-down'.
2231 When changing the time stamp, this means that it will change in steps
2232 of N minutes, as given by the second value.
2234 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2235 numbers should be factors of 60, so for example 5, 10, 15.
2237 When this is larger than 1, you can still force an exact time-stamp by using
2238 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2239 and by using a prefix arg to `S-up/down' to specify the exact number
2240 of minutes to shift."
2241 :group 'org-time
2242 :get '(lambda (var) ; Make sure all entries have 5 elements
2243 (if (integerp (default-value var))
2244 (list (default-value var) 5)
2245 (default-value var)))
2246 :type '(list
2247 (integer :tag "when inserting times")
2248 (integer :tag "when modifying times")))
2250 ;; Normalize old customizations of this variable.
2251 (when (integerp org-time-stamp-rounding-minutes)
2252 (setq org-time-stamp-rounding-minutes
2253 (list org-time-stamp-rounding-minutes
2254 org-time-stamp-rounding-minutes)))
2256 (defcustom org-display-custom-times nil
2257 "Non-nil means, overlay custom formats over all time stamps.
2258 The formats are defined through the variable `org-time-stamp-custom-formats'.
2259 To turn this on on a per-file basis, insert anywhere in the file:
2260 #+STARTUP: customtime"
2261 :group 'org-time
2262 :set 'set-default
2263 :type 'sexp)
2264 (make-variable-buffer-local 'org-display-custom-times)
2266 (defcustom org-time-stamp-custom-formats
2267 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2268 "Custom formats for time stamps. See `format-time-string' for the syntax.
2269 These are overlayed over the default ISO format if the variable
2270 `org-display-custom-times' is set. Time like %H:%M should be at the
2271 end of the second format. The custom formats are also honored by export
2272 commands, if custom time display is turned on at the time of export."
2273 :group 'org-time
2274 :type 'sexp)
2276 (defun org-time-stamp-format (&optional long inactive)
2277 "Get the right format for a time string."
2278 (let ((f (if long (cdr org-time-stamp-formats)
2279 (car org-time-stamp-formats))))
2280 (if inactive
2281 (concat "[" (substring f 1 -1) "]")
2282 f)))
2284 (defcustom org-time-clocksum-format "%d:%02d"
2285 "The format string used when creating CLOCKSUM lines, or when
2286 org-mode generates a time duration."
2287 :group 'org-time
2288 :type 'string)
2290 (defcustom org-time-clocksum-use-fractional nil
2291 "If non-nil, \\[org-clock-display] uses fractional times.
2292 org-mode generates a time duration."
2293 :group 'org-time
2294 :type 'boolean)
2296 (defcustom org-time-clocksum-fractional-format "%.2f"
2297 "The format string used when creating CLOCKSUM lines, or when
2298 org-mode generates a time duration."
2299 :group 'org-time
2300 :type 'string)
2302 (defcustom org-deadline-warning-days 14
2303 "No. of days before expiration during which a deadline becomes active.
2304 This variable governs the display in sparse trees and in the agenda.
2305 When 0 or negative, it means use this number (the absolute value of it)
2306 even if a deadline has a different individual lead time specified.
2308 Custom commands can set this variable in the options section."
2309 :group 'org-time
2310 :group 'org-agenda-daily/weekly
2311 :type 'integer)
2313 (defcustom org-read-date-prefer-future t
2314 "Non-nil means, assume future for incomplete date input from user.
2315 This affects the following situations:
2316 1. The user gives a month but not a year.
2317 For example, if it is april and you enter \"feb 2\", this will be read
2318 as feb 2, *next* year. \"May 5\", however, will be this year.
2319 2. The user gives a day, but no month.
2320 For example, if today is the 15th, and you enter \"3\", Org-mode will
2321 read this as the third of *next* month. However, if you enter \"17\",
2322 it will be considered as *this* month.
2324 If you set this variable to the symbol `time', then also the following
2325 will work:
2327 3. If the user gives a time, but no day. If the time is before now,
2328 to will be interpreted as tomorrow.
2330 Currently none of this works for ISO week specifications.
2332 When this option is nil, the current day, month and year will always be
2333 used as defaults."
2334 :group 'org-time
2335 :type '(choice
2336 (const :tag "Never" nil)
2337 (const :tag "Check month and day" t)
2338 (const :tag "Check month, day, and time" time)))
2340 (defcustom org-read-date-display-live t
2341 "Non-nil means, display current interpretation of date prompt live.
2342 This display will be in an overlay, in the minibuffer."
2343 :group 'org-time
2344 :type 'boolean)
2346 (defcustom org-read-date-popup-calendar t
2347 "Non-nil means, pop up a calendar when prompting for a date.
2348 In the calendar, the date can be selected with mouse-1. However, the
2349 minibuffer will also be active, and you can simply enter the date as well.
2350 When nil, only the minibuffer will be available."
2351 :group 'org-time
2352 :type 'boolean)
2353 (if (fboundp 'defvaralias)
2354 (defvaralias 'org-popup-calendar-for-date-prompt
2355 'org-read-date-popup-calendar))
2357 (defcustom org-read-date-minibuffer-setup-hook nil
2358 "Hook to be used to set up keys for the date/time interface.
2359 Add key definitions to `minibuffer-local-map', which will be a temporary
2360 copy."
2361 :group 'org-time
2362 :type 'hook)
2364 (defcustom org-extend-today-until 0
2365 "The hour when your day really ends. Must be an integer.
2366 This has influence for the following applications:
2367 - When switching the agenda to \"today\". It it is still earlier than
2368 the time given here, the day recognized as TODAY is actually yesterday.
2369 - When a date is read from the user and it is still before the time given
2370 here, the current date and time will be assumed to be yesterday, 23:59.
2371 Also, timestamps inserted in remember templates follow this rule.
2373 IMPORTANT: This is a feature whose implementation is and likely will
2374 remain incomplete. Really, it is only here because past midnight seems to
2375 be the favorite working time of John Wiegley :-)"
2376 :group 'org-time
2377 :type 'integer)
2379 (defcustom org-edit-timestamp-down-means-later nil
2380 "Non-nil means, S-down will increase the time in a time stamp.
2381 When nil, S-up will increase."
2382 :group 'org-time
2383 :type 'boolean)
2385 (defcustom org-calendar-follow-timestamp-change t
2386 "Non-nil means, make the calendar window follow timestamp changes.
2387 When a timestamp is modified and the calendar window is visible, it will be
2388 moved to the new date."
2389 :group 'org-time
2390 :type 'boolean)
2392 (defgroup org-tags nil
2393 "Options concerning tags in Org-mode."
2394 :tag "Org Tags"
2395 :group 'org)
2397 (defcustom org-tag-alist nil
2398 "List of tags allowed in Org-mode files.
2399 When this list is nil, Org-mode will base TAG input on what is already in the
2400 buffer.
2401 The value of this variable is an alist, the car of each entry must be a
2402 keyword as a string, the cdr may be a character that is used to select
2403 that tag through the fast-tag-selection interface.
2404 See the manual for details."
2405 :group 'org-tags
2406 :type '(repeat
2407 (choice
2408 (cons (string :tag "Tag name")
2409 (character :tag "Access char"))
2410 (list :tag "Start radio group"
2411 (const :startgroup)
2412 (option (string :tag "Group description")))
2413 (list :tag "End radio group"
2414 (const :endgroup)
2415 (option (string :tag "Group description")))
2416 (const :tag "New line" (:newline)))))
2418 (defcustom org-tag-persistent-alist nil
2419 "List of tags that will always appear in all Org-mode files.
2420 This is in addition to any in buffer settings or customizations
2421 of `org-tag-alist'.
2422 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2423 The value of this variable is an alist, the car of each entry must be a
2424 keyword as a string, the cdr may be a character that is used to select
2425 that tag through the fast-tag-selection interface.
2426 See the manual for details.
2427 To disable these tags on a per-file basis, insert anywhere in the file:
2428 #+STARTUP: noptag"
2429 :group 'org-tags
2430 :type '(repeat
2431 (choice
2432 (cons (string :tag "Tag name")
2433 (character :tag "Access char"))
2434 (const :tag "Start radio group" (:startgroup))
2435 (const :tag "End radio group" (:endgroup))
2436 (const :tag "New line" (:newline)))))
2438 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2439 "If non-nil, always offer completion for all tags of all agenda files.
2440 Instead of customizing this variable directly, you might want to
2441 set it locally for remember buffers, because there no list of
2442 tags in that file can be created dynamically (there are none).
2444 (add-hook 'org-remember-mode-hook
2445 (lambda ()
2446 (set (make-local-variable
2447 'org-complete-tags-always-offer-all-agenda-tags)
2448 t)))"
2449 :group 'org-tags
2450 :type 'boolean)
2452 (defvar org-file-tags nil
2453 "List of tags that can be inherited by all entries in the file.
2454 The tags will be inherited if the variable `org-use-tag-inheritance'
2455 says they should be.
2456 This variable is populated from #+FILETAGS lines.")
2458 (defcustom org-use-fast-tag-selection 'auto
2459 "Non-nil means, use fast tag selection scheme.
2460 This is a special interface to select and deselect tags with single keys.
2461 When nil, fast selection is never used.
2462 When the symbol `auto', fast selection is used if and only if selection
2463 characters for tags have been configured, either through the variable
2464 `org-tag-alist' or through a #+TAGS line in the buffer.
2465 When t, fast selection is always used and selection keys are assigned
2466 automatically if necessary."
2467 :group 'org-tags
2468 :type '(choice
2469 (const :tag "Always" t)
2470 (const :tag "Never" nil)
2471 (const :tag "When selection characters are configured" 'auto)))
2473 (defcustom org-fast-tag-selection-single-key nil
2474 "Non-nil means, fast tag selection exits after first change.
2475 When nil, you have to press RET to exit it.
2476 During fast tag selection, you can toggle this flag with `C-c'.
2477 This variable can also have the value `expert'. In this case, the window
2478 displaying the tags menu is not even shown, until you press C-c again."
2479 :group 'org-tags
2480 :type '(choice
2481 (const :tag "No" nil)
2482 (const :tag "Yes" t)
2483 (const :tag "Expert" expert)))
2485 (defvar org-fast-tag-selection-include-todo nil
2486 "Non-nil means, fast tags selection interface will also offer TODO states.
2487 This is an undocumented feature, you should not rely on it.")
2489 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2490 "The column to which tags should be indented in a headline.
2491 If this number is positive, it specifies the column. If it is negative,
2492 it means that the tags should be flushright to that column. For example,
2493 -80 works well for a normal 80 character screen."
2494 :group 'org-tags
2495 :type 'integer)
2497 (defcustom org-auto-align-tags t
2498 "Non-nil means, realign tags after pro/demotion of TODO state change.
2499 These operations change the length of a headline and therefore shift
2500 the tags around. With this options turned on, after each such operation
2501 the tags are again aligned to `org-tags-column'."
2502 :group 'org-tags
2503 :type 'boolean)
2505 (defcustom org-use-tag-inheritance t
2506 "Non-nil means, tags in levels apply also for sublevels.
2507 When nil, only the tags directly given in a specific line apply there.
2508 This may also be a list of tags that should be inherited, or a regexp that
2509 matches tags that should be inherited. Additional control is possible
2510 with the variable `org-tags-exclude-from-inheritance' which gives an
2511 explicit list of tags to be excluded from inheritance., even if the value of
2512 `org-use-tag-inheritance' would select it for inheritance.
2514 If this option is t, a match early-on in a tree can lead to a large
2515 number of matches in the subtree when constructing the agenda or creating
2516 a sparse tree. If you only want to see the first match in a tree during
2517 a search, check out the variable `org-tags-match-list-sublevels'."
2518 :group 'org-tags
2519 :type '(choice
2520 (const :tag "Not" nil)
2521 (const :tag "Always" t)
2522 (repeat :tag "Specific tags" (string :tag "Tag"))
2523 (regexp :tag "Tags matched by regexp")))
2525 (defcustom org-tags-exclude-from-inheritance nil
2526 "List of tags that should never be inherited.
2527 This is a way to exclude a few tags from inheritance. For way to do
2528 the opposite, to actively allow inheritance for selected tags,
2529 see the variable `org-use-tag-inheritance'."
2530 :group 'org-tags
2531 :type '(repeat (string :tag "Tag")))
2533 (defun org-tag-inherit-p (tag)
2534 "Check if TAG is one that should be inherited."
2535 (cond
2536 ((member tag org-tags-exclude-from-inheritance) nil)
2537 ((eq org-use-tag-inheritance t) t)
2538 ((not org-use-tag-inheritance) nil)
2539 ((stringp org-use-tag-inheritance)
2540 (string-match org-use-tag-inheritance tag))
2541 ((listp org-use-tag-inheritance)
2542 (member tag org-use-tag-inheritance))
2543 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2545 (defcustom org-tags-match-list-sublevels t
2546 "Non-nil means list also sublevels of headlines matching a search.
2547 This variable applies to tags/property searches, and also to stuck
2548 projects because this search is based on a tags match as well.
2550 When set to the symbol `indented', sublevels are indented with
2551 leading dots.
2553 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2554 the sublevels of a headline matching a tag search often also match
2555 the same search. Listing all of them can create very long lists.
2556 Setting this variable to nil causes subtrees of a match to be skipped.
2558 This variable is semi-obsolete and probably should always be true. It
2559 is better to limit inheritance to certain tags using the variables
2560 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2561 :group 'org-tags
2562 :type '(choice
2563 (const :tag "No, don't list them" nil)
2564 (const :tag "Yes, do list them" t)
2565 (const :tag "List them, indented with leading dots" indented)))
2567 (defcustom org-tags-sort-function nil
2568 "When set, tags are sorted using this function as a comparator"
2569 :group 'org-tags
2570 :type '(choice
2571 (const :tag "No sorting" nil)
2572 (const :tag "Alphabetical" string<)
2573 (const :tag "Reverse alphabetical" string>)
2574 (function :tag "Custom function" nil)))
2576 (defvar org-tags-history nil
2577 "History of minibuffer reads for tags.")
2578 (defvar org-last-tags-completion-table nil
2579 "The last used completion table for tags.")
2580 (defvar org-after-tags-change-hook nil
2581 "Hook that is run after the tags in a line have changed.")
2583 (defgroup org-properties nil
2584 "Options concerning properties in Org-mode."
2585 :tag "Org Properties"
2586 :group 'org)
2588 (defcustom org-property-format "%-10s %s"
2589 "How property key/value pairs should be formatted by `indent-line'.
2590 When `indent-line' hits a property definition, it will format the line
2591 according to this format, mainly to make sure that the values are
2592 lined-up with respect to each other."
2593 :group 'org-properties
2594 :type 'string)
2596 (defcustom org-use-property-inheritance nil
2597 "Non-nil means, properties apply also for sublevels.
2599 This setting is chiefly used during property searches. Turning it on can
2600 cause significant overhead when doing a search, which is why it is not
2601 on by default.
2603 When nil, only the properties directly given in the current entry count.
2604 When t, every property is inherited. The value may also be a list of
2605 properties that should have inheritance, or a regular expression matching
2606 properties that should be inherited.
2608 However, note that some special properties use inheritance under special
2609 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2610 and the properties ending in \"_ALL\" when they are used as descriptor
2611 for valid values of a property.
2613 Note for programmers:
2614 When querying an entry with `org-entry-get', you can control if inheritance
2615 should be used. By default, `org-entry-get' looks only at the local
2616 properties. You can request inheritance by setting the inherit argument
2617 to t (to force inheritance) or to `selective' (to respect the setting
2618 in this variable)."
2619 :group 'org-properties
2620 :type '(choice
2621 (const :tag "Not" nil)
2622 (const :tag "Always" t)
2623 (repeat :tag "Specific properties" (string :tag "Property"))
2624 (regexp :tag "Properties matched by regexp")))
2626 (defun org-property-inherit-p (property)
2627 "Check if PROPERTY is one that should be inherited."
2628 (cond
2629 ((eq org-use-property-inheritance t) t)
2630 ((not org-use-property-inheritance) nil)
2631 ((stringp org-use-property-inheritance)
2632 (string-match org-use-property-inheritance property))
2633 ((listp org-use-property-inheritance)
2634 (member property org-use-property-inheritance))
2635 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2637 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2638 "The default column format, if no other format has been defined.
2639 This variable can be set on the per-file basis by inserting a line
2641 #+COLUMNS: %25ITEM ....."
2642 :group 'org-properties
2643 :type 'string)
2645 (defcustom org-columns-ellipses ".."
2646 "The ellipses to be used when a field in column view is truncated.
2647 When this is the empty string, as many characters as possible are shown,
2648 but then there will be no visual indication that the field has been truncated.
2649 When this is a string of length N, the last N characters of a truncated
2650 field are replaced by this string. If the column is narrower than the
2651 ellipses string, only part of the ellipses string will be shown."
2652 :group 'org-properties
2653 :type 'string)
2655 (defcustom org-columns-modify-value-for-display-function nil
2656 "Function that modifies values for display in column view.
2657 For example, it can be used to cut out a certain part from a time stamp.
2658 The function must take 2 arguments:
2660 column-title The title of the column (*not* the property name)
2661 value The value that should be modified.
2663 The function should return the value that should be displayed,
2664 or nil if the normal value should be used."
2665 :group 'org-properties
2666 :type 'function)
2668 (defcustom org-effort-property "Effort"
2669 "The property that is being used to keep track of effort estimates.
2670 Effort estimates given in this property need to have the format H:MM."
2671 :group 'org-properties
2672 :group 'org-progress
2673 :type '(string :tag "Property"))
2675 (defconst org-global-properties-fixed
2676 '(("VISIBILITY_ALL" . "folded children content all")
2677 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2678 "List of property/value pairs that can be inherited by any entry.
2680 These are fixed values, for the preset properties. The user variable
2681 that can be used to add to this list is `org-global-properties'.
2683 The entries in this list are cons cells where the car is a property
2684 name and cdr is a string with the value. If the value represents
2685 multiple items like an \"_ALL\" property, separate the items by
2686 spaces.")
2688 (defcustom org-global-properties nil
2689 "List of property/value pairs that can be inherited by any entry.
2691 This list will be combined with the constant `org-global-properties-fixed'.
2693 The entries in this list are cons cells where the car is a property
2694 name and cdr is a string with the value.
2696 You can set buffer-local values for the same purpose in the variable
2697 `org-file-properties' this by adding lines like
2699 #+PROPERTY: NAME VALUE"
2700 :group 'org-properties
2701 :type '(repeat
2702 (cons (string :tag "Property")
2703 (string :tag "Value"))))
2705 (defvar org-file-properties nil
2706 "List of property/value pairs that can be inherited by any entry.
2707 Valid for the current buffer.
2708 This variable is populated from #+PROPERTY lines.")
2709 (make-variable-buffer-local 'org-file-properties)
2711 (defgroup org-agenda nil
2712 "Options concerning agenda views in Org-mode."
2713 :tag "Org Agenda"
2714 :group 'org)
2716 (defvar org-category nil
2717 "Variable used by org files to set a category for agenda display.
2718 Such files should use a file variable to set it, for example
2720 # -*- mode: org; org-category: \"ELisp\"
2722 or contain a special line
2724 #+CATEGORY: ELisp
2726 If the file does not specify a category, then file's base name
2727 is used instead.")
2728 (make-variable-buffer-local 'org-category)
2729 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2731 (defcustom org-agenda-files nil
2732 "The files to be used for agenda display.
2733 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2734 \\[org-remove-file]. You can also use customize to edit the list.
2736 If an entry is a directory, all files in that directory that are matched by
2737 `org-agenda-file-regexp' will be part of the file list.
2739 If the value of the variable is not a list but a single file name, then
2740 the list of agenda files is actually stored and maintained in that file, one
2741 agenda file per line."
2742 :group 'org-agenda
2743 :type '(choice
2744 (repeat :tag "List of files and directories" file)
2745 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2747 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2748 "Regular expression to match files for `org-agenda-files'.
2749 If any element in the list in that variable contains a directory instead
2750 of a normal file, all files in that directory that are matched by this
2751 regular expression will be included."
2752 :group 'org-agenda
2753 :type 'regexp)
2755 (defcustom org-agenda-text-search-extra-files nil
2756 "List of extra files to be searched by text search commands.
2757 These files will be search in addition to the agenda files by the
2758 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2759 Note that these files will only be searched for text search commands,
2760 not for the other agenda views like todo lists, tag searches or the weekly
2761 agenda. This variable is intended to list notes and possibly archive files
2762 that should also be searched by these two commands.
2763 In fact, if the first element in the list is the symbol `agenda-archives',
2764 than all archive files of all agenda files will be added to the search
2765 scope."
2766 :group 'org-agenda
2767 :type '(set :greedy t
2768 (const :tag "Agenda Archives" agenda-archives)
2769 (repeat :inline t (file))))
2771 (if (fboundp 'defvaralias)
2772 (defvaralias 'org-agenda-multi-occur-extra-files
2773 'org-agenda-text-search-extra-files))
2775 (defcustom org-agenda-skip-unavailable-files nil
2776 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2777 A nil value means to remove them, after a query, from the list."
2778 :group 'org-agenda
2779 :type 'boolean)
2781 (defcustom org-calendar-to-agenda-key [?c]
2782 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2783 The command `org-calendar-goto-agenda' will be bound to this key. The
2784 default is the character `c' because then `c' can be used to switch back and
2785 forth between agenda and calendar."
2786 :group 'org-agenda
2787 :type 'sexp)
2789 (defcustom org-calendar-agenda-action-key [?k]
2790 "The key to be installed in `calendar-mode-map' for agenda-action.
2791 The command `org-agenda-action' will be bound to this key. The
2792 default is the character `k' because we use the same key in the agenda."
2793 :group 'org-agenda
2794 :type 'sexp)
2796 (defcustom org-calendar-insert-diary-entry-key [?i]
2797 "The key to be installed in `calendar-mode-map' for adding diary entries.
2798 This option is irrelevant until `org-agenda-diary-file' has been configured
2799 to point to an Org-mode file. When that is the case, the command
2800 `org-agenda-diary-entry' will be bound to the key given here, by default
2801 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2802 if you want to continue doing this, you need to change this to a different
2803 key."
2804 :group 'org-agenda
2805 :type 'sexp)
2807 (defcustom org-agenda-diary-file 'diary-file
2808 "File to which to add new entries with the `i' key in agenda and calendar.
2809 When this is the symbol `diary-file', the functionality in the Emacs
2810 calendar will be used to add entries to the `diary-file'. But when this
2811 points to a file, `org-agenda-diary-entry' will be used instead."
2812 :group 'org-agenda
2813 :type '(choice
2814 (const :tag "The standard Emacs diary file" diary-file)
2815 (file :tag "Special Org file diary entries")))
2817 (eval-after-load "calendar"
2818 '(progn
2819 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2820 'org-calendar-goto-agenda)
2821 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2822 'org-agenda-action)
2823 (add-hook 'calendar-mode-hook
2824 (lambda ()
2825 (unless (eq org-agenda-diary-file 'diary-file)
2826 (define-key calendar-mode-map
2827 org-calendar-insert-diary-entry-key
2828 'org-agenda-diary-entry))))))
2830 (defgroup org-latex nil
2831 "Options for embedding LaTeX code into Org-mode."
2832 :tag "Org LaTeX"
2833 :group 'org)
2835 (defcustom org-format-latex-options
2836 '(:foreground default :background default :scale 1.0
2837 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2838 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2839 "Options for creating images from LaTeX fragments.
2840 This is a property list with the following properties:
2841 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2842 `default' means use the foreground of the default face.
2843 :background the background color, or \"Transparent\".
2844 `default' means use the background of the default face.
2845 :scale a scaling factor for the size of the images.
2846 :html-foreground, :html-background, :html-scale
2847 the same numbers for HTML export.
2848 :matchers a list indicating which matchers should be used to
2849 find LaTeX fragments. Valid members of this list are:
2850 \"begin\" find environments
2851 \"$1\" find single characters surrounded by $.$
2852 \"$\" find math expressions surrounded by $...$
2853 \"$$\" find math expressions surrounded by $$....$$
2854 \"\\(\" find math expressions surrounded by \\(...\\)
2855 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2856 :group 'org-latex
2857 :type 'plist)
2859 (defcustom org-format-latex-header "\\documentclass{article}
2860 \\usepackage{amssymb}
2861 \\usepackage[usenames]{color}
2862 \\usepackage{amsmath}
2863 \\usepackage{latexsym}
2864 \\usepackage[mathscr]{eucal}
2865 \\pagestyle{empty} % do not remove
2866 % The settings below are copied from fullpage.sty
2867 \\setlength{\\textwidth}{\\paperwidth}
2868 \\addtolength{\\textwidth}{-3cm}
2869 \\setlength{\\oddsidemargin}{1.5cm}
2870 \\addtolength{\\oddsidemargin}{-2.54cm}
2871 \\setlength{\\evensidemargin}{\\oddsidemargin}
2872 \\setlength{\\textheight}{\\paperheight}
2873 \\addtolength{\\textheight}{-\\headheight}
2874 \\addtolength{\\textheight}{-\\headsep}
2875 \\addtolength{\\textheight}{-\\footskip}
2876 \\addtolength{\\textheight}{-3cm}
2877 \\setlength{\\topmargin}{1.5cm}
2878 \\addtolength{\\topmargin}{-2.54cm}"
2879 "The document header used for processing LaTeX fragments.
2880 It is imperative that this header make sure that no page number
2881 appears on the page."
2882 :group 'org-latex
2883 :type 'string)
2885 ;; The following variable is defined here because is it also used
2886 ;; when formatting latex fragments. Originally it was part of the
2887 ;; LaTeX exporter, which is why the name includes "export".
2888 (defcustom org-export-latex-packages-alist nil
2889 "Alist of packages to be inserted in the header.
2890 Each cell is of the format \( \"option\" . \"package\" \)."
2891 :group 'org-export-latex
2892 :type '(repeat
2893 (list
2894 (string :tag "option")
2895 (string :tag "package"))))
2897 (defgroup org-font-lock nil
2898 "Font-lock settings for highlighting in Org-mode."
2899 :tag "Org Font Lock"
2900 :group 'org)
2902 (defcustom org-level-color-stars-only nil
2903 "Non-nil means fontify only the stars in each headline.
2904 When nil, the entire headline is fontified.
2905 Changing it requires restart of `font-lock-mode' to become effective
2906 also in regions already fontified."
2907 :group 'org-font-lock
2908 :type 'boolean)
2910 (defcustom org-hide-leading-stars nil
2911 "Non-nil means, hide the first N-1 stars in a headline.
2912 This works by using the face `org-hide' for these stars. This
2913 face is white for a light background, and black for a dark
2914 background. You may have to customize the face `org-hide' to
2915 make this work.
2916 Changing it requires restart of `font-lock-mode' to become effective
2917 also in regions already fontified.
2918 You may also set this on a per-file basis by adding one of the following
2919 lines to the buffer:
2921 #+STARTUP: hidestars
2922 #+STARTUP: showstars"
2923 :group 'org-font-lock
2924 :type 'boolean)
2926 (defcustom org-fontify-done-headline nil
2927 "Non-nil means, change the face of a headline if it is marked DONE.
2928 Normally, only the TODO/DONE keyword indicates the state of a headline.
2929 When this is non-nil, the headline after the keyword is set to the
2930 `org-headline-done' as an additional indication."
2931 :group 'org-font-lock
2932 :type 'boolean)
2934 (defcustom org-fontify-emphasized-text t
2935 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2936 Changing this variable requires a restart of Emacs to take effect."
2937 :group 'org-font-lock
2938 :type 'boolean)
2940 (defcustom org-fontify-whole-heading-line nil
2941 "Non-nil means fontify the whole line for headings.
2942 This is useful when setting a background color for the
2943 org-level-* faces."
2944 :group 'org-font-lock
2945 :type 'boolean)
2947 (defcustom org-highlight-latex-fragments-and-specials nil
2948 "Non-nil means, fontify what is treated specially by the exporters."
2949 :group 'org-font-lock
2950 :type 'boolean)
2952 (defcustom org-hide-emphasis-markers nil
2953 "Non-nil mean font-lock should hide the emphasis marker characters."
2954 :group 'org-font-lock
2955 :type 'boolean)
2957 (defvar org-emph-re nil
2958 "Regular expression for matching emphasis.")
2959 (defvar org-verbatim-re nil
2960 "Regular expression for matching verbatim text.")
2961 (defvar org-emphasis-regexp-components) ; defined just below
2962 (defvar org-emphasis-alist) ; defined just below
2963 (defun org-set-emph-re (var val)
2964 "Set variable and compute the emphasis regular expression."
2965 (set var val)
2966 (when (and (boundp 'org-emphasis-alist)
2967 (boundp 'org-emphasis-regexp-components)
2968 org-emphasis-alist org-emphasis-regexp-components)
2969 (let* ((e org-emphasis-regexp-components)
2970 (pre (car e))
2971 (post (nth 1 e))
2972 (border (nth 2 e))
2973 (body (nth 3 e))
2974 (nl (nth 4 e))
2975 (body1 (concat body "*?"))
2976 (markers (mapconcat 'car org-emphasis-alist ""))
2977 (vmarkers (mapconcat
2978 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2979 org-emphasis-alist "")))
2980 ;; make sure special characters appear at the right position in the class
2981 (if (string-match "\\^" markers)
2982 (setq markers (concat (replace-match "" t t markers) "^")))
2983 (if (string-match "-" markers)
2984 (setq markers (concat (replace-match "" t t markers) "-")))
2985 (if (string-match "\\^" vmarkers)
2986 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2987 (if (string-match "-" vmarkers)
2988 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2989 (if (> nl 0)
2990 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2991 (int-to-string nl) "\\}")))
2992 ;; Make the regexp
2993 (setq org-emph-re
2994 (concat "\\([" pre "]\\|^\\)"
2995 "\\("
2996 "\\([" markers "]\\)"
2997 "\\("
2998 "[^" border "]\\|"
2999 "[^" border "]"
3000 body1
3001 "[^" border "]"
3002 "\\)"
3003 "\\3\\)"
3004 "\\([" post "]\\|$\\)"))
3005 (setq org-verbatim-re
3006 (concat "\\([" pre "]\\|^\\)"
3007 "\\("
3008 "\\([" vmarkers "]\\)"
3009 "\\("
3010 "[^" border "]\\|"
3011 "[^" border "]"
3012 body1
3013 "[^" border "]"
3014 "\\)"
3015 "\\3\\)"
3016 "\\([" post "]\\|$\\)")))))
3018 (defcustom org-emphasis-regexp-components
3019 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3020 "Components used to build the regular expression for emphasis.
3021 This is a list with 6 entries. Terminology: In an emphasis string
3022 like \" *strong word* \", we call the initial space PREMATCH, the final
3023 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3024 and \"trong wor\" is the body. The different components in this variable
3025 specify what is allowed/forbidden in each part:
3027 pre Chars allowed as prematch. Beginning of line will be allowed too.
3028 post Chars allowed as postmatch. End of line will be allowed too.
3029 border The chars *forbidden* as border characters.
3030 body-regexp A regexp like \".\" to match a body character. Don't use
3031 non-shy groups here, and don't allow newline here.
3032 newline The maximum number of newlines allowed in an emphasis exp.
3034 Use customize to modify this, or restart Emacs after changing it."
3035 :group 'org-font-lock
3036 :set 'org-set-emph-re
3037 :type '(list
3038 (sexp :tag "Allowed chars in pre ")
3039 (sexp :tag "Allowed chars in post ")
3040 (sexp :tag "Forbidden chars in border ")
3041 (sexp :tag "Regexp for body ")
3042 (integer :tag "number of newlines allowed")
3043 (option (boolean :tag "Please ignore this button"))))
3045 (defcustom org-emphasis-alist
3046 `(("*" bold "<b>" "</b>")
3047 ("/" italic "<i>" "</i>")
3048 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3049 ("=" org-code "<code>" "</code>" verbatim)
3050 ("~" org-verbatim "<code>" "</code>" verbatim)
3051 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3052 "<del>" "</del>")
3054 "Special syntax for emphasized text.
3055 Text starting and ending with a special character will be emphasized, for
3056 example *bold*, _underlined_ and /italic/. This variable sets the marker
3057 characters, the face to be used by font-lock for highlighting in Org-mode
3058 Emacs buffers, and the HTML tags to be used for this.
3059 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3060 Use customize to modify this, or restart Emacs after changing it."
3061 :group 'org-font-lock
3062 :set 'org-set-emph-re
3063 :type '(repeat
3064 (list
3065 (string :tag "Marker character")
3066 (choice
3067 (face :tag "Font-lock-face")
3068 (plist :tag "Face property list"))
3069 (string :tag "HTML start tag")
3070 (string :tag "HTML end tag")
3071 (option (const verbatim)))))
3073 (defvar org-protecting-blocks
3074 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3075 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3076 This is needed for font-lock setup.")
3078 ;;; Miscellaneous options
3080 (defgroup org-completion nil
3081 "Completion in Org-mode."
3082 :tag "Org Completion"
3083 :group 'org)
3085 (defcustom org-completion-use-ido nil
3086 "Non-nil means, use ido completion wherever possible.
3087 Note that `ido-mode' must be active for this variable to be relevant.
3088 If you decide to turn this variable on, you might well want to turn off
3089 `org-outline-path-complete-in-steps'.
3090 See also `org-completion-use-iswitchb'."
3091 :group 'org-completion
3092 :type 'boolean)
3094 (defcustom org-completion-use-iswitchb nil
3095 "Non-nil means, use iswitchb completion wherever possible.
3096 Note that `iswitchb-mode' must be active for this variable to be relevant.
3097 If you decide to turn this variable on, you might well want to turn off
3098 `org-outline-path-complete-in-steps'.
3099 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3100 :group 'org-completion
3101 :type 'boolean)
3103 (defcustom org-completion-fallback-command 'hippie-expand
3104 "The expansion command called by \\[org-complete] in normal context.
3105 Normal means, no org-mode-specific context."
3106 :group 'org-completion
3107 :type 'function)
3109 ;;; Functions and variables from their packages
3110 ;; Declared here to avoid compiler warnings
3112 ;; XEmacs only
3113 (defvar outline-mode-menu-heading)
3114 (defvar outline-mode-menu-show)
3115 (defvar outline-mode-menu-hide)
3116 (defvar zmacs-regions) ; XEmacs regions
3118 ;; Emacs only
3119 (defvar mark-active)
3121 ;; Various packages
3122 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3123 (declare-function calendar-forward-day "cal-move" (arg))
3124 (declare-function calendar-goto-date "cal-move" (date))
3125 (declare-function calendar-goto-today "cal-move" ())
3126 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3127 (defvar calc-embedded-close-formula)
3128 (defvar calc-embedded-open-formula)
3129 (declare-function cdlatex-tab "ext:cdlatex" ())
3130 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3131 (defvar font-lock-unfontify-region-function)
3132 (declare-function iswitchb-read-buffer "iswitchb"
3133 (prompt &optional default require-match start matches-set))
3134 (defvar iswitchb-temp-buflist)
3135 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3136 (defvar org-agenda-tags-todo-honor-ignore-options)
3137 (declare-function org-agenda-skip "org-agenda" ())
3138 (declare-function
3139 org-format-agenda-item "org-agenda"
3140 (extra txt &optional category tags dotime noprefix remove-re habitp))
3141 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3142 (declare-function org-agenda-change-all-lines "org-agenda"
3143 (newhead hdmarker &optional fixface just-this))
3144 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3145 (declare-function org-agenda-maybe-redo "org-agenda" ())
3146 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3147 (beg end))
3148 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3149 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3150 "org-agenda" (&optional end))
3151 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3152 (declare-function org-indent-mode "org-indent" (&optional arg))
3153 (declare-function parse-time-string "parse-time" (string))
3154 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3155 (defvar remember-data-file)
3156 (defvar texmathp-why)
3157 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3158 (declare-function table--at-cell-p "table" (position &optional object at-column))
3160 (defvar w3m-current-url)
3161 (defvar w3m-current-title)
3163 (defvar org-latex-regexps)
3165 ;;; Autoload and prepare some org modules
3167 ;; Some table stuff that needs to be defined here, because it is used
3168 ;; by the functions setting up org-mode or checking for table context.
3170 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3171 "Detects an org-type or table-type table.")
3172 (defconst org-table-line-regexp "^[ \t]*|"
3173 "Detects an org-type table line.")
3174 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3175 "Detects an org-type table line.")
3176 (defconst org-table-hline-regexp "^[ \t]*|-"
3177 "Detects an org-type table hline.")
3178 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3179 "Detects a table-type table hline.")
3180 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3181 "Searching from within a table (any type) this finds the first line
3182 outside the table.")
3184 ;; Autoload the functions in org-table.el that are needed by functions here.
3186 (eval-and-compile
3187 (org-autoload "org-table"
3188 '(org-table-align org-table-begin org-table-blank-field
3189 org-table-convert org-table-convert-region org-table-copy-down
3190 org-table-copy-region org-table-create
3191 org-table-create-or-convert-from-region
3192 org-table-create-with-table.el org-table-current-dline
3193 org-table-cut-region org-table-delete-column org-table-edit-field
3194 org-table-edit-formulas org-table-end org-table-eval-formula
3195 org-table-export org-table-field-info
3196 org-table-get-stored-formulas org-table-goto-column
3197 org-table-hline-and-move org-table-import org-table-insert-column
3198 org-table-insert-hline org-table-insert-row org-table-iterate
3199 org-table-justify-field-maybe org-table-kill-row
3200 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3201 org-table-move-column org-table-move-column-left
3202 org-table-move-column-right org-table-move-row
3203 org-table-move-row-down org-table-move-row-up
3204 org-table-next-field org-table-next-row org-table-paste-rectangle
3205 org-table-previous-field org-table-recalculate
3206 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3207 org-table-toggle-coordinate-overlays
3208 org-table-toggle-formula-debugger org-table-wrap-region
3209 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3211 (defun org-at-table-p (&optional table-type)
3212 "Return t if the cursor is inside an org-type table.
3213 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3214 (if org-enable-table-editor
3215 (save-excursion
3216 (beginning-of-line 1)
3217 (looking-at (if table-type org-table-any-line-regexp
3218 org-table-line-regexp)))
3219 nil))
3220 (defsubst org-table-p () (org-at-table-p))
3222 (defun org-at-table.el-p ()
3223 "Return t if and only if we are at a table.el table."
3224 (and (org-at-table-p 'any)
3225 (save-excursion
3226 (goto-char (org-table-begin 'any))
3227 (looking-at org-table1-hline-regexp))))
3228 (defun org-table-recognize-table.el ()
3229 "If there is a table.el table nearby, recognize it and move into it."
3230 (if org-table-tab-recognizes-table.el
3231 (if (org-at-table.el-p)
3232 (progn
3233 (beginning-of-line 1)
3234 (if (looking-at org-table-dataline-regexp)
3236 (if (looking-at org-table1-hline-regexp)
3237 (progn
3238 (beginning-of-line 2)
3239 (if (looking-at org-table-any-border-regexp)
3240 (beginning-of-line -1)))))
3241 (if (re-search-forward "|" (org-table-end t) t)
3242 (progn
3243 (require 'table)
3244 (if (table--at-cell-p (point))
3246 (message "recognizing table.el table...")
3247 (table-recognize-table)
3248 (message "recognizing table.el table...done")))
3249 (error "This should not happen..."))
3251 nil)
3252 nil))
3254 (defun org-at-table-hline-p ()
3255 "Return t if the cursor is inside a hline in a table."
3256 (if org-enable-table-editor
3257 (save-excursion
3258 (beginning-of-line 1)
3259 (looking-at org-table-hline-regexp))
3260 nil))
3262 (defvar org-table-clean-did-remove-column nil)
3264 (defun org-table-map-tables (function)
3265 "Apply FUNCTION to the start of all tables in the buffer."
3266 (save-excursion
3267 (save-restriction
3268 (widen)
3269 (goto-char (point-min))
3270 (while (re-search-forward org-table-any-line-regexp nil t)
3271 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3272 (beginning-of-line 1)
3273 (when (looking-at org-table-line-regexp)
3274 (save-excursion (funcall function))
3275 (or (looking-at org-table-line-regexp)
3276 (forward-char 1)))
3277 (re-search-forward org-table-any-border-regexp nil 1))))
3278 (message "Mapping tables: done"))
3280 ;; Declare and autoload functions from org-exp.el & Co
3282 (declare-function org-default-export-plist "org-exp")
3283 (declare-function org-infile-export-plist "org-exp")
3284 (declare-function org-get-current-options "org-exp")
3285 (eval-and-compile
3286 (org-autoload "org-exp"
3287 '(org-export org-export-visible
3288 org-insert-export-options-template
3289 org-table-clean-before-export))
3290 (org-autoload "org-ascii"
3291 '(org-export-as-ascii org-export-ascii-preprocess
3292 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3293 org-export-region-as-ascii))
3294 (org-autoload "org-latex"
3295 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3296 org-replace-region-by-latex org-export-region-as-latex
3297 org-export-as-latex org-export-as-pdf
3298 org-export-as-pdf-and-open))
3299 (org-autoload "org-html"
3300 '(org-export-as-html-and-open
3301 org-export-as-html-batch org-export-as-html-to-buffer
3302 org-replace-region-by-html org-export-region-as-html
3303 org-export-as-html))
3304 (org-autoload "org-docbook"
3305 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3306 org-replace-region-by-docbook org-export-region-as-docbook
3307 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3308 org-export-as-docbook))
3309 (org-autoload "org-icalendar"
3310 '(org-export-icalendar-this-file
3311 org-export-icalendar-all-agenda-files
3312 org-export-icalendar-combine-agenda-files))
3313 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3314 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3316 ;; Declare and autoload functions from org-agenda.el
3318 (eval-and-compile
3319 (org-autoload "org-agenda"
3320 '(org-agenda org-agenda-list org-search-view
3321 org-todo-list org-tags-view org-agenda-list-stuck-projects
3322 org-diary org-agenda-to-appt
3323 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3325 ;; Autoload org-remember
3327 (eval-and-compile
3328 (org-autoload "org-remember"
3329 '(org-remember-insinuate org-remember-annotation
3330 org-remember-apply-template org-remember org-remember-handler)))
3332 ;; Autoload org-clock.el
3335 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3336 (beg end))
3337 (declare-function org-clock-update-mode-line "org-clock" ())
3338 (declare-function org-resolve-clocks "org-clock"
3339 (&optional also-non-dangling-p prompt last-valid))
3340 (defvar org-clock-start-time)
3341 (defvar org-clock-marker (make-marker)
3342 "Marker recording the last clock-in.")
3343 (defvar org-clock-hd-marker (make-marker)
3344 "Marker recording the last clock-in, but the headline position.")
3345 (defvar org-clock-heading ""
3346 "The heading of the current clock entry.")
3347 (defun org-clock-is-active ()
3348 "Return non-nil if clock is currently running.
3349 The return value is actually the clock marker."
3350 (marker-buffer org-clock-marker))
3352 (eval-and-compile
3353 (org-autoload
3354 "org-clock"
3355 '(org-clock-in org-clock-out org-clock-cancel
3356 org-clock-goto org-clock-sum org-clock-display
3357 org-clock-remove-overlays org-clock-report
3358 org-clocktable-shift org-dblock-write:clocktable
3359 org-get-clocktable org-resolve-clocks)))
3361 (defun org-clock-update-time-maybe ()
3362 "If this is a CLOCK line, update it and return t.
3363 Otherwise, return nil."
3364 (interactive)
3365 (save-excursion
3366 (beginning-of-line 1)
3367 (skip-chars-forward " \t")
3368 (when (looking-at org-clock-string)
3369 (let ((re (concat "[ \t]*" org-clock-string
3370 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3371 "\\([ \t]*=>.*\\)?\\)?"))
3372 ts te h m s neg)
3373 (cond
3374 ((not (looking-at re))
3375 nil)
3376 ((not (match-end 2))
3377 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3378 (> org-clock-marker (point))
3379 (<= org-clock-marker (point-at-eol)))
3380 ;; The clock is running here
3381 (setq org-clock-start-time
3382 (apply 'encode-time
3383 (org-parse-time-string (match-string 1))))
3384 (org-clock-update-mode-line)))
3386 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3387 (end-of-line 1)
3388 (setq ts (match-string 1)
3389 te (match-string 3))
3390 (setq s (- (org-float-time
3391 (apply 'encode-time (org-parse-time-string te)))
3392 (org-float-time
3393 (apply 'encode-time (org-parse-time-string ts))))
3394 neg (< s 0)
3395 s (abs s)
3396 h (floor (/ s 3600))
3397 s (- s (* 3600 h))
3398 m (floor (/ s 60))
3399 s (- s (* 60 s)))
3400 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3401 t))))))
3403 (defun org-check-running-clock ()
3404 "Check if the current buffer contains the running clock.
3405 If yes, offer to stop it and to save the buffer with the changes."
3406 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3407 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3408 (buffer-name))))
3409 (org-clock-out)
3410 (when (y-or-n-p "Save changed buffer?")
3411 (save-buffer))))
3413 (defun org-clocktable-try-shift (dir n)
3414 "Check if this line starts a clock table, if yes, shift the time block."
3415 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3416 (org-clocktable-shift dir n)))
3418 ;; Autoload org-timer.el
3420 (eval-and-compile
3421 (org-autoload
3422 "org-timer"
3423 '(org-timer-start org-timer org-timer-item
3424 org-timer-change-times-in-region
3425 org-timer-set-timer
3426 org-timer-reset-timers
3427 org-timer-show-remaining-time)))
3429 ;; Autoload org-feed.el
3431 (eval-and-compile
3432 (org-autoload
3433 "org-feed"
3434 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3437 ;; Autoload org-indent.el
3439 ;; Define the variable already here, to make sure we have it.
3440 (defvar org-indent-mode nil
3441 "Non-nil if Org-Indent mode is enabled.
3442 Use the command `org-indent-mode' to change this variable.")
3444 (eval-and-compile
3445 (org-autoload
3446 "org-indent"
3447 '(org-indent-mode)))
3449 ;; Autoload org-mobile.el
3451 (eval-and-compile
3452 (org-autoload
3453 "org-mobile"
3454 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3456 ;; Autoload archiving code
3457 ;; The stuff that is needed for cycling and tags has to be defined here.
3459 (defgroup org-archive nil
3460 "Options concerning archiving in Org-mode."
3461 :tag "Org Archive"
3462 :group 'org-structure)
3464 (defcustom org-archive-location "%s_archive::"
3465 "The location where subtrees should be archived.
3467 The value of this variable is a string, consisting of two parts,
3468 separated by a double-colon. The first part is a filename and
3469 the second part is a headline.
3471 When the filename is omitted, archiving happens in the same file.
3472 %s in the filename will be replaced by the current file
3473 name (without the directory part). Archiving to a different file
3474 is useful to keep archived entries from contributing to the
3475 Org-mode Agenda.
3477 The archived entries will be filed as subtrees of the specified
3478 headline. When the headline is omitted, the subtrees are simply
3479 filed away at the end of the file, as top-level entries. Also in
3480 the heading you can use %s to represent the file name, this can be
3481 useful when using the same archive for a number of different files.
3483 Here are a few examples:
3484 \"%s_archive::\"
3485 If the current file is Projects.org, archive in file
3486 Projects.org_archive, as top-level trees. This is the default.
3488 \"::* Archived Tasks\"
3489 Archive in the current file, under the top-level headline
3490 \"* Archived Tasks\".
3492 \"~/org/archive.org::\"
3493 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3495 \"~/org/archive.org::From %s\"
3496 Archive in file ~/org/archive.org (absolute path), under headlines
3497 \"From FILENAME\" where file name is the current file name.
3499 \"basement::** Finished Tasks\"
3500 Archive in file ./basement (relative path), as level 3 trees
3501 below the level 2 heading \"** Finished Tasks\".
3503 You may set this option on a per-file basis by adding to the buffer a
3504 line like
3506 #+ARCHIVE: basement::** Finished Tasks
3508 You may also define it locally for a subtree by setting an ARCHIVE property
3509 in the entry. If such a property is found in an entry, or anywhere up
3510 the hierarchy, it will be used."
3511 :group 'org-archive
3512 :type 'string)
3514 (defcustom org-archive-tag "ARCHIVE"
3515 "The tag that marks a subtree as archived.
3516 An archived subtree does not open during visibility cycling, and does
3517 not contribute to the agenda listings.
3518 After changing this, font-lock must be restarted in the relevant buffers to
3519 get the proper fontification."
3520 :group 'org-archive
3521 :group 'org-keywords
3522 :type 'string)
3524 (defcustom org-agenda-skip-archived-trees t
3525 "Non-nil means, the agenda will skip any items located in archived trees.
3526 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3527 variable is no longer recommended, you should leave it at the value t.
3528 Instead, use the key `v' to cycle the archives-mode in the agenda."
3529 :group 'org-archive
3530 :group 'org-agenda-skip
3531 :type 'boolean)
3533 (defcustom org-columns-skip-archived-trees t
3534 "Non-nil means, ignore archived trees when creating column view."
3535 :group 'org-archive
3536 :group 'org-properties
3537 :type 'boolean)
3539 (defcustom org-cycle-open-archived-trees nil
3540 "Non-nil means, `org-cycle' will open archived trees.
3541 An archived tree is a tree marked with the tag ARCHIVE.
3542 When nil, archived trees will stay folded. You can still open them with
3543 normal outline commands like `show-all', but not with the cycling commands."
3544 :group 'org-archive
3545 :group 'org-cycle
3546 :type 'boolean)
3548 (defcustom org-sparse-tree-open-archived-trees nil
3549 "Non-nil means sparse tree construction shows matches in archived trees.
3550 When nil, matches in these trees are highlighted, but the trees are kept in
3551 collapsed state."
3552 :group 'org-archive
3553 :group 'org-sparse-trees
3554 :type 'boolean)
3556 (defun org-cycle-hide-archived-subtrees (state)
3557 "Re-hide all archived subtrees after a visibility state change."
3558 (when (and (not org-cycle-open-archived-trees)
3559 (not (memq state '(overview folded))))
3560 (save-excursion
3561 (let* ((globalp (memq state '(contents all)))
3562 (beg (if globalp (point-min) (point)))
3563 (end (if globalp (point-max) (org-end-of-subtree t))))
3564 (org-hide-archived-subtrees beg end)
3565 (goto-char beg)
3566 (if (looking-at (concat ".*:" org-archive-tag ":"))
3567 (message "%s" (substitute-command-keys
3568 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3570 (defun org-force-cycle-archived ()
3571 "Cycle subtree even if it is archived."
3572 (interactive)
3573 (setq this-command 'org-cycle)
3574 (let ((org-cycle-open-archived-trees t))
3575 (call-interactively 'org-cycle)))
3577 (defun org-hide-archived-subtrees (beg end)
3578 "Re-hide all archived subtrees after a visibility state change."
3579 (save-excursion
3580 (let* ((re (concat ":" org-archive-tag ":")))
3581 (goto-char beg)
3582 (while (re-search-forward re end t)
3583 (and (org-on-heading-p) (org-flag-subtree t))
3584 (org-end-of-subtree t)))))
3586 (defun org-flag-subtree (flag)
3587 (save-excursion
3588 (org-back-to-heading t)
3589 (outline-end-of-heading)
3590 (outline-flag-region (point)
3591 (progn (org-end-of-subtree t) (point))
3592 flag)))
3594 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3596 (eval-and-compile
3597 (org-autoload "org-archive"
3598 '(org-add-archive-files org-archive-subtree
3599 org-archive-to-archive-sibling org-toggle-archive-tag
3600 org-archive-subtree-default
3601 org-archive-subtree-default-with-confirmation)))
3603 ;; Autoload Column View Code
3605 (declare-function org-columns-number-to-string "org-colview")
3606 (declare-function org-columns-get-format-and-top-level "org-colview")
3607 (declare-function org-columns-compute "org-colview")
3609 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3610 '(org-columns-number-to-string org-columns-get-format-and-top-level
3611 org-columns-compute org-agenda-columns org-columns-remove-overlays
3612 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3614 ;; Autoload ID code
3616 (declare-function org-id-store-link "org-id")
3617 (declare-function org-id-locations-load "org-id")
3618 (declare-function org-id-locations-save "org-id")
3619 (defvar org-id-track-globally)
3620 (org-autoload "org-id"
3621 '(org-id-get-create org-id-new org-id-copy org-id-get
3622 org-id-get-with-outline-path-completion
3623 org-id-get-with-outline-drilling
3624 org-id-goto org-id-find org-id-store-link))
3626 ;; Autoload Plotting Code
3628 (org-autoload "org-plot"
3629 '(org-plot/gnuplot))
3631 ;;; Variables for pre-computed regular expressions, all buffer local
3633 (defvar org-drawer-regexp nil
3634 "Matches first line of a hidden block.")
3635 (make-variable-buffer-local 'org-drawer-regexp)
3636 (defvar org-todo-regexp nil
3637 "Matches any of the TODO state keywords.")
3638 (make-variable-buffer-local 'org-todo-regexp)
3639 (defvar org-not-done-regexp nil
3640 "Matches any of the TODO state keywords except the last one.")
3641 (make-variable-buffer-local 'org-not-done-regexp)
3642 (defvar org-not-done-heading-regexp nil
3643 "Matches a TODO headline that is not done.")
3644 (make-variable-buffer-local 'org-not-done-regexp)
3645 (defvar org-todo-line-regexp nil
3646 "Matches a headline and puts TODO state into group 2 if present.")
3647 (make-variable-buffer-local 'org-todo-line-regexp)
3648 (defvar org-complex-heading-regexp nil
3649 "Matches a headline and puts everything into groups:
3650 group 1: the stars
3651 group 2: The todo keyword, maybe
3652 group 3: Priority cookie
3653 group 4: True headline
3654 group 5: Tags")
3655 (make-variable-buffer-local 'org-complex-heading-regexp)
3656 (defvar org-complex-heading-regexp-format nil)
3657 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3658 (defvar org-todo-line-tags-regexp nil
3659 "Matches a headline and puts TODO state into group 2 if present.
3660 Also put tags into group 4 if tags are present.")
3661 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3662 (defvar org-nl-done-regexp nil
3663 "Matches newline followed by a headline with the DONE keyword.")
3664 (make-variable-buffer-local 'org-nl-done-regexp)
3665 (defvar org-looking-at-done-regexp nil
3666 "Matches the DONE keyword a point.")
3667 (make-variable-buffer-local 'org-looking-at-done-regexp)
3668 (defvar org-ds-keyword-length 12
3669 "Maximum length of the Deadline and SCHEDULED keywords.")
3670 (make-variable-buffer-local 'org-ds-keyword-length)
3671 (defvar org-deadline-regexp nil
3672 "Matches the DEADLINE keyword.")
3673 (make-variable-buffer-local 'org-deadline-regexp)
3674 (defvar org-deadline-time-regexp nil
3675 "Matches the DEADLINE keyword together with a time stamp.")
3676 (make-variable-buffer-local 'org-deadline-time-regexp)
3677 (defvar org-deadline-line-regexp nil
3678 "Matches the DEADLINE keyword and the rest of the line.")
3679 (make-variable-buffer-local 'org-deadline-line-regexp)
3680 (defvar org-scheduled-regexp nil
3681 "Matches the SCHEDULED keyword.")
3682 (make-variable-buffer-local 'org-scheduled-regexp)
3683 (defvar org-scheduled-time-regexp nil
3684 "Matches the SCHEDULED keyword together with a time stamp.")
3685 (make-variable-buffer-local 'org-scheduled-time-regexp)
3686 (defvar org-closed-time-regexp nil
3687 "Matches the CLOSED keyword together with a time stamp.")
3688 (make-variable-buffer-local 'org-closed-time-regexp)
3690 (defvar org-keyword-time-regexp nil
3691 "Matches any of the 4 keywords, together with the time stamp.")
3692 (make-variable-buffer-local 'org-keyword-time-regexp)
3693 (defvar org-keyword-time-not-clock-regexp nil
3694 "Matches any of the 3 keywords, together with the time stamp.")
3695 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3696 (defvar org-maybe-keyword-time-regexp nil
3697 "Matches a timestamp, possibly preceeded by a keyword.")
3698 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3699 (defvar org-planning-or-clock-line-re nil
3700 "Matches a line with planning or clock info.")
3701 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3703 (defconst org-plain-time-of-day-regexp
3704 (concat
3705 "\\(\\<[012]?[0-9]"
3706 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3707 "\\(--?"
3708 "\\(\\<[012]?[0-9]"
3709 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3710 "\\)?")
3711 "Regular expression to match a plain time or time range.
3712 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3713 groups carry important information:
3714 0 the full match
3715 1 the first time, range or not
3716 8 the second time, if it is a range.")
3718 (defconst org-plain-time-extension-regexp
3719 (concat
3720 "\\(\\<[012]?[0-9]"
3721 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3722 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3723 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3724 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3725 groups carry important information:
3726 0 the full match
3727 7 hours of duration
3728 9 minutes of duration")
3730 (defconst org-stamp-time-of-day-regexp
3731 (concat
3732 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3733 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3734 "\\(--?"
3735 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3736 "Regular expression to match a timestamp time or time range.
3737 After a match, the following groups carry important information:
3738 0 the full match
3739 1 date plus weekday, for back referencing to make sure both times are on the same day
3740 2 the first time, range or not
3741 4 the second time, if it is a range.")
3743 (defconst org-startup-options
3744 '(("fold" org-startup-folded t)
3745 ("overview" org-startup-folded t)
3746 ("nofold" org-startup-folded nil)
3747 ("showall" org-startup-folded nil)
3748 ("showeverything" org-startup-folded showeverything)
3749 ("content" org-startup-folded content)
3750 ("indent" org-startup-indented t)
3751 ("noindent" org-startup-indented nil)
3752 ("hidestars" org-hide-leading-stars t)
3753 ("showstars" org-hide-leading-stars nil)
3754 ("odd" org-odd-levels-only t)
3755 ("oddeven" org-odd-levels-only nil)
3756 ("align" org-startup-align-all-tables t)
3757 ("noalign" org-startup-align-all-tables nil)
3758 ("customtime" org-display-custom-times t)
3759 ("logdone" org-log-done time)
3760 ("lognotedone" org-log-done note)
3761 ("nologdone" org-log-done nil)
3762 ("lognoteclock-out" org-log-note-clock-out t)
3763 ("nolognoteclock-out" org-log-note-clock-out nil)
3764 ("logrepeat" org-log-repeat state)
3765 ("lognoterepeat" org-log-repeat note)
3766 ("nologrepeat" org-log-repeat nil)
3767 ("logreschedule" org-log-reschedule time)
3768 ("lognotereschedule" org-log-reschedule note)
3769 ("nologreschedule" org-log-reschedule nil)
3770 ("logredeadline" org-log-redeadline time)
3771 ("lognoteredeadline" org-log-redeadline note)
3772 ("nologredeadline" org-log-redeadline nil)
3773 ("fninline" org-footnote-define-inline t)
3774 ("nofninline" org-footnote-define-inline nil)
3775 ("fnlocal" org-footnote-section nil)
3776 ("fnauto" org-footnote-auto-label t)
3777 ("fnprompt" org-footnote-auto-label nil)
3778 ("fnconfirm" org-footnote-auto-label confirm)
3779 ("fnplain" org-footnote-auto-label plain)
3780 ("fnadjust" org-footnote-auto-adjust t)
3781 ("nofnadjust" org-footnote-auto-adjust nil)
3782 ("constcgs" constants-unit-system cgs)
3783 ("constSI" constants-unit-system SI)
3784 ("noptag" org-tag-persistent-alist nil)
3785 ("hideblocks" org-hide-block-startup t)
3786 ("nohideblocks" org-hide-block-startup nil)
3787 ("beamer" org-startup-with-beamer-mode t))
3788 "Variable associated with STARTUP options for org-mode.
3789 Each element is a list of three items: The startup options as written
3790 in the #+STARTUP line, the corresponding variable, and the value to
3791 set this variable to if the option is found. An optional forth element PUSH
3792 means to push this value onto the list in the variable.")
3794 (defun org-set-regexps-and-options ()
3795 "Precompute regular expressions for current buffer."
3796 (when (org-mode-p)
3797 (org-set-local 'org-todo-kwd-alist nil)
3798 (org-set-local 'org-todo-key-alist nil)
3799 (org-set-local 'org-todo-key-trigger nil)
3800 (org-set-local 'org-todo-keywords-1 nil)
3801 (org-set-local 'org-done-keywords nil)
3802 (org-set-local 'org-todo-heads nil)
3803 (org-set-local 'org-todo-sets nil)
3804 (org-set-local 'org-todo-log-states nil)
3805 (org-set-local 'org-file-properties nil)
3806 (org-set-local 'org-file-tags nil)
3807 (let ((re (org-make-options-regexp
3808 '("CATEGORY" "TODO" "COLUMNS"
3809 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3810 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3811 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3812 (splitre "[ \t]+")
3813 kwds kws0 kwsa key log value cat arch tags const links hw dws
3814 tail sep kws1 prio props ftags drawers beamer-p
3815 ext-setup-or-nil setup-contents (start 0))
3816 (save-excursion
3817 (save-restriction
3818 (widen)
3819 (goto-char (point-min))
3820 (while (or (and ext-setup-or-nil
3821 (string-match re ext-setup-or-nil start)
3822 (setq start (match-end 0)))
3823 (and (setq ext-setup-or-nil nil start 0)
3824 (re-search-forward re nil t)))
3825 (setq key (upcase (match-string 1 ext-setup-or-nil))
3826 value (org-match-string-no-properties 2 ext-setup-or-nil))
3827 (cond
3828 ((equal key "CATEGORY")
3829 (if (string-match "[ \t]+$" value)
3830 (setq value (replace-match "" t t value)))
3831 (setq cat value))
3832 ((member key '("SEQ_TODO" "TODO"))
3833 (push (cons 'sequence (org-split-string value splitre)) kwds))
3834 ((equal key "TYP_TODO")
3835 (push (cons 'type (org-split-string value splitre)) kwds))
3836 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3837 ;; general TODO-like setup
3838 (push (cons (intern (downcase (match-string 1 key)))
3839 (org-split-string value splitre)) kwds))
3840 ((equal key "TAGS")
3841 (setq tags (append tags (if tags '("\\n") nil)
3842 (org-split-string value splitre))))
3843 ((equal key "COLUMNS")
3844 (org-set-local 'org-columns-default-format value))
3845 ((equal key "LINK")
3846 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3847 (push (cons (match-string 1 value)
3848 (org-trim (match-string 2 value)))
3849 links)))
3850 ((equal key "PRIORITIES")
3851 (setq prio (org-split-string value " +")))
3852 ((equal key "PROPERTY")
3853 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3854 (push (cons (match-string 1 value) (match-string 2 value))
3855 props)))
3856 ((equal key "FILETAGS")
3857 (when (string-match "\\S-" value)
3858 (setq ftags
3859 (append
3860 ftags
3861 (apply 'append
3862 (mapcar (lambda (x) (org-split-string x ":"))
3863 (org-split-string value)))))))
3864 ((equal key "DRAWERS")
3865 (setq drawers (org-split-string value splitre)))
3866 ((equal key "CONSTANTS")
3867 (setq const (append const (org-split-string value splitre))))
3868 ((equal key "STARTUP")
3869 (let ((opts (org-split-string value splitre))
3870 l var val)
3871 (while (setq l (pop opts))
3872 (when (setq l (assoc l org-startup-options))
3873 (setq var (nth 1 l) val (nth 2 l))
3874 (if (not (nth 3 l))
3875 (set (make-local-variable var) val)
3876 (if (not (listp (symbol-value var)))
3877 (set (make-local-variable var) nil))
3878 (set (make-local-variable var) (symbol-value var))
3879 (add-to-list var val))))))
3880 ((equal key "ARCHIVE")
3881 (string-match " *$" value)
3882 (setq arch (replace-match "" t t value))
3883 (remove-text-properties 0 (length arch)
3884 '(face t fontified t) arch))
3885 ((equal key "LATEX_CLASS")
3886 (setq beamer-p (equal value "beamer")))
3887 ((equal key "SETUPFILE")
3888 (setq setup-contents (org-file-contents
3889 (expand-file-name
3890 (org-remove-double-quotes value))
3891 'noerror))
3892 (if (not ext-setup-or-nil)
3893 (setq ext-setup-or-nil setup-contents start 0)
3894 (setq ext-setup-or-nil
3895 (concat (substring ext-setup-or-nil 0 start)
3896 "\n" setup-contents "\n"
3897 (substring ext-setup-or-nil start)))))
3898 ))))
3899 (when cat
3900 (org-set-local 'org-category (intern cat))
3901 (push (cons "CATEGORY" cat) props))
3902 (when prio
3903 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3904 (setq prio (mapcar 'string-to-char prio))
3905 (org-set-local 'org-highest-priority (nth 0 prio))
3906 (org-set-local 'org-lowest-priority (nth 1 prio))
3907 (org-set-local 'org-default-priority (nth 2 prio)))
3908 (and props (org-set-local 'org-file-properties (nreverse props)))
3909 (and ftags (org-set-local 'org-file-tags
3910 (mapcar 'org-add-prop-inherited ftags)))
3911 (and drawers (org-set-local 'org-drawers drawers))
3912 (and arch (org-set-local 'org-archive-location arch))
3913 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3914 ;; Process the TODO keywords
3915 (unless kwds
3916 ;; Use the global values as if they had been given locally.
3917 (setq kwds (default-value 'org-todo-keywords))
3918 (if (stringp (car kwds))
3919 (setq kwds (list (cons org-todo-interpretation
3920 (default-value 'org-todo-keywords)))))
3921 (setq kwds (reverse kwds)))
3922 (setq kwds (nreverse kwds))
3923 (let (inter kws kw)
3924 (while (setq kws (pop kwds))
3925 (let ((kws (or
3926 (run-hook-with-args-until-success
3927 'org-todo-setup-filter-hook kws)
3928 kws)))
3929 (setq inter (pop kws) sep (member "|" kws)
3930 kws0 (delete "|" (copy-sequence kws))
3931 kwsa nil
3932 kws1 (mapcar
3933 (lambda (x)
3934 ;; 1 2
3935 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3936 (progn
3937 (setq kw (match-string 1 x)
3938 key (and (match-end 2) (match-string 2 x))
3939 log (org-extract-log-state-settings x))
3940 (push (cons kw (and key (string-to-char key))) kwsa)
3941 (and log (push log org-todo-log-states))
3943 (error "Invalid TODO keyword %s" x)))
3944 kws0)
3945 kwsa (if kwsa (append '((:startgroup))
3946 (nreverse kwsa)
3947 '((:endgroup))))
3948 hw (car kws1)
3949 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3950 tail (list inter hw (car dws) (org-last dws))))
3951 (add-to-list 'org-todo-heads hw 'append)
3952 (push kws1 org-todo-sets)
3953 (setq org-done-keywords (append org-done-keywords dws nil))
3954 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3955 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3956 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3957 (setq org-todo-sets (nreverse org-todo-sets)
3958 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3959 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3960 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3961 ;; Process the constants
3962 (when const
3963 (let (e cst)
3964 (while (setq e (pop const))
3965 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3966 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3967 (setq org-table-formula-constants-local cst)))
3969 ;; Process the tags.
3970 (when tags
3971 (let (e tgs)
3972 (while (setq e (pop tags))
3973 (cond
3974 ((equal e "{") (push '(:startgroup) tgs))
3975 ((equal e "}") (push '(:endgroup) tgs))
3976 ((equal e "\\n") (push '(:newline) tgs))
3977 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3978 (push (cons (match-string 1 e)
3979 (string-to-char (match-string 2 e)))
3980 tgs))
3981 (t (push (list e) tgs))))
3982 (org-set-local 'org-tag-alist nil)
3983 (while (setq e (pop tgs))
3984 (or (and (stringp (car e))
3985 (assoc (car e) org-tag-alist))
3986 (push e org-tag-alist)))))
3988 ;; Compute the regular expressions and other local variables
3989 (if (not org-done-keywords)
3990 (setq org-done-keywords (and org-todo-keywords-1
3991 (list (org-last org-todo-keywords-1)))))
3992 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3993 (length org-scheduled-string)
3994 (length org-clock-string)
3995 (length org-closed-string)))
3996 org-drawer-regexp
3997 (concat "^[ \t]*:\\("
3998 (mapconcat 'regexp-quote org-drawers "\\|")
3999 "\\):[ \t]*$")
4000 org-not-done-keywords
4001 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4002 org-todo-regexp
4003 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4004 "\\|") "\\)\\>")
4005 org-not-done-regexp
4006 (concat "\\<\\("
4007 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4008 "\\)\\>")
4009 org-not-done-heading-regexp
4010 (concat "^\\(\\*+\\)[ \t]+\\("
4011 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4012 "\\)\\>")
4013 org-todo-line-regexp
4014 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4015 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4016 "\\)\\>\\)?[ \t]*\\(.*\\)")
4017 org-complex-heading-regexp
4018 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4019 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4020 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4021 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4022 org-complex-heading-regexp-format
4023 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4024 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4025 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4026 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4027 org-nl-done-regexp
4028 (concat "\n\\*+[ \t]+"
4029 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4030 "\\)" "\\>")
4031 org-todo-line-tags-regexp
4032 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4033 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4034 (org-re
4035 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4036 org-looking-at-done-regexp
4037 (concat "^" "\\(?:"
4038 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4039 "\\>")
4040 org-deadline-regexp (concat "\\<" org-deadline-string)
4041 org-deadline-time-regexp
4042 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4043 org-deadline-line-regexp
4044 (concat "\\<\\(" org-deadline-string "\\).*")
4045 org-scheduled-regexp
4046 (concat "\\<" org-scheduled-string)
4047 org-scheduled-time-regexp
4048 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4049 org-closed-time-regexp
4050 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4051 org-keyword-time-regexp
4052 (concat "\\<\\(" org-scheduled-string
4053 "\\|" org-deadline-string
4054 "\\|" org-closed-string
4055 "\\|" org-clock-string "\\)"
4056 " *[[<]\\([^]>]+\\)[]>]")
4057 org-keyword-time-not-clock-regexp
4058 (concat "\\<\\(" org-scheduled-string
4059 "\\|" org-deadline-string
4060 "\\|" org-closed-string
4061 "\\)"
4062 " *[[<]\\([^]>]+\\)[]>]")
4063 org-maybe-keyword-time-regexp
4064 (concat "\\(\\<\\(" org-scheduled-string
4065 "\\|" org-deadline-string
4066 "\\|" org-closed-string
4067 "\\|" org-clock-string "\\)\\)?"
4068 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4069 org-planning-or-clock-line-re
4070 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4071 "\\|" org-deadline-string
4072 "\\|" org-closed-string "\\|" org-clock-string
4073 "\\)\\>\\)")
4075 (org-compute-latex-and-specials-regexp)
4076 (org-set-font-lock-defaults))))
4078 (defun org-file-contents (file &optional noerror)
4079 "Return the contents of FILE, as a string."
4080 (if (or (not file)
4081 (not (file-readable-p file)))
4082 (if noerror
4083 (progn
4084 (message "Cannot read file %s" file)
4085 (ding) (sit-for 2)
4087 (error "Cannot read file %s" file))
4088 (with-temp-buffer
4089 (insert-file-contents file)
4090 (buffer-string))))
4092 (defun org-extract-log-state-settings (x)
4093 "Extract the log state setting from a TODO keyword string.
4094 This will extract info from a string like \"WAIT(w@/!)\"."
4095 (let (kw key log1 log2)
4096 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4097 (setq kw (match-string 1 x)
4098 key (and (match-end 2) (match-string 2 x))
4099 log1 (and (match-end 3) (match-string 3 x))
4100 log2 (and (match-end 4) (match-string 4 x)))
4101 (and (or log1 log2)
4102 (list kw
4103 (and log1 (if (equal log1 "!") 'time 'note))
4104 (and log2 (if (equal log2 "!") 'time 'note)))))))
4106 (defun org-remove-keyword-keys (list)
4107 "Remove a pair of parenthesis at the end of each string in LIST."
4108 (mapcar (lambda (x)
4109 (if (string-match "(.*)$" x)
4110 (substring x 0 (match-beginning 0))
4112 list))
4114 ;; FIXME: this could be done much better, using second characters etc.
4115 (defun org-assign-fast-keys (alist)
4116 "Assign fast keys to a keyword-key alist.
4117 Respect keys that are already there."
4118 (let (new e k c c1 c2 (char ?a))
4119 (while (setq e (pop alist))
4120 (cond
4121 ((equal e '(:startgroup)) (push e new))
4122 ((equal e '(:endgroup)) (push e new))
4123 ((equal e '(:newline)) (push e new))
4125 (setq k (car e) c2 nil)
4126 (if (cdr e)
4127 (setq c (cdr e))
4128 ;; automatically assign a character.
4129 (setq c1 (string-to-char
4130 (downcase (substring
4131 k (if (= (string-to-char k) ?@) 1 0)))))
4132 (if (or (rassoc c1 new) (rassoc c1 alist))
4133 (while (or (rassoc char new) (rassoc char alist))
4134 (setq char (1+ char)))
4135 (setq c2 c1))
4136 (setq c (or c2 char)))
4137 (push (cons k c) new))))
4138 (nreverse new)))
4140 ;;; Some variables used in various places
4142 (defvar org-window-configuration nil
4143 "Used in various places to store a window configuration.")
4144 (defvar org-selected-window nil
4145 "Used in various places to store a window configuration.")
4146 (defvar org-finish-function nil
4147 "Function to be called when `C-c C-c' is used.
4148 This is for getting out of special buffers like remember.")
4151 ;; FIXME: Occasionally check by commenting these, to make sure
4152 ;; no other functions uses these, forgetting to let-bind them.
4153 (defvar entry)
4154 (defvar last-state)
4155 (defvar date)
4157 ;; Defined somewhere in this file, but used before definition.
4158 (defvar org-html-entities)
4159 (defvar org-struct-menu)
4160 (defvar org-org-menu)
4161 (defvar org-tbl-menu)
4163 ;;;; Define the Org-mode
4165 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4166 (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."))
4169 ;; We use a before-change function to check if a table might need
4170 ;; an update.
4171 (defvar org-table-may-need-update t
4172 "Indicates that a table might need an update.
4173 This variable is set by `org-before-change-function'.
4174 `org-table-align' sets it back to nil.")
4175 (defun org-before-change-function (beg end)
4176 "Every change indicates that a table might need an update."
4177 (setq org-table-may-need-update t))
4178 (defvar org-mode-map)
4179 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4180 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4181 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4182 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4183 (defvar org-table-buffer-is-an nil)
4184 (defconst org-outline-regexp "\\*+ ")
4186 ;;;###autoload
4187 (define-derived-mode org-mode outline-mode "Org"
4188 "Outline-based notes management and organizer, alias
4189 \"Carsten's outline-mode for keeping track of everything.\"
4191 Org-mode develops organizational tasks around a NOTES file which
4192 contains information about projects as plain text. Org-mode is
4193 implemented on top of outline-mode, which is ideal to keep the content
4194 of large files well structured. It supports ToDo items, deadlines and
4195 time stamps, which magically appear in the diary listing of the Emacs
4196 calendar. Tables are easily created with a built-in table editor.
4197 Plain text URL-like links connect to websites, emails (VM), Usenet
4198 messages (Gnus), BBDB entries, and any files related to the project.
4199 For printing and sharing of notes, an Org-mode file (or a part of it)
4200 can be exported as a structured ASCII or HTML file.
4202 The following commands are available:
4204 \\{org-mode-map}"
4206 ;; Get rid of Outline menus, they are not needed
4207 ;; Need to do this here because define-derived-mode sets up
4208 ;; the keymap so late. Still, it is a waste to call this each time
4209 ;; we switch another buffer into org-mode.
4210 (if (featurep 'xemacs)
4211 (when (boundp 'outline-mode-menu-heading)
4212 ;; Assume this is Greg's port, it used easymenu
4213 (easy-menu-remove outline-mode-menu-heading)
4214 (easy-menu-remove outline-mode-menu-show)
4215 (easy-menu-remove outline-mode-menu-hide))
4216 (define-key org-mode-map [menu-bar headings] 'undefined)
4217 (define-key org-mode-map [menu-bar hide] 'undefined)
4218 (define-key org-mode-map [menu-bar show] 'undefined))
4220 (org-load-modules-maybe)
4221 (easy-menu-add org-org-menu)
4222 (easy-menu-add org-tbl-menu)
4223 (org-install-agenda-files-menu)
4224 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4225 (org-add-to-invisibility-spec '(org-cwidth))
4226 (org-add-to-invisibility-spec '(org-hide-block . t))
4227 (when (featurep 'xemacs)
4228 (org-set-local 'line-move-ignore-invisible t))
4229 (org-set-local 'outline-regexp org-outline-regexp)
4230 (org-set-local 'outline-level 'org-outline-level)
4231 (when (and org-ellipsis
4232 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4233 (fboundp 'make-glyph-code))
4234 (unless org-display-table
4235 (setq org-display-table (make-display-table)))
4236 (set-display-table-slot
4237 org-display-table 4
4238 (vconcat (mapcar
4239 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4240 org-ellipsis)))
4241 (if (stringp org-ellipsis) org-ellipsis "..."))))
4242 (setq buffer-display-table org-display-table))
4243 (org-set-regexps-and-options)
4244 (when (and org-tag-faces (not org-tags-special-faces-re))
4245 ;; tag faces set outside customize.... force initialization.
4246 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4247 ;; Calc embedded
4248 (org-set-local 'calc-embedded-open-mode "# ")
4249 (modify-syntax-entry ?# "<")
4250 (modify-syntax-entry ?@ "w")
4251 (if org-startup-truncated (setq truncate-lines t))
4252 (org-set-local 'font-lock-unfontify-region-function
4253 'org-unfontify-region)
4254 ;; Activate before-change-function
4255 (org-set-local 'org-table-may-need-update t)
4256 (org-add-hook 'before-change-functions 'org-before-change-function nil
4257 'local)
4258 ;; Check for running clock before killing a buffer
4259 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4260 ;; Paragraphs and auto-filling
4261 (org-set-autofill-regexps)
4262 (setq indent-line-function 'org-indent-line-function)
4263 (org-update-radio-target-regexp)
4264 ;; Make sure dependence stuff works reliably, even for users who set it
4265 ;; too late :-(
4266 (if org-enforce-todo-dependencies
4267 (add-hook 'org-blocker-hook
4268 'org-block-todo-from-children-or-siblings-or-parent)
4269 (remove-hook 'org-blocker-hook
4270 'org-block-todo-from-children-or-siblings-or-parent))
4271 (if org-enforce-todo-checkbox-dependencies
4272 (add-hook 'org-blocker-hook
4273 'org-block-todo-from-checkboxes)
4274 (remove-hook 'org-blocker-hook
4275 'org-block-todo-from-checkboxes))
4277 ;; Comment characters
4278 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4279 (org-set-local 'comment-padding " ")
4281 ;; Align options lines
4282 (org-set-local
4283 'align-mode-rules-list
4284 '((org-in-buffer-settings
4285 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4286 (modes . '(org-mode)))))
4288 ;; Imenu
4289 (org-set-local 'imenu-create-index-function
4290 'org-imenu-get-tree)
4292 ;; Make isearch reveal context
4293 (if (or (featurep 'xemacs)
4294 (not (boundp 'outline-isearch-open-invisible-function)))
4295 ;; Emacs 21 and XEmacs make use of the hook
4296 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4297 ;; Emacs 22 deals with this through a special variable
4298 (org-set-local 'outline-isearch-open-invisible-function
4299 (lambda (&rest ignore) (org-show-context 'isearch))))
4301 ;; Turn on org-beamer-mode?
4302 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4304 ;; If empty file that did not turn on org-mode automatically, make it to.
4305 (if (and org-insert-mode-line-in-empty-file
4306 (interactive-p)
4307 (= (point-min) (point-max)))
4308 (insert "# -*- mode: org -*-\n\n"))
4310 (unless org-inhibit-startup
4311 (when org-startup-align-all-tables
4312 (let ((bmp (buffer-modified-p)))
4313 (org-table-map-tables 'org-table-align)
4314 (set-buffer-modified-p bmp)))
4315 (when org-startup-indented
4316 (require 'org-indent)
4317 (org-indent-mode 1))
4318 (org-set-startup-visibility)))
4320 (when (fboundp 'abbrev-table-put)
4321 (abbrev-table-put org-mode-abbrev-table
4322 :parents (list text-mode-abbrev-table)))
4324 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4326 (defun org-current-time ()
4327 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4328 (if (> (car org-time-stamp-rounding-minutes) 1)
4329 (let ((r (car org-time-stamp-rounding-minutes))
4330 (time (decode-time)))
4331 (apply 'encode-time
4332 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4333 (nthcdr 2 time))))
4334 (current-time)))
4336 ;;;; Font-Lock stuff, including the activators
4338 (defvar org-mouse-map (make-sparse-keymap))
4339 (org-defkey org-mouse-map
4340 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4341 (org-defkey org-mouse-map
4342 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4343 (when org-mouse-1-follows-link
4344 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4345 (when org-tab-follows-link
4346 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4347 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4349 (require 'font-lock)
4351 (defconst org-non-link-chars "]\t\n\r<>")
4352 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4353 "shell" "elisp"))
4354 (defvar org-link-types-re nil
4355 "Matches a link that has a url-like prefix like \"http:\"")
4356 (defvar org-link-re-with-space nil
4357 "Matches a link with spaces, optional angular brackets around it.")
4358 (defvar org-link-re-with-space2 nil
4359 "Matches a link with spaces, optional angular brackets around it.")
4360 (defvar org-link-re-with-space3 nil
4361 "Matches a link with spaces, only for internal part in bracket links.")
4362 (defvar org-angle-link-re nil
4363 "Matches link with angular brackets, spaces are allowed.")
4364 (defvar org-plain-link-re nil
4365 "Matches plain link, without spaces.")
4366 (defvar org-bracket-link-regexp nil
4367 "Matches a link in double brackets.")
4368 (defvar org-bracket-link-analytic-regexp nil
4369 "Regular expression used to analyze links.
4370 Here is what the match groups contain after a match:
4371 1: http:
4372 2: http
4373 3: path
4374 4: [desc]
4375 5: desc")
4376 (defvar org-bracket-link-analytic-regexp++ nil
4377 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4378 (defvar org-any-link-re nil
4379 "Regular expression matching any link.")
4381 (defun org-make-link-regexps ()
4382 "Update the link regular expressions.
4383 This should be called after the variable `org-link-types' has changed."
4384 (setq org-link-types-re
4385 (concat
4386 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4387 org-link-re-with-space
4388 (concat
4389 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4390 "\\([^" org-non-link-chars " ]"
4391 "[^" org-non-link-chars "]*"
4392 "[^" org-non-link-chars " ]\\)>?")
4393 org-link-re-with-space2
4394 (concat
4395 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4396 "\\([^" org-non-link-chars " ]"
4397 "[^\t\n\r]*"
4398 "[^" org-non-link-chars " ]\\)>?")
4399 org-link-re-with-space3
4400 (concat
4401 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4402 "\\([^" org-non-link-chars " ]"
4403 "[^\t\n\r]*\\)")
4404 org-angle-link-re
4405 (concat
4406 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4407 "\\([^" org-non-link-chars " ]"
4408 "[^" org-non-link-chars "]*"
4409 "\\)>")
4410 org-plain-link-re
4411 (concat
4412 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4413 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4414 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4415 org-bracket-link-regexp
4416 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4417 org-bracket-link-analytic-regexp
4418 (concat
4419 "\\[\\["
4420 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4421 "\\([^]]+\\)"
4422 "\\]"
4423 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4424 "\\]")
4425 org-bracket-link-analytic-regexp++
4426 (concat
4427 "\\[\\["
4428 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4429 "\\([^]]+\\)"
4430 "\\]"
4431 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4432 "\\]")
4433 org-any-link-re
4434 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4435 org-angle-link-re "\\)\\|\\("
4436 org-plain-link-re "\\)")))
4438 (org-make-link-regexps)
4440 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4441 "Regular expression for fast time stamp matching.")
4442 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4443 "Regular expression for fast time stamp matching.")
4444 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4445 "Regular expression matching time strings for analysis.
4446 This one does not require the space after the date, so it can be used
4447 on a string that terminates immediately after the date.")
4448 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4449 "Regular expression matching time strings for analysis.")
4450 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4451 "Regular expression matching time stamps, with groups.")
4452 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4453 "Regular expression matching time stamps (also [..]), with groups.")
4454 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4455 "Regular expression matching a time stamp range.")
4456 (defconst org-tr-regexp-both
4457 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4458 "Regular expression matching a time stamp range.")
4459 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4460 org-ts-regexp "\\)?")
4461 "Regular expression matching a time stamp or time stamp range.")
4462 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4463 org-ts-regexp-both "\\)?")
4464 "Regular expression matching a time stamp or time stamp range.
4465 The time stamps may be either active or inactive.")
4467 (defvar org-emph-face nil)
4469 (defun org-do-emphasis-faces (limit)
4470 "Run through the buffer and add overlays to links."
4471 (let (rtn a)
4472 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4473 (if (not (= (char-after (match-beginning 3))
4474 (char-after (match-beginning 4))))
4475 (progn
4476 (setq rtn t)
4477 (setq a (assoc (match-string 3) org-emphasis-alist))
4478 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4479 'face
4480 (nth 1 a))
4481 (and (nth 4 a)
4482 (org-remove-flyspell-overlays-in
4483 (match-beginning 0) (match-end 0)))
4484 (add-text-properties (match-beginning 2) (match-end 2)
4485 '(font-lock-multiline t))
4486 (when org-hide-emphasis-markers
4487 (add-text-properties (match-end 4) (match-beginning 5)
4488 '(invisible org-link))
4489 (add-text-properties (match-beginning 3) (match-end 3)
4490 '(invisible org-link)))))
4491 (backward-char 1))
4492 rtn))
4494 (defun org-emphasize (&optional char)
4495 "Insert or change an emphasis, i.e. a font like bold or italic.
4496 If there is an active region, change that region to a new emphasis.
4497 If there is no region, just insert the marker characters and position
4498 the cursor between them.
4499 CHAR should be either the marker character, or the first character of the
4500 HTML tag associated with that emphasis. If CHAR is a space, the means
4501 to remove the emphasis of the selected region.
4502 If char is not given (for example in an interactive call) it
4503 will be prompted for."
4504 (interactive)
4505 (let ((eal org-emphasis-alist) e det
4506 (erc org-emphasis-regexp-components)
4507 (prompt "")
4508 (string "") beg end move tag c s)
4509 (if (org-region-active-p)
4510 (setq beg (region-beginning) end (region-end)
4511 string (buffer-substring beg end))
4512 (setq move t))
4514 (while (setq e (pop eal))
4515 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4516 c (aref tag 0))
4517 (push (cons c (string-to-char (car e))) det)
4518 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4519 (substring tag 1)))))
4520 (setq det (nreverse det))
4521 (unless char
4522 (message "%s" (concat "Emphasis marker or tag:" prompt))
4523 (setq char (read-char-exclusive)))
4524 (setq char (or (cdr (assoc char det)) char))
4525 (if (equal char ?\ )
4526 (setq s "" move nil)
4527 (unless (assoc (char-to-string char) org-emphasis-alist)
4528 (error "No such emphasis marker: \"%c\"" char))
4529 (setq s (char-to-string char)))
4530 (while (and (> (length string) 1)
4531 (equal (substring string 0 1) (substring string -1))
4532 (assoc (substring string 0 1) org-emphasis-alist))
4533 (setq string (substring string 1 -1)))
4534 (setq string (concat s string s))
4535 (if beg (delete-region beg end))
4536 (unless (or (bolp)
4537 (string-match (concat "[" (nth 0 erc) "\n]")
4538 (char-to-string (char-before (point)))))
4539 (insert " "))
4540 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4541 (char-to-string (char-after (point))))
4542 (insert " ") (backward-char 1))
4543 (insert string)
4544 (and move (backward-char 1))))
4546 (defconst org-nonsticky-props
4547 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4549 (defsubst org-rear-nonsticky-at (pos)
4550 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4552 (defun org-activate-plain-links (limit)
4553 "Run through the buffer and add overlays to links."
4554 (catch 'exit
4555 (let (f)
4556 (if (re-search-forward org-plain-link-re limit t)
4557 (progn
4558 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4559 (setq f (get-text-property (match-beginning 0) 'face))
4560 (if (or (eq f 'org-tag)
4561 (and (listp f) (memq 'org-tag f)))
4563 (add-text-properties (match-beginning 0) (match-end 0)
4564 (list 'mouse-face 'highlight
4565 'face 'org-link
4566 'keymap org-mouse-map))
4567 (org-rear-nonsticky-at (match-end 0)))
4568 t)))))
4570 (defun org-activate-code (limit)
4571 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4572 (progn
4573 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4574 (remove-text-properties (match-beginning 0) (match-end 0)
4575 '(display t invisible t intangible t))
4576 t)))
4578 (defun org-fontify-meta-lines-and-blocks (limit)
4579 "Fontify #+ lines and blocks, in the correct ways."
4580 (let ((case-fold-search t))
4581 (if (re-search-forward
4582 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4583 limit t)
4584 (let ((beg (match-beginning 0))
4585 (beg1 (line-beginning-position 2))
4586 (dc1 (downcase (match-string 2)))
4587 (dc3 (downcase (match-string 3)))
4588 end end1 quoting block-type)
4589 (cond
4590 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4591 ;; a single line of backend-specific content
4592 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4593 (remove-text-properties (match-beginning 0) (match-end 0)
4594 '(display t invisible t intangible t))
4595 (add-text-properties (match-beginning 1) (match-end 3)
4596 '(font-lock-fontified t face org-meta-line))
4597 (add-text-properties (match-beginning 6) (match-end 6)
4598 '(font-lock-fontified t face org-block))
4600 ((and (match-end 4) (equal dc3 "begin"))
4601 ;; Truely a block
4602 (setq block-type (downcase (match-string 5))
4603 quoting (member block-type org-protecting-blocks))
4604 (when (re-search-forward
4605 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4606 nil t) ;; on purpose, we look further than LIMIT
4607 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4608 (when quoting
4609 (remove-text-properties beg end
4610 '(display t invisible t intangible t)))
4611 (add-text-properties
4612 beg end
4613 '(font-lock-fontified t font-lock-multiline t))
4614 (add-text-properties beg beg1 '(face org-meta-line))
4615 (add-text-properties end1 end '(face org-meta-line))
4616 (cond
4617 (quoting
4618 (add-text-properties beg1 end1 '(face org-block)))
4619 ((string= block-type "quote")
4620 (add-text-properties beg1 end1 '(face org-quote)))
4621 ((string= block-type "verse")
4622 (add-text-properties beg1 end1 '(face org-verse))))
4624 ((not (member (char-after beg) '(?\ ?\t)))
4625 ;; just any other in-buffer setting, but not indented
4626 (add-text-properties
4627 beg (match-end 0)
4628 '(font-lock-fontified t face org-meta-line))
4630 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4631 "orgtbl:" "tblfm:" "tblname:"))
4632 (and (match-end 4) (equal dc3 "attr")))
4633 (add-text-properties
4634 beg (match-end 0)
4635 '(font-lock-fontified t face org-meta-line))
4637 ((member dc3 '(" " ""))
4638 (add-text-properties
4639 beg (match-end 0)
4640 '(font-lock-fontified t face font-lock-comment-face)))
4641 (t nil))))))
4643 (defun org-activate-angle-links (limit)
4644 "Run through the buffer and add overlays to links."
4645 (if (re-search-forward org-angle-link-re limit t)
4646 (progn
4647 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4648 (add-text-properties (match-beginning 0) (match-end 0)
4649 (list 'mouse-face 'highlight
4650 'keymap org-mouse-map))
4651 (org-rear-nonsticky-at (match-end 0))
4652 t)))
4654 (defun org-activate-footnote-links (limit)
4655 "Run through the buffer and add overlays to links."
4656 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4657 limit t)
4658 (progn
4659 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4660 (add-text-properties (match-beginning 2) (match-end 2)
4661 (list 'mouse-face 'highlight
4662 'keymap org-mouse-map
4663 'help-echo
4664 (if (= (point-at-bol) (match-beginning 2))
4665 "Footnote definition"
4666 "Footnote reference")
4668 (org-rear-nonsticky-at (match-end 2))
4669 t)))
4671 (defun org-activate-bracket-links (limit)
4672 "Run through the buffer and add overlays to bracketed links."
4673 (if (re-search-forward org-bracket-link-regexp limit t)
4674 (let* ((help (concat "LINK: "
4675 (org-match-string-no-properties 1)))
4676 ;; FIXME: above we should remove the escapes.
4677 ;; but that requires another match, protecting match data,
4678 ;; a lot of overhead for font-lock.
4679 (ip (org-maybe-intangible
4680 (list 'invisible 'org-link
4681 'keymap org-mouse-map 'mouse-face 'highlight
4682 'font-lock-multiline t 'help-echo help)))
4683 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4684 'font-lock-multiline t 'help-echo help)))
4685 ;; We need to remove the invisible property here. Table narrowing
4686 ;; may have made some of this invisible.
4687 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4688 (remove-text-properties (match-beginning 0) (match-end 0)
4689 '(invisible nil))
4690 (if (match-end 3)
4691 (progn
4692 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4693 (org-rear-nonsticky-at (match-beginning 3))
4694 (add-text-properties (match-beginning 3) (match-end 3) vp)
4695 (org-rear-nonsticky-at (match-end 3))
4696 (add-text-properties (match-end 3) (match-end 0) ip)
4697 (org-rear-nonsticky-at (match-end 0)))
4698 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4699 (org-rear-nonsticky-at (match-beginning 1))
4700 (add-text-properties (match-beginning 1) (match-end 1) vp)
4701 (org-rear-nonsticky-at (match-end 1))
4702 (add-text-properties (match-end 1) (match-end 0) ip)
4703 (org-rear-nonsticky-at (match-end 0)))
4704 t)))
4706 (defun org-activate-dates (limit)
4707 "Run through the buffer and add overlays to dates."
4708 (if (re-search-forward org-tsr-regexp-both limit t)
4709 (progn
4710 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4711 (add-text-properties (match-beginning 0) (match-end 0)
4712 (list 'mouse-face 'highlight
4713 'keymap org-mouse-map))
4714 (org-rear-nonsticky-at (match-end 0))
4715 (when org-display-custom-times
4716 (if (match-end 3)
4717 (org-display-custom-time (match-beginning 3) (match-end 3)))
4718 (org-display-custom-time (match-beginning 1) (match-end 1)))
4719 t)))
4721 (defvar org-target-link-regexp nil
4722 "Regular expression matching radio targets in plain text.")
4723 (make-variable-buffer-local 'org-target-link-regexp)
4724 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4725 "Regular expression matching a link target.")
4726 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4727 "Regular expression matching a radio target.")
4728 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4729 "Regular expression matching any target.")
4731 (defun org-activate-target-links (limit)
4732 "Run through the buffer and add overlays to target matches."
4733 (when org-target-link-regexp
4734 (let ((case-fold-search t))
4735 (if (re-search-forward org-target-link-regexp limit t)
4736 (progn
4737 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4738 (add-text-properties (match-beginning 0) (match-end 0)
4739 (list 'mouse-face 'highlight
4740 'keymap org-mouse-map
4741 'help-echo "Radio target link"
4742 'org-linked-text t))
4743 (org-rear-nonsticky-at (match-end 0))
4744 t)))))
4746 (defun org-update-radio-target-regexp ()
4747 "Find all radio targets in this file and update the regular expression."
4748 (interactive)
4749 (when (memq 'radio org-activate-links)
4750 (setq org-target-link-regexp
4751 (org-make-target-link-regexp (org-all-targets 'radio)))
4752 (org-restart-font-lock)))
4754 (defun org-hide-wide-columns (limit)
4755 (let (s e)
4756 (setq s (text-property-any (point) (or limit (point-max))
4757 'org-cwidth t))
4758 (when s
4759 (setq e (next-single-property-change s 'org-cwidth))
4760 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4761 (goto-char e)
4762 t)))
4764 (defvar org-latex-and-specials-regexp nil
4765 "Regular expression for highlighting export special stuff.")
4766 (defvar org-match-substring-regexp)
4767 (defvar org-match-substring-with-braces-regexp)
4769 ;; This should be with the exporter code, but we also use if for font-locking
4770 (defconst org-export-html-special-string-regexps
4771 '(("\\\\-" . "&shy;")
4772 ("---\\([^-]\\)" . "&mdash;\\1")
4773 ("--\\([^-]\\)" . "&ndash;\\1")
4774 ("\\.\\.\\." . "&hellip;"))
4775 "Regular expressions for special string conversion.")
4778 (defun org-compute-latex-and-specials-regexp ()
4779 "Compute regular expression for stuff treated specially by exporters."
4780 (if (not org-highlight-latex-fragments-and-specials)
4781 (org-set-local 'org-latex-and-specials-regexp nil)
4782 (require 'org-exp)
4783 (let*
4784 ((matchers (plist-get org-format-latex-options :matchers))
4785 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4786 org-latex-regexps)))
4787 (options (org-combine-plists (org-default-export-plist)
4788 (org-infile-export-plist)))
4789 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4790 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4791 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4792 (org-export-html-expand (plist-get options :expand-quoted-html))
4793 (org-export-with-special-strings (plist-get options :special-strings))
4794 (re-sub
4795 (cond
4796 ((equal org-export-with-sub-superscripts '{})
4797 (list org-match-substring-with-braces-regexp))
4798 (org-export-with-sub-superscripts
4799 (list org-match-substring-regexp))
4800 (t nil)))
4801 (re-latex
4802 (if org-export-with-LaTeX-fragments
4803 (mapcar (lambda (x) (nth 1 x)) latexs)))
4804 (re-macros
4805 (if org-export-with-TeX-macros
4806 (list (concat "\\\\"
4807 (regexp-opt
4808 (append (mapcar 'car org-html-entities)
4809 (if (boundp 'org-latex-entities)
4810 (mapcar (lambda (x)
4811 (or (car-safe x) x))
4812 org-latex-entities)
4813 nil))
4814 'words))) ; FIXME
4816 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4817 (re-special (if org-export-with-special-strings
4818 (mapcar (lambda (x) (car x))
4819 org-export-html-special-string-regexps)))
4820 (re-rest
4821 (delq nil
4822 (list
4823 (if org-export-html-expand "@<[^>\n]+>")
4824 ))))
4825 (org-set-local
4826 'org-latex-and-specials-regexp
4827 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4828 re-rest) "\\|")))))
4830 (defun org-do-latex-and-special-faces (limit)
4831 "Run through the buffer and add overlays to links."
4832 (when org-latex-and-specials-regexp
4833 (let (rtn d)
4834 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4835 limit t))
4836 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4837 'face))
4838 '(org-code org-verbatim underline)))
4839 (progn
4840 (setq rtn t
4841 d (cond ((member (char-after (1+ (match-beginning 0)))
4842 '(?_ ?^)) 1)
4843 (t 0)))
4844 (font-lock-prepend-text-property
4845 (+ d (match-beginning 0)) (match-end 0)
4846 'face 'org-latex-and-export-specials)
4847 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4848 '(font-lock-multiline t)))))
4849 rtn)))
4851 (defun org-restart-font-lock ()
4852 "Restart font-lock-mode, to force refontification."
4853 (when (and (boundp 'font-lock-mode) font-lock-mode)
4854 (font-lock-mode -1)
4855 (font-lock-mode 1)))
4857 (defun org-all-targets (&optional radio)
4858 "Return a list of all targets in this file.
4859 With optional argument RADIO, only find radio targets."
4860 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4861 rtn)
4862 (save-excursion
4863 (goto-char (point-min))
4864 (while (re-search-forward re nil t)
4865 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4866 rtn)))
4868 (defun org-make-target-link-regexp (targets)
4869 "Make regular expression matching all strings in TARGETS.
4870 The regular expression finds the targets also if there is a line break
4871 between words."
4872 (and targets
4873 (concat
4874 "\\<\\("
4875 (mapconcat
4876 (lambda (x)
4877 (while (string-match " +" x)
4878 (setq x (replace-match "\\s-+" t t x)))
4880 targets
4881 "\\|")
4882 "\\)\\>")))
4884 (defun org-activate-tags (limit)
4885 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4886 (progn
4887 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4888 (add-text-properties (match-beginning 1) (match-end 1)
4889 (list 'mouse-face 'highlight
4890 'keymap org-mouse-map))
4891 (org-rear-nonsticky-at (match-end 1))
4892 t)))
4894 (defun org-outline-level ()
4895 "Compute the outline level of the heading at point.
4896 This function assumes that the cursor is at the beginning of a line matched
4897 by outline-regexp. Otherwise it returns garbage.
4898 If this is called at a normal headline, the level is the number of stars.
4899 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4900 For plain list items, if they are matched by `outline-regexp', this returns
4901 1000 plus the line indentation."
4902 (save-excursion
4903 (looking-at outline-regexp)
4904 (if (match-beginning 1)
4905 (+ (org-get-string-indentation (match-string 1)) 1000)
4906 (1- (- (match-end 0) (match-beginning 0))))))
4908 (defvar org-font-lock-keywords nil)
4910 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4911 "Regular expression matching a property line.")
4913 (defvar org-font-lock-hook nil
4914 "Functions to be called for special font lock stuff.")
4916 (defun org-font-lock-hook (limit)
4917 (run-hook-with-args 'org-font-lock-hook limit))
4919 (defun org-set-font-lock-defaults ()
4920 (let* ((em org-fontify-emphasized-text)
4921 (lk org-activate-links)
4922 (org-font-lock-extra-keywords
4923 (list
4924 ;; Call the hook
4925 '(org-font-lock-hook)
4926 ;; Headlines
4927 `(,(if org-fontify-whole-heading-line
4928 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4929 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4930 (1 (org-get-level-face 1))
4931 (2 (org-get-level-face 2))
4932 (3 (org-get-level-face 3)))
4933 ;; Table lines
4934 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4935 (1 'org-table t))
4936 ;; Table internals
4937 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4938 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4939 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4940 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4941 ;; Drawers
4942 (list org-drawer-regexp '(0 'org-special-keyword t))
4943 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4944 ;; Properties
4945 (list org-property-re
4946 '(1 'org-special-keyword t)
4947 '(3 'org-property-value t))
4948 ;; Links
4949 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4950 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4951 (if (memq 'plain lk) '(org-activate-plain-links))
4952 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4953 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4954 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4955 (if (memq 'footnote lk) '(org-activate-footnote-links
4956 (2 'org-footnote t)))
4957 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4958 '(org-hide-wide-columns (0 nil append))
4959 ;; TODO lines
4960 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4961 '(1 (org-get-todo-face 1) t))
4962 ;; DONE
4963 (if org-fontify-done-headline
4964 (list (concat "^[*]+ +\\<\\("
4965 (mapconcat 'regexp-quote org-done-keywords "\\|")
4966 "\\)\\(.*\\)")
4967 '(2 'org-headline-done t))
4968 nil)
4969 ;; Priorities
4970 '(org-font-lock-add-priority-faces)
4971 ;; Tags
4972 '(org-font-lock-add-tag-faces)
4973 ;; Special keywords
4974 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4975 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4976 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4977 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4978 ;; Emphasis
4979 (if em
4980 (if (featurep 'xemacs)
4981 '(org-do-emphasis-faces (0 nil append))
4982 '(org-do-emphasis-faces)))
4983 ;; Checkboxes
4984 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4985 2 'org-checkbox prepend)
4986 (if org-provide-checkbox-statistics
4987 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4988 (0 (org-get-checkbox-statistics-face) t)))
4989 ;; Description list items
4990 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4991 2 'bold prepend)
4992 ;; ARCHIVEd headings
4993 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4994 '(1 'org-archived prepend))
4995 ;; Specials
4996 '(org-do-latex-and-special-faces)
4997 ;; Code
4998 '(org-activate-code (1 'org-code t))
4999 ;; COMMENT
5000 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5001 "\\|" org-quote-string "\\)\\>")
5002 '(1 'org-special-keyword t))
5003 '("^#.*" (0 'font-lock-comment-face t))
5004 ;; Blocks and meta lines
5005 '(org-fontify-meta-lines-and-blocks)
5007 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5008 ;; Now set the full font-lock-keywords
5009 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5010 (org-set-local 'font-lock-defaults
5011 '(org-font-lock-keywords t nil nil backward-paragraph))
5012 (kill-local-variable 'font-lock-keywords) nil))
5014 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5015 "Fontify string S like in Org-mode"
5016 (with-temp-buffer
5017 (insert s)
5018 (let ((org-odd-levels-only odd-levels))
5019 (org-mode)
5020 (font-lock-fontify-buffer)
5021 (buffer-string))))
5023 (defvar org-m nil)
5024 (defvar org-l nil)
5025 (defvar org-f nil)
5026 (defun org-get-level-face (n)
5027 "Get the right face for match N in font-lock matching of headlines."
5028 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5029 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5030 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5031 (cond
5032 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5033 ((eq n 2) org-f)
5034 (t (if org-level-color-stars-only nil org-f))))
5036 (defun org-get-todo-face (kwd)
5037 "Get the right face for a TODO keyword KWD.
5038 If KWD is a number, get the corresponding match group."
5039 (if (numberp kwd) (setq kwd (match-string kwd)))
5040 (or (cdr (assoc kwd org-todo-keyword-faces))
5041 (and (member kwd org-done-keywords) 'org-done)
5042 'org-todo))
5044 (defun org-font-lock-add-tag-faces (limit)
5045 "Add the special tag faces."
5046 (when (and org-tag-faces org-tags-special-faces-re)
5047 (while (re-search-forward org-tags-special-faces-re limit t)
5048 (add-text-properties (match-beginning 1) (match-end 1)
5049 (list 'face (org-get-tag-face 1)
5050 'font-lock-fontified t))
5051 (backward-char 1))))
5053 (defun org-font-lock-add-priority-faces (limit)
5054 "Add the special priority faces."
5055 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5056 (add-text-properties
5057 (match-beginning 0) (match-end 0)
5058 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5059 org-priority-faces))
5060 'org-special-keyword)
5061 'font-lock-fontified t))))
5063 (defun org-get-tag-face (kwd)
5064 "Get the right face for a TODO keyword KWD.
5065 If KWD is a number, get the corresponding match group."
5066 (if (numberp kwd) (setq kwd (match-string kwd)))
5067 (or (cdr (assoc kwd org-tag-faces))
5068 'org-tag))
5070 (defun org-unfontify-region (beg end &optional maybe_loudly)
5071 "Remove fontification and activation overlays from links."
5072 (font-lock-default-unfontify-region beg end)
5073 (let* ((buffer-undo-list t)
5074 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5075 (inhibit-modification-hooks t)
5076 deactivate-mark buffer-file-name buffer-file-truename)
5077 (remove-text-properties
5078 beg end
5079 (if org-indent-mode
5080 ;; also remove line-prefix and wrap-prefix properties
5081 '(mouse-face t keymap t org-linked-text t
5082 invisible t intangible t
5083 line-prefix t wrap-prefix t
5084 org-no-flyspell t)
5085 '(mouse-face t keymap t org-linked-text t
5086 invisible t intangible t
5087 org-no-flyspell t)))))
5089 ;;;; Visibility cycling, including org-goto and indirect buffer
5091 ;;; Cycling
5093 (defvar org-cycle-global-status nil)
5094 (make-variable-buffer-local 'org-cycle-global-status)
5095 (defvar org-cycle-subtree-status nil)
5096 (make-variable-buffer-local 'org-cycle-subtree-status)
5098 ;;;###autoload
5100 (defvar org-inlinetask-min-level)
5102 (defun org-cycle (&optional arg)
5103 "TAB-action and visibility cycling for Org-mode.
5105 This is the command invoked in Org-mode by the TAB key. Its main purpose
5106 is outline visibility cycling, but it also invokes other actions
5107 in special contexts.
5109 - When this function is called with a prefix argument, rotate the entire
5110 buffer through 3 states (global cycling)
5111 1. OVERVIEW: Show only top-level headlines.
5112 2. CONTENTS: Show all headlines of all levels, but no body text.
5113 3. SHOW ALL: Show everything.
5114 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5115 determined by the variable `org-startup-folded', and by any VISIBILITY
5116 properties in the buffer.
5117 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5118 including any drawers.
5120 - When inside a table, re-align the table and move to the next field.
5122 - When point is at the beginning of a headline, rotate the subtree started
5123 by this line through 3 different states (local cycling)
5124 1. FOLDED: Only the main headline is shown.
5125 2. CHILDREN: The main headline and the direct children are shown.
5126 From this state, you can move to one of the children
5127 and zoom in further.
5128 3. SUBTREE: Show the entire subtree, including body text.
5129 If there is no subtree, switch directly from CHILDREN to FOLDED.
5131 - When there is a numeric prefix, go up to a heading with level ARG, do
5132 a `show-subtree' and return to the previous cursor position. If ARG
5133 is negative, go up that many levels.
5135 - When point is not at the beginning of a headline, execute the global
5136 binding for TAB, which is re-indenting the line. See the option
5137 `org-cycle-emulate-tab' for details.
5139 - Special case: if point is at the beginning of the buffer and there is
5140 no headline in line 1, this function will act as if called with prefix arg.
5141 But only if also the variable `org-cycle-global-at-bob' is t."
5142 (interactive "P")
5143 (org-load-modules-maybe)
5144 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5145 (and org-cycle-level-after-item/entry-creation
5146 (or (org-cycle-level)
5147 (org-cycle-item-indentation))))
5148 (let* ((limit-level
5149 (or org-cycle-max-level
5150 (and (boundp 'org-inlinetask-min-level)
5151 org-inlinetask-min-level
5152 (1- org-inlinetask-min-level))))
5153 (nstars (and limit-level
5154 (if org-odd-levels-only
5155 (and limit-level (1- (* limit-level 2)))
5156 limit-level)))
5157 (outline-regexp
5158 (cond
5159 ((not (org-mode-p)) outline-regexp)
5160 ((or (eq org-cycle-include-plain-lists 'integrate)
5161 (and org-cycle-include-plain-lists (org-at-item-p)))
5162 (concat "\\(?:\\*"
5163 (if nstars (format "\\{1,%d\\}" nstars) "+")
5164 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5165 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5166 (bob-special (and org-cycle-global-at-bob (bobp)
5167 (not (looking-at outline-regexp))))
5168 (org-cycle-hook
5169 (if bob-special
5170 (delq 'org-optimize-window-after-visibility-change
5171 (copy-sequence org-cycle-hook))
5172 org-cycle-hook))
5173 (pos (point)))
5175 (if (or bob-special (equal arg '(4)))
5176 ;; special case: use global cycling
5177 (setq arg t))
5179 (cond
5181 ((equal arg '(16))
5182 (org-set-startup-visibility)
5183 (message "Startup visibility, plus VISIBILITY properties"))
5185 ((equal arg '(64))
5186 (show-all)
5187 (message "Entire buffer visible, including drawers"))
5189 ((org-at-table-p 'any)
5190 ;; Enter the table or move to the next field in the table
5191 (or (org-table-recognize-table.el)
5192 (progn
5193 (if arg (org-table-edit-field t)
5194 (org-table-justify-field-maybe)
5195 (call-interactively 'org-table-next-field)))))
5197 ((run-hook-with-args-until-success
5198 'org-tab-after-check-for-table-hook))
5200 ((eq arg t) ;; Global cycling
5201 (org-cycle-internal-global))
5203 ((and org-drawers org-drawer-regexp
5204 (save-excursion
5205 (beginning-of-line 1)
5206 (looking-at org-drawer-regexp)))
5207 ;; Toggle block visibility
5208 (org-flag-drawer
5209 (not (get-char-property (match-end 0) 'invisible))))
5211 ((integerp arg)
5212 ;; Show-subtree, ARG levels up from here.
5213 (save-excursion
5214 (org-back-to-heading)
5215 (outline-up-heading (if (< arg 0) (- arg)
5216 (- (funcall outline-level) arg)))
5217 (org-show-subtree)))
5219 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5220 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5222 (org-cycle-internal-local))
5224 ;; TAB emulation and template completion
5225 (buffer-read-only (org-back-to-heading))
5227 ((run-hook-with-args-until-success
5228 'org-tab-after-check-for-cycling-hook))
5230 ((org-try-structure-completion))
5232 ((org-try-cdlatex-tab))
5234 ((run-hook-with-args-until-success
5235 'org-tab-before-tab-emulation-hook))
5237 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5238 (or (not (bolp))
5239 (not (looking-at outline-regexp))))
5240 (call-interactively (global-key-binding "\t")))
5242 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5243 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5244 (or (and (eq org-cycle-emulate-tab 'white)
5245 (= (match-end 0) (point-at-eol)))
5246 (and (eq org-cycle-emulate-tab 'whitestart)
5247 (>= (match-end 0) pos))))
5249 (eq org-cycle-emulate-tab t))
5250 (call-interactively (global-key-binding "\t")))
5252 (t (save-excursion
5253 (org-back-to-heading)
5254 (org-cycle)))))))
5256 (defun org-cycle-internal-global ()
5257 "Do the global cycling action."
5258 (cond
5259 ((and (eq last-command this-command)
5260 (eq org-cycle-global-status 'overview))
5261 ;; We just created the overview - now do table of contents
5262 ;; This can be slow in very large buffers, so indicate action
5263 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5264 (message "CONTENTS...")
5265 (org-content)
5266 (message "CONTENTS...done")
5267 (setq org-cycle-global-status 'contents)
5268 (run-hook-with-args 'org-cycle-hook 'contents))
5270 ((and (eq last-command this-command)
5271 (eq org-cycle-global-status 'contents))
5272 ;; We just showed the table of contents - now show everything
5273 (run-hook-with-args 'org-pre-cycle-hook 'all)
5274 (show-all)
5275 (message "SHOW ALL")
5276 (setq org-cycle-global-status 'all)
5277 (run-hook-with-args 'org-cycle-hook 'all))
5280 ;; Default action: go to overview
5281 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5282 (org-overview)
5283 (message "OVERVIEW")
5284 (setq org-cycle-global-status 'overview)
5285 (run-hook-with-args 'org-cycle-hook 'overview))))
5287 (defun org-cycle-internal-local ()
5288 "Do the local cycling action."
5289 (org-back-to-heading)
5290 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5291 ;; First, some boundaries
5292 (save-excursion
5293 (org-back-to-heading)
5294 (setq level (funcall outline-level))
5295 (save-excursion
5296 (beginning-of-line 2)
5297 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5298 ; XEmacs does not have `next-single-char-property-change'
5299 ; I'm not sure about Emacs 21.
5300 (while (and (not (eobp)) ;; this is like `next-line'
5301 (get-char-property (1- (point)) 'invisible))
5302 (beginning-of-line 2))
5303 (while (and (not (eobp)) ;; this is like `next-line'
5304 (get-char-property (1- (point)) 'invisible))
5305 (goto-char (next-single-char-property-change (point) 'invisible))
5306 ;;;??? (or (bolp) (beginning-of-line 2))))
5307 (and (eolp) (beginning-of-line 2))))
5308 (setq eol (point)))
5309 (outline-end-of-heading) (setq eoh (point))
5310 (save-excursion
5311 (outline-next-heading)
5312 (setq has-children (and (org-at-heading-p t)
5313 (> (funcall outline-level) level))))
5314 (org-end-of-subtree t)
5315 (unless (eobp)
5316 (skip-chars-forward " \t\n")
5317 (beginning-of-line 1) ; in case this is an item
5319 (setq eos (if (eobp) (point) (1- (point)))))
5320 ;; Find out what to do next and set `this-command'
5321 (cond
5322 ((= eos eoh)
5323 ;; Nothing is hidden behind this heading
5324 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5325 (message "EMPTY ENTRY")
5326 (setq org-cycle-subtree-status nil)
5327 (save-excursion
5328 (goto-char eos)
5329 (outline-next-heading)
5330 (if (org-invisible-p) (org-flag-heading nil))))
5331 ((and (or (>= eol eos)
5332 (not (string-match "\\S-" (buffer-substring eol eos))))
5333 (or has-children
5334 (not (setq children-skipped
5335 org-cycle-skip-children-state-if-no-children))))
5336 ;; Entire subtree is hidden in one line: children view
5337 (run-hook-with-args 'org-pre-cycle-hook 'children)
5338 (org-show-entry)
5339 (show-children)
5340 (message "CHILDREN")
5341 (save-excursion
5342 (goto-char eos)
5343 (outline-next-heading)
5344 (if (org-invisible-p) (org-flag-heading nil)))
5345 (setq org-cycle-subtree-status 'children)
5346 (run-hook-with-args 'org-cycle-hook 'children))
5347 ((or children-skipped
5348 (and (eq last-command this-command)
5349 (eq org-cycle-subtree-status 'children)))
5350 ;; We just showed the children, or no children are there,
5351 ;; now show everything.
5352 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5353 (org-show-subtree)
5354 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5355 (setq org-cycle-subtree-status 'subtree)
5356 (run-hook-with-args 'org-cycle-hook 'subtree))
5358 ;; Default action: hide the subtree.
5359 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5360 (hide-subtree)
5361 (message "FOLDED")
5362 (setq org-cycle-subtree-status 'folded)
5363 (run-hook-with-args 'org-cycle-hook 'folded)))))
5365 ;;;###autoload
5366 (defun org-global-cycle (&optional arg)
5367 "Cycle the global visibility. For details see `org-cycle'.
5368 With C-u prefix arg, switch to startup visibility.
5369 With a numeric prefix, show all headlines up to that level."
5370 (interactive "P")
5371 (let ((org-cycle-include-plain-lists
5372 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5373 (cond
5374 ((integerp arg)
5375 (show-all)
5376 (hide-sublevels arg)
5377 (setq org-cycle-global-status 'contents))
5378 ((equal arg '(4))
5379 (org-set-startup-visibility)
5380 (message "Startup visibility, plus VISIBILITY properties."))
5382 (org-cycle '(4))))))
5384 (defun org-set-startup-visibility ()
5385 "Set the visibility required by startup options and properties."
5386 (cond
5387 ((eq org-startup-folded t)
5388 (org-cycle '(4)))
5389 ((eq org-startup-folded 'content)
5390 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5391 (org-cycle '(4)) (org-cycle '(4)))))
5392 (unless (eq org-startup-folded 'showeverything)
5393 (if org-hide-block-startup (org-hide-block-all))
5394 (org-set-visibility-according-to-property 'no-cleanup)
5395 (org-cycle-hide-archived-subtrees 'all)
5396 (org-cycle-hide-drawers 'all)
5397 (org-cycle-show-empty-lines 'all)))
5399 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5400 "Switch subtree visibilities according to :VISIBILITY: property."
5401 (interactive)
5402 (let (org-show-entry-below state)
5403 (save-excursion
5404 (goto-char (point-min))
5405 (while (re-search-forward
5406 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5407 nil t)
5408 (setq state (match-string 1))
5409 (save-excursion
5410 (org-back-to-heading t)
5411 (hide-subtree)
5412 (org-reveal)
5413 (cond
5414 ((equal state '("fold" "folded"))
5415 (hide-subtree))
5416 ((equal state "children")
5417 (org-show-hidden-entry)
5418 (show-children))
5419 ((equal state "content")
5420 (save-excursion
5421 (save-restriction
5422 (org-narrow-to-subtree)
5423 (org-content))))
5424 ((member state '("all" "showall"))
5425 (show-subtree)))))
5426 (unless no-cleanup
5427 (org-cycle-hide-archived-subtrees 'all)
5428 (org-cycle-hide-drawers 'all)
5429 (org-cycle-show-empty-lines 'all)))))
5431 (defun org-overview ()
5432 "Switch to overview mode, showing only top-level headlines.
5433 Really, this shows all headlines with level equal or greater than the level
5434 of the first headline in the buffer. This is important, because if the
5435 first headline is not level one, then (hide-sublevels 1) gives confusing
5436 results."
5437 (interactive)
5438 (let ((level (save-excursion
5439 (goto-char (point-min))
5440 (if (re-search-forward (concat "^" outline-regexp) nil t)
5441 (progn
5442 (goto-char (match-beginning 0))
5443 (funcall outline-level))))))
5444 (and level (hide-sublevels level))))
5446 (defun org-content (&optional arg)
5447 "Show all headlines in the buffer, like a table of contents.
5448 With numerical argument N, show content up to level N."
5449 (interactive "P")
5450 (save-excursion
5451 ;; Visit all headings and show their offspring
5452 (and (integerp arg) (org-overview))
5453 (goto-char (point-max))
5454 (catch 'exit
5455 (while (and (progn (condition-case nil
5456 (outline-previous-visible-heading 1)
5457 (error (goto-char (point-min))))
5459 (looking-at outline-regexp))
5460 (if (integerp arg)
5461 (show-children (1- arg))
5462 (show-branches))
5463 (if (bobp) (throw 'exit nil))))))
5466 (defun org-optimize-window-after-visibility-change (state)
5467 "Adjust the window after a change in outline visibility.
5468 This function is the default value of the hook `org-cycle-hook'."
5469 (when (get-buffer-window (current-buffer))
5470 (cond
5471 ((eq state 'content) nil)
5472 ((eq state 'all) nil)
5473 ((eq state 'folded) nil)
5474 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5475 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5477 (defun org-remove-empty-overlays-at (pos)
5478 "Remove outline overlays that do not contain non-white stuff."
5479 (mapc
5480 (lambda (o)
5481 (and (eq 'outline (org-overlay-get o 'invisible))
5482 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5483 (org-overlay-end o))))
5484 (org-delete-overlay o)))
5485 (org-overlays-at pos)))
5487 (defun org-clean-visibility-after-subtree-move ()
5488 "Fix visibility issues after moving a subtree."
5489 ;; First, find a reasonable region to look at:
5490 ;; Start two siblings above, end three below
5491 (let* ((beg (save-excursion
5492 (and (org-get-last-sibling)
5493 (org-get-last-sibling))
5494 (point)))
5495 (end (save-excursion
5496 (and (org-get-next-sibling)
5497 (org-get-next-sibling)
5498 (org-get-next-sibling))
5499 (if (org-at-heading-p)
5500 (point-at-eol)
5501 (point))))
5502 (level (looking-at "\\*+"))
5503 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5504 (save-excursion
5505 (save-restriction
5506 (narrow-to-region beg end)
5507 (when re
5508 ;; Properly fold already folded siblings
5509 (goto-char (point-min))
5510 (while (re-search-forward re nil t)
5511 (if (and (not (org-invisible-p))
5512 (save-excursion
5513 (goto-char (point-at-eol)) (org-invisible-p)))
5514 (hide-entry))))
5515 (org-cycle-show-empty-lines 'overview)
5516 (org-cycle-hide-drawers 'overview)))))
5518 (defun org-cycle-show-empty-lines (state)
5519 "Show empty lines above all visible headlines.
5520 The region to be covered depends on STATE when called through
5521 `org-cycle-hook'. Lisp program can use t for STATE to get the
5522 entire buffer covered. Note that an empty line is only shown if there
5523 are at least `org-cycle-separator-lines' empty lines before the headline."
5524 (when (not (= org-cycle-separator-lines 0))
5525 (save-excursion
5526 (let* ((n (abs org-cycle-separator-lines))
5527 (re (cond
5528 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5529 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5530 (t (let ((ns (number-to-string (- n 2))))
5531 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5532 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5533 beg end b e)
5534 (cond
5535 ((memq state '(overview contents t))
5536 (setq beg (point-min) end (point-max)))
5537 ((memq state '(children folded))
5538 (setq beg (point) end (progn (org-end-of-subtree t t)
5539 (beginning-of-line 2)
5540 (point)))))
5541 (when beg
5542 (goto-char beg)
5543 (while (re-search-forward re end t)
5544 (unless (get-char-property (match-end 1) 'invisible)
5545 (setq e (match-end 1))
5546 (if (< org-cycle-separator-lines 0)
5547 (setq b (save-excursion
5548 (goto-char (match-beginning 0))
5549 (org-back-over-empty-lines)
5550 (if (save-excursion
5551 (goto-char (max (point-min) (1- (point))))
5552 (org-on-heading-p))
5553 (1- (point))
5554 (point))))
5555 (setq b (match-beginning 1)))
5556 (outline-flag-region b e nil)))))))
5557 ;; Never hide empty lines at the end of the file.
5558 (save-excursion
5559 (goto-char (point-max))
5560 (outline-previous-heading)
5561 (outline-end-of-heading)
5562 (if (and (looking-at "[ \t\n]+")
5563 (= (match-end 0) (point-max)))
5564 (outline-flag-region (point) (match-end 0) nil))))
5566 (defun org-show-empty-lines-in-parent ()
5567 "Move to the parent and re-show empty lines before visible headlines."
5568 (save-excursion
5569 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5570 (org-cycle-show-empty-lines context))))
5572 (defun org-files-list ()
5573 "Return `org-agenda-files' list, plus all open org-mode files.
5574 This is useful for operations that need to scan all of a user's
5575 open and agenda-wise Org files."
5576 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5577 (dolist (buf (buffer-list))
5578 (with-current-buffer buf
5579 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5580 (let ((file (expand-file-name (buffer-file-name))))
5581 (unless (member file files)
5582 (push file files))))))
5583 files))
5585 (defsubst org-entry-beginning-position ()
5586 "Return the beginning position of the current entry."
5587 (save-excursion (outline-back-to-heading t) (point)))
5589 (defsubst org-entry-end-position ()
5590 "Return the end position of the current entry."
5591 (save-excursion (outline-next-heading) (point)))
5593 (defun org-cycle-hide-drawers (state)
5594 "Re-hide all drawers after a visibility state change."
5595 (when (and (org-mode-p)
5596 (not (memq state '(overview folded contents))))
5597 (save-excursion
5598 (let* ((globalp (memq state '(contents all)))
5599 (beg (if globalp (point-min) (point)))
5600 (end (if globalp (point-max)
5601 (if (eq state 'children)
5602 (save-excursion (outline-next-heading) (point))
5603 (org-end-of-subtree t)))))
5604 (goto-char beg)
5605 (while (re-search-forward org-drawer-regexp end t)
5606 (org-flag-drawer t))))))
5608 (defun org-flag-drawer (flag)
5609 (save-excursion
5610 (beginning-of-line 1)
5611 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5612 (let ((b (match-end 0))
5613 (outline-regexp org-outline-regexp))
5614 (if (re-search-forward
5615 "^[ \t]*:END:"
5616 (save-excursion (outline-next-heading) (point)) t)
5617 (outline-flag-region b (point-at-eol) flag)
5618 (error ":END: line missing at position %s" b))))))
5620 (defun org-subtree-end-visible-p ()
5621 "Is the end of the current subtree visible?"
5622 (pos-visible-in-window-p
5623 (save-excursion (org-end-of-subtree t) (point))))
5625 (defun org-first-headline-recenter (&optional N)
5626 "Move cursor to the first headline and recenter the headline.
5627 Optional argument N means, put the headline into the Nth line of the window."
5628 (goto-char (point-min))
5629 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5630 (beginning-of-line)
5631 (recenter (prefix-numeric-value N))))
5633 ;;; Folding of blocks
5635 (defconst org-block-regexp
5637 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5638 "Regular expression for hiding blocks.")
5640 (defvar org-hide-block-overlays nil
5641 "Overlays hiding blocks.")
5642 (make-variable-buffer-local 'org-hide-block-overlays)
5644 (defun org-block-map (function &optional start end)
5645 "Call func at the head of all source blocks in the current
5646 buffer. Optional arguments START and END can be used to limit
5647 the range."
5648 (let ((start (or start (point-min)))
5649 (end (or end (point-max))))
5650 (save-excursion
5651 (goto-char start)
5652 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5653 (save-excursion
5654 (save-match-data
5655 (goto-char (match-beginning 0))
5656 (funcall function)))))))
5658 (defun org-hide-block-toggle-all ()
5659 "Toggle the visibility of all blocks in the current buffer."
5660 (org-block-map #'org-hide-block-toggle))
5662 (defun org-hide-block-all ()
5663 "Fold all blocks in the current buffer."
5664 (interactive)
5665 (org-show-block-all)
5666 (org-block-map #'org-hide-block-toggle-maybe))
5668 (defun org-show-block-all ()
5669 "Unfold all blocks in the current buffer."
5670 (mapc 'org-delete-overlay org-hide-block-overlays)
5671 (setq org-hide-block-overlays nil))
5673 (defun org-hide-block-toggle-maybe ()
5674 "Toggle visibility of block at point."
5675 (interactive)
5676 (let ((case-fold-search t))
5677 (if (save-excursion
5678 (beginning-of-line 1)
5679 (looking-at org-block-regexp))
5680 (progn (org-hide-block-toggle)
5681 t) ;; to signal that we took action
5682 nil))) ;; to signal that we did not
5684 (defun org-hide-block-toggle (&optional force)
5685 "Toggle the visibility of the current block."
5686 (interactive)
5687 (save-excursion
5688 (beginning-of-line)
5689 (if (re-search-forward org-block-regexp nil t)
5690 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5691 (end (match-end 0)) ;; end of entire body
5693 (if (memq t (mapcar (lambda (overlay)
5694 (eq (org-overlay-get overlay 'invisible)
5695 'org-hide-block))
5696 (org-overlays-at start)))
5697 (if (or (not force) (eq force 'off))
5698 (mapc (lambda (ov)
5699 (when (member ov org-hide-block-overlays)
5700 (setq org-hide-block-overlays
5701 (delq ov org-hide-block-overlays)))
5702 (when (eq (org-overlay-get ov 'invisible)
5703 'org-hide-block)
5704 (org-delete-overlay ov)))
5705 (org-overlays-at start)))
5706 (setq ov (org-make-overlay start end))
5707 (org-overlay-put ov 'invisible 'org-hide-block)
5708 ;; make the block accessible to isearch
5709 (org-overlay-put
5710 ov 'isearch-open-invisible
5711 (lambda (ov)
5712 (when (member ov org-hide-block-overlays)
5713 (setq org-hide-block-overlays
5714 (delq ov org-hide-block-overlays)))
5715 (when (eq (org-overlay-get ov 'invisible)
5716 'org-hide-block)
5717 (org-delete-overlay ov))))
5718 (push ov org-hide-block-overlays)))
5719 (error "Not looking at a source block"))))
5721 ;; org-tab-after-check-for-cycling-hook
5722 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5723 ;; Remove overlays when changing major mode
5724 (add-hook 'org-mode-hook
5725 (lambda () (org-add-hook 'change-major-mode-hook
5726 'org-show-block-all 'append 'local)))
5728 ;;; Org-goto
5730 (defvar org-goto-window-configuration nil)
5731 (defvar org-goto-marker nil)
5732 (defvar org-goto-map
5733 (let ((map (make-sparse-keymap)))
5734 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5735 (while (setq cmd (pop cmds))
5736 (substitute-key-definition cmd cmd map global-map)))
5737 (suppress-keymap map)
5738 (org-defkey map "\C-m" 'org-goto-ret)
5739 (org-defkey map [(return)] 'org-goto-ret)
5740 (org-defkey map [(left)] 'org-goto-left)
5741 (org-defkey map [(right)] 'org-goto-right)
5742 (org-defkey map [(control ?g)] 'org-goto-quit)
5743 (org-defkey map "\C-i" 'org-cycle)
5744 (org-defkey map [(tab)] 'org-cycle)
5745 (org-defkey map [(down)] 'outline-next-visible-heading)
5746 (org-defkey map [(up)] 'outline-previous-visible-heading)
5747 (if org-goto-auto-isearch
5748 (if (fboundp 'define-key-after)
5749 (define-key-after map [t] 'org-goto-local-auto-isearch)
5750 nil)
5751 (org-defkey map "q" 'org-goto-quit)
5752 (org-defkey map "n" 'outline-next-visible-heading)
5753 (org-defkey map "p" 'outline-previous-visible-heading)
5754 (org-defkey map "f" 'outline-forward-same-level)
5755 (org-defkey map "b" 'outline-backward-same-level)
5756 (org-defkey map "u" 'outline-up-heading))
5757 (org-defkey map "/" 'org-occur)
5758 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5759 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5760 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5761 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5762 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5763 map))
5765 (defconst org-goto-help
5766 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5767 RET=jump to location [Q]uit and return to previous location
5768 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5770 (defvar org-goto-start-pos) ; dynamically scoped parameter
5772 ;; FIXME: Docstring does not mention both interfaces
5773 (defun org-goto (&optional alternative-interface)
5774 "Look up a different location in the current file, keeping current visibility.
5776 When you want look-up or go to a different location in a document, the
5777 fastest way is often to fold the entire buffer and then dive into the tree.
5778 This method has the disadvantage, that the previous location will be folded,
5779 which may not be what you want.
5781 This command works around this by showing a copy of the current buffer
5782 in an indirect buffer, in overview mode. You can dive into the tree in
5783 that copy, use org-occur and incremental search to find a location.
5784 When pressing RET or `Q', the command returns to the original buffer in
5785 which the visibility is still unchanged. After RET is will also jump to
5786 the location selected in the indirect buffer and expose the
5787 the headline hierarchy above."
5788 (interactive "P")
5789 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5790 (org-refile-use-outline-path t)
5791 (org-refile-target-verify-function nil)
5792 (interface
5793 (if (not alternative-interface)
5794 org-goto-interface
5795 (if (eq org-goto-interface 'outline)
5796 'outline-path-completion
5797 'outline)))
5798 (org-goto-start-pos (point))
5799 (selected-point
5800 (if (eq interface 'outline)
5801 (car (org-get-location (current-buffer) org-goto-help))
5802 (nth 3 (org-refile-get-location "Goto: ")))))
5803 (if selected-point
5804 (progn
5805 (org-mark-ring-push org-goto-start-pos)
5806 (goto-char selected-point)
5807 (if (or (org-invisible-p) (org-invisible-p2))
5808 (org-show-context 'org-goto)))
5809 (message "Quit"))))
5811 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5812 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5813 (defvar org-goto-local-auto-isearch-map) ; defined below
5815 (defun org-get-location (buf help)
5816 "Let the user select a location in the Org-mode buffer BUF.
5817 This function uses a recursive edit. It returns the selected position
5818 or nil."
5819 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5820 (isearch-hide-immediately nil)
5821 (isearch-search-fun-function
5822 (lambda () 'org-goto-local-search-headings))
5823 (org-goto-selected-point org-goto-exit-command))
5824 (save-excursion
5825 (save-window-excursion
5826 (delete-other-windows)
5827 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5828 (switch-to-buffer
5829 (condition-case nil
5830 (make-indirect-buffer (current-buffer) "*org-goto*")
5831 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5832 (with-output-to-temp-buffer "*Help*"
5833 (princ help))
5834 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5835 (setq buffer-read-only nil)
5836 (let ((org-startup-truncated t)
5837 (org-startup-folded nil)
5838 (org-startup-align-all-tables nil))
5839 (org-mode)
5840 (org-overview))
5841 (setq buffer-read-only t)
5842 (if (and (boundp 'org-goto-start-pos)
5843 (integer-or-marker-p org-goto-start-pos))
5844 (let ((org-show-hierarchy-above t)
5845 (org-show-siblings t)
5846 (org-show-following-heading t))
5847 (goto-char org-goto-start-pos)
5848 (and (org-invisible-p) (org-show-context)))
5849 (goto-char (point-min)))
5850 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5851 (message "Select location and press RET")
5852 (use-local-map org-goto-map)
5853 (recursive-edit)
5855 (kill-buffer "*org-goto*")
5856 (cons org-goto-selected-point org-goto-exit-command)))
5858 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5859 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5860 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5861 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5863 (defun org-goto-local-search-headings (string bound noerror)
5864 "Search and make sure that any matches are in headlines."
5865 (catch 'return
5866 (while (if isearch-forward
5867 (search-forward string bound noerror)
5868 (search-backward string bound noerror))
5869 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5870 (and (member :headline context)
5871 (not (member :tags context))))
5872 (throw 'return (point))))))
5874 (defun org-goto-local-auto-isearch ()
5875 "Start isearch."
5876 (interactive)
5877 (goto-char (point-min))
5878 (let ((keys (this-command-keys)))
5879 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5880 (isearch-mode t)
5881 (isearch-process-search-char (string-to-char keys)))))
5883 (defun org-goto-ret (&optional arg)
5884 "Finish `org-goto' by going to the new location."
5885 (interactive "P")
5886 (setq org-goto-selected-point (point)
5887 org-goto-exit-command 'return)
5888 (throw 'exit nil))
5890 (defun org-goto-left ()
5891 "Finish `org-goto' by going to the new location."
5892 (interactive)
5893 (if (org-on-heading-p)
5894 (progn
5895 (beginning-of-line 1)
5896 (setq org-goto-selected-point (point)
5897 org-goto-exit-command 'left)
5898 (throw 'exit nil))
5899 (error "Not on a heading")))
5901 (defun org-goto-right ()
5902 "Finish `org-goto' by going to the new location."
5903 (interactive)
5904 (if (org-on-heading-p)
5905 (progn
5906 (setq org-goto-selected-point (point)
5907 org-goto-exit-command 'right)
5908 (throw 'exit nil))
5909 (error "Not on a heading")))
5911 (defun org-goto-quit ()
5912 "Finish `org-goto' without cursor motion."
5913 (interactive)
5914 (setq org-goto-selected-point nil)
5915 (setq org-goto-exit-command 'quit)
5916 (throw 'exit nil))
5918 ;;; Indirect buffer display of subtrees
5920 (defvar org-indirect-dedicated-frame nil
5921 "This is the frame being used for indirect tree display.")
5922 (defvar org-last-indirect-buffer nil)
5924 (defun org-tree-to-indirect-buffer (&optional arg)
5925 "Create indirect buffer and narrow it to current subtree.
5926 With numerical prefix ARG, go up to this level and then take that tree.
5927 If ARG is negative, go up that many levels.
5928 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5929 indirect buffer previously made with this command, to avoid proliferation of
5930 indirect buffers. However, when you call the command with a `C-u' prefix, or
5931 when `org-indirect-buffer-display' is `new-frame', the last buffer
5932 is kept so that you can work with several indirect buffers at the same time.
5933 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5934 requests that a new frame be made for the new buffer, so that the dedicated
5935 frame is not changed."
5936 (interactive "P")
5937 (let ((cbuf (current-buffer))
5938 (cwin (selected-window))
5939 (pos (point))
5940 beg end level heading ibuf)
5941 (save-excursion
5942 (org-back-to-heading t)
5943 (when (numberp arg)
5944 (setq level (org-outline-level))
5945 (if (< arg 0) (setq arg (+ level arg)))
5946 (while (> (setq level (org-outline-level)) arg)
5947 (outline-up-heading 1 t)))
5948 (setq beg (point)
5949 heading (org-get-heading))
5950 (org-end-of-subtree t t) (setq end (point)))
5951 (if (and (buffer-live-p org-last-indirect-buffer)
5952 (not (eq org-indirect-buffer-display 'new-frame))
5953 (not arg))
5954 (kill-buffer org-last-indirect-buffer))
5955 (setq ibuf (org-get-indirect-buffer cbuf)
5956 org-last-indirect-buffer ibuf)
5957 (cond
5958 ((or (eq org-indirect-buffer-display 'new-frame)
5959 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5960 (select-frame (make-frame))
5961 (delete-other-windows)
5962 (switch-to-buffer ibuf)
5963 (org-set-frame-title heading))
5964 ((eq org-indirect-buffer-display 'dedicated-frame)
5965 (raise-frame
5966 (select-frame (or (and org-indirect-dedicated-frame
5967 (frame-live-p org-indirect-dedicated-frame)
5968 org-indirect-dedicated-frame)
5969 (setq org-indirect-dedicated-frame (make-frame)))))
5970 (delete-other-windows)
5971 (switch-to-buffer ibuf)
5972 (org-set-frame-title (concat "Indirect: " heading)))
5973 ((eq org-indirect-buffer-display 'current-window)
5974 (switch-to-buffer ibuf))
5975 ((eq org-indirect-buffer-display 'other-window)
5976 (pop-to-buffer ibuf))
5977 (t (error "Invalid value")))
5978 (if (featurep 'xemacs)
5979 (save-excursion (org-mode) (turn-on-font-lock)))
5980 (narrow-to-region beg end)
5981 (show-all)
5982 (goto-char pos)
5983 (and (window-live-p cwin) (select-window cwin))))
5985 (defun org-get-indirect-buffer (&optional buffer)
5986 (setq buffer (or buffer (current-buffer)))
5987 (let ((n 1) (base (buffer-name buffer)) bname)
5988 (while (buffer-live-p
5989 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5990 (setq n (1+ n)))
5991 (condition-case nil
5992 (make-indirect-buffer buffer bname 'clone)
5993 (error (make-indirect-buffer buffer bname)))))
5995 (defun org-set-frame-title (title)
5996 "Set the title of the current frame to the string TITLE."
5997 ;; FIXME: how to name a single frame in XEmacs???
5998 (unless (featurep 'xemacs)
5999 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6001 ;;;; Structure editing
6003 ;;; Inserting headlines
6005 (defun org-previous-line-empty-p ()
6006 (save-excursion
6007 (and (not (bobp))
6008 (or (beginning-of-line 0) t)
6009 (save-match-data
6010 (looking-at "[ \t]*$")))))
6012 (defun org-insert-heading (&optional force-heading)
6013 "Insert a new heading or item with same depth at point.
6014 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6015 If point is at the beginning of a headline, insert a sibling before the
6016 current headline. If point is not at the beginning, do not split the line,
6017 but create the new headline after the current line."
6018 (interactive "P")
6019 (if (or (= (buffer-size) 0)
6020 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
6021 (org-on-heading-p))))
6022 (not (org-in-item-p))))
6023 (insert "\n* ")
6024 (when (or force-heading (not (org-insert-item)))
6025 (let* ((empty-line-p nil)
6026 (head (save-excursion
6027 (condition-case nil
6028 (progn
6029 (org-back-to-heading)
6030 (setq empty-line-p (org-previous-line-empty-p))
6031 (match-string 0))
6032 (error "*"))))
6033 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6034 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6035 pos hide-previous previous-pos)
6036 (cond
6037 ((and (org-on-heading-p) (bolp)
6038 (or (bobp)
6039 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6040 ;; insert before the current line
6041 (open-line (if blank 2 1)))
6042 ((and (bolp)
6043 (not org-insert-heading-respect-content)
6044 (or (bobp)
6045 (save-excursion
6046 (backward-char 1) (not (org-invisible-p)))))
6047 ;; insert right here
6048 nil)
6050 ;; somewhere in the line
6051 (save-excursion
6052 (setq previous-pos (point-at-bol))
6053 (end-of-line)
6054 (setq hide-previous (org-invisible-p)))
6055 (and org-insert-heading-respect-content (org-show-subtree))
6056 (let ((split
6057 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6058 (save-excursion
6059 (let ((p (point)))
6060 (goto-char (point-at-bol))
6061 (and (looking-at org-complex-heading-regexp)
6062 (> p (match-beginning 4)))))))
6063 tags pos)
6064 (cond
6065 (org-insert-heading-respect-content
6066 (org-end-of-subtree nil t)
6067 (or (bolp) (newline))
6068 (or (org-previous-line-empty-p)
6069 (and blank (newline)))
6070 (open-line 1))
6071 ((org-on-heading-p)
6072 (when hide-previous
6073 (show-children)
6074 (org-show-entry))
6075 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6076 (setq tags (and (match-end 2) (match-string 2)))
6077 (and (match-end 1)
6078 (delete-region (match-beginning 1) (match-end 1)))
6079 (setq pos (point-at-bol))
6080 (or split (end-of-line 1))
6081 (delete-horizontal-space)
6082 (newline (if blank 2 1))
6083 (when tags
6084 (save-excursion
6085 (goto-char pos)
6086 (end-of-line 1)
6087 (insert " " tags)
6088 (org-set-tags nil 'align))))
6090 (or split (end-of-line 1))
6091 (newline (if blank 2 1)))))))
6092 (insert head) (just-one-space)
6093 (setq pos (point))
6094 (end-of-line 1)
6095 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6096 (when (and org-insert-heading-respect-content hide-previous)
6097 (save-excursion
6098 (goto-char previous-pos)
6099 (hide-subtree)))
6100 (run-hooks 'org-insert-heading-hook)))))
6102 (defun org-get-heading (&optional no-tags)
6103 "Return the heading of the current entry, without the stars."
6104 (save-excursion
6105 (org-back-to-heading t)
6106 (if (looking-at
6107 (if no-tags
6108 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6109 "\\*+[ \t]+\\([^\r\n]*\\)"))
6110 (match-string 1) "")))
6112 (defun org-heading-components ()
6113 "Return the components of the current heading.
6114 This is a list with the following elements:
6115 - the level as an integer
6116 - the reduced level, different if `org-odd-levels-only' is set.
6117 - the TODO keyword, or nil
6118 - the priority character, like ?A, or nil if no priority is given
6119 - the headline text itself, or the tags string if no headline text
6120 - the tags string, or nil."
6121 (save-excursion
6122 (org-back-to-heading t)
6123 (if (looking-at org-complex-heading-regexp)
6124 (list (length (match-string 1))
6125 (org-reduced-level (length (match-string 1)))
6126 (org-match-string-no-properties 2)
6127 (and (match-end 3) (aref (match-string 3) 2))
6128 (org-match-string-no-properties 4)
6129 (org-match-string-no-properties 5)))))
6131 (defun org-get-entry ()
6132 "Get the entry text, after heading, entire subtree."
6133 (save-excursion
6134 (org-back-to-heading t)
6135 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6137 (defun org-insert-heading-after-current ()
6138 "Insert a new heading with same level as current, after current subtree."
6139 (interactive)
6140 (org-back-to-heading)
6141 (org-insert-heading)
6142 (org-move-subtree-down)
6143 (end-of-line 1))
6145 (defun org-insert-heading-respect-content ()
6146 (interactive)
6147 (let ((org-insert-heading-respect-content t))
6148 (org-insert-heading t)))
6150 (defun org-insert-todo-heading-respect-content (&optional force-state)
6151 (interactive "P")
6152 (let ((org-insert-heading-respect-content t))
6153 (org-insert-todo-heading force-state t)))
6155 (defun org-insert-todo-heading (arg &optional force-heading)
6156 "Insert a new heading with the same level and TODO state as current heading.
6157 If the heading has no TODO state, or if the state is DONE, use the first
6158 state (TODO by default). Also with prefix arg, force first state."
6159 (interactive "P")
6160 (when (or force-heading (not (org-insert-item 'checkbox)))
6161 (org-insert-heading force-heading)
6162 (save-excursion
6163 (org-back-to-heading)
6164 (outline-previous-heading)
6165 (looking-at org-todo-line-regexp))
6166 (let*
6167 ((new-mark-x
6168 (if (or arg
6169 (not (match-beginning 2))
6170 (member (match-string 2) org-done-keywords))
6171 (car org-todo-keywords-1)
6172 (match-string 2)))
6173 (new-mark
6175 (run-hook-with-args-until-success
6176 'org-todo-get-default-hook new-mark-x nil)
6177 new-mark-x)))
6178 (beginning-of-line 1)
6179 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6180 (if org-treat-insert-todo-heading-as-state-change
6181 (org-todo new-mark)
6182 (insert new-mark " "))))
6183 (when org-provide-todo-statistics
6184 (org-update-parent-todo-statistics))))
6186 (defun org-insert-subheading (arg)
6187 "Insert a new subheading and demote it.
6188 Works for outline headings and for plain lists alike."
6189 (interactive "P")
6190 (org-insert-heading arg)
6191 (cond
6192 ((org-on-heading-p) (org-do-demote))
6193 ((org-at-item-p) (org-indent-item 1))))
6195 (defun org-insert-todo-subheading (arg)
6196 "Insert a new subheading with TODO keyword or checkbox and demote it.
6197 Works for outline headings and for plain lists alike."
6198 (interactive "P")
6199 (org-insert-todo-heading arg)
6200 (cond
6201 ((org-on-heading-p) (org-do-demote))
6202 ((org-at-item-p) (org-indent-item 1))))
6204 ;;; Promotion and Demotion
6206 (defvar org-after-demote-entry-hook nil
6207 "Hook run after an entry has been demoted.
6208 The cursor will be at the beginning of the entry.
6209 When a subtree is being demoted, the hook will be called for each node.")
6211 (defvar org-after-promote-entry-hook nil
6212 "Hook run after an entry has been promoted.
6213 The cursor will be at the beginning of the entry.
6214 When a subtree is being promoted, the hook will be called for each node.")
6216 (defun org-promote-subtree ()
6217 "Promote the entire subtree.
6218 See also `org-promote'."
6219 (interactive)
6220 (save-excursion
6221 (org-map-tree 'org-promote))
6222 (org-fix-position-after-promote))
6224 (defun org-demote-subtree ()
6225 "Demote the entire subtree. See `org-demote'.
6226 See also `org-promote'."
6227 (interactive)
6228 (save-excursion
6229 (org-map-tree 'org-demote))
6230 (org-fix-position-after-promote))
6233 (defun org-do-promote ()
6234 "Promote the current heading higher up the tree.
6235 If the region is active in `transient-mark-mode', promote all headings
6236 in the region."
6237 (interactive)
6238 (save-excursion
6239 (if (org-region-active-p)
6240 (org-map-region 'org-promote (region-beginning) (region-end))
6241 (org-promote)))
6242 (org-fix-position-after-promote))
6244 (defun org-do-demote ()
6245 "Demote the current heading lower down the tree.
6246 If the region is active in `transient-mark-mode', demote all headings
6247 in the region."
6248 (interactive)
6249 (save-excursion
6250 (if (org-region-active-p)
6251 (org-map-region 'org-demote (region-beginning) (region-end))
6252 (org-demote)))
6253 (org-fix-position-after-promote))
6255 (defun org-fix-position-after-promote ()
6256 "Make sure that after pro/demotion cursor position is right."
6257 (let ((pos (point)))
6258 (when (save-excursion
6259 (beginning-of-line 1)
6260 (looking-at org-todo-line-regexp)
6261 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6262 (cond ((eobp) (insert " "))
6263 ((eolp) (insert " "))
6264 ((equal (char-after) ?\ ) (forward-char 1))))))
6266 (defun org-current-level ()
6267 "Return the level of the current entry, or nil if before the first headline.
6268 The level is the number of stars at the beginning of the headline."
6269 (save-excursion
6270 (condition-case nil
6271 (progn
6272 (org-back-to-heading t)
6273 (funcall outline-level))
6274 (error nil))))
6276 (defun org-reduced-level (l)
6277 "Compute the effective level of a heading.
6278 This takes into account the setting of `org-odd-levels-only'."
6279 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6281 (defun org-get-valid-level (level &optional change)
6282 "Rectify a level change under the influence of `org-odd-levels-only'
6283 LEVEL is a current level, CHANGE is by how much the level should be
6284 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6285 even level numbers will become the next higher odd number."
6286 (if org-odd-levels-only
6287 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6288 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6289 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6290 (max 1 (+ level (or change 0)))))
6292 (if (boundp 'define-obsolete-function-alias)
6293 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6294 (define-obsolete-function-alias 'org-get-legal-level
6295 'org-get-valid-level)
6296 (define-obsolete-function-alias 'org-get-legal-level
6297 'org-get-valid-level "23.1")))
6299 (defun org-promote ()
6300 "Promote the current heading higher up the tree.
6301 If the region is active in `transient-mark-mode', promote all headings
6302 in the region."
6303 (org-back-to-heading t)
6304 (let* ((level (save-match-data (funcall outline-level)))
6305 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6306 (diff (abs (- level (length up-head) -1))))
6307 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6308 (replace-match up-head nil t)
6309 ;; Fixup tag positioning
6310 (and org-auto-align-tags (org-set-tags nil t))
6311 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6312 (run-hooks 'org-after-promote-entry-hook)))
6314 (defun org-demote ()
6315 "Demote the current heading lower down the tree.
6316 If the region is active in `transient-mark-mode', demote all headings
6317 in the region."
6318 (org-back-to-heading t)
6319 (let* ((level (save-match-data (funcall outline-level)))
6320 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6321 (diff (abs (- level (length down-head) -1))))
6322 (replace-match down-head nil t)
6323 ;; Fixup tag positioning
6324 (and org-auto-align-tags (org-set-tags nil t))
6325 (if org-adapt-indentation (org-fixup-indentation diff))
6326 (run-hooks 'org-after-demote-entry-hook)))
6328 (defvar org-tab-ind-state nil)
6330 (defun org-cycle-level ()
6331 (let ((org-adapt-indentation nil))
6332 (when (and (looking-at "[ \t]*$")
6333 (org-looking-back
6334 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6335 (setq this-command 'org-cycle-level)
6336 (if (eq last-command 'org-cycle-level)
6337 (condition-case nil
6338 (progn (org-do-promote)
6339 (if (equal org-tab-ind-state (org-current-level))
6340 (org-do-promote)))
6341 (error
6342 (progn
6343 (save-excursion
6344 (beginning-of-line 1)
6345 (and (looking-at "\\*+")
6346 (replace-match
6347 (make-string org-tab-ind-state ?*))))
6348 (setq this-command 'org-cycle))))
6349 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6350 (org-do-demote))
6351 t)))
6353 (defun org-map-tree (fun)
6354 "Call FUN for every heading underneath the current one."
6355 (org-back-to-heading)
6356 (let ((level (funcall outline-level)))
6357 (save-excursion
6358 (funcall fun)
6359 (while (and (progn
6360 (outline-next-heading)
6361 (> (funcall outline-level) level))
6362 (not (eobp)))
6363 (funcall fun)))))
6365 (defun org-map-region (fun beg end)
6366 "Call FUN for every heading between BEG and END."
6367 (let ((org-ignore-region t))
6368 (save-excursion
6369 (setq end (copy-marker end))
6370 (goto-char beg)
6371 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6372 (< (point) end))
6373 (funcall fun))
6374 (while (and (progn
6375 (outline-next-heading)
6376 (< (point) end))
6377 (not (eobp)))
6378 (funcall fun)))))
6380 (defun org-fixup-indentation (diff)
6381 "Change the indentation in the current entry by DIFF
6382 However, if any line in the current entry has no indentation, or if it
6383 would end up with no indentation after the change, nothing at all is done."
6384 (save-excursion
6385 (let ((end (save-excursion (outline-next-heading)
6386 (point-marker)))
6387 (prohibit (if (> diff 0)
6388 "^\\S-"
6389 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6390 col)
6391 (unless (save-excursion (end-of-line 1)
6392 (re-search-forward prohibit end t))
6393 (while (and (< (point) end)
6394 (re-search-forward "^[ \t]+" end t))
6395 (goto-char (match-end 0))
6396 (setq col (current-column))
6397 (if (< diff 0) (replace-match ""))
6398 (org-indent-to-column (+ diff col))))
6399 (move-marker end nil))))
6401 (defun org-convert-to-odd-levels ()
6402 "Convert an org-mode file with all levels allowed to one with odd levels.
6403 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6404 level 5 etc."
6405 (interactive)
6406 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6407 (let ((outline-regexp org-outline-regexp)
6408 (outline-level 'org-outline-level)
6409 (org-odd-levels-only nil) n)
6410 (save-excursion
6411 (goto-char (point-min))
6412 (while (re-search-forward "^\\*\\*+ " nil t)
6413 (setq n (- (length (match-string 0)) 2))
6414 (while (>= (setq n (1- n)) 0)
6415 (org-demote))
6416 (end-of-line 1))))))
6418 (defun org-convert-to-oddeven-levels ()
6419 "Convert an org-mode file with only odd levels to one with odd and even levels.
6420 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6421 section with an even level, conversion would destroy the structure of the file. An error
6422 is signaled in this case."
6423 (interactive)
6424 (goto-char (point-min))
6425 ;; First check if there are no even levels
6426 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6427 (org-show-context t)
6428 (error "Not all levels are odd in this file. Conversion not possible"))
6429 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6430 (let ((outline-regexp org-outline-regexp)
6431 (outline-level 'org-outline-level)
6432 (org-odd-levels-only nil) n)
6433 (save-excursion
6434 (goto-char (point-min))
6435 (while (re-search-forward "^\\*\\*+ " nil t)
6436 (setq n (/ (1- (length (match-string 0))) 2))
6437 (while (>= (setq n (1- n)) 0)
6438 (org-promote))
6439 (end-of-line 1))))))
6441 (defun org-tr-level (n)
6442 "Make N odd if required."
6443 (if org-odd-levels-only (1+ (/ n 2)) n))
6445 ;;; Vertical tree motion, cutting and pasting of subtrees
6447 (defun org-move-subtree-up (&optional arg)
6448 "Move the current subtree up past ARG headlines of the same level."
6449 (interactive "p")
6450 (org-move-subtree-down (- (prefix-numeric-value arg))))
6452 (defun org-move-subtree-down (&optional arg)
6453 "Move the current subtree down past ARG headlines of the same level."
6454 (interactive "p")
6455 (setq arg (prefix-numeric-value arg))
6456 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6457 'org-get-last-sibling))
6458 (ins-point (make-marker))
6459 (cnt (abs arg))
6460 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6461 ;; Select the tree
6462 (org-back-to-heading)
6463 (setq beg0 (point))
6464 (save-excursion
6465 (setq ne-beg (org-back-over-empty-lines))
6466 (setq beg (point)))
6467 (save-match-data
6468 (save-excursion (outline-end-of-heading)
6469 (setq folded (org-invisible-p)))
6470 (outline-end-of-subtree))
6471 (outline-next-heading)
6472 (setq ne-end (org-back-over-empty-lines))
6473 (setq end (point))
6474 (goto-char beg0)
6475 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6476 ;; include less whitespace
6477 (save-excursion
6478 (goto-char beg)
6479 (forward-line (- ne-beg ne-end))
6480 (setq beg (point))))
6481 ;; Find insertion point, with error handling
6482 (while (> cnt 0)
6483 (or (and (funcall movfunc) (looking-at outline-regexp))
6484 (progn (goto-char beg0)
6485 (error "Cannot move past superior level or buffer limit")))
6486 (setq cnt (1- cnt)))
6487 (if (> arg 0)
6488 ;; Moving forward - still need to move over subtree
6489 (progn (org-end-of-subtree t t)
6490 (save-excursion
6491 (org-back-over-empty-lines)
6492 (or (bolp) (newline)))))
6493 (setq ne-ins (org-back-over-empty-lines))
6494 (move-marker ins-point (point))
6495 (setq txt (buffer-substring beg end))
6496 (org-save-markers-in-region beg end)
6497 (delete-region beg end)
6498 (org-remove-empty-overlays-at beg)
6499 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6500 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6501 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6502 (let ((bbb (point)))
6503 (insert-before-markers txt)
6504 (org-reinstall-markers-in-region bbb)
6505 (move-marker ins-point bbb))
6506 (or (bolp) (insert "\n"))
6507 (setq ins-end (point))
6508 (goto-char ins-point)
6509 (org-skip-whitespace)
6510 (when (and (< arg 0)
6511 (org-first-sibling-p)
6512 (> ne-ins ne-beg))
6513 ;; Move whitespace back to beginning
6514 (save-excursion
6515 (goto-char ins-end)
6516 (let ((kill-whole-line t))
6517 (kill-line (- ne-ins ne-beg)) (point)))
6518 (insert (make-string (- ne-ins ne-beg) ?\n)))
6519 (move-marker ins-point nil)
6520 (if folded
6521 (hide-subtree)
6522 (org-show-entry)
6523 (show-children)
6524 (org-cycle-hide-drawers 'children))
6525 (org-clean-visibility-after-subtree-move)))
6527 (defvar org-subtree-clip ""
6528 "Clipboard for cut and paste of subtrees.
6529 This is actually only a copy of the kill, because we use the normal kill
6530 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6532 (defvar org-subtree-clip-folded nil
6533 "Was the last copied subtree folded?
6534 This is used to fold the tree back after pasting.")
6536 (defun org-cut-subtree (&optional n)
6537 "Cut the current subtree into the clipboard.
6538 With prefix arg N, cut this many sequential subtrees.
6539 This is a short-hand for marking the subtree and then cutting it."
6540 (interactive "p")
6541 (org-copy-subtree n 'cut))
6543 (defun org-copy-subtree (&optional n cut force-store-markers)
6544 "Cut the current subtree into the clipboard.
6545 With prefix arg N, cut this many sequential subtrees.
6546 This is a short-hand for marking the subtree and then copying it.
6547 If CUT is non-nil, actually cut the subtree.
6548 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6549 of some markers in the region, even if CUT is non-nil. This is
6550 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6551 (interactive "p")
6552 (let (beg end folded (beg0 (point)))
6553 (if (interactive-p)
6554 (org-back-to-heading nil) ; take what looks like a subtree
6555 (org-back-to-heading t)) ; take what is really there
6556 (org-back-over-empty-lines)
6557 (setq beg (point))
6558 (skip-chars-forward " \t\r\n")
6559 (save-match-data
6560 (save-excursion (outline-end-of-heading)
6561 (setq folded (org-invisible-p)))
6562 (condition-case nil
6563 (org-forward-same-level (1- n) t)
6564 (error nil))
6565 (org-end-of-subtree t t))
6566 (org-back-over-empty-lines)
6567 (setq end (point))
6568 (goto-char beg0)
6569 (when (> end beg)
6570 (setq org-subtree-clip-folded folded)
6571 (when (or cut force-store-markers)
6572 (org-save-markers-in-region beg end))
6573 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6574 (setq org-subtree-clip (current-kill 0))
6575 (message "%s: Subtree(s) with %d characters"
6576 (if cut "Cut" "Copied")
6577 (length org-subtree-clip)))))
6579 (defun org-paste-subtree (&optional level tree for-yank)
6580 "Paste the clipboard as a subtree, with modification of headline level.
6581 The entire subtree is promoted or demoted in order to match a new headline
6582 level.
6584 If the cursor is at the beginning of a headline, the same level as
6585 that headline is used to paste the tree
6587 If not, the new level is derived from the *visible* headings
6588 before and after the insertion point, and taken to be the inferior headline
6589 level of the two. So if the previous visible heading is level 3 and the
6590 next is level 4 (or vice versa), level 4 will be used for insertion.
6591 This makes sure that the subtree remains an independent subtree and does
6592 not swallow low level entries.
6594 You can also force a different level, either by using a numeric prefix
6595 argument, or by inserting the heading marker by hand. For example, if the
6596 cursor is after \"*****\", then the tree will be shifted to level 5.
6598 If optional TREE is given, use this text instead of the kill ring.
6600 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6601 move back over whitespace before inserting, and move point to the end of
6602 the inserted text when done."
6603 (interactive "P")
6604 (setq tree (or tree (and kill-ring (current-kill 0))))
6605 (unless (org-kill-is-subtree-p tree)
6606 (error "%s"
6607 (substitute-command-keys
6608 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6609 (let* ((visp (not (org-invisible-p)))
6610 (txt tree)
6611 (^re (concat "^\\(" outline-regexp "\\)"))
6612 (re (concat "\\(" outline-regexp "\\)"))
6613 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6615 (old-level (if (string-match ^re txt)
6616 (- (match-end 0) (match-beginning 0) 1)
6617 -1))
6618 (force-level (cond (level (prefix-numeric-value level))
6619 ((and (looking-at "[ \t]*$")
6620 (string-match
6621 ^re_ (buffer-substring
6622 (point-at-bol) (point))))
6623 (- (match-end 1) (match-beginning 1)))
6624 ((and (bolp)
6625 (looking-at org-outline-regexp))
6626 (- (match-end 0) (point) 1))
6627 (t nil)))
6628 (previous-level (save-excursion
6629 (condition-case nil
6630 (progn
6631 (outline-previous-visible-heading 1)
6632 (if (looking-at re)
6633 (- (match-end 0) (match-beginning 0) 1)
6635 (error 1))))
6636 (next-level (save-excursion
6637 (condition-case nil
6638 (progn
6639 (or (looking-at outline-regexp)
6640 (outline-next-visible-heading 1))
6641 (if (looking-at re)
6642 (- (match-end 0) (match-beginning 0) 1)
6644 (error 1))))
6645 (new-level (or force-level (max previous-level next-level)))
6646 (shift (if (or (= old-level -1)
6647 (= new-level -1)
6648 (= old-level new-level))
6650 (- new-level old-level)))
6651 (delta (if (> shift 0) -1 1))
6652 (func (if (> shift 0) 'org-demote 'org-promote))
6653 (org-odd-levels-only nil)
6654 beg end newend)
6655 ;; Remove the forced level indicator
6656 (if force-level
6657 (delete-region (point-at-bol) (point)))
6658 ;; Paste
6659 (beginning-of-line 1)
6660 (unless for-yank (org-back-over-empty-lines))
6661 (setq beg (point))
6662 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6663 (insert-before-markers txt)
6664 (unless (string-match "\n\\'" txt) (insert "\n"))
6665 (setq newend (point))
6666 (org-reinstall-markers-in-region beg)
6667 (setq end (point))
6668 (goto-char beg)
6669 (skip-chars-forward " \t\n\r")
6670 (setq beg (point))
6671 (if (and (org-invisible-p) visp)
6672 (save-excursion (outline-show-heading)))
6673 ;; Shift if necessary
6674 (unless (= shift 0)
6675 (save-restriction
6676 (narrow-to-region beg end)
6677 (while (not (= shift 0))
6678 (org-map-region func (point-min) (point-max))
6679 (setq shift (+ delta shift)))
6680 (goto-char (point-min))
6681 (setq newend (point-max))))
6682 (when (or (interactive-p) for-yank)
6683 (message "Clipboard pasted as level %d subtree" new-level))
6684 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6685 kill-ring
6686 (eq org-subtree-clip (current-kill 0))
6687 org-subtree-clip-folded)
6688 ;; The tree was folded before it was killed/copied
6689 (hide-subtree))
6690 (and for-yank (goto-char newend))))
6692 (defun org-kill-is-subtree-p (&optional txt)
6693 "Check if the current kill is an outline subtree, or a set of trees.
6694 Returns nil if kill does not start with a headline, or if the first
6695 headline level is not the largest headline level in the tree.
6696 So this will actually accept several entries of equal levels as well,
6697 which is OK for `org-paste-subtree'.
6698 If optional TXT is given, check this string instead of the current kill."
6699 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6700 (start-level (and kill
6701 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6702 org-outline-regexp "\\)")
6703 kill)
6704 (- (match-end 2) (match-beginning 2) 1)))
6705 (re (concat "^" org-outline-regexp))
6706 (start (1+ (or (match-beginning 2) -1))))
6707 (if (not start-level)
6708 (progn
6709 nil) ;; does not even start with a heading
6710 (catch 'exit
6711 (while (setq start (string-match re kill (1+ start)))
6712 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6713 (throw 'exit nil)))
6714 t))))
6716 (defvar org-markers-to-move nil
6717 "Markers that should be moved with a cut-and-paste operation.
6718 Those markers are stored together with their positions relative to
6719 the start of the region.")
6721 (defun org-save-markers-in-region (beg end)
6722 "Check markers in region.
6723 If these markers are between BEG and END, record their position relative
6724 to BEG, so that after moving the block of text, we can put the markers back
6725 into place.
6726 This function gets called just before an entry or tree gets cut from the
6727 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6728 called immediately, to move the markers with the entries."
6729 (setq org-markers-to-move nil)
6730 (when (featurep 'org-clock)
6731 (org-clock-save-markers-for-cut-and-paste beg end))
6732 (when (featurep 'org-agenda)
6733 (org-agenda-save-markers-for-cut-and-paste beg end)))
6735 (defun org-check-and-save-marker (marker beg end)
6736 "Check if MARKER is between BEG and END.
6737 If yes, remember the marker and the distance to BEG."
6738 (when (and (marker-buffer marker)
6739 (equal (marker-buffer marker) (current-buffer)))
6740 (if (and (>= marker beg) (< marker end))
6741 (push (cons marker (- marker beg)) org-markers-to-move))))
6743 (defun org-reinstall-markers-in-region (beg)
6744 "Move all remembered markers to their position relative to BEG."
6745 (mapc (lambda (x)
6746 (move-marker (car x) (+ beg (cdr x))))
6747 org-markers-to-move)
6748 (setq org-markers-to-move nil))
6750 (defun org-narrow-to-subtree ()
6751 "Narrow buffer to the current subtree."
6752 (interactive)
6753 (save-excursion
6754 (save-match-data
6755 (narrow-to-region
6756 (progn (org-back-to-heading t) (point))
6757 (progn (org-end-of-subtree t t) (point))))))
6759 (defun org-clone-subtree-with-time-shift (n &optional shift)
6760 "Clone the task (subtree) at point N times.
6761 The clones will be inserted as siblings.
6763 In interactive use, the user will be prompted for the number of clones
6764 to be produced, and for a time SHIFT, which may be a repeater as used
6765 in time stamps, for example `+3d'.
6767 When a valid repeater is given and the entry contains any time stamps,
6768 the clones will become a sequence in time, with time stamps in the
6769 subtree shifted for each clone produced. If SHIFT is nil or the
6770 empty string, time stamps will be left alone.
6772 If the original subtree did contain time stamps with a repeater,
6773 the following will happen:
6774 - the repeater will be removed in each clone
6775 - an additional clone will be produced, with the current, unshifted
6776 date(s) in the entry.
6777 - the original entry will be placed *after* all the clones, with
6778 repeater intact.
6779 - the start days in the repeater in the original entry will be shifted
6780 to past the last clone.
6781 I this way you can spell out a number of instances of a repeating task,
6782 and still retain the repeater to cover future instances of the task."
6783 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6784 (let (beg end template task
6785 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6786 (if (not (and (integerp n) (> n 0)))
6787 (error "Invalid number of replications %s" n))
6788 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6789 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6790 shift)))
6791 (error "Invalid shift specification %s" shift))
6792 (when doshift
6793 (setq shift-n (string-to-number (match-string 1 shift))
6794 shift-what (cdr (assoc (match-string 2 shift)
6795 '(("d" . day) ("w" . week)
6796 ("m" . month) ("y" . year))))))
6797 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6798 (setq nmin 1 nmax n)
6799 (org-back-to-heading t)
6800 (setq beg (point))
6801 (org-end-of-subtree t t)
6802 (or (bolp) (insert "\n"))
6803 (setq end (point))
6804 (setq template (buffer-substring beg end))
6805 (when (and doshift
6806 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6807 (delete-region beg end)
6808 (setq end beg)
6809 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6810 (goto-char end)
6811 (loop for n from nmin to nmax do
6812 (if (not doshift)
6813 (setq task template)
6814 (with-temp-buffer
6815 (insert template)
6816 (org-mode)
6817 (goto-char (point-min))
6818 (while (re-search-forward org-ts-regexp-both nil t)
6819 (org-timestamp-change (* n shift-n) shift-what))
6820 (unless (= n n-no-remove)
6821 (goto-char (point-min))
6822 (while (re-search-forward org-ts-regexp nil t)
6823 (save-excursion
6824 (goto-char (match-beginning 0))
6825 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6826 (delete-region (match-beginning 1) (match-end 1))))))
6827 (setq task (buffer-string))))
6828 (insert task))
6829 (goto-char beg)))
6831 ;;; Outline Sorting
6833 (defun org-sort (with-case)
6834 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6835 Optional argument WITH-CASE means sort case-sensitively.
6836 With a double prefix argument, also remove duplicate entries."
6837 (interactive "P")
6838 (if (org-at-table-p)
6839 (org-call-with-arg 'org-table-sort-lines with-case)
6840 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6842 (defun org-sort-remove-invisible (s)
6843 (remove-text-properties 0 (length s) org-rm-props s)
6844 (while (string-match org-bracket-link-regexp s)
6845 (setq s (replace-match (if (match-end 2)
6846 (match-string 3 s)
6847 (match-string 1 s)) t t s)))
6850 (defvar org-priority-regexp) ; defined later in the file
6852 (defvar org-after-sorting-entries-or-items-hook nil
6853 "Hook that is run after a bunch of entries or items have been sorted.
6854 When children are sorted, the cursor is in the parent line when this
6855 hook gets called. When a region or a plain list is sorted, the cursor
6856 will be in the first entry of the sorted region/list.")
6858 (defun org-sort-entries-or-items
6859 (&optional with-case sorting-type getkey-func compare-func property)
6860 "Sort entries on a certain level of an outline tree, or plain list items.
6861 If there is an active region, the entries in the region are sorted.
6862 Else, if the cursor is before the first entry, sort the top-level items.
6863 Else, the children of the entry at point are sorted.
6864 If the cursor is at the first item in a plain list, the list items will be
6865 sorted.
6867 Sorting can be alphabetically, numerically, by date/time as given by
6868 a time stamp, by a property or by priority.
6870 The command prompts for the sorting type unless it has been given to the
6871 function through the SORTING-TYPE argument, which needs to a character,
6872 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6873 precise meaning of each character:
6875 n Numerically, by converting the beginning of the entry/item to a number.
6876 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6877 t By date/time, either the first active time stamp in the entry, or, if
6878 none exist, by the first inactive one.
6879 In items, only the first line will be checked.
6880 s By the scheduled date/time.
6881 d By deadline date/time.
6882 c By creation time, which is assumed to be the first inactive time stamp
6883 at the beginning of a line.
6884 p By priority according to the cookie.
6885 r By the value of a property.
6887 Capital letters will reverse the sort order.
6889 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6890 called with point at the beginning of the record. It must return either
6891 a string or a number that should serve as the sorting key for that record.
6893 Comparing entries ignores case by default. However, with an optional argument
6894 WITH-CASE, the sorting considers case as well."
6895 (interactive "P")
6896 (let ((case-func (if with-case 'identity 'downcase))
6897 start beg end stars re re2
6898 txt what tmp plain-list-p)
6899 ;; Find beginning and end of region to sort
6900 (cond
6901 ((org-region-active-p)
6902 ;; we will sort the region
6903 (setq end (region-end)
6904 what "region")
6905 (goto-char (region-beginning))
6906 (if (not (org-on-heading-p)) (outline-next-heading))
6907 (setq start (point)))
6908 ((org-at-item-p)
6909 ;; we will sort this plain list
6910 (org-beginning-of-item-list) (setq start (point))
6911 (org-end-of-item-list)
6912 (or (bolp) (insert "\n"))
6913 (setq end (point))
6914 (goto-char start)
6915 (setq plain-list-p t
6916 what "plain list"))
6917 ((or (org-on-heading-p)
6918 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6919 ;; we will sort the children of the current headline
6920 (org-back-to-heading)
6921 (setq start (point)
6922 end (progn (org-end-of-subtree t t)
6923 (or (bolp) (insert "\n"))
6924 (org-back-over-empty-lines)
6925 (point))
6926 what "children")
6927 (goto-char start)
6928 (show-subtree)
6929 (outline-next-heading))
6931 ;; we will sort the top-level entries in this file
6932 (goto-char (point-min))
6933 (or (org-on-heading-p) (outline-next-heading))
6934 (setq start (point))
6935 (goto-char (point-max))
6936 (beginning-of-line 1)
6937 (when (looking-at ".*?\\S-")
6938 ;; File ends in a non-white line
6939 (end-of-line 1)
6940 (insert "\n"))
6941 (setq end (point-max))
6942 (setq what "top-level")
6943 (goto-char start)
6944 (show-all)))
6946 (setq beg (point))
6947 (if (>= beg end) (error "Nothing to sort"))
6949 (unless plain-list-p
6950 (looking-at "\\(\\*+\\)")
6951 (setq stars (match-string 1)
6952 re (concat "^" (regexp-quote stars) " +")
6953 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6954 txt (buffer-substring beg end))
6955 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6956 (if (and (not (equal stars "*")) (string-match re2 txt))
6957 (error "Region to sort contains a level above the first entry")))
6959 (unless sorting-type
6960 (message
6961 (if plain-list-p
6962 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6963 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6964 [t]ime [s]cheduled [d]eadline [c]reated
6965 A/N/T/S/D/C/P/O/F means reversed:")
6966 what)
6967 (setq sorting-type (read-char-exclusive))
6969 (and (= (downcase sorting-type) ?f)
6970 (setq getkey-func
6971 (org-icompleting-read "Sort using function: "
6972 obarray 'fboundp t nil nil))
6973 (setq getkey-func (intern getkey-func)))
6975 (and (= (downcase sorting-type) ?r)
6976 (setq property
6977 (org-icompleting-read "Property: "
6978 (mapcar 'list (org-buffer-property-keys t))
6979 nil t))))
6981 (message "Sorting entries...")
6983 (save-restriction
6984 (narrow-to-region start end)
6986 (let ((dcst (downcase sorting-type))
6987 (case-fold-search nil)
6988 (now (current-time)))
6989 (sort-subr
6990 (/= dcst sorting-type)
6991 ;; This function moves to the beginning character of the "record" to
6992 ;; be sorted.
6993 (if plain-list-p
6994 (lambda nil
6995 (if (org-at-item-p) t (goto-char (point-max))))
6996 (lambda nil
6997 (if (re-search-forward re nil t)
6998 (goto-char (match-beginning 0))
6999 (goto-char (point-max)))))
7000 ;; This function moves to the last character of the "record" being
7001 ;; sorted.
7002 (if plain-list-p
7003 'org-end-of-item
7004 (lambda nil
7005 (save-match-data
7006 (condition-case nil
7007 (outline-forward-same-level 1)
7008 (error
7009 (goto-char (point-max)))))))
7011 ;; This function returns the value that gets sorted against.
7012 (if plain-list-p
7013 (lambda nil
7014 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7015 (cond
7016 ((= dcst ?n)
7017 (string-to-number (buffer-substring (match-end 0)
7018 (point-at-eol))))
7019 ((= dcst ?a)
7020 (buffer-substring (match-end 0) (point-at-eol)))
7021 ((= dcst ?t)
7022 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7023 (re-search-forward org-ts-regexp-both
7024 (point-at-eol) t))
7025 (org-time-string-to-seconds (match-string 0))
7026 (org-float-time now)))
7027 ((= dcst ?f)
7028 (if getkey-func
7029 (progn
7030 (setq tmp (funcall getkey-func))
7031 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7032 tmp)
7033 (error "Invalid key function `%s'" getkey-func)))
7034 (t (error "Invalid sorting type `%c'" sorting-type)))))
7035 (lambda nil
7036 (cond
7037 ((= dcst ?n)
7038 (if (looking-at org-complex-heading-regexp)
7039 (string-to-number (match-string 4))
7040 nil))
7041 ((= dcst ?a)
7042 (if (looking-at org-complex-heading-regexp)
7043 (funcall case-func (match-string 4))
7044 nil))
7045 ((= dcst ?t)
7046 (let ((end (save-excursion (outline-next-heading) (point))))
7047 (if (or (re-search-forward org-ts-regexp end t)
7048 (re-search-forward org-ts-regexp-both end t))
7049 (org-time-string-to-seconds (match-string 0))
7050 (org-float-time now))))
7051 ((= dcst ?c)
7052 (let ((end (save-excursion (outline-next-heading) (point))))
7053 (if (re-search-forward
7054 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7055 end t)
7056 (org-time-string-to-seconds (match-string 0))
7057 (org-float-time now))))
7058 ((= dcst ?s)
7059 (let ((end (save-excursion (outline-next-heading) (point))))
7060 (if (re-search-forward org-scheduled-time-regexp end t)
7061 (org-time-string-to-seconds (match-string 1))
7062 (org-float-time now))))
7063 ((= dcst ?d)
7064 (let ((end (save-excursion (outline-next-heading) (point))))
7065 (if (re-search-forward org-deadline-time-regexp end t)
7066 (org-time-string-to-seconds (match-string 1))
7067 (org-float-time now))))
7068 ((= dcst ?p)
7069 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7070 (string-to-char (match-string 2))
7071 org-default-priority))
7072 ((= dcst ?r)
7073 (or (org-entry-get nil property) ""))
7074 ((= dcst ?o)
7075 (if (looking-at org-complex-heading-regexp)
7076 (- 9999 (length (member (match-string 2)
7077 org-todo-keywords-1)))))
7078 ((= dcst ?f)
7079 (if getkey-func
7080 (progn
7081 (setq tmp (funcall getkey-func))
7082 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7083 tmp)
7084 (error "Invalid key function `%s'" getkey-func)))
7085 (t (error "Invalid sorting type `%c'" sorting-type)))))
7087 (cond
7088 ((= dcst ?a) 'string<)
7089 ((= dcst ?f) compare-func)
7090 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7091 (t nil)))))
7092 (run-hooks 'org-after-sorting-entries-or-items-hook)
7093 (message "Sorting entries...done")))
7095 (defun org-do-sort (table what &optional with-case sorting-type)
7096 "Sort TABLE of WHAT according to SORTING-TYPE.
7097 The user will be prompted for the SORTING-TYPE if the call to this
7098 function does not specify it. WHAT is only for the prompt, to indicate
7099 what is being sorted. The sorting key will be extracted from
7100 the car of the elements of the table.
7101 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7102 (unless sorting-type
7103 (message
7104 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7105 what)
7106 (setq sorting-type (read-char-exclusive)))
7107 (let ((dcst (downcase sorting-type))
7108 extractfun comparefun)
7109 ;; Define the appropriate functions
7110 (cond
7111 ((= dcst ?n)
7112 (setq extractfun 'string-to-number
7113 comparefun (if (= dcst sorting-type) '< '>)))
7114 ((= dcst ?a)
7115 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7116 (lambda(x) (downcase (org-sort-remove-invisible x))))
7117 comparefun (if (= dcst sorting-type)
7118 'string<
7119 (lambda (a b) (and (not (string< a b))
7120 (not (string= a b)))))))
7121 ((= dcst ?t)
7122 (setq extractfun
7123 (lambda (x)
7124 (if (or (string-match org-ts-regexp x)
7125 (string-match org-ts-regexp-both x))
7126 (org-float-time
7127 (org-time-string-to-time (match-string 0 x)))
7129 comparefun (if (= dcst sorting-type) '< '>)))
7130 (t (error "Invalid sorting type `%c'" sorting-type)))
7132 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7133 table)
7134 (lambda (a b) (funcall comparefun (car a) (car b))))))
7137 ;;; The orgstruct minor mode
7139 ;; Define a minor mode which can be used in other modes in order to
7140 ;; integrate the org-mode structure editing commands.
7142 ;; This is really a hack, because the org-mode structure commands use
7143 ;; keys which normally belong to the major mode. Here is how it
7144 ;; works: The minor mode defines all the keys necessary to operate the
7145 ;; structure commands, but wraps the commands into a function which
7146 ;; tests if the cursor is currently at a headline or a plain list
7147 ;; item. If that is the case, the structure command is used,
7148 ;; temporarily setting many Org-mode variables like regular
7149 ;; expressions for filling etc. However, when any of those keys is
7150 ;; used at a different location, function uses `key-binding' to look
7151 ;; up if the key has an associated command in another currently active
7152 ;; keymap (minor modes, major mode, global), and executes that
7153 ;; command. There might be problems if any of the keys is otherwise
7154 ;; used as a prefix key.
7156 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7157 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7158 ;; addresses this by checking explicitly for both bindings.
7160 (defvar orgstruct-mode-map (make-sparse-keymap)
7161 "Keymap for the minor `orgstruct-mode'.")
7163 (defvar org-local-vars nil
7164 "List of local variables, for use by `orgstruct-mode'")
7166 ;;;###autoload
7167 (define-minor-mode orgstruct-mode
7168 "Toggle the minor more `orgstruct-mode'.
7169 This mode is for using Org-mode structure commands in other modes.
7170 The following key behave as if Org-mode was active, if the cursor
7171 is on a headline, or on a plain list item (both in the definition
7172 of Org-mode).
7174 M-up Move entry/item up
7175 M-down Move entry/item down
7176 M-left Promote
7177 M-right Demote
7178 M-S-up Move entry/item up
7179 M-S-down Move entry/item down
7180 M-S-left Promote subtree
7181 M-S-right Demote subtree
7182 M-q Fill paragraph and items like in Org-mode
7183 C-c ^ Sort entries
7184 C-c - Cycle list bullet
7185 TAB Cycle item visibility
7186 M-RET Insert new heading/item
7187 S-M-RET Insert new TODO heading / Checkbox item
7188 C-c C-c Set tags / toggle checkbox"
7189 nil " OrgStruct" nil
7190 (org-load-modules-maybe)
7191 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7193 ;;;###autoload
7194 (defun turn-on-orgstruct ()
7195 "Unconditionally turn on `orgstruct-mode'."
7196 (orgstruct-mode 1))
7198 (defun orgstruct++-mode (&optional arg)
7199 "Toggle `orgstruct-mode', the enhanced version of it.
7200 In addition to setting orgstruct-mode, this also exports all indentation
7201 and autofilling variables from org-mode into the buffer. It will also
7202 recognize item context in multiline items.
7203 Note that turning off orgstruct-mode will *not* remove the
7204 indentation/paragraph settings. This can only be done by refreshing the
7205 major mode, for example with \\[normal-mode]."
7206 (interactive "P")
7207 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7208 (if (< arg 1)
7209 (orgstruct-mode -1)
7210 (orgstruct-mode 1)
7211 (let (var val)
7212 (mapc
7213 (lambda (x)
7214 (when (string-match
7215 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7216 (symbol-name (car x)))
7217 (setq var (car x) val (nth 1 x))
7218 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7219 org-local-vars)
7220 (org-set-local 'orgstruct-is-++ t))))
7222 (defvar orgstruct-is-++ nil
7223 "Is orgstruct-mode in ++ version in the current-buffer?")
7224 (make-variable-buffer-local 'orgstruct-is-++)
7226 ;;;###autoload
7227 (defun turn-on-orgstruct++ ()
7228 "Unconditionally turn on `orgstruct++-mode'."
7229 (orgstruct++-mode 1))
7231 (defun orgstruct-error ()
7232 "Error when there is no default binding for a structure key."
7233 (interactive)
7234 (error "This key has no function outside structure elements"))
7236 (defun orgstruct-setup ()
7237 "Setup orgstruct keymaps."
7238 (let ((nfunc 0)
7239 (bindings
7240 (list
7241 '([(meta up)] org-metaup)
7242 '([(meta down)] org-metadown)
7243 '([(meta left)] org-metaleft)
7244 '([(meta right)] org-metaright)
7245 '([(meta shift up)] org-shiftmetaup)
7246 '([(meta shift down)] org-shiftmetadown)
7247 '([(meta shift left)] org-shiftmetaleft)
7248 '([(meta shift right)] org-shiftmetaright)
7249 '([?\e (up)] org-metaup)
7250 '([?\e (down)] org-metadown)
7251 '([?\e (left)] org-metaleft)
7252 '([?\e (right)] org-metaright)
7253 '([?\e (shift up)] org-shiftmetaup)
7254 '([?\e (shift down)] org-shiftmetadown)
7255 '([?\e (shift left)] org-shiftmetaleft)
7256 '([?\e (shift right)] org-shiftmetaright)
7257 '([(shift up)] org-shiftup)
7258 '([(shift down)] org-shiftdown)
7259 '([(shift left)] org-shiftleft)
7260 '([(shift right)] org-shiftright)
7261 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7262 '("\M-q" fill-paragraph)
7263 '("\C-c^" org-sort)
7264 '("\C-c-" org-cycle-list-bullet)))
7265 elt key fun cmd)
7266 (while (setq elt (pop bindings))
7267 (setq nfunc (1+ nfunc))
7268 (setq key (org-key (car elt))
7269 fun (nth 1 elt)
7270 cmd (orgstruct-make-binding fun nfunc key))
7271 (org-defkey orgstruct-mode-map key cmd))
7273 ;; Special treatment needed for TAB and RET
7274 (org-defkey orgstruct-mode-map [(tab)]
7275 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7276 (org-defkey orgstruct-mode-map "\C-i"
7277 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7279 (org-defkey orgstruct-mode-map "\M-\C-m"
7280 (orgstruct-make-binding 'org-insert-heading 105
7281 "\M-\C-m" [(meta return)]))
7282 (org-defkey orgstruct-mode-map [(meta return)]
7283 (orgstruct-make-binding 'org-insert-heading 106
7284 [(meta return)] "\M-\C-m"))
7286 (org-defkey orgstruct-mode-map [(shift meta return)]
7287 (orgstruct-make-binding 'org-insert-todo-heading 107
7288 [(meta return)] "\M-\C-m"))
7290 (org-defkey orgstruct-mode-map "\e\C-m"
7291 (orgstruct-make-binding 'org-insert-heading 108
7292 "\e\C-m" [?\e (return)]))
7293 (org-defkey orgstruct-mode-map [?\e (return)]
7294 (orgstruct-make-binding 'org-insert-heading 109
7295 [?\e (return)] "\e\C-m"))
7296 (org-defkey orgstruct-mode-map [?\e (shift return)]
7297 (orgstruct-make-binding 'org-insert-todo-heading 110
7298 [?\e (return)] "\e\C-m"))
7300 (unless org-local-vars
7301 (setq org-local-vars (org-get-local-variables)))
7305 (defun orgstruct-make-binding (fun n &rest keys)
7306 "Create a function for binding in the structure minor mode.
7307 FUN is the command to call inside a table. N is used to create a unique
7308 command name. KEYS are keys that should be checked in for a command
7309 to execute outside of tables."
7310 (eval
7311 (list 'defun
7312 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7313 '(arg)
7314 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7315 "Outside of structure, run the binding of `"
7316 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7317 "'.")
7318 '(interactive "p")
7319 (list 'if
7320 `(org-context-p 'headline 'item
7321 (and orgstruct-is-++
7322 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7323 'item-body))
7324 (list 'org-run-like-in-org-mode (list 'quote fun))
7325 (list 'let '(orgstruct-mode)
7326 (list 'call-interactively
7327 (append '(or)
7328 (mapcar (lambda (k)
7329 (list 'key-binding k))
7330 keys)
7331 '('orgstruct-error))))))))
7333 (defun org-context-p (&rest contexts)
7334 "Check if local context is any of CONTEXTS.
7335 Possible values in the list of contexts are `table', `headline', and `item'."
7336 (let ((pos (point)))
7337 (goto-char (point-at-bol))
7338 (prog1 (or (and (memq 'table contexts)
7339 (looking-at "[ \t]*|"))
7340 (and (memq 'headline contexts)
7341 ;;????????? (looking-at "\\*+"))
7342 (looking-at outline-regexp))
7343 (and (memq 'item contexts)
7344 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7345 (and (memq 'item-body contexts)
7346 (org-in-item-p)))
7347 (goto-char pos))))
7349 (defun org-get-local-variables ()
7350 "Return a list of all local variables in an org-mode buffer."
7351 (let (varlist)
7352 (with-current-buffer (get-buffer-create "*Org tmp*")
7353 (erase-buffer)
7354 (org-mode)
7355 (setq varlist (buffer-local-variables)))
7356 (kill-buffer "*Org tmp*")
7357 (delq nil
7358 (mapcar
7359 (lambda (x)
7360 (setq x
7361 (if (symbolp x)
7362 (list x)
7363 (list (car x) (list 'quote (cdr x)))))
7364 (if (string-match
7365 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7366 (symbol-name (car x)))
7367 x nil))
7368 varlist))))
7370 ;;;###autoload
7371 (defun org-run-like-in-org-mode (cmd)
7372 "Run a command, pretending that the current buffer is in Org-mode.
7373 This will temporarily bind local variables that are typically bound in
7374 Org-mode to the values they have in Org-mode, and then interactively
7375 call CMD."
7376 (org-load-modules-maybe)
7377 (unless org-local-vars
7378 (setq org-local-vars (org-get-local-variables)))
7379 (eval (list 'let org-local-vars
7380 (list 'call-interactively (list 'quote cmd)))))
7382 ;;;; Archiving
7384 (defun org-get-category (&optional pos)
7385 "Get the category applying to position POS."
7386 (get-text-property (or pos (point)) 'org-category))
7388 (defun org-refresh-category-properties ()
7389 "Refresh category text properties in the buffer."
7390 (let ((def-cat (cond
7391 ((null org-category)
7392 (if buffer-file-name
7393 (file-name-sans-extension
7394 (file-name-nondirectory buffer-file-name))
7395 "???"))
7396 ((symbolp org-category) (symbol-name org-category))
7397 (t org-category)))
7398 beg end cat pos optionp)
7399 (org-unmodified
7400 (save-excursion
7401 (save-restriction
7402 (widen)
7403 (goto-char (point-min))
7404 (put-text-property (point) (point-max) 'org-category def-cat)
7405 (while (re-search-forward
7406 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7407 (setq pos (match-end 0)
7408 optionp (equal (char-after (match-beginning 0)) ?#)
7409 cat (org-trim (match-string 2)))
7410 (if optionp
7411 (setq beg (point-at-bol) end (point-max))
7412 (org-back-to-heading t)
7413 (setq beg (point) end (org-end-of-subtree t t)))
7414 (put-text-property beg end 'org-category cat)
7415 (goto-char pos)))))))
7418 ;;;; Link Stuff
7420 ;;; Link abbreviations
7422 (defun org-link-expand-abbrev (link)
7423 "Apply replacements as defined in `org-link-abbrev-alist."
7424 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7425 (let* ((key (match-string 1 link))
7426 (as (or (assoc key org-link-abbrev-alist-local)
7427 (assoc key org-link-abbrev-alist)))
7428 (tag (and (match-end 2) (match-string 3 link)))
7429 rpl)
7430 (if (not as)
7431 link
7432 (setq rpl (cdr as))
7433 (cond
7434 ((symbolp rpl) (funcall rpl tag))
7435 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7436 ((string-match "%h" rpl)
7437 (replace-match (url-hexify-string (or tag "")) t t rpl))
7438 (t (concat rpl tag)))))
7439 link))
7441 ;;; Storing and inserting links
7443 (defvar org-insert-link-history nil
7444 "Minibuffer history for links inserted with `org-insert-link'.")
7446 (defvar org-stored-links nil
7447 "Contains the links stored with `org-store-link'.")
7449 (defvar org-store-link-plist nil
7450 "Plist with info about the most recently link created with `org-store-link'.")
7452 (defvar org-link-protocols nil
7453 "Link protocols added to Org-mode using `org-add-link-type'.")
7455 (defvar org-store-link-functions nil
7456 "List of functions that are called to create and store a link.
7457 Each function will be called in turn until one returns a non-nil
7458 value. Each function should check if it is responsible for creating
7459 this link (for example by looking at the major mode).
7460 If not, it must exit and return nil.
7461 If yes, it should return a non-nil value after a calling
7462 `org-store-link-props' with a list of properties and values.
7463 Special properties are:
7465 :type The link prefix. like \"http\". This must be given.
7466 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7467 This is obligatory as well.
7468 :description Optional default description for the second pair
7469 of brackets in an Org-mode link. The user can still change
7470 this when inserting this link into an Org-mode buffer.
7472 In addition to these, any additional properties can be specified
7473 and then used in remember templates.")
7475 (defun org-add-link-type (type &optional follow export)
7476 "Add TYPE to the list of `org-link-types'.
7477 Re-compute all regular expressions depending on `org-link-types'
7479 FOLLOW and EXPORT are two functions.
7481 FOLLOW should take the link path as the single argument and do whatever
7482 is necessary to follow the link, for example find a file or display
7483 a mail message.
7485 EXPORT should format the link path for export to one of the export formats.
7486 It should be a function accepting three arguments:
7488 path the path of the link, the text after the prefix (like \"http:\")
7489 desc the description of the link, if any, nil if there was no description
7490 format the export format, a symbol like `html' or `latex'.
7492 The function may use the FORMAT information to return different values
7493 depending on the format. The return value will be put literally into
7494 the exported file.
7495 Org-mode has a built-in default for exporting links. If you are happy with
7496 this default, there is no need to define an export function for the link
7497 type. For a simple example of an export function, see `org-bbdb.el'."
7498 (add-to-list 'org-link-types type t)
7499 (org-make-link-regexps)
7500 (if (assoc type org-link-protocols)
7501 (setcdr (assoc type org-link-protocols) (list follow export))
7502 (push (list type follow export) org-link-protocols)))
7504 (defvar org-agenda-buffer-name)
7506 ;;;###autoload
7507 (defun org-store-link (arg)
7508 "\\<org-mode-map>Store an org-link to the current location.
7509 This link is added to `org-stored-links' and can later be inserted
7510 into an org-buffer with \\[org-insert-link].
7512 For some link types, a prefix arg is interpreted:
7513 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7514 For file links, arg negates `org-context-in-file-links'."
7515 (interactive "P")
7516 (org-load-modules-maybe)
7517 (setq org-store-link-plist nil) ; reset
7518 (let ((outline-regexp (org-get-limited-outline-regexp))
7519 link cpltxt desc description search txt custom-id)
7520 (cond
7522 ((run-hook-with-args-until-success 'org-store-link-functions)
7523 (setq link (plist-get org-store-link-plist :link)
7524 desc (or (plist-get org-store-link-plist :description) link)))
7526 ((equal (buffer-name) "*Org Edit Src Example*")
7527 (let (label gc)
7528 (while (or (not label)
7529 (save-excursion
7530 (save-restriction
7531 (widen)
7532 (goto-char (point-min))
7533 (re-search-forward
7534 (regexp-quote (format org-coderef-label-format label))
7535 nil t))))
7536 (when label (message "Label exists already") (sit-for 2))
7537 (setq label (read-string "Code line label: " label)))
7538 (end-of-line 1)
7539 (setq link (format org-coderef-label-format label))
7540 (setq gc (- 79 (length link)))
7541 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7542 (insert link)
7543 (setq link (concat "(" label ")") desc nil)))
7545 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7546 ;; We are in the agenda, link to referenced location
7547 (let ((m (or (get-text-property (point) 'org-hd-marker)
7548 (get-text-property (point) 'org-marker))))
7549 (when m
7550 (org-with-point-at m
7551 (call-interactively 'org-store-link)))))
7553 ((eq major-mode 'calendar-mode)
7554 (let ((cd (calendar-cursor-to-date)))
7555 (setq link
7556 (format-time-string
7557 (car org-time-stamp-formats)
7558 (apply 'encode-time
7559 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7560 nil nil nil))))
7561 (org-store-link-props :type "calendar" :date cd)))
7563 ((eq major-mode 'w3-mode)
7564 (setq cpltxt (if (and (buffer-name)
7565 (not (string-match "Untitled" (buffer-name))))
7566 (buffer-name)
7567 (url-view-url t))
7568 link (org-make-link (url-view-url t)))
7569 (org-store-link-props :type "w3" :url (url-view-url t)))
7571 ((eq major-mode 'w3m-mode)
7572 (setq cpltxt (or w3m-current-title w3m-current-url)
7573 link (org-make-link w3m-current-url))
7574 (org-store-link-props :type "w3m" :url (url-view-url t)))
7576 ((setq search (run-hook-with-args-until-success
7577 'org-create-file-search-functions))
7578 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7579 "::" search))
7580 (setq cpltxt (or description link)))
7582 ((eq major-mode 'image-mode)
7583 (setq cpltxt (concat "file:"
7584 (abbreviate-file-name buffer-file-name))
7585 link (org-make-link cpltxt))
7586 (org-store-link-props :type "image" :file buffer-file-name))
7588 ((eq major-mode 'dired-mode)
7589 ;; link to the file in the current line
7590 (setq cpltxt (concat "file:"
7591 (abbreviate-file-name
7592 (expand-file-name
7593 (dired-get-filename nil t))))
7594 link (org-make-link cpltxt)))
7596 ((and buffer-file-name (org-mode-p))
7597 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7598 (cond
7599 ((org-in-regexp "<<\\(.*?\\)>>")
7600 (setq cpltxt
7601 (concat "file:"
7602 (abbreviate-file-name buffer-file-name)
7603 "::" (match-string 1))
7604 link (org-make-link cpltxt)))
7605 ((and (featurep 'org-id)
7606 (or (eq org-link-to-org-use-id t)
7607 (and (eq org-link-to-org-use-id 'create-if-interactive)
7608 (interactive-p))
7609 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7610 (interactive-p)
7611 (not custom-id))
7612 (and org-link-to-org-use-id
7613 (condition-case nil
7614 (org-entry-get nil "ID")
7615 (error nil)))))
7616 ;; We can make a link using the ID.
7617 (setq link (condition-case nil
7618 (prog1 (org-id-store-link)
7619 (setq desc (plist-get org-store-link-plist
7620 :description)))
7621 (error
7622 ;; probably before first headline, link to file only
7623 (concat "file:"
7624 (abbreviate-file-name buffer-file-name))))))
7626 ;; Just link to current headline
7627 (setq cpltxt (concat "file:"
7628 (abbreviate-file-name buffer-file-name)))
7629 ;; Add a context search string
7630 (when (org-xor org-context-in-file-links arg)
7631 (setq txt (cond
7632 ((org-on-heading-p) nil)
7633 ((org-region-active-p)
7634 (buffer-substring (region-beginning) (region-end)))
7635 (t nil)))
7636 (when (or (null txt) (string-match "\\S-" txt))
7637 (setq cpltxt
7638 (concat cpltxt "::"
7639 (condition-case nil
7640 (org-make-org-heading-search-string txt)
7641 (error "")))
7642 desc (or (nth 4 (ignore-errors
7643 (org-heading-components))) "NONE"))))
7644 (if (string-match "::\\'" cpltxt)
7645 (setq cpltxt (substring cpltxt 0 -2)))
7646 (setq link (org-make-link cpltxt)))))
7648 ((buffer-file-name (buffer-base-buffer))
7649 ;; Just link to this file here.
7650 (setq cpltxt (concat "file:"
7651 (abbreviate-file-name
7652 (buffer-file-name (buffer-base-buffer)))))
7653 ;; Add a context string
7654 (when (org-xor org-context-in-file-links arg)
7655 (setq txt (if (org-region-active-p)
7656 (buffer-substring (region-beginning) (region-end))
7657 (buffer-substring (point-at-bol) (point-at-eol))))
7658 ;; Only use search option if there is some text.
7659 (when (string-match "\\S-" txt)
7660 (setq cpltxt
7661 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7662 desc "NONE")))
7663 (setq link (org-make-link cpltxt)))
7665 ((interactive-p)
7666 (error "Cannot link to a buffer which is not visiting a file"))
7668 (t (setq link nil)))
7670 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7671 (setq link (or link cpltxt)
7672 desc (or desc cpltxt))
7673 (if (equal desc "NONE") (setq desc nil))
7675 (if (and (or (interactive-p) executing-kbd-macro) link)
7676 (progn
7677 (setq org-stored-links
7678 (cons (list link desc) org-stored-links))
7679 (message "Stored: %s" (or desc link))
7680 (when custom-id
7681 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7682 "::#" custom-id))
7683 (setq org-stored-links
7684 (cons (list link desc) org-stored-links))))
7685 (and link (org-make-link-string link desc)))))
7687 (defun org-store-link-props (&rest plist)
7688 "Store link properties, extract names and addresses."
7689 (let (x adr)
7690 (when (setq x (plist-get plist :from))
7691 (setq adr (mail-extract-address-components x))
7692 (setq plist (plist-put plist :fromname (car adr)))
7693 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7694 (when (setq x (plist-get plist :to))
7695 (setq adr (mail-extract-address-components x))
7696 (setq plist (plist-put plist :toname (car adr)))
7697 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7698 (let ((from (plist-get plist :from))
7699 (to (plist-get plist :to)))
7700 (when (and from to org-from-is-user-regexp)
7701 (setq plist
7702 (plist-put plist :fromto
7703 (if (string-match org-from-is-user-regexp from)
7704 (concat "to %t")
7705 (concat "from %f"))))))
7706 (setq org-store-link-plist plist))
7708 (defun org-add-link-props (&rest plist)
7709 "Add these properties to the link property list."
7710 (let (key value)
7711 (while plist
7712 (setq key (pop plist) value (pop plist))
7713 (setq org-store-link-plist
7714 (plist-put org-store-link-plist key value)))))
7716 (defun org-email-link-description (&optional fmt)
7717 "Return the description part of an email link.
7718 This takes information from `org-store-link-plist' and formats it
7719 according to FMT (default from `org-email-link-description-format')."
7720 (setq fmt (or fmt org-email-link-description-format))
7721 (let* ((p org-store-link-plist)
7722 (to (plist-get p :toaddress))
7723 (from (plist-get p :fromaddress))
7724 (table
7725 (list
7726 (cons "%c" (plist-get p :fromto))
7727 (cons "%F" (plist-get p :from))
7728 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7729 (cons "%T" (plist-get p :to))
7730 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7731 (cons "%s" (plist-get p :subject))
7732 (cons "%m" (plist-get p :message-id)))))
7733 (when (string-match "%c" fmt)
7734 ;; Check if the user wrote this message
7735 (if (and org-from-is-user-regexp from to
7736 (save-match-data (string-match org-from-is-user-regexp from)))
7737 (setq fmt (replace-match "to %t" t t fmt))
7738 (setq fmt (replace-match "from %f" t t fmt))))
7739 (org-replace-escapes fmt table)))
7741 (defun org-make-org-heading-search-string (&optional string heading)
7742 "Make search string for STRING or current headline."
7743 (interactive)
7744 (let ((s (or string (org-get-heading))))
7745 (unless (and string (not heading))
7746 ;; We are using a headline, clean up garbage in there.
7747 (if (string-match org-todo-regexp s)
7748 (setq s (replace-match "" t t s)))
7749 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7750 (setq s (replace-match "" t t s)))
7751 (setq s (org-trim s))
7752 (if (string-match (concat "^\\(" org-quote-string "\\|"
7753 org-comment-string "\\)") s)
7754 (setq s (replace-match "" t t s)))
7755 (while (string-match org-ts-regexp s)
7756 (setq s (replace-match "" t t s))))
7757 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7758 (setq s (replace-match " " t t s)))
7759 (or string (setq s (concat "*" s))) ; Add * for headlines
7760 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7762 (defun org-make-link (&rest strings)
7763 "Concatenate STRINGS."
7764 (apply 'concat strings))
7766 (defun org-make-link-string (link &optional description)
7767 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7768 (unless (string-match "\\S-" link)
7769 (error "Empty link"))
7770 (when (and description
7771 (stringp description)
7772 (not (string-match "\\S-" description)))
7773 (setq description nil))
7774 (when (stringp description)
7775 ;; Remove brackets from the description, they are fatal.
7776 (while (string-match "\\[" description)
7777 (setq description (replace-match "{" t t description)))
7778 (while (string-match "\\]" description)
7779 (setq description (replace-match "}" t t description))))
7780 (when (equal (org-link-escape link) description)
7781 ;; No description needed, it is identical
7782 (setq description nil))
7783 (when (and (not description)
7784 (not (equal link (org-link-escape link))))
7785 (setq description (org-extract-attributes link)))
7786 (concat "[[" (org-link-escape link) "]"
7787 (if description (concat "[" description "]") "")
7788 "]"))
7790 (defconst org-link-escape-chars
7791 '((?\ . "%20")
7792 (?\[ . "%5B")
7793 (?\] . "%5D")
7794 (?\340 . "%E0") ; `a
7795 (?\342 . "%E2") ; ^a
7796 (?\347 . "%E7") ; ,c
7797 (?\350 . "%E8") ; `e
7798 (?\351 . "%E9") ; 'e
7799 (?\352 . "%EA") ; ^e
7800 (?\356 . "%EE") ; ^i
7801 (?\364 . "%F4") ; ^o
7802 (?\371 . "%F9") ; `u
7803 (?\373 . "%FB") ; ^u
7804 (?\; . "%3B")
7805 (?? . "%3F")
7806 (?= . "%3D")
7807 (?+ . "%2B")
7809 "Association list of escapes for some characters problematic in links.
7810 This is the list that is used for internal purposes.")
7812 (defvar org-url-encoding-use-url-hexify nil)
7814 (defconst org-link-escape-chars-browser
7815 '((?\ . "%20")) ; 32 for the SPC char
7816 "Association list of escapes for some characters problematic in links.
7817 This is the list that is used before handing over to the browser.")
7819 (defun org-link-escape (text &optional table)
7820 "Escape characters in TEXT that are problematic for links."
7821 (if org-url-encoding-use-url-hexify
7822 (url-hexify-string text)
7823 (setq table (or table org-link-escape-chars))
7824 (when text
7825 (let ((re (mapconcat (lambda (x) (regexp-quote
7826 (char-to-string (car x))))
7827 table "\\|")))
7828 (while (string-match re text)
7829 (setq text
7830 (replace-match
7831 (cdr (assoc (string-to-char (match-string 0 text))
7832 table))
7833 t t text)))
7834 text))))
7836 (defun org-link-unescape (text &optional table)
7837 "Reverse the action of `org-link-escape'."
7838 (if org-url-encoding-use-url-hexify
7839 (url-unhex-string text)
7840 (setq table (or table org-link-escape-chars))
7841 (when text
7842 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7843 table "\\|")))
7844 (while (string-match re text)
7845 (setq text
7846 (replace-match
7847 (char-to-string (car (rassoc (match-string 0 text) table)))
7848 t t text)))
7849 text))))
7851 (defun org-xor (a b)
7852 "Exclusive or."
7853 (if a (not b) b))
7855 (defun org-fixup-message-id-for-http (s)
7856 "Replace special characters in a message id, so it can be used in an http query."
7857 (while (string-match "<" s)
7858 (setq s (replace-match "%3C" t t s)))
7859 (while (string-match ">" s)
7860 (setq s (replace-match "%3E" t t s)))
7861 (while (string-match "@" s)
7862 (setq s (replace-match "%40" t t s)))
7865 ;;;###autoload
7866 (defun org-insert-link-global ()
7867 "Insert a link like Org-mode does.
7868 This command can be called in any mode to insert a link in Org-mode syntax."
7869 (interactive)
7870 (org-load-modules-maybe)
7871 (org-run-like-in-org-mode 'org-insert-link))
7873 (defun org-insert-link (&optional complete-file link-location)
7874 "Insert a link. At the prompt, enter the link.
7876 Completion can be used to insert any of the link protocol prefixes like
7877 http or ftp in use.
7879 The history can be used to select a link previously stored with
7880 `org-store-link'. When the empty string is entered (i.e. if you just
7881 press RET at the prompt), the link defaults to the most recently
7882 stored link. As SPC triggers completion in the minibuffer, you need to
7883 use M-SPC or C-q SPC to force the insertion of a space character.
7885 You will also be prompted for a description, and if one is given, it will
7886 be displayed in the buffer instead of the link.
7888 If there is already a link at point, this command will allow you to edit link
7889 and description parts.
7891 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7892 be selected using completion. The path to the file will be relative to the
7893 current directory if the file is in the current directory or a subdirectory.
7894 Otherwise, the link will be the absolute path as completed in the minibuffer
7895 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7896 option `org-link-file-path-type'.
7898 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7899 the current directory or below.
7901 With three \\[universal-argument] prefixes, negate the meaning of
7902 `org-keep-stored-link-after-insertion'.
7904 If `org-make-link-description-function' is non-nil, this function will be
7905 called with the link target, and the result will be the default
7906 link description.
7908 If the LINK-LOCATION parameter is non-nil, this value will be
7909 used as the link location instead of reading one interactively."
7910 (interactive "P")
7911 (let* ((wcf (current-window-configuration))
7912 (region (if (org-region-active-p)
7913 (buffer-substring (region-beginning) (region-end))))
7914 (remove (and region (list (region-beginning) (region-end))))
7915 (desc region)
7916 tmphist ; byte-compile incorrectly complains about this
7917 (link link-location)
7918 entry file all-prefixes)
7919 (cond
7920 (link-location) ; specified by arg, just use it.
7921 ((org-in-regexp org-bracket-link-regexp 1)
7922 ;; We do have a link at point, and we are going to edit it.
7923 (setq remove (list (match-beginning 0) (match-end 0)))
7924 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7925 (setq link (read-string "Link: "
7926 (org-link-unescape
7927 (org-match-string-no-properties 1)))))
7928 ((or (org-in-regexp org-angle-link-re)
7929 (org-in-regexp org-plain-link-re))
7930 ;; Convert to bracket link
7931 (setq remove (list (match-beginning 0) (match-end 0))
7932 link (read-string "Link: "
7933 (org-remove-angle-brackets (match-string 0)))))
7934 ((member complete-file '((4) (16)))
7935 ;; Completing read for file names.
7936 (setq link (org-file-complete-link complete-file)))
7938 ;; Read link, with completion for stored links.
7939 (with-output-to-temp-buffer "*Org Links*"
7940 (princ "Insert a link.
7941 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7942 (when org-stored-links
7943 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7944 (princ (mapconcat
7945 (lambda (x)
7946 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7947 (reverse org-stored-links) "\n"))))
7948 (let ((cw (selected-window)))
7949 (select-window (get-buffer-window "*Org Links*"))
7950 (setq truncate-lines t)
7951 (unless (pos-visible-in-window-p (point-max))
7952 (org-fit-window-to-buffer))
7953 (and (window-live-p cw) (select-window cw)))
7954 ;; Fake a link history, containing the stored links.
7955 (setq tmphist (append (mapcar 'car org-stored-links)
7956 org-insert-link-history))
7957 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7958 (mapcar 'car org-link-abbrev-alist)
7959 org-link-types))
7960 (unwind-protect
7961 (progn
7962 (setq link
7963 (let ((org-completion-use-ido nil)
7964 (org-completion-use-iswitchb nil))
7965 (org-completing-read
7966 "Link: "
7967 (append
7968 (mapcar (lambda (x) (list (concat x ":")))
7969 all-prefixes)
7970 (mapcar 'car org-stored-links))
7971 nil nil nil
7972 'tmphist
7973 (car (car org-stored-links)))))
7974 (if (not (string-match "\\S-" link))
7975 (error "No link selected"))
7976 (if (or (member link all-prefixes)
7977 (and (equal ":" (substring link -1))
7978 (member (substring link 0 -1) all-prefixes)
7979 (setq link (substring link 0 -1))))
7980 (setq link (org-link-try-special-completion link))))
7981 (set-window-configuration wcf)
7982 (kill-buffer "*Org Links*"))
7983 (setq entry (assoc link org-stored-links))
7984 (or entry (push link org-insert-link-history))
7985 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7986 (not org-keep-stored-link-after-insertion))
7987 (setq org-stored-links (delq (assoc link org-stored-links)
7988 org-stored-links)))
7989 (setq desc (or desc (nth 1 entry)))))
7991 (if (string-match org-plain-link-re link)
7992 ;; URL-like link, normalize the use of angular brackets.
7993 (setq link (org-make-link (org-remove-angle-brackets link))))
7995 ;; Check if we are linking to the current file with a search option
7996 ;; If yes, simplify the link by using only the search option.
7997 (when (and buffer-file-name
7998 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7999 (let* ((path (match-string 1 link))
8000 (case-fold-search nil)
8001 (search (match-string 2 link)))
8002 (save-match-data
8003 (if (equal (file-truename buffer-file-name) (file-truename path))
8004 ;; We are linking to this same file, with a search option
8005 (setq link search)))))
8007 ;; Check if we can/should use a relative path. If yes, simplify the link
8008 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8009 (let* ((type (match-string 1 link))
8010 (path (match-string 2 link))
8011 (origpath path)
8012 (case-fold-search nil))
8013 (cond
8014 ((or (eq org-link-file-path-type 'absolute)
8015 (equal complete-file '(16)))
8016 (setq path (abbreviate-file-name (expand-file-name path))))
8017 ((eq org-link-file-path-type 'noabbrev)
8018 (setq path (expand-file-name path)))
8019 ((eq org-link-file-path-type 'relative)
8020 (setq path (file-relative-name path)))
8022 (save-match-data
8023 (if (string-match (concat "^" (regexp-quote
8024 (file-name-as-directory
8025 (expand-file-name "."))))
8026 (expand-file-name path))
8027 ;; We are linking a file with relative path name.
8028 (setq path (substring (expand-file-name path)
8029 (match-end 0)))
8030 (setq path (abbreviate-file-name (expand-file-name path)))))))
8031 (setq link (concat type path))
8032 (if (equal desc origpath)
8033 (setq desc path))))
8035 (if org-make-link-description-function
8036 (setq desc (funcall org-make-link-description-function link desc)))
8038 (setq desc (read-string "Description: " desc))
8039 (unless (string-match "\\S-" desc) (setq desc nil))
8040 (if remove (apply 'delete-region remove))
8041 (insert (org-make-link-string link desc))))
8043 (defun org-link-try-special-completion (type)
8044 "If there is completion support for link type TYPE, offer it."
8045 (let ((fun (intern (concat "org-" type "-complete-link"))))
8046 (if (functionp fun)
8047 (funcall fun)
8048 (read-string "Link (no completion support): " (concat type ":")))))
8050 (defun org-file-complete-link (&optional arg)
8051 "Create a file link using completion."
8052 (let (file link)
8053 (setq file (read-file-name "File: "))
8054 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8055 (pwd1 (file-name-as-directory (abbreviate-file-name
8056 (expand-file-name ".")))))
8057 (cond
8058 ((equal arg '(16))
8059 (setq link (org-make-link
8060 "file:"
8061 (abbreviate-file-name (expand-file-name file)))))
8062 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8063 (setq link (org-make-link "file:" (match-string 1 file))))
8064 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8065 (expand-file-name file))
8066 (setq link (org-make-link
8067 "file:" (match-string 1 (expand-file-name file)))))
8068 (t (setq link (org-make-link "file:" file)))))
8069 link))
8071 (defun org-completing-read (&rest args)
8072 "Completing-read with SPACE being a normal character."
8073 (let ((minibuffer-local-completion-map
8074 (copy-keymap minibuffer-local-completion-map)))
8075 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8076 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8077 (apply 'org-icompleting-read args)))
8079 (defun org-completing-read-no-i (&rest args)
8080 (let (org-completion-use-ido org-completion-use-iswitchb)
8081 (apply 'org-completing-read args)))
8083 (defun org-iswitchb-completing-read (prompt choices &rest args)
8084 "Use iswitch as a completing-read replacement to choose from choices.
8085 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8086 from."
8087 (let* ((iswitchb-use-virtual-buffers nil)
8088 (iswitchb-make-buflist-hook
8089 (lambda ()
8090 (setq iswitchb-temp-buflist choices))))
8091 (iswitchb-read-buffer prompt)))
8093 (defun org-icompleting-read (&rest args)
8094 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8095 (org-without-partial-completion
8096 (if (and org-completion-use-ido
8097 (fboundp 'ido-completing-read)
8098 (boundp 'ido-mode) ido-mode
8099 (listp (second args)))
8100 (let ((ido-enter-matching-directory nil))
8101 (apply 'ido-completing-read (concat (car args))
8102 (if (consp (car (nth 1 args)))
8103 (mapcar (lambda (x) (car x)) (nth 1 args))
8104 (nth 1 args))
8105 (cddr args)))
8106 (if (and org-completion-use-iswitchb
8107 (boundp 'iswitchb-mode) iswitchb-mode
8108 (listp (second args)))
8109 (apply 'org-iswitchb-completing-read (concat (car args))
8110 (if (consp (car (nth 1 args)))
8111 (mapcar (lambda (x) (car x)) (nth 1 args))
8112 (nth 1 args))
8113 (cddr args))
8114 (apply 'completing-read args)))))
8116 (defun org-extract-attributes (s)
8117 "Extract the attributes cookie from a string and set as text property."
8118 (let (a attr (start 0) key value)
8119 (save-match-data
8120 (when (string-match "{{\\([^}]+\\)}}$" s)
8121 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8122 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8123 (setq key (match-string 1 a) value (match-string 2 a)
8124 start (match-end 0)
8125 attr (plist-put attr (intern key) value))))
8126 (org-add-props s nil 'org-attr attr))
8129 (defun org-extract-attributes-from-string (tag)
8130 (let (key value attr)
8131 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8132 (setq key (match-string 1 tag) value (match-string 2 tag)
8133 tag (replace-match "" t t tag)
8134 attr (plist-put attr (intern key) value)))
8135 (cons tag attr)))
8137 (defun org-attributes-to-string (plist)
8138 "Format a property list into an HTML attribute list."
8139 (let ((s "") key value)
8140 (while plist
8141 (setq key (pop plist) value (pop plist))
8142 (and value
8143 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8146 ;;; Opening/following a link
8148 (defvar org-link-search-failed nil)
8150 (defun org-next-link ()
8151 "Move forward to the next link.
8152 If the link is in hidden text, expose it."
8153 (interactive)
8154 (when (and org-link-search-failed (eq this-command last-command))
8155 (goto-char (point-min))
8156 (message "Link search wrapped back to beginning of buffer"))
8157 (setq org-link-search-failed nil)
8158 (let* ((pos (point))
8159 (ct (org-context))
8160 (a (assoc :link ct)))
8161 (if a (goto-char (nth 2 a)))
8162 (if (re-search-forward org-any-link-re nil t)
8163 (progn
8164 (goto-char (match-beginning 0))
8165 (if (org-invisible-p) (org-show-context)))
8166 (goto-char pos)
8167 (setq org-link-search-failed t)
8168 (error "No further link found"))))
8170 (defun org-previous-link ()
8171 "Move backward to the previous link.
8172 If the link is in hidden text, expose it."
8173 (interactive)
8174 (when (and org-link-search-failed (eq this-command last-command))
8175 (goto-char (point-max))
8176 (message "Link search wrapped back to end of buffer"))
8177 (setq org-link-search-failed nil)
8178 (let* ((pos (point))
8179 (ct (org-context))
8180 (a (assoc :link ct)))
8181 (if a (goto-char (nth 1 a)))
8182 (if (re-search-backward org-any-link-re nil t)
8183 (progn
8184 (goto-char (match-beginning 0))
8185 (if (org-invisible-p) (org-show-context)))
8186 (goto-char pos)
8187 (setq org-link-search-failed t)
8188 (error "No further link found"))))
8190 (defun org-translate-link (s)
8191 "Translate a link string if a translation function has been defined."
8192 (if (and org-link-translation-function
8193 (fboundp org-link-translation-function)
8194 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8195 (progn
8196 (setq s (funcall org-link-translation-function
8197 (match-string 1) (match-string 2)))
8198 (concat (car s) ":" (cdr s)))
8201 (defun org-translate-link-from-planner (type path)
8202 "Translate a link from Emacs Planner syntax so that Org can follow it.
8203 This is still an experimental function, your mileage may vary."
8204 (cond
8205 ((member type '("http" "https" "news" "ftp"))
8206 ;; standard Internet links are the same.
8207 nil)
8208 ((and (equal type "irc") (string-match "^//" path))
8209 ;; Planner has two / at the beginning of an irc link, we have 1.
8210 ;; We should have zero, actually....
8211 (setq path (substring path 1)))
8212 ((and (equal type "lisp") (string-match "^/" path))
8213 ;; Planner has a slash, we do not.
8214 (setq type "elisp" path (substring path 1)))
8215 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8216 ;; A typical message link. Planner has the id after the final slash,
8217 ;; we separate it with a hash mark
8218 (setq path (concat (match-string 1 path) "#"
8219 (org-remove-angle-brackets (match-string 2 path)))))
8221 (cons type path))
8223 (defun org-find-file-at-mouse (ev)
8224 "Open file link or URL at mouse."
8225 (interactive "e")
8226 (mouse-set-point ev)
8227 (org-open-at-point 'in-emacs))
8229 (defun org-open-at-mouse (ev)
8230 "Open file link or URL at mouse."
8231 (interactive "e")
8232 (mouse-set-point ev)
8233 (if (eq major-mode 'org-agenda-mode)
8234 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8235 (org-open-at-point))
8237 (defvar org-window-config-before-follow-link nil
8238 "The window configuration before following a link.
8239 This is saved in case the need arises to restore it.")
8241 (defvar org-open-link-marker (make-marker)
8242 "Marker pointing to the location where `org-open-at-point; was called.")
8244 ;;;###autoload
8245 (defun org-open-at-point-global ()
8246 "Follow a link like Org-mode does.
8247 This command can be called in any mode to follow a link that has
8248 Org-mode syntax."
8249 (interactive)
8250 (org-run-like-in-org-mode 'org-open-at-point))
8252 ;;;###autoload
8253 (defun org-open-link-from-string (s &optional arg reference-buffer)
8254 "Open a link in the string S, as if it was in Org-mode."
8255 (interactive "sLink: \nP")
8256 (let ((reference-buffer (or reference-buffer (current-buffer))))
8257 (with-temp-buffer
8258 (let ((org-inhibit-startup t))
8259 (org-mode)
8260 (insert s)
8261 (goto-char (point-min))
8262 (org-open-at-point arg reference-buffer)))))
8264 (defun org-open-at-point (&optional in-emacs reference-buffer)
8265 "Open link at or after point.
8266 If there is no link at point, this function will search forward up to
8267 the end of the current line.
8268 Normally, files will be opened by an appropriate application. If the
8269 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8270 With a double prefix argument, try to open outside of Emacs, in the
8271 application the system uses for this file type."
8272 (interactive "P")
8273 (org-load-modules-maybe)
8274 (move-marker org-open-link-marker (point))
8275 (setq org-window-config-before-follow-link (current-window-configuration))
8276 (org-remove-occur-highlights nil nil t)
8277 (cond
8278 ((and (org-on-heading-p)
8279 (not (org-in-regexp
8280 (concat org-plain-link-re "\\|"
8281 org-bracket-link-regexp "\\|"
8282 org-angle-link-re "\\|"
8283 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8284 (or (org-offer-links-in-entry in-emacs)
8285 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8286 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8287 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8288 (org-footnote-action))
8290 (let (type path link line search (pos (point)))
8291 (catch 'match
8292 (save-excursion
8293 (skip-chars-forward "^]\n\r")
8294 (when (org-in-regexp org-bracket-link-regexp 1)
8295 (setq link (org-extract-attributes
8296 (org-link-unescape (org-match-string-no-properties 1))))
8297 (while (string-match " *\n *" link)
8298 (setq link (replace-match " " t t link)))
8299 (setq link (org-link-expand-abbrev link))
8300 (cond
8301 ((or (file-name-absolute-p link)
8302 (string-match "^\\.\\.?/" link))
8303 (setq type "file" path link))
8304 ((string-match org-link-re-with-space3 link)
8305 (setq type (match-string 1 link) path (match-string 2 link)))
8306 (t (setq type "thisfile" path link)))
8307 (throw 'match t)))
8309 (when (get-text-property (point) 'org-linked-text)
8310 (setq type "thisfile"
8311 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8312 (1+ (point)) (point))
8313 path (buffer-substring
8314 (previous-single-property-change pos 'org-linked-text)
8315 (next-single-property-change pos 'org-linked-text)))
8316 (throw 'match t))
8318 (save-excursion
8319 (when (or (org-in-regexp org-angle-link-re)
8320 (org-in-regexp org-plain-link-re))
8321 (setq type (match-string 1) path (match-string 2))
8322 (throw 'match t)))
8323 (save-excursion
8324 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8325 (setq type "tags"
8326 path (match-string 1))
8327 (while (string-match ":" path)
8328 (setq path (replace-match "+" t t path)))
8329 (throw 'match t)))
8330 (when (org-in-regexp "<\\([^><\n]+\\)>")
8331 (setq type "tree-match"
8332 path (match-string 1))
8333 (throw 'match t)))
8334 (unless path
8335 (error "No link found"))
8337 ;; switch back to reference buffer
8338 ;; needed when if called in a temporary buffer through
8339 ;; org-open-link-from-string
8340 (with-current-buffer (or reference-buffer (current-buffer))
8342 ;; Remove any trailing spaces in path
8343 (if (string-match " +\\'" path)
8344 (setq path (replace-match "" t t path)))
8345 (if (and org-link-translation-function
8346 (fboundp org-link-translation-function))
8347 ;; Check if we need to translate the link
8348 (let ((tmp (funcall org-link-translation-function type path)))
8349 (setq type (car tmp) path (cdr tmp))))
8351 (cond
8353 ((assoc type org-link-protocols)
8354 (funcall (nth 1 (assoc type org-link-protocols)) path))
8356 ((equal type "mailto")
8357 (let ((cmd (car org-link-mailto-program))
8358 (args (cdr org-link-mailto-program)) args1
8359 (address path) (subject "") a)
8360 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8361 (setq address (match-string 1 path)
8362 subject (org-link-escape (match-string 2 path))))
8363 (while args
8364 (cond
8365 ((not (stringp (car args))) (push (pop args) args1))
8366 (t (setq a (pop args))
8367 (if (string-match "%a" a)
8368 (setq a (replace-match address t t a)))
8369 (if (string-match "%s" a)
8370 (setq a (replace-match subject t t a)))
8371 (push a args1))))
8372 (apply cmd (nreverse args1))))
8374 ((member type '("http" "https" "ftp" "news"))
8375 (browse-url (concat type ":" (org-link-escape
8376 path org-link-escape-chars-browser))))
8378 ((member type '("message"))
8379 (browse-url (concat type ":" path)))
8381 ((string= type "tags")
8382 (org-tags-view in-emacs path))
8383 ((string= type "thisfile")
8384 (if in-emacs
8385 (switch-to-buffer-other-window
8386 (org-get-buffer-for-internal-link (current-buffer)))
8387 (org-mark-ring-push))
8388 (let ((cmd `(org-link-search
8389 ,path
8390 ,(cond ((equal in-emacs '(4)) 'occur)
8391 ((equal in-emacs '(16)) 'org-occur)
8392 (t nil))
8393 ,pos)))
8394 (condition-case nil (eval cmd)
8395 (error (progn (widen) (eval cmd))))))
8397 ((string= type "tree-match")
8398 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8400 ((string= type "file")
8401 (if (string-match "::\\([0-9]+\\)\\'" path)
8402 (setq line (string-to-number (match-string 1 path))
8403 path (substring path 0 (match-beginning 0)))
8404 (if (string-match "::\\(.+\\)\\'" path)
8405 (setq search (match-string 1 path)
8406 path (substring path 0 (match-beginning 0)))))
8407 (if (string-match "[*?{]" (file-name-nondirectory path))
8408 (dired path)
8409 (org-open-file path in-emacs line search)))
8411 ((string= type "news")
8412 (require 'org-gnus)
8413 (org-gnus-follow-link path))
8415 ((string= type "shell")
8416 (let ((cmd path))
8417 (if (or (not org-confirm-shell-link-function)
8418 (funcall org-confirm-shell-link-function
8419 (format "Execute \"%s\" in shell? "
8420 (org-add-props cmd nil
8421 'face 'org-warning))))
8422 (progn
8423 (message "Executing %s" cmd)
8424 (shell-command cmd))
8425 (error "Abort"))))
8427 ((string= type "elisp")
8428 (let ((cmd path))
8429 (if (or (not org-confirm-elisp-link-function)
8430 (funcall org-confirm-elisp-link-function
8431 (format "Execute \"%s\" as elisp? "
8432 (org-add-props cmd nil
8433 'face 'org-warning))))
8434 (message "%s => %s" cmd
8435 (if (equal (string-to-char cmd) ?\()
8436 (eval (read cmd))
8437 (call-interactively (read cmd))))
8438 (error "Abort"))))
8441 (browse-url-at-point)))))))
8442 (move-marker org-open-link-marker nil)
8443 (run-hook-with-args 'org-follow-link-hook))
8445 (defun org-offer-links-in-entry (&optional nth zero)
8446 "Offer links in the current entry and follow the selected link.
8447 If there is only one link, follow it immediately as well.
8448 If NTH is an integer, immediately pick the NTH link found.
8449 If ZERO is a string, check also this string for a link, and if
8450 there is one, offer it as link number zero."
8451 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8452 "\\(" org-angle-link-re "\\)\\|"
8453 "\\(" org-plain-link-re "\\)"))
8454 (cnt ?0)
8455 (in-emacs (if (integerp nth) nil nth))
8456 have-zero end links link c)
8457 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8458 (push (match-string 0 zero) links)
8459 (setq cnt (1- cnt) have-zero t))
8460 (save-excursion
8461 (org-back-to-heading t)
8462 (setq end (save-excursion (outline-next-heading) (point)))
8463 (while (re-search-forward re end t)
8464 (push (match-string 0) links))
8465 (setq links (org-uniquify (reverse links))))
8467 (cond
8468 ((null links)
8469 (message "No links"))
8470 ((equal (length links) 1)
8471 (setq link (car links)))
8472 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8473 (setq link (nth (if have-zero nth (1- nth)) links)))
8474 (t ; we have to select a link
8475 (save-excursion
8476 (save-window-excursion
8477 (delete-other-windows)
8478 (with-output-to-temp-buffer "*Select Link*"
8479 (mapc (lambda (l)
8480 (if (not (string-match org-bracket-link-regexp l))
8481 (princ (format "[%c] %s\n" (incf cnt)
8482 (org-remove-angle-brackets l)))
8483 (if (match-end 3)
8484 (princ (format "[%c] %s (%s)\n" (incf cnt)
8485 (match-string 3 l) (match-string 1 l)))
8486 (princ (format "[%c] %s\n" (incf cnt)
8487 (match-string 1 l))))))
8488 links))
8489 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8490 (message "Select link to open:")
8491 (setq c (read-char-exclusive))
8492 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8493 (when (equal c ?q) (error "Abort"))
8494 (setq nth (- c ?0))
8495 (if have-zero (setq nth (1+ nth)))
8496 (unless (and (integerp nth) (>= (length links) nth))
8497 (error "Invalid link selection"))
8498 (setq link (nth (1- nth) links))))
8499 (if link
8500 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8501 nil)))
8503 ;;;; Time estimates
8505 (defun org-get-effort (&optional pom)
8506 "Get the effort estimate for the current entry."
8507 (org-entry-get pom org-effort-property))
8509 ;;; File search
8511 (defvar org-create-file-search-functions nil
8512 "List of functions to construct the right search string for a file link.
8513 These functions are called in turn with point at the location to
8514 which the link should point.
8516 A function in the hook should first test if it would like to
8517 handle this file type, for example by checking the major-mode or
8518 the file extension. If it decides not to handle this file, it
8519 should just return nil to give other functions a chance. If it
8520 does handle the file, it must return the search string to be used
8521 when following the link. The search string will be part of the
8522 file link, given after a double colon, and `org-open-at-point'
8523 will automatically search for it. If special measures must be
8524 taken to make the search successful, another function should be
8525 added to the companion hook `org-execute-file-search-functions',
8526 which see.
8528 A function in this hook may also use `setq' to set the variable
8529 `description' to provide a suggestion for the descriptive text to
8530 be used for this link when it gets inserted into an Org-mode
8531 buffer with \\[org-insert-link].")
8533 (defvar org-execute-file-search-functions nil
8534 "List of functions to execute a file search triggered by a link.
8536 Functions added to this hook must accept a single argument, the
8537 search string that was part of the file link, the part after the
8538 double colon. The function must first check if it would like to
8539 handle this search, for example by checking the major-mode or the
8540 file extension. If it decides not to handle this search, it
8541 should just return nil to give other functions a chance. If it
8542 does handle the search, it must return a non-nil value to keep
8543 other functions from trying.
8545 Each function can access the current prefix argument through the
8546 variable `current-prefix-argument'. Note that a single prefix is
8547 used to force opening a link in Emacs, so it may be good to only
8548 use a numeric or double prefix to guide the search function.
8550 In case this is needed, a function in this hook can also restore
8551 the window configuration before `org-open-at-point' was called using:
8553 (set-window-configuration org-window-config-before-follow-link)")
8555 (defun org-link-search (s &optional type avoid-pos)
8556 "Search for a link search option.
8557 If S is surrounded by forward slashes, it is interpreted as a
8558 regular expression. In org-mode files, this will create an `org-occur'
8559 sparse tree. In ordinary files, `occur' will be used to list matches.
8560 If the current buffer is in `dired-mode', grep will be used to search
8561 in all files. If AVOID-POS is given, ignore matches near that position."
8562 (let ((case-fold-search t)
8563 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8564 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8565 (append '(("") (" ") ("\t") ("\n"))
8566 org-emphasis-alist)
8567 "\\|") "\\)"))
8568 (pos (point))
8569 (pre nil) (post nil)
8570 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8571 (cond
8572 ;; First check if there are any special
8573 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8574 ;; Now try the builtin stuff
8575 ((and (equal (string-to-char s0) ?#)
8576 (> (length s0) 1)
8577 (save-excursion
8578 (goto-char (point-min))
8579 (and
8580 (re-search-forward
8581 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8582 (setq type 'dedicated
8583 pos (match-beginning 0))))
8584 ;; There is an exact target for this
8585 (goto-char pos)
8586 (org-back-to-heading t)))
8587 ((save-excursion
8588 (goto-char (point-min))
8589 (and
8590 (re-search-forward
8591 (concat "<<" (regexp-quote s0) ">>") nil t)
8592 (setq type 'dedicated
8593 pos (match-beginning 0))))
8594 ;; There is an exact target for this
8595 (goto-char pos))
8596 ((and (string-match "^(\\(.*\\))$" s0)
8597 (save-excursion
8598 (goto-char (point-min))
8599 (and
8600 (re-search-forward
8601 (concat "[^[]" (regexp-quote
8602 (format org-coderef-label-format
8603 (match-string 1 s0))))
8604 nil t)
8605 (setq type 'dedicated
8606 pos (1+ (match-beginning 0))))))
8607 ;; There is a coderef target for this
8608 (goto-char pos))
8609 ((string-match "^/\\(.*\\)/$" s)
8610 ;; A regular expression
8611 (cond
8612 ((org-mode-p)
8613 (org-occur (match-string 1 s)))
8614 ;;((eq major-mode 'dired-mode)
8615 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8616 (t (org-do-occur (match-string 1 s)))))
8618 ;; A normal search strings
8619 (when (equal (string-to-char s) ?*)
8620 ;; Anchor on headlines, post may include tags.
8621 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8622 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8623 s (substring s 1)))
8624 (remove-text-properties
8625 0 (length s)
8626 '(face nil mouse-face nil keymap nil fontified nil) s)
8627 ;; Make a series of regular expressions to find a match
8628 (setq words (org-split-string s "[ \n\r\t]+")
8630 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8631 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8632 "\\)" markers)
8633 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8634 re2a (concat "[ \t\r\n]" re2a_)
8635 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8636 re4 (concat "[^a-zA-Z_]" re4_)
8638 re1 (concat pre re2 post)
8639 re3 (concat pre (if pre re4_ re4) post)
8640 re5 (concat pre ".*" re4)
8641 re2 (concat pre re2)
8642 re2a (concat pre (if pre re2a_ re2a))
8643 re4 (concat pre (if pre re4_ re4))
8644 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8645 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8646 re5 "\\)"
8648 (cond
8649 ((eq type 'org-occur) (org-occur reall))
8650 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8651 (t (goto-char (point-min))
8652 (setq type 'fuzzy)
8653 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8654 (org-search-not-self 1 re1 nil t)
8655 (org-search-not-self 1 re2 nil t)
8656 (org-search-not-self 1 re2a nil t)
8657 (org-search-not-self 1 re3 nil t)
8658 (org-search-not-self 1 re4 nil t)
8659 (org-search-not-self 1 re5 nil t)
8661 (goto-char (match-beginning 1))
8662 (goto-char pos)
8663 (error "No match")))))
8665 ;; Normal string-search
8666 (goto-char (point-min))
8667 (if (search-forward s nil t)
8668 (goto-char (match-beginning 0))
8669 (error "No match"))))
8670 (and (org-mode-p) (org-show-context 'link-search))
8671 type))
8673 (defun org-search-not-self (group &rest args)
8674 "Execute `re-search-forward', but only accept matches that do not
8675 enclose the position of `org-open-link-marker'."
8676 (let ((m org-open-link-marker))
8677 (catch 'exit
8678 (while (apply 're-search-forward args)
8679 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8680 (goto-char (match-end group))
8681 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8682 (> (match-beginning 0) (marker-position m))
8683 (< (match-end 0) (marker-position m)))
8684 (save-match-data
8685 (or (not (org-in-regexp
8686 org-bracket-link-analytic-regexp 1))
8687 (not (match-end 4)) ; no description
8688 (and (<= (match-beginning 4) (point))
8689 (>= (match-end 4) (point))))))
8690 (throw 'exit (point))))))))
8692 (defun org-get-buffer-for-internal-link (buffer)
8693 "Return a buffer to be used for displaying the link target of internal links."
8694 (cond
8695 ((not org-display-internal-link-with-indirect-buffer)
8696 buffer)
8697 ((string-match "(Clone)$" (buffer-name buffer))
8698 (message "Buffer is already a clone, not making another one")
8699 ;; we also do not modify visibility in this case
8700 buffer)
8701 (t ; make a new indirect buffer for displaying the link
8702 (let* ((bn (buffer-name buffer))
8703 (ibn (concat bn "(Clone)"))
8704 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8705 (with-current-buffer ib (org-overview))
8706 ib))))
8708 (defun org-do-occur (regexp &optional cleanup)
8709 "Call the Emacs command `occur'.
8710 If CLEANUP is non-nil, remove the printout of the regular expression
8711 in the *Occur* buffer. This is useful if the regex is long and not useful
8712 to read."
8713 (occur regexp)
8714 (when cleanup
8715 (let ((cwin (selected-window)) win beg end)
8716 (when (setq win (get-buffer-window "*Occur*"))
8717 (select-window win))
8718 (goto-char (point-min))
8719 (when (re-search-forward "match[a-z]+" nil t)
8720 (setq beg (match-end 0))
8721 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8722 (setq end (1- (match-beginning 0)))))
8723 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8724 (goto-char (point-min))
8725 (select-window cwin))))
8727 ;;; The mark ring for links jumps
8729 (defvar org-mark-ring nil
8730 "Mark ring for positions before jumps in Org-mode.")
8731 (defvar org-mark-ring-last-goto nil
8732 "Last position in the mark ring used to go back.")
8733 ;; Fill and close the ring
8734 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8735 (loop for i from 1 to org-mark-ring-length do
8736 (push (make-marker) org-mark-ring))
8737 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8738 org-mark-ring)
8740 (defun org-mark-ring-push (&optional pos buffer)
8741 "Put the current position or POS into the mark ring and rotate it."
8742 (interactive)
8743 (setq pos (or pos (point)))
8744 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8745 (move-marker (car org-mark-ring)
8746 (or pos (point))
8747 (or buffer (current-buffer)))
8748 (message "%s"
8749 (substitute-command-keys
8750 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8752 (defun org-mark-ring-goto (&optional n)
8753 "Jump to the previous position in the mark ring.
8754 With prefix arg N, jump back that many stored positions. When
8755 called several times in succession, walk through the entire ring.
8756 Org-mode commands jumping to a different position in the current file,
8757 or to another Org-mode file, automatically push the old position
8758 onto the ring."
8759 (interactive "p")
8760 (let (p m)
8761 (if (eq last-command this-command)
8762 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8763 (setq p org-mark-ring))
8764 (setq org-mark-ring-last-goto p)
8765 (setq m (car p))
8766 (switch-to-buffer (marker-buffer m))
8767 (goto-char m)
8768 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8770 (defun org-remove-angle-brackets (s)
8771 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8772 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8774 (defun org-add-angle-brackets (s)
8775 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8776 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8778 (defun org-remove-double-quotes (s)
8779 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8780 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8783 ;;; Following specific links
8785 (defun org-follow-timestamp-link ()
8786 (cond
8787 ((org-at-date-range-p t)
8788 (let ((org-agenda-start-on-weekday)
8789 (t1 (match-string 1))
8790 (t2 (match-string 2)))
8791 (setq t1 (time-to-days (org-time-string-to-time t1))
8792 t2 (time-to-days (org-time-string-to-time t2)))
8793 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8794 ((org-at-timestamp-p t)
8795 (org-agenda-list nil (time-to-days (org-time-string-to-time
8796 (substring (match-string 1) 0 10)))
8798 (t (error "This should not happen"))))
8801 ;;; Following file links
8802 (defvar org-wait nil)
8803 (defun org-open-file (path &optional in-emacs line search)
8804 "Open the file at PATH.
8805 First, this expands any special file name abbreviations. Then the
8806 configuration variable `org-file-apps' is checked if it contains an
8807 entry for this file type, and if yes, the corresponding command is launched.
8809 If no application is found, Emacs simply visits the file.
8811 With optional prefix argument IN-EMACS, Emacs will visit the file.
8812 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8813 and o use an external application to visit the file.
8815 Optional LINE specifies a line to go to, optional SEARCH a string to
8816 search for. If LINE or SEARCH is given, the file will always be
8817 opened in Emacs.
8818 If the file does not exist, an error is thrown."
8819 (setq in-emacs (or in-emacs line search))
8820 (let* ((file (if (equal path "")
8821 buffer-file-name
8822 (substitute-in-file-name (expand-file-name path))))
8823 (apps (append org-file-apps (org-default-apps)))
8824 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8825 (dirp (if remp nil (file-directory-p file)))
8826 (file (if (and dirp org-open-directory-means-index-dot-org)
8827 (concat (file-name-as-directory file) "index.org")
8828 file))
8829 (a-m-a-p (assq 'auto-mode apps))
8830 (dfile (downcase file))
8831 (old-buffer (current-buffer))
8832 (old-pos (point))
8833 (old-mode major-mode)
8834 ext cmd)
8835 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8836 (setq ext (match-string 1 dfile))
8837 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8838 (setq ext (match-string 1 dfile))))
8839 (cond
8840 ((equal in-emacs '(16))
8841 (setq cmd (cdr (assoc 'system apps))))
8842 (in-emacs (setq cmd 'emacs))
8844 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8845 (and dirp (cdr (assoc 'directory apps)))
8846 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8847 'string-match)
8848 (cdr (assoc ext apps))
8849 (cdr (assoc t apps))))))
8850 (when (eq cmd 'system)
8851 (setq cmd (cdr (assoc 'system apps))))
8852 (when (eq cmd 'default)
8853 (setq cmd (cdr (assoc t apps))))
8854 (when (eq cmd 'mailcap)
8855 (require 'mailcap)
8856 (mailcap-parse-mailcaps)
8857 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8858 (command (mailcap-mime-info mime-type)))
8859 (if (stringp command)
8860 (setq cmd command)
8861 (setq cmd 'emacs))))
8862 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8863 (not (file-exists-p file))
8864 (not org-open-non-existing-files))
8865 (error "No such file: %s" file))
8866 (cond
8867 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8868 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8869 (while (string-match "['\"]%s['\"]" cmd)
8870 (setq cmd (replace-match "%s" t t cmd)))
8871 (while (string-match "%s" cmd)
8872 (setq cmd (replace-match
8873 (save-match-data
8874 (shell-quote-argument
8875 (convert-standard-filename file)))
8876 t t cmd)))
8877 (save-window-excursion
8878 (start-process-shell-command cmd nil cmd)
8879 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8881 ((or (stringp cmd)
8882 (eq cmd 'emacs))
8883 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8884 (widen)
8885 (if line (org-goto-line line)
8886 (if search (org-link-search search))))
8887 ((consp cmd)
8888 (let ((file (convert-standard-filename file)))
8889 (eval cmd)))
8890 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8891 (and (org-mode-p) (eq old-mode 'org-mode)
8892 (or (not (equal old-buffer (current-buffer)))
8893 (not (equal old-pos (point))))
8894 (org-mark-ring-push old-pos old-buffer))))
8896 (defun org-default-apps ()
8897 "Return the default applications for this operating system."
8898 (cond
8899 ((eq system-type 'darwin)
8900 org-file-apps-defaults-macosx)
8901 ((eq system-type 'windows-nt)
8902 org-file-apps-defaults-windowsnt)
8903 (t org-file-apps-defaults-gnu)))
8905 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8906 "Convert extensions to regular expressions in the cars of LIST.
8907 Also, weed out any non-string entries, because the return value is used
8908 only for regexp matching.
8909 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8910 point to the symbol `emacs', indicating that the file should
8911 be opened in Emacs."
8912 (append
8913 (delq nil
8914 (mapcar (lambda (x)
8915 (if (not (stringp (car x)))
8917 (if (string-match "\\W" (car x))
8919 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8920 list))
8921 (if add-auto-mode
8922 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8924 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8925 (defun org-file-remote-p (file)
8926 "Test whether FILE specifies a location on a remote system.
8927 Return non-nil if the location is indeed remote.
8929 For example, the filename \"/user@host:/foo\" specifies a location
8930 on the system \"/user@host:\"."
8931 (cond ((fboundp 'file-remote-p)
8932 (file-remote-p file))
8933 ((fboundp 'tramp-handle-file-remote-p)
8934 (tramp-handle-file-remote-p file))
8935 ((and (boundp 'ange-ftp-name-format)
8936 (string-match (car ange-ftp-name-format) file))
8938 (t nil)))
8941 ;;;; Refiling
8943 (defun org-get-org-file ()
8944 "Read a filename, with default directory `org-directory'."
8945 (let ((default (or org-default-notes-file remember-data-file)))
8946 (read-file-name (format "File name [%s]: " default)
8947 (file-name-as-directory org-directory)
8948 default)))
8950 (defun org-notes-order-reversed-p ()
8951 "Check if the current file should receive notes in reversed order."
8952 (cond
8953 ((not org-reverse-note-order) nil)
8954 ((eq t org-reverse-note-order) t)
8955 ((not (listp org-reverse-note-order)) nil)
8956 (t (catch 'exit
8957 (let ((all org-reverse-note-order)
8958 entry)
8959 (while (setq entry (pop all))
8960 (if (string-match (car entry) buffer-file-name)
8961 (throw 'exit (cdr entry))))
8962 nil)))))
8964 (defvar org-refile-target-table nil
8965 "The list of refile targets, created by `org-refile'.")
8967 (defvar org-agenda-new-buffers nil
8968 "Buffers created to visit agenda files.")
8970 (defun org-get-refile-targets (&optional default-buffer)
8971 "Produce a table with refile targets."
8972 (let ((case-fold-search nil)
8973 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8974 (entries (or org-refile-targets '((nil . (:level . 1)))))
8975 targets txt re files f desc descre fast-path-p level pos0)
8976 (message "Getting targets...")
8977 (with-current-buffer (or default-buffer (current-buffer))
8978 (while (setq entry (pop entries))
8979 (setq files (car entry) desc (cdr entry))
8980 (setq fast-path-p nil)
8981 (cond
8982 ((null files) (setq files (list (current-buffer))))
8983 ((eq files 'org-agenda-files)
8984 (setq files (org-agenda-files 'unrestricted)))
8985 ((and (symbolp files) (fboundp files))
8986 (setq files (funcall files)))
8987 ((and (symbolp files) (boundp files))
8988 (setq files (symbol-value files))))
8989 (if (stringp files) (setq files (list files)))
8990 (cond
8991 ((eq (car desc) :tag)
8992 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8993 ((eq (car desc) :todo)
8994 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8995 ((eq (car desc) :regexp)
8996 (setq descre (cdr desc)))
8997 ((eq (car desc) :level)
8998 (setq descre (concat "^\\*\\{" (number-to-string
8999 (if org-odd-levels-only
9000 (1- (* 2 (cdr desc)))
9001 (cdr desc)))
9002 "\\}[ \t]")))
9003 ((eq (car desc) :maxlevel)
9004 (setq fast-path-p t)
9005 (setq descre (concat "^\\*\\{1," (number-to-string
9006 (if org-odd-levels-only
9007 (1- (* 2 (cdr desc)))
9008 (cdr desc)))
9009 "\\}[ \t]")))
9010 (t (error "Bad refiling target description %s" desc)))
9011 (while (setq f (pop files))
9012 (with-current-buffer
9013 (if (bufferp f) f (org-get-agenda-file-buffer f))
9014 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9015 (setq f (and f (expand-file-name f)))
9016 (if (eq org-refile-use-outline-path 'file)
9017 (push (list (file-name-nondirectory f) f nil nil) targets))
9018 (save-excursion
9019 (save-restriction
9020 (widen)
9021 (goto-char (point-min))
9022 (while (re-search-forward descre nil t)
9023 (goto-char (setq pos0 (point-at-bol)))
9024 (catch 'next
9025 (when org-refile-target-verify-function
9026 (save-match-data
9027 (or (funcall org-refile-target-verify-function)
9028 (throw 'next t))))
9029 (when (looking-at org-complex-heading-regexp)
9030 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9031 txt (org-link-display-format (match-string 4))
9032 re (concat "^" (regexp-quote
9033 (buffer-substring (match-beginning 1)
9034 (match-end 4)))))
9035 (if (match-end 5) (setq re (concat re "[ \t]+"
9036 (regexp-quote
9037 (match-string 5)))))
9038 (setq re (concat re "[ \t]*$"))
9039 (when org-refile-use-outline-path
9040 (setq txt (mapconcat 'org-protect-slash
9041 (append
9042 (if (eq org-refile-use-outline-path 'file)
9043 (list (file-name-nondirectory
9044 (buffer-file-name (buffer-base-buffer))))
9045 (if (eq org-refile-use-outline-path 'full-file-path)
9046 (list (buffer-file-name (buffer-base-buffer)))))
9047 (org-get-outline-path fast-path-p level txt)
9048 (list txt))
9049 "/")))
9050 (push (list txt f re (point)) targets)))
9051 (when (= (point) pos0)
9052 ;; verification function has not moved point
9053 (goto-char (point-at-eol))))))))))
9054 (message "Getting targets...done")
9055 (nreverse targets)))
9057 (defun org-protect-slash (s)
9058 (while (string-match "/" s)
9059 (setq s (replace-match "\\" t t s)))
9062 (defvar org-olpa (make-vector 20 nil))
9064 (defun org-get-outline-path (&optional fastp level heading)
9065 "Return the outline path to the current entry, as a list.
9066 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9067 routine which makes outline path derivations for an entire file,
9068 avoiding backtracing."
9069 (if fastp
9070 (progn
9071 (if (> level 19)
9072 (error "Outline path failure, more than 19 levels."))
9073 (loop for i from level upto 19 do
9074 (aset org-olpa i nil))
9075 (prog1
9076 (delq nil (append org-olpa nil))
9077 (aset org-olpa level heading)))
9078 (let (rtn)
9079 (save-excursion
9080 (save-restriction
9081 (widen)
9082 (while (org-up-heading-safe)
9083 (when (looking-at org-complex-heading-regexp)
9084 (push (org-match-string-no-properties 4) rtn)))
9085 rtn)))))
9087 (defun org-format-outline-path (path &optional width prefix)
9088 "Format the outlie path PATH for display.
9089 Width is the maximum number of characters that is available.
9090 Prefix is a prefix to be included in the returned string,
9091 such as the file name."
9092 (setq width (or width 79))
9093 (if prefix (setq width (- width (length prefix))))
9094 (if (not path)
9095 (or prefix "")
9096 (let* ((nsteps (length path))
9097 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9098 (maxwidth (if (<= total-width width)
9099 10000 ;; everything fits
9100 ;; we need to shorten the level headings
9101 (/ (- width nsteps) nsteps)))
9102 (org-odd-levels-only nil)
9103 (n 0)
9104 (total (1+ (length prefix))))
9105 (setq maxwidth (max maxwidth 10))
9106 (concat prefix
9107 (mapconcat
9108 (lambda (h)
9109 (setq n (1+ n))
9110 (if (and (= n nsteps) (< maxwidth 10000))
9111 (setq maxwidth (- total-width total)))
9112 (if (< (length h) maxwidth)
9113 (progn (setq total (+ total (length h) 1)) h)
9114 (setq h (substring h 0 (- maxwidth 2))
9115 total (+ total maxwidth 1))
9116 (if (string-match "[ \t]+\\'" h)
9117 (setq h (substring h 0 (match-beginning 0))))
9118 (setq h (concat h "..")))
9119 (org-add-props h nil 'face
9120 (nth (% (1- n) org-n-level-faces)
9121 org-level-faces))
9123 path "/")))))
9125 (defun org-display-outline-path (&optional file current)
9126 "Display the current outline path in the echo area."
9127 (interactive "P")
9128 (let ((bfn (buffer-file-name (buffer-base-buffer)))
9129 (path (and (org-mode-p) (org-get-outline-path))))
9130 (if current (setq path (append path
9131 (save-excursion
9132 (org-back-to-heading t)
9133 (if (looking-at org-complex-heading-regexp)
9134 (list (match-string 4)))))))
9135 (message "%s"
9136 (org-format-outline-path
9137 path
9138 (1- (frame-width))
9139 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9141 (defvar org-refile-history nil
9142 "History for refiling operations.")
9144 (defvar org-after-refile-insert-hook nil
9145 "Hook run after `org-refile' has inserted its stuff at the new location.
9146 Note that this is still *before* the stuff will be removed from
9147 the *old* location.")
9149 (defun org-refile (&optional goto default-buffer rfloc)
9150 "Move the entry at point to another heading.
9151 The list of target headings is compiled using the information in
9152 `org-refile-targets', which see. This list is created before each use
9153 and will therefore always be up-to-date.
9155 At the target location, the entry is filed as a subitem of the target heading.
9156 Depending on `org-reverse-note-order', the new subitem will either be the
9157 first or the last subitem.
9159 If there is an active region, all entries in that region will be moved.
9160 However, the region must fulfil the requirement that the first heading
9161 is the first one sets the top-level of the moved text - at most siblings
9162 below it are allowed.
9164 With prefix arg GOTO, the command will only visit the target location,
9165 not actually move anything.
9166 With a double prefix `C-u C-u', go to the location where the last refiling
9167 operation has put the subtree.
9168 With a prefix argument of `2', refile to the running clock.
9170 RFLOC can be a refile location obtained in a different way.
9172 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9173 (interactive "P")
9174 (let* ((cbuf (current-buffer))
9175 (regionp (org-region-active-p))
9176 (region-start (and regionp (region-beginning)))
9177 (region-end (and regionp (region-end)))
9178 (region-length (and regionp (- region-end region-start)))
9179 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9180 pos it nbuf file re level reversed)
9181 (setq last-command nil)
9182 (when regionp
9183 (goto-char region-start)
9184 (or (bolp) (goto-char (point-at-bol)))
9185 (setq region-start (point))
9186 (unless (org-kill-is-subtree-p
9187 (buffer-substring region-start region-end))
9188 (error "The region is not a (sequence of) subtree(s)")))
9189 (if (equal goto '(16))
9190 (org-refile-goto-last-stored)
9191 (when (or
9192 (and (equal goto 2)
9193 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9194 (prog1
9195 (setq it (list (or org-clock-heading "running clock")
9196 (buffer-file-name
9197 (marker-buffer org-clock-hd-marker))
9199 (marker-position org-clock-hd-marker)))
9200 (setq goto nil)))
9201 (setq it (or rfloc
9202 (save-excursion
9203 (org-refile-get-location
9204 (if goto "Goto: " "Refile to: ") default-buffer
9205 org-refile-allow-creating-parent-nodes)))))
9206 (setq file (nth 1 it)
9207 re (nth 2 it)
9208 pos (nth 3 it))
9209 (if (and (not goto)
9211 (equal (buffer-file-name) file)
9212 (if regionp
9213 (and (>= pos region-start)
9214 (<= pos region-end))
9215 (and (>= pos (point))
9216 (< pos (save-excursion
9217 (org-end-of-subtree t t))))))
9218 (error "Cannot refile to position inside the tree or region"))
9220 (setq nbuf (or (find-buffer-visiting file)
9221 (find-file-noselect file)))
9222 (if goto
9223 (progn
9224 (switch-to-buffer nbuf)
9225 (goto-char pos)
9226 (org-show-context 'org-goto))
9227 (if regionp
9228 (progn
9229 (org-kill-new (buffer-substring region-start region-end))
9230 (org-save-markers-in-region region-start region-end))
9231 (org-copy-subtree 1 nil t))
9232 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9233 (find-file-noselect file)))
9234 (setq reversed (org-notes-order-reversed-p))
9235 (save-excursion
9236 (save-restriction
9237 (widen)
9238 (if pos
9239 (progn
9240 (goto-char pos)
9241 (looking-at outline-regexp)
9242 (setq level (org-get-valid-level (funcall outline-level) 1))
9243 (goto-char
9244 (if reversed
9245 (or (outline-next-heading) (point-max))
9246 (or (save-excursion (org-get-next-sibling))
9247 (org-end-of-subtree t t)
9248 (point-max)))))
9249 (setq level 1)
9250 (if (not reversed)
9251 (goto-char (point-max))
9252 (goto-char (point-min))
9253 (or (outline-next-heading) (goto-char (point-max)))))
9254 (if (not (bolp)) (newline))
9255 (bookmark-set "org-refile-last-stored")
9256 (org-paste-subtree level)
9257 (if (fboundp 'deactivate-mark) (deactivate-mark))
9258 (run-hooks 'org-after-refile-insert-hook))))
9259 (if regionp
9260 (delete-region (point) (+ (point) region-length))
9261 (org-cut-subtree))
9262 (when (featurep 'org-inlinetask)
9263 (org-inlinetask-remove-END-maybe))
9264 (setq org-markers-to-move nil)
9265 (message "Refiled to \"%s\"" (car it))))))
9266 (org-reveal))
9268 (defun org-refile-goto-last-stored ()
9269 "Go to the location where the last refile was stored."
9270 (interactive)
9271 (bookmark-jump "org-refile-last-stored")
9272 (message "This is the location of the last refile"))
9274 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9275 "Prompt the user for a refile location, using PROMPT."
9276 (let ((org-refile-targets org-refile-targets)
9277 (org-refile-use-outline-path org-refile-use-outline-path))
9278 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9279 (unless org-refile-target-table
9280 (error "No refile targets"))
9281 (let* ((cbuf (current-buffer))
9282 (partial-completion-mode nil)
9283 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9284 (cfunc (if (and org-refile-use-outline-path
9285 org-outline-path-complete-in-steps)
9286 'org-olpath-completing-read
9287 'org-icompleting-read))
9288 (extra (if org-refile-use-outline-path "/" ""))
9289 (filename (and cfn (expand-file-name cfn)))
9290 (tbl (mapcar
9291 (lambda (x)
9292 (if (and (not (member org-refile-use-outline-path
9293 '(file full-file-path)))
9294 (not (equal filename (nth 1 x))))
9295 (cons (concat (car x) extra " ("
9296 (file-name-nondirectory (nth 1 x)) ")")
9297 (cdr x))
9298 (cons (concat (car x) extra) (cdr x))))
9299 org-refile-target-table))
9300 (completion-ignore-case t)
9301 pa answ parent-target child parent old-hist)
9302 (setq old-hist org-refile-history)
9303 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9304 nil 'org-refile-history))
9305 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9306 (if pa
9307 (progn
9308 (when (or (not org-refile-history)
9309 (not (eq old-hist org-refile-history))
9310 (not (equal (car pa) (car org-refile-history))))
9311 (setq org-refile-history
9312 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9313 org-refile-history
9314 (cdr org-refile-history))))
9315 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9316 (pop org-refile-history)))
9318 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9319 (setq parent (match-string 1 answ)
9320 child (match-string 2 answ))
9321 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9322 (when (and parent-target
9323 (or (eq new-nodes t)
9324 (and (eq new-nodes 'confirm)
9325 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9326 (org-refile-new-child parent-target child))))))
9328 (defun org-refile-new-child (parent-target child)
9329 "Use refile target PARENT-TARGET to add new CHILD below it."
9330 (unless parent-target
9331 (error "Cannot find parent for new node"))
9332 (let ((file (nth 1 parent-target))
9333 (pos (nth 3 parent-target))
9334 level)
9335 (with-current-buffer (or (find-buffer-visiting file)
9336 (find-file-noselect file))
9337 (save-excursion
9338 (save-restriction
9339 (widen)
9340 (if pos
9341 (goto-char pos)
9342 (goto-char (point-max))
9343 (if (not (bolp)) (newline)))
9344 (when (looking-at outline-regexp)
9345 (setq level (funcall outline-level))
9346 (org-end-of-subtree t t))
9347 (org-back-over-empty-lines)
9348 (insert "\n" (make-string
9349 (if pos (org-get-valid-level level 1) 1) ?*)
9350 " " child "\n")
9351 (beginning-of-line 0)
9352 (list (concat (car parent-target) "/" child) file "" (point)))))))
9354 (defun org-olpath-completing-read (prompt collection &rest args)
9355 "Read an outline path like a file name."
9356 (let ((thetable collection)
9357 (org-completion-use-ido nil) ; does not work with ido.
9358 (org-completion-use-iswitchb nil)) ; or iswitchb
9359 (apply
9360 'org-icompleting-read prompt
9361 (lambda (string predicate &optional flag)
9362 (let (rtn r f (l (length string)))
9363 (cond
9364 ((eq flag nil)
9365 ;; try completion
9366 (try-completion string thetable))
9367 ((eq flag t)
9368 ;; all-completions
9369 (setq rtn (all-completions string thetable predicate))
9370 (mapcar
9371 (lambda (x)
9372 (setq r (substring x l))
9373 (if (string-match " ([^)]*)$" x)
9374 (setq f (match-string 0 x))
9375 (setq f ""))
9376 (if (string-match "/" r)
9377 (concat string (substring r 0 (match-end 0)) f)
9379 rtn))
9380 ((eq flag 'lambda)
9381 ;; exact match?
9382 (assoc string thetable)))
9384 args)))
9386 ;;;; Dynamic blocks
9388 (defun org-find-dblock (name)
9389 "Find the first dynamic block with name NAME in the buffer.
9390 If not found, stay at current position and return nil."
9391 (let (pos)
9392 (save-excursion
9393 (goto-char (point-min))
9394 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9395 nil t)
9396 (match-beginning 0))))
9397 (if pos (goto-char pos))
9398 pos))
9400 (defconst org-dblock-start-re
9401 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9402 "Matches the start line of a dynamic block, with parameters.")
9404 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9405 "Matches the end of a dynamic block.")
9407 (defun org-create-dblock (plist)
9408 "Create a dynamic block section, with parameters taken from PLIST.
9409 PLIST must contain a :name entry which is used as name of the block."
9410 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9411 (end-of-line 1)
9412 (newline))
9413 (let ((col (current-column))
9414 (name (plist-get plist :name)))
9415 (insert "#+BEGIN: " name)
9416 (while plist
9417 (if (eq (car plist) :name)
9418 (setq plist (cddr plist))
9419 (insert " " (prin1-to-string (pop plist)))))
9420 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9421 (beginning-of-line -2)))
9423 (defun org-prepare-dblock ()
9424 "Prepare dynamic block for refresh.
9425 This empties the block, puts the cursor at the insert position and returns
9426 the property list including an extra property :name with the block name."
9427 (unless (looking-at org-dblock-start-re)
9428 (error "Not at a dynamic block"))
9429 (let* ((begdel (1+ (match-end 0)))
9430 (name (org-no-properties (match-string 1)))
9431 (params (append (list :name name)
9432 (read (concat "(" (match-string 3) ")")))))
9433 (save-excursion
9434 (beginning-of-line 1)
9435 (skip-chars-forward " \t")
9436 (setq params (plist-put params :indentation-column (current-column))))
9437 (unless (re-search-forward org-dblock-end-re nil t)
9438 (error "Dynamic block not terminated"))
9439 (setq params
9440 (append params
9441 (list :content (buffer-substring
9442 begdel (match-beginning 0)))))
9443 (delete-region begdel (match-beginning 0))
9444 (goto-char begdel)
9445 (open-line 1)
9446 params))
9448 (defun org-map-dblocks (&optional command)
9449 "Apply COMMAND to all dynamic blocks in the current buffer.
9450 If COMMAND is not given, use `org-update-dblock'."
9451 (let ((cmd (or command 'org-update-dblock))
9452 pos)
9453 (save-excursion
9454 (goto-char (point-min))
9455 (while (re-search-forward org-dblock-start-re nil t)
9456 (goto-char (setq pos (match-beginning 0)))
9457 (condition-case nil
9458 (funcall cmd)
9459 (error (message "Error during update of dynamic block")))
9460 (goto-char pos)
9461 (unless (re-search-forward org-dblock-end-re nil t)
9462 (error "Dynamic block not terminated"))))))
9464 (defun org-dblock-update (&optional arg)
9465 "User command for updating dynamic blocks.
9466 Update the dynamic block at point. With prefix ARG, update all dynamic
9467 blocks in the buffer."
9468 (interactive "P")
9469 (if arg
9470 (org-update-all-dblocks)
9471 (or (looking-at org-dblock-start-re)
9472 (org-beginning-of-dblock))
9473 (org-update-dblock)))
9475 (defun org-update-dblock ()
9476 "Update the dynamic block at point
9477 This means to empty the block, parse for parameters and then call
9478 the correct writing function."
9479 (save-window-excursion
9480 (let* ((pos (point))
9481 (line (org-current-line))
9482 (params (org-prepare-dblock))
9483 (name (plist-get params :name))
9484 (indent (plist-get params :indentation-column))
9485 (cmd (intern (concat "org-dblock-write:" name))))
9486 (message "Updating dynamic block `%s' at line %d..." name line)
9487 (funcall cmd params)
9488 (message "Updating dynamic block `%s' at line %d...done" name line)
9489 (goto-char pos)
9490 (when (and indent (> indent 0))
9491 (setq indent (make-string indent ?\ ))
9492 (save-excursion
9493 (org-beginning-of-dblock)
9494 (forward-line 1)
9495 (while (not (looking-at org-dblock-end-re))
9496 (insert indent)
9497 (beginning-of-line 2))
9498 (when (looking-at org-dblock-end-re)
9499 (and (looking-at "[ \t]+")
9500 (replace-match ""))
9501 (insert indent)))))))
9503 (defun org-beginning-of-dblock ()
9504 "Find the beginning of the dynamic block at point.
9505 Error if there is no such block at point."
9506 (let ((pos (point))
9507 beg)
9508 (end-of-line 1)
9509 (if (and (re-search-backward org-dblock-start-re nil t)
9510 (setq beg (match-beginning 0))
9511 (re-search-forward org-dblock-end-re nil t)
9512 (> (match-end 0) pos))
9513 (goto-char beg)
9514 (goto-char pos)
9515 (error "Not in a dynamic block"))))
9517 (defun org-update-all-dblocks ()
9518 "Update all dynamic blocks in the buffer.
9519 This function can be used in a hook."
9520 (when (org-mode-p)
9521 (org-map-dblocks 'org-update-dblock)))
9524 ;;;; Completion
9526 (defconst org-additional-option-like-keywords
9527 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9528 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9529 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9530 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9531 "BEGIN:" "END:"
9532 "ORGTBL" "TBLFM:" "TBLNAME:"
9533 "BEGIN_EXAMPLE" "END_EXAMPLE"
9534 "BEGIN_QUOTE" "END_QUOTE"
9535 "BEGIN_VERSE" "END_VERSE"
9536 "BEGIN_CENTER" "END_CENTER"
9537 "BEGIN_SRC" "END_SRC"
9538 "CATEGORY" "COLUMNS"
9539 "CAPTION" "LABEL"
9540 "SETUPFILE"
9541 "BIND"
9542 "MACRO"))
9544 (defcustom org-structure-template-alist
9546 ("s" "#+begin_src ?\n\n#+end_src"
9547 "<src lang=\"?\">\n\n</src>")
9548 ("e" "#+begin_example\n?\n#+end_example"
9549 "<example>\n?\n</example>")
9550 ("q" "#+begin_quote\n?\n#+end_quote"
9551 "<quote>\n?\n</quote>")
9552 ("v" "#+begin_verse\n?\n#+end_verse"
9553 "<verse>\n?\n/verse>")
9554 ("c" "#+begin_center\n?\n#+end_center"
9555 "<center>\n?\n/center>")
9556 ("l" "#+begin_latex\n?\n#+end_latex"
9557 "<literal style=\"latex\">\n?\n</literal>")
9558 ("L" "#+latex: "
9559 "<literal style=\"latex\">?</literal>")
9560 ("h" "#+begin_html\n?\n#+end_html"
9561 "<literal style=\"html\">\n?\n</literal>")
9562 ("H" "#+html: "
9563 "<literal style=\"html\">?</literal>")
9564 ("a" "#+begin_ascii\n?\n#+end_ascii")
9565 ("A" "#+ascii: ")
9566 ("i" "#+include %file ?"
9567 "<include file=%file markup=\"?\">")
9569 "Structure completion elements.
9570 This is a list of abbreviation keys and values. The value gets inserted
9571 it you type @samp{.} followed by the key and then the completion key,
9572 usually `M-TAB'. %file will be replaced by a file name after prompting
9573 for the file using completion.
9574 There are two templates for each key, the first uses the original Org syntax,
9575 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9576 the default when the /org-mtags.el/ module has been loaded. See also the
9577 variable `org-mtags-prefer-muse-templates'.
9578 This is an experimental feature, it is undecided if it is going to stay in."
9579 :group 'org-completion
9580 :type '(repeat
9581 (string :tag "Key")
9582 (string :tag "Template")
9583 (string :tag "Muse Template")))
9585 (defun org-try-structure-completion ()
9586 "Try to complete a structure template before point.
9587 This looks for strings like \"<e\" on an otherwise empty line and
9588 expands them."
9589 (let ((l (buffer-substring (point-at-bol) (point)))
9591 (when (and (looking-at "[ \t]*$")
9592 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9593 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9594 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9595 (match-beginning 1)) a)
9596 t)))
9598 (defun org-complete-expand-structure-template (start cell)
9599 "Expand a structure template."
9600 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9601 (rpl (nth (if musep 2 1) cell))
9602 (ind ""))
9603 (delete-region start (point))
9604 (when (string-match "\\`#\\+" rpl)
9605 (cond
9606 ((bolp))
9607 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9608 (setq ind (buffer-substring (point-at-bol) (point))))
9609 (t (newline))))
9610 (setq start (point))
9611 (if (string-match "%file" rpl)
9612 (setq rpl (replace-match
9613 (concat
9614 "\""
9615 (save-match-data
9616 (abbreviate-file-name (read-file-name "Include file: ")))
9617 "\"")
9618 t t rpl)))
9619 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9620 (concat "\n" ind)))
9621 (insert rpl)
9622 (if (re-search-backward "\\?" start t) (delete-char 1))))
9625 (defun org-complete (&optional arg)
9626 "Perform completion on word at point.
9627 At the beginning of a headline, this completes TODO keywords as given in
9628 `org-todo-keywords'.
9629 If the current word is preceded by a backslash, completes the TeX symbols
9630 that are supported for HTML support.
9631 If the current word is preceded by \"#+\", completes special words for
9632 setting file options.
9633 In the line after \"#+STARTUP:, complete valid keywords.\"
9634 At all other locations, this simply calls the value of
9635 `org-completion-fallback-command'."
9636 (interactive "P")
9637 (org-without-partial-completion
9638 (catch 'exit
9639 (let* ((a nil)
9640 (end (point))
9641 (beg1 (save-excursion
9642 (skip-chars-backward (org-re "[:alnum:]_@"))
9643 (point)))
9644 (beg (save-excursion
9645 (skip-chars-backward "a-zA-Z0-9_:$")
9646 (point)))
9647 (confirm (lambda (x) (stringp (car x))))
9648 (searchhead (equal (char-before beg) ?*))
9649 (struct
9650 (when (and (member (char-before beg1) '(?. ?<))
9651 (setq a (assoc (buffer-substring beg1 (point))
9652 org-structure-template-alist)))
9653 (org-complete-expand-structure-template (1- beg1) a)
9654 (throw 'exit t)))
9655 (tag (and (equal (char-before beg1) ?:)
9656 (equal (char-after (point-at-bol)) ?*)))
9657 (prop (and (equal (char-before beg1) ?:)
9658 (not (equal (char-after (point-at-bol)) ?*))))
9659 (texp (equal (char-before beg) ?\\))
9660 (link (equal (char-before beg) ?\[))
9661 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9662 beg)
9663 "#+"))
9664 (startup (string-match "^#\\+STARTUP:.*"
9665 (buffer-substring (point-at-bol) (point))))
9666 (completion-ignore-case opt)
9667 (type nil)
9668 (tbl nil)
9669 (table (cond
9670 (opt
9671 (setq type :opt)
9672 (require 'org-exp)
9673 (append
9674 (delq nil
9675 (mapcar
9676 (lambda (x)
9677 (if (string-match
9678 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9679 (cons (match-string 2 x)
9680 (match-string 1 x))))
9681 (org-split-string (org-get-current-options) "\n")))
9682 (mapcar 'list org-additional-option-like-keywords)))
9683 (startup
9684 (setq type :startup)
9685 org-startup-options)
9686 (link (append org-link-abbrev-alist-local
9687 org-link-abbrev-alist))
9688 (texp
9689 (setq type :tex)
9690 org-html-entities)
9691 ((string-match "\\`\\*+[ \t]+\\'"
9692 (buffer-substring (point-at-bol) beg))
9693 (setq type :todo)
9694 (mapcar 'list org-todo-keywords-1))
9695 (searchhead
9696 (setq type :searchhead)
9697 (save-excursion
9698 (goto-char (point-min))
9699 (while (re-search-forward org-todo-line-regexp nil t)
9700 (push (list
9701 (org-make-org-heading-search-string
9702 (match-string 3) t))
9703 tbl)))
9704 tbl)
9705 (tag (setq type :tag beg beg1)
9706 (or org-tag-alist (org-get-buffer-tags)))
9707 (prop (setq type :prop beg beg1)
9708 (mapcar 'list (org-buffer-property-keys nil t t)))
9709 (t (progn
9710 (call-interactively org-completion-fallback-command)
9711 (throw 'exit nil)))))
9712 (pattern (buffer-substring-no-properties beg end))
9713 (completion (try-completion pattern table confirm)))
9714 (cond ((eq completion t)
9715 (if (not (assoc (upcase pattern) table))
9716 (message "Already complete")
9717 (if (and (equal type :opt)
9718 (not (member (car (assoc (upcase pattern) table))
9719 org-additional-option-like-keywords)))
9720 (insert (substring (cdr (assoc (upcase pattern) table))
9721 (length pattern)))
9722 (if (memq type '(:tag :prop)) (insert ":")))))
9723 ((null completion)
9724 (message "Can't find completion for \"%s\"" pattern)
9725 (ding))
9726 ((not (string= pattern completion))
9727 (delete-region beg end)
9728 (if (string-match " +$" completion)
9729 (setq completion (replace-match "" t t completion)))
9730 (insert completion)
9731 (if (get-buffer-window "*Completions*")
9732 (delete-window (get-buffer-window "*Completions*")))
9733 (if (assoc completion table)
9734 (if (eq type :todo) (insert " ")
9735 (if (memq type '(:tag :prop)) (insert ":"))))
9736 (if (and (equal type :opt) (assoc completion table))
9737 (message "%s" (substitute-command-keys
9738 "Press \\[org-complete] again to insert example settings"))))
9740 (message "Making completion list...")
9741 (let ((list (sort (all-completions pattern table confirm)
9742 'string<)))
9743 (with-output-to-temp-buffer "*Completions*"
9744 (condition-case nil
9745 ;; Protection needed for XEmacs and emacs 21
9746 (display-completion-list list pattern)
9747 (error (display-completion-list list)))))
9748 (message "Making completion list...%s" "done")))))))
9750 ;;;; TODO, DEADLINE, Comments
9752 (defun org-toggle-comment ()
9753 "Change the COMMENT state of an entry."
9754 (interactive)
9755 (save-excursion
9756 (org-back-to-heading)
9757 (let (case-fold-search)
9758 (if (looking-at (concat outline-regexp
9759 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9760 (replace-match "" t t nil 1)
9761 (if (looking-at outline-regexp)
9762 (progn
9763 (goto-char (match-end 0))
9764 (insert org-comment-string " ")))))))
9766 (defvar org-last-todo-state-is-todo nil
9767 "This is non-nil when the last TODO state change led to a TODO state.
9768 If the last change removed the TODO tag or switched to DONE, then
9769 this is nil.")
9771 (defvar org-setting-tags nil) ; dynamically skipped
9773 (defun org-parse-local-options (string var)
9774 "Parse STRING for startup setting relevant for variable VAR."
9775 (let ((rtn (symbol-value var))
9776 e opts)
9777 (save-match-data
9778 (if (or (not string) (not (string-match "\\S-" string)))
9780 (setq opts (delq nil (mapcar (lambda (x)
9781 (setq e (assoc x org-startup-options))
9782 (if (eq (nth 1 e) var) e nil))
9783 (org-split-string string "[ \t]+"))))
9784 (if (not opts)
9786 (setq rtn nil)
9787 (while (setq e (pop opts))
9788 (if (not (nth 3 e))
9789 (setq rtn (nth 2 e))
9790 (if (not (listp rtn)) (setq rtn nil))
9791 (push (nth 2 e) rtn)))
9792 rtn)))))
9794 (defvar org-todo-setup-filter-hook nil
9795 "Hook for functions that pre-filter todo specs.
9797 Each function takes a todo spec and returns either `nil' or the spec
9798 transformed into canonical form." )
9800 (defvar org-todo-get-default-hook nil
9801 "Hook for functions that get a default item for todo.
9803 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9804 `nil' or a string to be used for the todo mark." )
9806 (defvar org-agenda-headline-snapshot-before-repeat)
9808 (defun org-todo (&optional arg)
9809 "Change the TODO state of an item.
9810 The state of an item is given by a keyword at the start of the heading,
9811 like
9812 *** TODO Write paper
9813 *** DONE Call mom
9815 The different keywords are specified in the variable `org-todo-keywords'.
9816 By default the available states are \"TODO\" and \"DONE\".
9817 So for this example: when the item starts with TODO, it is changed to DONE.
9818 When it starts with DONE, the DONE is removed. And when neither TODO nor
9819 DONE are present, add TODO at the beginning of the heading.
9821 With C-u prefix arg, use completion to determine the new state.
9822 With numeric prefix arg, switch to that state.
9823 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9824 With a triple C-u prefix, circumvent any state blocking.
9826 For calling through lisp, arg is also interpreted in the following way:
9827 'none -> empty state
9828 \"\"(empty string) -> switch to empty state
9829 'done -> switch to DONE
9830 'nextset -> switch to the next set of keywords
9831 'previousset -> switch to the previous set of keywords
9832 \"WAITING\" -> switch to the specified keyword, but only if it
9833 really is a member of `org-todo-keywords'."
9834 (interactive "P")
9835 (if (equal arg '(16)) (setq arg 'nextset))
9836 (let ((org-blocker-hook org-blocker-hook)
9837 (case-fold-search nil))
9838 (when (equal arg '(64))
9839 (setq arg nil org-blocker-hook nil))
9840 (when (and org-blocker-hook
9841 (or org-inhibit-blocking
9842 (org-entry-get nil "NOBLOCKING")))
9843 (setq org-blocker-hook nil))
9844 (save-excursion
9845 (catch 'exit
9846 (org-back-to-heading t)
9847 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9848 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9849 (looking-at " *"))
9850 (let* ((match-data (match-data))
9851 (startpos (point-at-bol))
9852 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9853 (org-log-done org-log-done)
9854 (org-log-repeat org-log-repeat)
9855 (org-todo-log-states org-todo-log-states)
9856 (this (match-string 1))
9857 (hl-pos (match-beginning 0))
9858 (head (org-get-todo-sequence-head this))
9859 (ass (assoc head org-todo-kwd-alist))
9860 (interpret (nth 1 ass))
9861 (done-word (nth 3 ass))
9862 (final-done-word (nth 4 ass))
9863 (last-state (or this ""))
9864 (completion-ignore-case t)
9865 (member (member this org-todo-keywords-1))
9866 (tail (cdr member))
9867 (state (cond
9868 ((and org-todo-key-trigger
9869 (or (and (equal arg '(4))
9870 (eq org-use-fast-todo-selection 'prefix))
9871 (and (not arg) org-use-fast-todo-selection
9872 (not (eq org-use-fast-todo-selection
9873 'prefix)))))
9874 ;; Use fast selection
9875 (org-fast-todo-selection))
9876 ((and (equal arg '(4))
9877 (or (not org-use-fast-todo-selection)
9878 (not org-todo-key-trigger)))
9879 ;; Read a state with completion
9880 (org-icompleting-read
9881 "State: " (mapcar (lambda(x) (list x))
9882 org-todo-keywords-1)
9883 nil t))
9884 ((eq arg 'right)
9885 (if this
9886 (if tail (car tail) nil)
9887 (car org-todo-keywords-1)))
9888 ((eq arg 'left)
9889 (if (equal member org-todo-keywords-1)
9891 (if this
9892 (nth (- (length org-todo-keywords-1)
9893 (length tail) 2)
9894 org-todo-keywords-1)
9895 (org-last org-todo-keywords-1))))
9896 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9897 (setq arg nil))) ; hack to fall back to cycling
9898 (arg
9899 ;; user or caller requests a specific state
9900 (cond
9901 ((equal arg "") nil)
9902 ((eq arg 'none) nil)
9903 ((eq arg 'done) (or done-word (car org-done-keywords)))
9904 ((eq arg 'nextset)
9905 (or (car (cdr (member head org-todo-heads)))
9906 (car org-todo-heads)))
9907 ((eq arg 'previousset)
9908 (let ((org-todo-heads (reverse org-todo-heads)))
9909 (or (car (cdr (member head org-todo-heads)))
9910 (car org-todo-heads))))
9911 ((car (member arg org-todo-keywords-1)))
9912 ((stringp arg)
9913 (error "State `%s' not valid in this file" arg))
9914 ((nth (1- (prefix-numeric-value arg))
9915 org-todo-keywords-1))))
9916 ((null member) (or head (car org-todo-keywords-1)))
9917 ((equal this final-done-word) nil) ;; -> make empty
9918 ((null tail) nil) ;; -> first entry
9919 ((memq interpret '(type priority))
9920 (if (eq this-command last-command)
9921 (car tail)
9922 (if (> (length tail) 0)
9923 (or done-word (car org-done-keywords))
9924 nil)))
9926 (car tail))))
9927 (state (or
9928 (run-hook-with-args-until-success
9929 'org-todo-get-default-hook state last-state)
9930 state))
9931 (next (if state (concat " " state " ") " "))
9932 (change-plist (list :type 'todo-state-change :from this :to state
9933 :position startpos))
9934 dolog now-done-p)
9935 (when org-blocker-hook
9936 (setq org-last-todo-state-is-todo
9937 (not (member this org-done-keywords)))
9938 (unless (save-excursion
9939 (save-match-data
9940 (run-hook-with-args-until-failure
9941 'org-blocker-hook change-plist)))
9942 (if (interactive-p)
9943 (error "TODO state change from %s to %s blocked" this state)
9944 ;; fail silently
9945 (message "TODO state change from %s to %s blocked" this state)
9946 (throw 'exit nil))))
9947 (store-match-data match-data)
9948 (replace-match next t t)
9949 (unless (pos-visible-in-window-p hl-pos)
9950 (message "TODO state changed to %s" (org-trim next)))
9951 (unless head
9952 (setq head (org-get-todo-sequence-head state)
9953 ass (assoc head org-todo-kwd-alist)
9954 interpret (nth 1 ass)
9955 done-word (nth 3 ass)
9956 final-done-word (nth 4 ass)))
9957 (when (memq arg '(nextset previousset))
9958 (message "Keyword-Set %d/%d: %s"
9959 (- (length org-todo-sets) -1
9960 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9961 (length org-todo-sets)
9962 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9963 (setq org-last-todo-state-is-todo
9964 (not (member state org-done-keywords)))
9965 (setq now-done-p (and (member state org-done-keywords)
9966 (not (member this org-done-keywords))))
9967 (and logging (org-local-logging logging))
9968 (when (and (or org-todo-log-states org-log-done)
9969 (not (eq org-inhibit-logging t))
9970 (not (memq arg '(nextset previousset))))
9971 ;; we need to look at recording a time and note
9972 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9973 (nth 2 (assoc this org-todo-log-states))))
9974 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9975 (setq dolog 'time))
9976 (when (and state
9977 (member state org-not-done-keywords)
9978 (not (member this org-not-done-keywords)))
9979 ;; This is now a todo state and was not one before
9980 ;; If there was a CLOSED time stamp, get rid of it.
9981 (org-add-planning-info nil nil 'closed))
9982 (when (and now-done-p org-log-done)
9983 ;; It is now done, and it was not done before
9984 (org-add-planning-info 'closed (org-current-time))
9985 (if (and (not dolog) (eq 'note org-log-done))
9986 (org-add-log-setup 'done state this 'findpos 'note)))
9987 (when (and state dolog)
9988 ;; This is a non-nil state, and we need to log it
9989 (org-add-log-setup 'state state this 'findpos dolog)))
9990 ;; Fixup tag positioning
9991 (org-todo-trigger-tag-changes state)
9992 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9993 (when org-provide-todo-statistics
9994 (org-update-parent-todo-statistics))
9995 (run-hooks 'org-after-todo-state-change-hook)
9996 (if (and arg (not (member state org-done-keywords)))
9997 (setq head (org-get-todo-sequence-head state)))
9998 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9999 ;; Do we need to trigger a repeat?
10000 (when now-done-p
10001 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10002 ;; This is for the agenda, take a snapshot of the headline.
10003 (save-match-data
10004 (setq org-agenda-headline-snapshot-before-repeat
10005 (org-get-heading))))
10006 (org-auto-repeat-maybe state))
10007 ;; Fixup cursor location if close to the keyword
10008 (if (and (outline-on-heading-p)
10009 (not (bolp))
10010 (save-excursion (beginning-of-line 1)
10011 (looking-at org-todo-line-regexp))
10012 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10013 (progn
10014 (goto-char (or (match-end 2) (match-end 1)))
10015 (and (looking-at " ") (just-one-space))))
10016 (when org-trigger-hook
10017 (save-excursion
10018 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10020 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10021 "Block turning an entry into a TODO, using the hierarchy.
10022 This checks whether the current task should be blocked from state
10023 changes. Such blocking occurs when:
10025 1. The task has children which are not all in a completed state.
10027 2. A task has a parent with the property :ORDERED:, and there
10028 are siblings prior to the current task with incomplete
10029 status.
10031 3. The parent of the task is blocked because it has siblings that should
10032 be done first, or is child of a block grandparent TODO entry."
10034 (catch 'dont-block
10035 ;; If this is not a todo state change, or if this entry is already DONE,
10036 ;; do not block
10037 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10038 (member (plist-get change-plist :from)
10039 (cons 'done org-done-keywords))
10040 (member (plist-get change-plist :to)
10041 (cons 'todo org-not-done-keywords))
10042 (not (plist-get change-plist :to)))
10043 (throw 'dont-block t))
10044 ;; If this task has children, and any are undone, it's blocked
10045 (save-excursion
10046 (org-back-to-heading t)
10047 (let ((this-level (funcall outline-level)))
10048 (outline-next-heading)
10049 (let ((child-level (funcall outline-level)))
10050 (while (and (not (eobp))
10051 (> child-level this-level))
10052 ;; this todo has children, check whether they are all
10053 ;; completed
10054 (if (and (not (org-entry-is-done-p))
10055 (org-entry-is-todo-p))
10056 (throw 'dont-block nil))
10057 (outline-next-heading)
10058 (setq child-level (funcall outline-level))))))
10059 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10060 ;; any previous siblings are undone, it's blocked
10061 (save-excursion
10062 (org-back-to-heading t)
10063 (let* ((pos (point))
10064 (parent-pos (and (org-up-heading-safe) (point))))
10065 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10066 (when (and (org-entry-get (point) "ORDERED")
10067 (forward-line 1)
10068 (re-search-forward org-not-done-heading-regexp pos t))
10069 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10070 ;; Search further up the hierarchy, to see if an anchestor is blocked
10071 (while t
10072 (goto-char parent-pos)
10073 (if (not (looking-at org-not-done-heading-regexp))
10074 (throw 'dont-block t)) ; do not block, parent is not a TODO
10075 (setq pos (point))
10076 (setq parent-pos (and (org-up-heading-safe) (point)))
10077 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10078 (when (and (org-entry-get (point) "ORDERED")
10079 (forward-line 1)
10080 (re-search-forward org-not-done-heading-regexp pos t))
10081 (throw 'dont-block nil))))))) ; block, older sibling not done.
10083 (defcustom org-track-ordered-property-with-tag nil
10084 "Should the ORDERED property also be shown as a tag?
10085 The ORDERED property decides if an entry should require subtasks to be
10086 completed in sequence. Since a property is not very visible, setting
10087 this option means that toggling the ORDERED property with the command
10088 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10089 not relevant for the behavior, but it makes things more visible.
10091 Note that toggling the tag with tags commands will not change the property
10092 and therefore not influence behavior!
10094 This can be t, meaning the tag ORDERED should be used, It can also be a
10095 string to select a different tag for this task."
10096 :group 'org-todo
10097 :type '(choice
10098 (const :tag "No tracking" nil)
10099 (const :tag "Track with ORDERED tag" t)
10100 (string :tag "Use other tag")))
10102 (defun org-toggle-ordered-property ()
10103 "Toggle the ORDERED property of the current entry.
10104 For better visibility, you can track the value of this property with a tag.
10105 See variable `org-track-ordered-property-with-tag'."
10106 (interactive)
10107 (let* ((t1 org-track-ordered-property-with-tag)
10108 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10109 (save-excursion
10110 (org-back-to-heading)
10111 (if (org-entry-get nil "ORDERED")
10112 (progn
10113 (org-delete-property "ORDERED")
10114 (and tag (org-toggle-tag tag 'off))
10115 (message "Subtasks can be completed in arbitrary order"))
10116 (org-entry-put nil "ORDERED" "t")
10117 (and tag (org-toggle-tag tag 'on))
10118 (message "Subtasks must be completed in sequence")))))
10120 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10121 (defun org-block-todo-from-checkboxes (change-plist)
10122 "Block turning an entry into a TODO, using checkboxes.
10123 This checks whether the current task should be blocked from state
10124 changes because there are unchecked boxes in this entry."
10125 (catch 'dont-block
10126 ;; If this is not a todo state change, or if this entry is already DONE,
10127 ;; do not block
10128 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10129 (member (plist-get change-plist :from)
10130 (cons 'done org-done-keywords))
10131 (member (plist-get change-plist :to)
10132 (cons 'todo org-not-done-keywords))
10133 (not (plist-get change-plist :to)))
10134 (throw 'dont-block t))
10135 ;; If this task has checkboxes that are not checked, it's blocked
10136 (save-excursion
10137 (org-back-to-heading t)
10138 (let ((beg (point)) end)
10139 (outline-next-heading)
10140 (setq end (point))
10141 (goto-char beg)
10142 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10143 end t)
10144 (progn
10145 (if (boundp 'org-blocked-by-checkboxes)
10146 (setq org-blocked-by-checkboxes t))
10147 (throw 'dont-block nil)))))
10148 t)) ; do not block
10150 (defun org-update-statistics-cookies (all)
10151 "Update the statistics cookie, either from TODO or from checkboxes.
10152 This should be called with the cursor in a line with a statistics cookie."
10153 (interactive "P")
10154 (if all
10155 (progn
10156 (org-update-checkbox-count 'all)
10157 (org-map-entries 'org-update-parent-todo-statistics))
10158 (if (not (org-on-heading-p))
10159 (org-update-checkbox-count)
10160 (let ((pos (move-marker (make-marker) (point)))
10161 end l1 l2)
10162 (ignore-errors (org-back-to-heading t))
10163 (if (not (org-on-heading-p))
10164 (org-update-checkbox-count)
10165 (setq l1 (org-outline-level))
10166 (setq end (save-excursion
10167 (outline-next-heading)
10168 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10169 (point)))
10170 (if (and (save-excursion (re-search-forward
10171 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10172 (not (save-excursion (re-search-forward
10173 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10174 (org-update-checkbox-count)
10175 (if (and l2 (> l2 l1))
10176 (progn
10177 (goto-char end)
10178 (org-update-parent-todo-statistics))
10179 (error "No data for statistics cookie"))))
10180 (goto-char pos)
10181 (move-marker pos nil)))))
10183 (defvar org-entry-property-inherited-from) ;; defined below
10184 (defun org-update-parent-todo-statistics ()
10185 "Update any statistics cookie in the parent of the current headline.
10186 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10187 the entire subtree and this will travel up the hierarchy and update
10188 statistics everywhere."
10189 (interactive)
10190 (let* ((lim 0) prop
10191 (recursive (or (not org-hierarchical-todo-statistics)
10192 (string-match
10193 "\\<recursive\\>"
10194 (or (setq prop (org-entry-get
10195 nil "COOKIE_DATA" 'inherit)) ""))))
10196 (lim (or (and prop (marker-position
10197 org-entry-property-inherited-from))
10198 lim))
10199 (first t)
10200 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10201 level ltoggle l1 new ndel
10202 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10203 (catch 'exit
10204 (save-excursion
10205 (beginning-of-line 1)
10206 (if (org-at-heading-p)
10207 (setq ltoggle (funcall outline-level))
10208 (error "This should not happen"))
10209 (while (and (setq level (org-up-heading-safe))
10210 (or recursive first)
10211 (>= (point) lim))
10212 (setq first nil cookie-present nil)
10213 (unless (and level
10214 (not (string-match
10215 "\\<checkbox\\>"
10216 (downcase
10217 (or (org-entry-get
10218 nil "COOKIE_DATA")
10219 "")))))
10220 (throw 'exit nil))
10221 (while (re-search-forward box-re (point-at-eol) t)
10222 (setq cnt-all 0 cnt-done 0 cookie-present t)
10223 (setq is-percent (match-end 2))
10224 (save-match-data
10225 (unless (outline-next-heading) (throw 'exit nil))
10226 (while (and (looking-at org-complex-heading-regexp)
10227 (> (setq l1 (length (match-string 1))) level))
10228 (setq kwd (and (or recursive (= l1 ltoggle))
10229 (match-string 2)))
10230 (if (or (eq org-provide-todo-statistics 'all-headlines)
10231 (and (listp org-provide-todo-statistics)
10232 (or (member kwd org-provide-todo-statistics)
10233 (member kwd org-done-keywords))))
10234 (setq cnt-all (1+ cnt-all))
10235 (if (eq org-provide-todo-statistics t)
10236 (and kwd (setq cnt-all (1+ cnt-all)))))
10237 (and (member kwd org-done-keywords)
10238 (setq cnt-done (1+ cnt-done)))
10239 (outline-next-heading)))
10240 (setq new
10241 (if is-percent
10242 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10243 (format "[%d/%d]" cnt-done cnt-all))
10244 ndel (- (match-end 0) (match-beginning 0)))
10245 (goto-char (match-beginning 0))
10246 (insert new)
10247 (delete-region (point) (+ (point) ndel)))
10248 (when cookie-present
10249 (run-hook-with-args 'org-after-todo-statistics-hook
10250 cnt-done (- cnt-all cnt-done))))))
10251 (run-hooks 'org-todo-statistics-hook)))
10253 (defvar org-after-todo-statistics-hook nil
10254 "Hook that is called after a TODO statistics cookie has been updated.
10255 Each function is called with two arguments: the number of not-done entries
10256 and the number of done entries.
10258 For example, the following function, when added to this hook, will switch
10259 an entry to DONE when all children are done, and back to TODO when new
10260 entries are set to a TODO status. Note that this hook is only called
10261 when there is a statistics cookie in the headline!
10263 (defun org-summary-todo (n-done n-not-done)
10264 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10265 (let (org-log-done org-log-states) ; turn off logging
10266 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10269 (defvar org-todo-statistics-hook nil
10270 "Hook that is run whenever Org thinks TODO statistics should be updated.
10271 This hook runs even if there is no statistics cookie present, in which case
10272 `org-after-todo-statistics-hook' would not run.")
10274 (defun org-todo-trigger-tag-changes (state)
10275 "Apply the changes defined in `org-todo-state-tags-triggers'."
10276 (let ((l org-todo-state-tags-triggers)
10277 changes)
10278 (when (or (not state) (equal state ""))
10279 (setq changes (append changes (cdr (assoc "" l)))))
10280 (when (and (stringp state) (> (length state) 0))
10281 (setq changes (append changes (cdr (assoc state l)))))
10282 (when (member state org-not-done-keywords)
10283 (setq changes (append changes (cdr (assoc 'todo l)))))
10284 (when (member state org-done-keywords)
10285 (setq changes (append changes (cdr (assoc 'done l)))))
10286 (dolist (c changes)
10287 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10289 (defun org-local-logging (value)
10290 "Get logging settings from a property VALUE."
10291 (let* (words w a)
10292 ;; directly set the variables, they are already local.
10293 (setq org-log-done nil
10294 org-log-repeat nil
10295 org-todo-log-states nil)
10296 (setq words (org-split-string value))
10297 (while (setq w (pop words))
10298 (cond
10299 ((setq a (assoc w org-startup-options))
10300 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10301 (set (nth 1 a) (nth 2 a))))
10302 ((setq a (org-extract-log-state-settings w))
10303 (and (member (car a) org-todo-keywords-1)
10304 (push a org-todo-log-states)))))))
10306 (defun org-get-todo-sequence-head (kwd)
10307 "Return the head of the TODO sequence to which KWD belongs.
10308 If KWD is not set, check if there is a text property remembering the
10309 right sequence."
10310 (let (p)
10311 (cond
10312 ((not kwd)
10313 (or (get-text-property (point-at-bol) 'org-todo-head)
10314 (progn
10315 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10316 nil (point-at-eol)))
10317 (get-text-property p 'org-todo-head))))
10318 ((not (member kwd org-todo-keywords-1))
10319 (car org-todo-keywords-1))
10320 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10322 (defun org-fast-todo-selection ()
10323 "Fast TODO keyword selection with single keys.
10324 Returns the new TODO keyword, or nil if no state change should occur."
10325 (let* ((fulltable org-todo-key-alist)
10326 (done-keywords org-done-keywords) ;; needed for the faces.
10327 (maxlen (apply 'max (mapcar
10328 (lambda (x)
10329 (if (stringp (car x)) (string-width (car x)) 0))
10330 fulltable)))
10331 (expert nil)
10332 (fwidth (+ maxlen 3 1 3))
10333 (ncol (/ (- (window-width) 4) fwidth))
10334 tg cnt e c tbl
10335 groups ingroup)
10336 (save-excursion
10337 (save-window-excursion
10338 (if expert
10339 (set-buffer (get-buffer-create " *Org todo*"))
10340 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10341 (erase-buffer)
10342 (org-set-local 'org-done-keywords done-keywords)
10343 (setq tbl fulltable cnt 0)
10344 (while (setq e (pop tbl))
10345 (cond
10346 ((equal e '(:startgroup))
10347 (push '() groups) (setq ingroup t)
10348 (when (not (= cnt 0))
10349 (setq cnt 0)
10350 (insert "\n"))
10351 (insert "{ "))
10352 ((equal e '(:endgroup))
10353 (setq ingroup nil cnt 0)
10354 (insert "}\n"))
10355 ((equal e '(:newline))
10356 (when (not (= cnt 0))
10357 (setq cnt 0)
10358 (insert "\n")
10359 (setq e (car tbl))
10360 (while (equal (car tbl) '(:newline))
10361 (insert "\n")
10362 (setq tbl (cdr tbl)))))
10364 (setq tg (car e) c (cdr e))
10365 (if ingroup (push tg (car groups)))
10366 (setq tg (org-add-props tg nil 'face
10367 (org-get-todo-face tg)))
10368 (if (and (= cnt 0) (not ingroup)) (insert " "))
10369 (insert "[" c "] " tg (make-string
10370 (- fwidth 4 (length tg)) ?\ ))
10371 (when (= (setq cnt (1+ cnt)) ncol)
10372 (insert "\n")
10373 (if ingroup (insert " "))
10374 (setq cnt 0)))))
10375 (insert "\n")
10376 (goto-char (point-min))
10377 (if (not expert) (org-fit-window-to-buffer))
10378 (message "[a-z..]:Set [SPC]:clear")
10379 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10380 (cond
10381 ((or (= c ?\C-g)
10382 (and (= c ?q) (not (rassoc c fulltable))))
10383 (setq quit-flag t))
10384 ((= c ?\ ) nil)
10385 ((setq e (rassoc c fulltable) tg (car e))
10387 (t (setq quit-flag t)))))))
10389 (defun org-entry-is-todo-p ()
10390 (member (org-get-todo-state) org-not-done-keywords))
10392 (defun org-entry-is-done-p ()
10393 (member (org-get-todo-state) org-done-keywords))
10395 (defun org-get-todo-state ()
10396 (save-excursion
10397 (org-back-to-heading t)
10398 (and (looking-at org-todo-line-regexp)
10399 (match-end 2)
10400 (match-string 2))))
10402 (defun org-at-date-range-p (&optional inactive-ok)
10403 "Is the cursor inside a date range?"
10404 (interactive)
10405 (save-excursion
10406 (catch 'exit
10407 (let ((pos (point)))
10408 (skip-chars-backward "^[<\r\n")
10409 (skip-chars-backward "<[")
10410 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10411 (>= (match-end 0) pos)
10412 (throw 'exit t))
10413 (skip-chars-backward "^<[\r\n")
10414 (skip-chars-backward "<[")
10415 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10416 (>= (match-end 0) pos)
10417 (throw 'exit t)))
10418 nil)))
10420 (defun org-get-repeat (&optional tagline)
10421 "Check if there is a deadline/schedule with repeater in this entry."
10422 (save-match-data
10423 (save-excursion
10424 (org-back-to-heading t)
10425 (and (re-search-forward (if tagline
10426 (concat tagline "\\s-*" org-repeat-re)
10427 org-repeat-re)
10428 (org-entry-end-position) t)
10429 (match-string-no-properties 1)))))
10431 (defvar org-last-changed-timestamp)
10432 (defvar org-last-inserted-timestamp)
10433 (defvar org-log-post-message)
10434 (defvar org-log-note-purpose)
10435 (defvar org-log-note-how)
10436 (defvar org-log-note-extra)
10437 (defun org-auto-repeat-maybe (done-word)
10438 "Check if the current headline contains a repeated deadline/schedule.
10439 If yes, set TODO state back to what it was and change the base date
10440 of repeating deadline/scheduled time stamps to new date.
10441 This function is run automatically after each state change to a DONE state."
10442 ;; last-state is dynamically scoped into this function
10443 (let* ((repeat (org-get-repeat))
10444 (aa (assoc last-state org-todo-kwd-alist))
10445 (interpret (nth 1 aa))
10446 (head (nth 2 aa))
10447 (whata '(("d" . day) ("m" . month) ("y" . year)))
10448 (msg "Entry repeats: ")
10449 (org-log-done nil)
10450 (org-todo-log-states nil)
10451 (nshiftmax 10) (nshift 0)
10452 re type n what ts time)
10453 (when repeat
10454 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10455 (org-todo (if (eq interpret 'type) last-state head))
10456 (org-entry-put nil "LAST_REPEAT" (format-time-string
10457 (org-time-stamp-format t t)))
10458 (when org-log-repeat
10459 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10460 (memq 'org-add-log-note post-command-hook))
10461 ;; OK, we are already setup for some record
10462 (if (eq org-log-repeat 'note)
10463 ;; make sure we take a note, not only a time stamp
10464 (setq org-log-note-how 'note))
10465 ;; Set up for taking a record
10466 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10467 last-state
10468 'findpos org-log-repeat)))
10469 (org-back-to-heading t)
10470 (org-add-planning-info nil nil 'closed)
10471 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10472 org-deadline-time-regexp "\\)\\|\\("
10473 org-ts-regexp "\\)"))
10474 (while (re-search-forward
10475 re (save-excursion (outline-next-heading) (point)) t)
10476 (setq type (if (match-end 1) org-scheduled-string
10477 (if (match-end 3) org-deadline-string "Plain:"))
10478 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10479 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10480 (setq n (string-to-number (match-string 2 ts))
10481 what (match-string 3 ts))
10482 (if (equal what "w") (setq n (* n 7) what "d"))
10483 ;; Preparation, see if we need to modify the start date for the change
10484 (when (match-end 1)
10485 (setq time (save-match-data (org-time-string-to-time ts)))
10486 (cond
10487 ((equal (match-string 1 ts) ".")
10488 ;; Shift starting date to today
10489 (org-timestamp-change
10490 (- (time-to-days (current-time)) (time-to-days time))
10491 'day))
10492 ((equal (match-string 1 ts) "+")
10493 (while (or (= nshift 0)
10494 (<= (time-to-days time) (time-to-days (current-time))))
10495 (when (= (incf nshift) nshiftmax)
10496 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10497 (error "Abort")))
10498 (org-timestamp-change n (cdr (assoc what whata)))
10499 (org-at-timestamp-p t)
10500 (setq ts (match-string 1))
10501 (setq time (save-match-data (org-time-string-to-time ts))))
10502 (org-timestamp-change (- n) (cdr (assoc what whata)))
10503 ;; rematch, so that we have everything in place for the real shift
10504 (org-at-timestamp-p t)
10505 (setq ts (match-string 1))
10506 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10507 (org-timestamp-change n (cdr (assoc what whata)))
10508 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10509 (setq org-log-post-message msg)
10510 (message "%s" msg))))
10512 (defun org-show-todo-tree (arg)
10513 "Make a compact tree which shows all headlines marked with TODO.
10514 The tree will show the lines where the regexp matches, and all higher
10515 headlines above the match.
10516 With a \\[universal-argument] prefix, prompt for a regexp to match.
10517 With a numeric prefix N, construct a sparse tree for the Nth element
10518 of `org-todo-keywords-1'."
10519 (interactive "P")
10520 (let ((case-fold-search nil)
10521 (kwd-re
10522 (cond ((null arg) org-not-done-regexp)
10523 ((equal arg '(4))
10524 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10525 (mapcar 'list org-todo-keywords-1))))
10526 (concat "\\("
10527 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10528 "\\)\\>")))
10529 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10530 (regexp-quote (nth (1- (prefix-numeric-value arg))
10531 org-todo-keywords-1)))
10532 (t (error "Invalid prefix argument: %s" arg)))))
10533 (message "%d TODO entries found"
10534 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10536 (defun org-deadline (&optional remove time)
10537 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10538 With argument REMOVE, remove any deadline from the item.
10539 When TIME is set, it should be an internal time specification, and the
10540 scheduling will use the corresponding date."
10541 (interactive "P")
10542 (let ((old-date (org-entry-get nil "DEADLINE")))
10543 (if remove
10544 (progn
10545 (org-remove-timestamp-with-keyword org-deadline-string)
10546 (message "Item no longer has a deadline."))
10547 (if (org-get-repeat)
10548 (error "Cannot change deadline on task with repeater, please do that by hand")
10549 (org-add-planning-info 'deadline time 'closed)
10550 (when (and old-date org-log-redeadline
10551 (not (equal old-date
10552 (substring org-last-inserted-timestamp 1 -1))))
10553 (org-add-log-setup 'redeadline nil old-date 'findpos
10554 org-log-redeadline))
10555 (message "Deadline on %s" org-last-inserted-timestamp)))))
10557 (defun org-schedule (&optional remove time)
10558 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10559 With argument REMOVE, remove any scheduling date from the item.
10560 When TIME is set, it should be an internal time specification, and the
10561 scheduling will use the corresponding date."
10562 (interactive "P")
10563 (let ((old-date (org-entry-get nil "SCHEDULED")))
10564 (if remove
10565 (progn
10566 (org-remove-timestamp-with-keyword org-scheduled-string)
10567 (message "Item is no longer scheduled."))
10568 (if (org-get-repeat)
10569 (error "Cannot reschedule task with repeater, please do that by hand")
10570 (org-add-planning-info 'scheduled time 'closed)
10571 (when (and old-date org-log-reschedule
10572 (not (equal old-date
10573 (substring org-last-inserted-timestamp 1 -1))))
10574 (org-add-log-setup 'reschedule nil old-date 'findpos
10575 org-log-reschedule))
10576 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10578 (defun org-get-scheduled-time (pom &optional inherit)
10579 "Get the scheduled time as a time tuple, of a format suitable
10580 for calling org-schedule with, or if there is no scheduling,
10581 returns nil."
10582 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10583 (when time
10584 (apply 'encode-time (org-parse-time-string time)))))
10586 (defun org-get-deadline-time (pom &optional inherit)
10587 "Get the deadine as a time tuple, of a format suitable for
10588 calling org-deadline with, or if there is no scheduling, returns
10589 nil."
10590 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10591 (when time
10592 (apply 'encode-time (org-parse-time-string time)))))
10594 (defun org-remove-timestamp-with-keyword (keyword)
10595 "Remove all time stamps with KEYWORD in the current entry."
10596 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10597 beg)
10598 (save-excursion
10599 (org-back-to-heading t)
10600 (setq beg (point))
10601 (outline-next-heading)
10602 (while (re-search-backward re beg t)
10603 (replace-match "")
10604 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10605 (equal (char-before) ?\ ))
10606 (backward-delete-char 1)
10607 (if (string-match "^[ \t]*$" (buffer-substring
10608 (point-at-bol) (point-at-eol)))
10609 (delete-region (point-at-bol)
10610 (min (point-max) (1+ (point-at-eol))))))))))
10612 (defun org-add-planning-info (what &optional time &rest remove)
10613 "Insert new timestamp with keyword in the line directly after the headline.
10614 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10615 If non is given, the user is prompted for a date.
10616 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10617 be removed."
10618 (interactive)
10619 (let (org-time-was-given org-end-time-was-given ts
10620 end default-time default-input)
10622 (catch 'exit
10623 (when (and (not time) (memq what '(scheduled deadline)))
10624 ;; Try to get a default date/time from existing timestamp
10625 (save-excursion
10626 (org-back-to-heading t)
10627 (setq end (save-excursion (outline-next-heading) (point)))
10628 (when (re-search-forward (if (eq what 'scheduled)
10629 org-scheduled-time-regexp
10630 org-deadline-time-regexp)
10631 end t)
10632 (setq ts (match-string 1)
10633 default-time
10634 (apply 'encode-time (org-parse-time-string ts))
10635 default-input (and ts (org-get-compact-tod ts))))))
10636 (when what
10637 ;; If necessary, get the time from the user
10638 (setq time (or time (org-read-date nil 'to-time nil nil
10639 default-time default-input))))
10641 (when (and org-insert-labeled-timestamps-at-point
10642 (member what '(scheduled deadline)))
10643 (insert
10644 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10645 (org-insert-time-stamp time org-time-was-given
10646 nil nil nil (list org-end-time-was-given))
10647 (setq what nil))
10648 (save-excursion
10649 (save-restriction
10650 (let (col list elt ts buffer-invisibility-spec)
10651 (org-back-to-heading t)
10652 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10653 (goto-char (match-end 1))
10654 (setq col (current-column))
10655 (goto-char (match-end 0))
10656 (if (eobp) (insert "\n") (forward-char 1))
10657 (when (and (not what)
10658 (not (looking-at
10659 (concat "[ \t]*"
10660 org-keyword-time-not-clock-regexp))))
10661 ;; Nothing to add, nothing to remove...... :-)
10662 (throw 'exit nil))
10663 (if (and (not (looking-at outline-regexp))
10664 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10665 "[^\r\n]*"))
10666 (not (equal (match-string 1) org-clock-string)))
10667 (narrow-to-region (match-beginning 0) (match-end 0))
10668 (insert-before-markers "\n")
10669 (backward-char 1)
10670 (narrow-to-region (point) (point))
10671 (and org-adapt-indentation (org-indent-to-column col)))
10672 ;; Check if we have to remove something.
10673 (setq list (cons what remove))
10674 (while list
10675 (setq elt (pop list))
10676 (goto-char (point-min))
10677 (when (or (and (eq elt 'scheduled)
10678 (re-search-forward org-scheduled-time-regexp nil t))
10679 (and (eq elt 'deadline)
10680 (re-search-forward org-deadline-time-regexp nil t))
10681 (and (eq elt 'closed)
10682 (re-search-forward org-closed-time-regexp nil t)))
10683 (replace-match "")
10684 (if (looking-at "--+<[^>]+>") (replace-match ""))
10685 (skip-chars-backward " ")
10686 (if (looking-at " +") (replace-match ""))))
10687 (goto-char (point-max))
10688 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10689 (when what
10690 (insert
10691 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10692 (cond ((eq what 'scheduled) org-scheduled-string)
10693 ((eq what 'deadline) org-deadline-string)
10694 ((eq what 'closed) org-closed-string))
10695 " ")
10696 (setq ts (org-insert-time-stamp
10697 time
10698 (or org-time-was-given
10699 (and (eq what 'closed) org-log-done-with-time))
10700 (eq what 'closed)
10701 nil nil (list org-end-time-was-given)))
10702 (end-of-line 1))
10703 (goto-char (point-min))
10704 (widen)
10705 (if (and (looking-at "[ \t]+\n")
10706 (equal (char-before) ?\n))
10707 (delete-region (1- (point)) (point-at-eol)))
10708 ts))))))
10710 (defvar org-log-note-marker (make-marker))
10711 (defvar org-log-note-purpose nil)
10712 (defvar org-log-note-state nil)
10713 (defvar org-log-note-previous-state nil)
10714 (defvar org-log-note-how nil)
10715 (defvar org-log-note-extra nil)
10716 (defvar org-log-note-window-configuration nil)
10717 (defvar org-log-note-return-to (make-marker))
10718 (defvar org-log-post-message nil
10719 "Message to be displayed after a log note has been stored.
10720 The auto-repeater uses this.")
10722 (defun org-add-note ()
10723 "Add a note to the current entry.
10724 This is done in the same way as adding a state change note."
10725 (interactive)
10726 (org-add-log-setup 'note nil nil 'findpos nil))
10728 (defvar org-property-end-re)
10729 (defun org-add-log-setup (&optional purpose state prev-state
10730 findpos how &optional extra)
10731 "Set up the post command hook to take a note.
10732 If this is about to TODO state change, the new state is expected in STATE.
10733 When FINDPOS is non-nil, find the correct position for the note in
10734 the current entry. If not, assume that it can be inserted at point.
10735 HOW is an indicator what kind of note should be created.
10736 EXTRA is additional text that will be inserted into the notes buffer."
10737 (let* ((org-log-into-drawer (org-log-into-drawer))
10738 (drawer (cond ((stringp org-log-into-drawer)
10739 org-log-into-drawer)
10740 (org-log-into-drawer "LOGBOOK")
10741 (t nil))))
10742 (save-restriction
10743 (save-excursion
10744 (when findpos
10745 (org-back-to-heading t)
10746 (narrow-to-region (point) (save-excursion
10747 (outline-next-heading) (point)))
10748 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10749 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10750 "[^\r\n]*\\)?"))
10751 (goto-char (match-end 0))
10752 (cond
10753 (drawer
10754 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10755 nil t)
10756 (progn
10757 (goto-char (match-end 0))
10758 (or org-log-states-order-reversed
10759 (and (re-search-forward org-property-end-re nil t)
10760 (goto-char (1- (match-beginning 0))))))
10761 (insert "\n:" drawer ":\n:END:")
10762 (beginning-of-line 0)
10763 (org-indent-line-function)
10764 (beginning-of-line 2)
10765 (org-indent-line-function)
10766 (end-of-line 0)))
10767 ((and org-log-state-notes-insert-after-drawers
10768 (save-excursion
10769 (forward-line) (looking-at org-drawer-regexp)))
10770 (forward-line)
10771 (while (looking-at org-drawer-regexp)
10772 (goto-char (match-end 0))
10773 (re-search-forward org-property-end-re (point-max) t)
10774 (forward-line))
10775 (forward-line -1)))
10776 (unless org-log-states-order-reversed
10777 (and (= (char-after) ?\n) (forward-char 1))
10778 (org-skip-over-state-notes)
10779 (skip-chars-backward " \t\n\r")))
10780 (move-marker org-log-note-marker (point))
10781 (setq org-log-note-purpose purpose
10782 org-log-note-state state
10783 org-log-note-previous-state prev-state
10784 org-log-note-how how
10785 org-log-note-extra extra)
10786 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10788 (defun org-skip-over-state-notes ()
10789 "Skip past the list of State notes in an entry."
10790 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10791 (while (looking-at "[ \t]*- State")
10792 (condition-case nil
10793 (org-next-item)
10794 (error (org-end-of-item)))))
10796 (defun org-add-log-note (&optional purpose)
10797 "Pop up a window for taking a note, and add this note later at point."
10798 (remove-hook 'post-command-hook 'org-add-log-note)
10799 (setq org-log-note-window-configuration (current-window-configuration))
10800 (delete-other-windows)
10801 (move-marker org-log-note-return-to (point))
10802 (switch-to-buffer (marker-buffer org-log-note-marker))
10803 (goto-char org-log-note-marker)
10804 (org-switch-to-buffer-other-window "*Org Note*")
10805 (erase-buffer)
10806 (if (memq org-log-note-how '(time state))
10807 (let (current-prefix-arg) (org-store-log-note))
10808 (let ((org-inhibit-startup t)) (org-mode))
10809 (insert (format "# Insert note for %s.
10810 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10811 (cond
10812 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10813 ((eq org-log-note-purpose 'done) "closed todo item")
10814 ((eq org-log-note-purpose 'state)
10815 (format "state change from \"%s\" to \"%s\""
10816 (or org-log-note-previous-state "")
10817 (or org-log-note-state "")))
10818 ((eq org-log-note-purpose 'reschedule)
10819 "rescheduling")
10820 ((eq org-log-note-purpose 'redeadline)
10821 "changing deadline")
10822 ((eq org-log-note-purpose 'note)
10823 "this entry")
10824 (t (error "This should not happen")))))
10825 (if org-log-note-extra (insert org-log-note-extra))
10826 (org-set-local 'org-finish-function 'org-store-log-note)))
10828 (defvar org-note-abort nil) ; dynamically scoped
10829 (defun org-store-log-note ()
10830 "Finish taking a log note, and insert it to where it belongs."
10831 (let ((txt (buffer-string))
10832 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10833 lines ind)
10834 (kill-buffer (current-buffer))
10835 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10836 (setq txt (replace-match "" t t txt)))
10837 (if (string-match "\\s-+\\'" txt)
10838 (setq txt (replace-match "" t t txt)))
10839 (setq lines (org-split-string txt "\n"))
10840 (when (and note (string-match "\\S-" note))
10841 (setq note
10842 (org-replace-escapes
10843 note
10844 (list (cons "%u" (user-login-name))
10845 (cons "%U" user-full-name)
10846 (cons "%t" (format-time-string
10847 (org-time-stamp-format 'long 'inactive)
10848 (current-time)))
10849 (cons "%s" (if org-log-note-state
10850 (concat "\"" org-log-note-state "\"")
10851 ""))
10852 (cons "%S" (if org-log-note-previous-state
10853 (concat "\"" org-log-note-previous-state "\"")
10854 "\"\"")))))
10855 (if lines (setq note (concat note " \\\\")))
10856 (push note lines))
10857 (when (or current-prefix-arg org-note-abort)
10858 (when org-log-into-drawer
10859 (org-remove-empty-drawer-at
10860 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10861 org-log-note-marker))
10862 (setq lines nil))
10863 (when lines
10864 (with-current-buffer (marker-buffer org-log-note-marker)
10865 (save-excursion
10866 (goto-char org-log-note-marker)
10867 (move-marker org-log-note-marker nil)
10868 (end-of-line 1)
10869 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10870 (insert "- " (pop lines))
10871 (org-indent-line-function)
10872 (beginning-of-line 1)
10873 (looking-at "[ \t]*")
10874 (setq ind (concat (match-string 0) " "))
10875 (end-of-line 1)
10876 (while lines (insert "\n" ind (pop lines)))
10877 (message "Note stored")
10878 (org-back-to-heading t)
10879 (org-cycle-hide-drawers 'children)))))
10880 (set-window-configuration org-log-note-window-configuration)
10881 (with-current-buffer (marker-buffer org-log-note-return-to)
10882 (goto-char org-log-note-return-to))
10883 (move-marker org-log-note-return-to nil)
10884 (and org-log-post-message (message "%s" org-log-post-message)))
10886 (defun org-remove-empty-drawer-at (drawer pos)
10887 "Remove an empty drawer DRAWER at position POS.
10888 POS may also be a marker."
10889 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10890 (save-excursion
10891 (save-restriction
10892 (widen)
10893 (goto-char pos)
10894 (if (org-in-regexp
10895 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10896 (replace-match ""))))))
10898 (defun org-sparse-tree (&optional arg)
10899 "Create a sparse tree, prompt for the details.
10900 This command can create sparse trees. You first need to select the type
10901 of match used to create the tree:
10903 t Show entries with a specific TODO keyword.
10904 m Show entries selected by a tags/property match.
10905 p Enter a property name and its value (both with completion on existing
10906 names/values) and show entries with that property.
10907 / Show entries matching a regular expression (`r' can be used as well)
10908 d Show deadlines due within `org-deadline-warning-days'.
10909 b Show deadlines and scheduled items before a date.
10910 a Show deadlines and scheduled items after a date."
10911 (interactive "P")
10912 (let (ans kwd value)
10913 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10914 (setq ans (read-char-exclusive))
10915 (cond
10916 ((equal ans ?d)
10917 (call-interactively 'org-check-deadlines))
10918 ((equal ans ?b)
10919 (call-interactively 'org-check-before-date))
10920 ((equal ans ?a)
10921 (call-interactively 'org-check-after-date))
10922 ((equal ans ?t)
10923 (org-show-todo-tree '(4)))
10924 ((member ans '(?T ?m))
10925 (call-interactively 'org-match-sparse-tree))
10926 ((member ans '(?p ?P))
10927 (setq kwd (org-icompleting-read "Property: "
10928 (mapcar 'list (org-buffer-property-keys))))
10929 (setq value (org-icompleting-read "Value: "
10930 (mapcar 'list (org-property-values kwd))))
10931 (unless (string-match "\\`{.*}\\'" value)
10932 (setq value (concat "\"" value "\"")))
10933 (org-match-sparse-tree arg (concat kwd "=" value)))
10934 ((member ans '(?r ?R ?/))
10935 (call-interactively 'org-occur))
10936 (t (error "No such sparse tree command \"%c\"" ans)))))
10938 (defvar org-occur-highlights nil
10939 "List of overlays used for occur matches.")
10940 (make-variable-buffer-local 'org-occur-highlights)
10941 (defvar org-occur-parameters nil
10942 "Parameters of the active org-occur calls.
10943 This is a list, each call to org-occur pushes as cons cell,
10944 containing the regular expression and the callback, onto the list.
10945 The list can contain several entries if `org-occur' has been called
10946 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10947 will only contain one set of parameters. When the highlights are
10948 removed (for example with `C-c C-c', or with the next edit (depending
10949 on `org-remove-highlights-with-change'), this variable is emptied
10950 as well.")
10951 (make-variable-buffer-local 'org-occur-parameters)
10953 (defun org-occur (regexp &optional keep-previous callback)
10954 "Make a compact tree which shows all matches of REGEXP.
10955 The tree will show the lines where the regexp matches, and all higher
10956 headlines above the match. It will also show the heading after the match,
10957 to make sure editing the matching entry is easy.
10958 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10959 call to `org-occur' will be kept, to allow stacking of calls to this
10960 command.
10961 If CALLBACK is non-nil, it is a function which is called to confirm
10962 that the match should indeed be shown."
10963 (interactive "sRegexp: \nP")
10964 (when (equal regexp "")
10965 (error "Regexp cannot be empty"))
10966 (unless keep-previous
10967 (org-remove-occur-highlights nil nil t))
10968 (push (cons regexp callback) org-occur-parameters)
10969 (let ((cnt 0))
10970 (save-excursion
10971 (goto-char (point-min))
10972 (if (or (not keep-previous) ; do not want to keep
10973 (not org-occur-highlights)) ; no previous matches
10974 ;; hide everything
10975 (org-overview))
10976 (while (re-search-forward regexp nil t)
10977 (when (or (not callback)
10978 (save-match-data (funcall callback)))
10979 (setq cnt (1+ cnt))
10980 (when org-highlight-sparse-tree-matches
10981 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10982 (org-show-context 'occur-tree))))
10983 (when org-remove-highlights-with-change
10984 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10985 nil 'local))
10986 (unless org-sparse-tree-open-archived-trees
10987 (org-hide-archived-subtrees (point-min) (point-max)))
10988 (run-hooks 'org-occur-hook)
10989 (if (interactive-p)
10990 (message "%d match(es) for regexp %s" cnt regexp))
10991 cnt))
10993 (defun org-show-context (&optional key)
10994 "Make sure point and context and visible.
10995 How much context is shown depends upon the variables
10996 `org-show-hierarchy-above', `org-show-following-heading'. and
10997 `org-show-siblings'."
10998 (let ((heading-p (org-on-heading-p t))
10999 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11000 (following-p (org-get-alist-option org-show-following-heading key))
11001 (entry-p (org-get-alist-option org-show-entry-below key))
11002 (siblings-p (org-get-alist-option org-show-siblings key)))
11003 (catch 'exit
11004 ;; Show heading or entry text
11005 (if (and heading-p (not entry-p))
11006 (org-flag-heading nil) ; only show the heading
11007 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11008 (org-show-hidden-entry))) ; show entire entry
11009 (when following-p
11010 ;; Show next sibling, or heading below text
11011 (save-excursion
11012 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11013 (org-flag-heading nil))))
11014 (when siblings-p (org-show-siblings))
11015 (when hierarchy-p
11016 ;; show all higher headings, possibly with siblings
11017 (save-excursion
11018 (while (and (condition-case nil
11019 (progn (org-up-heading-all 1) t)
11020 (error nil))
11021 (not (bobp)))
11022 (org-flag-heading nil)
11023 (when siblings-p (org-show-siblings))))))))
11025 (defun org-reveal (&optional siblings)
11026 "Show current entry, hierarchy above it, and the following headline.
11027 This can be used to show a consistent set of context around locations
11028 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11029 not t for the search context.
11031 With optional argument SIBLINGS, on each level of the hierarchy all
11032 siblings are shown. This repairs the tree structure to what it would
11033 look like when opened with hierarchical calls to `org-cycle'."
11034 (interactive "P")
11035 (let ((org-show-hierarchy-above t)
11036 (org-show-following-heading t)
11037 (org-show-siblings (if siblings t org-show-siblings)))
11038 (org-show-context nil)))
11040 (defun org-highlight-new-match (beg end)
11041 "Highlight from BEG to END and mark the highlight is an occur headline."
11042 (let ((ov (org-make-overlay beg end)))
11043 (org-overlay-put ov 'face 'secondary-selection)
11044 (push ov org-occur-highlights)))
11046 (defun org-remove-occur-highlights (&optional beg end noremove)
11047 "Remove the occur highlights from the buffer.
11048 BEG and END are ignored. If NOREMOVE is nil, remove this function
11049 from the `before-change-functions' in the current buffer."
11050 (interactive)
11051 (unless org-inhibit-highlight-removal
11052 (mapc 'org-delete-overlay org-occur-highlights)
11053 (setq org-occur-highlights nil)
11054 (setq org-occur-parameters nil)
11055 (unless noremove
11056 (remove-hook 'before-change-functions
11057 'org-remove-occur-highlights 'local))))
11059 ;;;; Priorities
11061 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11062 "Regular expression matching the priority indicator.")
11064 (defvar org-remove-priority-next-time nil)
11066 (defun org-priority-up ()
11067 "Increase the priority of the current item."
11068 (interactive)
11069 (org-priority 'up))
11071 (defun org-priority-down ()
11072 "Decrease the priority of the current item."
11073 (interactive)
11074 (org-priority 'down))
11076 (defun org-priority (&optional action)
11077 "Change the priority of an item by ARG.
11078 ACTION can be `set', `up', `down', or a character."
11079 (interactive)
11080 (unless org-enable-priority-commands
11081 (error "Priority commands are disabled"))
11082 (setq action (or action 'set))
11083 (let (current new news have remove)
11084 (save-excursion
11085 (org-back-to-heading t)
11086 (if (looking-at org-priority-regexp)
11087 (setq current (string-to-char (match-string 2))
11088 have t)
11089 (setq current org-default-priority))
11090 (cond
11091 ((eq action 'remove)
11092 (setq remove t new ?\ ))
11093 ((or (eq action 'set)
11094 (if (featurep 'xemacs) (characterp action) (integerp action)))
11095 (if (not (eq action 'set))
11096 (setq new action)
11097 (message "Priority %c-%c, SPC to remove: "
11098 org-highest-priority org-lowest-priority)
11099 (setq new (read-char-exclusive)))
11100 (if (and (= (upcase org-highest-priority) org-highest-priority)
11101 (= (upcase org-lowest-priority) org-lowest-priority))
11102 (setq new (upcase new)))
11103 (cond ((equal new ?\ ) (setq remove t))
11104 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11105 (error "Priority must be between `%c' and `%c'"
11106 org-highest-priority org-lowest-priority))))
11107 ((eq action 'up)
11108 (if (and (not have) (eq last-command this-command))
11109 (setq new org-lowest-priority)
11110 (setq new (if (and org-priority-start-cycle-with-default (not have))
11111 org-default-priority (1- current)))))
11112 ((eq action 'down)
11113 (if (and (not have) (eq last-command this-command))
11114 (setq new org-highest-priority)
11115 (setq new (if (and org-priority-start-cycle-with-default (not have))
11116 org-default-priority (1+ current)))))
11117 (t (error "Invalid action")))
11118 (if (or (< (upcase new) org-highest-priority)
11119 (> (upcase new) org-lowest-priority))
11120 (setq remove t))
11121 (setq news (format "%c" new))
11122 (if have
11123 (if remove
11124 (replace-match "" t t nil 1)
11125 (replace-match news t t nil 2))
11126 (if remove
11127 (error "No priority cookie found in line")
11128 (let ((case-fold-search nil))
11129 (looking-at org-todo-line-regexp))
11130 (if (match-end 2)
11131 (progn
11132 (goto-char (match-end 2))
11133 (insert " [#" news "]"))
11134 (goto-char (match-beginning 3))
11135 (insert "[#" news "] "))))
11136 (org-preserve-lc (org-set-tags nil 'align)))
11137 (if remove
11138 (message "Priority removed")
11139 (message "Priority of current item set to %s" news))))
11141 (defun org-get-priority (s)
11142 "Find priority cookie and return priority."
11143 (save-match-data
11144 (if (not (string-match org-priority-regexp s))
11145 (* 1000 (- org-lowest-priority org-default-priority))
11146 (* 1000 (- org-lowest-priority
11147 (string-to-char (match-string 2 s)))))))
11149 ;;;; Tags
11151 (defvar org-agenda-archives-mode)
11152 (defvar org-map-continue-from nil
11153 "Position from where mapping should continue.
11154 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11156 (defvar org-scanner-tags nil
11157 "The current tag list while the tags scanner is running.")
11158 (defvar org-trust-scanner-tags nil
11159 "Should `org-get-tags-at' use the tags fro the scanner.
11160 This is for internal dynamical scoping only.
11161 When this is non-nil, the function `org-get-tags-at' will return the value
11162 of `org-scanner-tags' instead of building the list by itself. This
11163 can lead to large speed-ups when the tags scanner is used in a file with
11164 many entries, and when the list of tags is retrieved, for example to
11165 obtain a list of properties. Building the tags list for each entry in such
11166 a file becomes an N^2 operation - but with this variable set, it scales
11167 as N.")
11169 (defun org-scan-tags (action matcher &optional todo-only)
11170 "Scan headline tags with inheritance and produce output ACTION.
11172 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11173 or `agenda' to produce an entry list for an agenda view. It can also be
11174 a Lisp form or a function that should be called at each matched headline, in
11175 this case the return value is a list of all return values from these calls.
11177 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11178 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11179 only lines with a TODO keyword are included in the output."
11180 (require 'org-agenda)
11181 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11182 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11183 (org-re
11184 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11185 (props (list 'face 'default
11186 'done-face 'org-agenda-done
11187 'undone-face 'default
11188 'mouse-face 'highlight
11189 'org-not-done-regexp org-not-done-regexp
11190 'org-todo-regexp org-todo-regexp
11191 'help-echo
11192 (format "mouse-2 or RET jump to org file %s"
11193 (abbreviate-file-name
11194 (or (buffer-file-name (buffer-base-buffer))
11195 (buffer-name (buffer-base-buffer)))))))
11196 (case-fold-search nil)
11197 (org-map-continue-from nil)
11198 lspos tags tags-list
11199 (tags-alist (list (cons 0 org-file-tags)))
11200 (llast 0) rtn rtn1 level category i txt
11201 todo marker entry priority)
11202 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11203 (setq action (list 'lambda nil action)))
11204 (save-excursion
11205 (goto-char (point-min))
11206 (when (eq action 'sparse-tree)
11207 (org-overview)
11208 (org-remove-occur-highlights))
11209 (while (re-search-forward re nil t)
11210 (catch :skip
11211 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11212 tags (if (match-end 4) (org-match-string-no-properties 4)))
11213 (goto-char (setq lspos (match-beginning 0)))
11214 (setq level (org-reduced-level (funcall outline-level))
11215 category (org-get-category))
11216 (setq i llast llast level)
11217 ;; remove tag lists from same and sublevels
11218 (while (>= i level)
11219 (when (setq entry (assoc i tags-alist))
11220 (setq tags-alist (delete entry tags-alist)))
11221 (setq i (1- i)))
11222 ;; add the next tags
11223 (when tags
11224 (setq tags (org-split-string tags ":")
11225 tags-alist
11226 (cons (cons level tags) tags-alist)))
11227 ;; compile tags for current headline
11228 (setq tags-list
11229 (if org-use-tag-inheritance
11230 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11231 tags)
11232 org-scanner-tags tags-list)
11233 (when org-use-tag-inheritance
11234 (setcdr (car tags-alist)
11235 (mapcar (lambda (x)
11236 (setq x (copy-sequence x))
11237 (org-add-prop-inherited x))
11238 (cdar tags-alist))))
11239 (when (and tags org-use-tag-inheritance
11240 (or (not (eq t org-use-tag-inheritance))
11241 org-tags-exclude-from-inheritance))
11242 ;; selective inheritance, remove uninherited ones
11243 (setcdr (car tags-alist)
11244 (org-remove-uniherited-tags (cdar tags-alist))))
11245 (when (and (or (not todo-only)
11246 (and (member todo org-not-done-keywords)
11247 (or (not org-agenda-tags-todo-honor-ignore-options)
11248 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11249 (let ((case-fold-search t)) (eval matcher))
11251 (not (member org-archive-tag tags-list))
11252 ;; we have an archive tag, should we use this anyway?
11253 (or (not org-agenda-skip-archived-trees)
11254 (and (eq action 'agenda) org-agenda-archives-mode))))
11255 (unless (eq action 'sparse-tree) (org-agenda-skip))
11257 ;; select this headline
11259 (cond
11260 ((eq action 'sparse-tree)
11261 (and org-highlight-sparse-tree-matches
11262 (org-get-heading) (match-end 0)
11263 (org-highlight-new-match
11264 (match-beginning 0) (match-beginning 1)))
11265 (org-show-context 'tags-tree))
11266 ((eq action 'agenda)
11267 (setq txt (org-format-agenda-item
11269 (concat
11270 (if (eq org-tags-match-list-sublevels 'indented)
11271 (make-string (1- level) ?.) "")
11272 (org-get-heading))
11273 category
11274 tags-list
11276 priority (org-get-priority txt))
11277 (goto-char lspos)
11278 (setq marker (org-agenda-new-marker))
11279 (org-add-props txt props
11280 'org-marker marker 'org-hd-marker marker 'org-category category
11281 'todo-state todo
11282 'priority priority 'type "tagsmatch")
11283 (push txt rtn))
11284 ((functionp action)
11285 (setq org-map-continue-from nil)
11286 (save-excursion
11287 (setq rtn1 (funcall action))
11288 (push rtn1 rtn)))
11289 (t (error "Invalid action")))
11291 ;; if we are to skip sublevels, jump to end of subtree
11292 (unless org-tags-match-list-sublevels
11293 (org-end-of-subtree t)
11294 (backward-char 1))))
11295 ;; Get the correct position from where to continue
11296 (if org-map-continue-from
11297 (goto-char org-map-continue-from)
11298 (and (= (point) lspos) (end-of-line 1)))))
11299 (when (and (eq action 'sparse-tree)
11300 (not org-sparse-tree-open-archived-trees))
11301 (org-hide-archived-subtrees (point-min) (point-max)))
11302 (nreverse rtn)))
11304 (defun org-remove-uniherited-tags (tags)
11305 "Remove all tags that are not inherited from the list TAGS."
11306 (cond
11307 ((eq org-use-tag-inheritance t)
11308 (if org-tags-exclude-from-inheritance
11309 (org-delete-all org-tags-exclude-from-inheritance tags)
11310 tags))
11311 ((not org-use-tag-inheritance) nil)
11312 ((stringp org-use-tag-inheritance)
11313 (delq nil (mapcar
11314 (lambda (x)
11315 (if (and (string-match org-use-tag-inheritance x)
11316 (not (member x org-tags-exclude-from-inheritance)))
11317 x nil))
11318 tags)))
11319 ((listp org-use-tag-inheritance)
11320 (delq nil (mapcar
11321 (lambda (x)
11322 (if (member x org-use-tag-inheritance) x nil))
11323 tags)))))
11325 (defvar todo-only) ;; dynamically scoped
11327 (defun org-match-sparse-tree (&optional todo-only match)
11328 "Create a sparse tree according to tags string MATCH.
11329 MATCH can contain positive and negative selection of tags, like
11330 \"+WORK+URGENT-WITHBOSS\".
11331 If optional argument TODO-ONLY is non-nil, only select lines that are
11332 also TODO lines."
11333 (interactive "P")
11334 (org-prepare-agenda-buffers (list (current-buffer)))
11335 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11337 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11339 (defvar org-cached-props nil)
11340 (defun org-cached-entry-get (pom property)
11341 (if (or (eq t org-use-property-inheritance)
11342 (and (stringp org-use-property-inheritance)
11343 (string-match org-use-property-inheritance property))
11344 (and (listp org-use-property-inheritance)
11345 (member property org-use-property-inheritance)))
11346 ;; Caching is not possible, check it directly
11347 (org-entry-get pom property 'inherit)
11348 ;; Get all properties, so that we can do complicated checks easily
11349 (cdr (assoc property (or org-cached-props
11350 (setq org-cached-props
11351 (org-entry-properties pom)))))))
11353 (defun org-global-tags-completion-table (&optional files)
11354 "Return the list of all tags in all agenda buffer/files."
11355 (save-excursion
11356 (org-uniquify
11357 (delq nil
11358 (apply 'append
11359 (mapcar
11360 (lambda (file)
11361 (set-buffer (find-file-noselect file))
11362 (append (org-get-buffer-tags)
11363 (mapcar (lambda (x) (if (stringp (car-safe x))
11364 (list (car-safe x)) nil))
11365 org-tag-alist)))
11366 (if (and files (car files))
11367 files
11368 (org-agenda-files))))))))
11370 (defun org-make-tags-matcher (match)
11371 "Create the TAGS//TODO matcher form for the selection string MATCH."
11372 ;; todo-only is scoped dynamically into this function, and the function
11373 ;; may change it if the matcher asks for it.
11374 (unless match
11375 ;; Get a new match request, with completion
11376 (let ((org-last-tags-completion-table
11377 (org-global-tags-completion-table)))
11378 (setq match (org-completing-read-no-i
11379 "Match: " 'org-tags-completion-function nil nil nil
11380 'org-tags-history))))
11382 ;; Parse the string and create a lisp form
11383 (let ((match0 match)
11384 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11385 minus tag mm
11386 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11387 orterms term orlist re-p str-p level-p level-op time-p
11388 prop-p pn pv po cat-p gv rest)
11389 (if (string-match "/+" match)
11390 ;; match contains also a todo-matching request
11391 (progn
11392 (setq tagsmatch (substring match 0 (match-beginning 0))
11393 todomatch (substring match (match-end 0)))
11394 (if (string-match "^!" todomatch)
11395 (setq todo-only t todomatch (substring todomatch 1)))
11396 (if (string-match "^\\s-*$" todomatch)
11397 (setq todomatch nil)))
11398 ;; only matching tags
11399 (setq tagsmatch match todomatch nil))
11401 ;; Make the tags matcher
11402 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11403 (setq tagsmatcher t)
11404 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11405 (while (setq term (pop orterms))
11406 (while (and (equal (substring term -1) "\\") orterms)
11407 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11408 (while (string-match re term)
11409 (setq rest (substring term (match-end 0))
11410 minus (and (match-end 1)
11411 (equal (match-string 1 term) "-"))
11412 tag (match-string 2 term)
11413 re-p (equal (string-to-char tag) ?{)
11414 level-p (match-end 4)
11415 prop-p (match-end 5)
11416 mm (cond
11417 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11418 (level-p
11419 (setq level-op (org-op-to-function (match-string 3 term)))
11420 `(,level-op level ,(string-to-number
11421 (match-string 4 term))))
11422 (prop-p
11423 (setq pn (match-string 5 term)
11424 po (match-string 6 term)
11425 pv (match-string 7 term)
11426 cat-p (equal pn "CATEGORY")
11427 re-p (equal (string-to-char pv) ?{)
11428 str-p (equal (string-to-char pv) ?\")
11429 time-p (save-match-data
11430 (string-match "^\"[[<].*[]>]\"$" pv))
11431 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11432 (if time-p (setq pv (org-matcher-time pv)))
11433 (setq po (org-op-to-function po (if time-p 'time str-p)))
11434 (cond
11435 ((equal pn "CATEGORY")
11436 (setq gv '(get-text-property (point) 'org-category)))
11437 ((equal pn "TODO")
11438 (setq gv 'todo))
11440 (setq gv `(org-cached-entry-get nil ,pn))))
11441 (if re-p
11442 (if (eq po 'org<>)
11443 `(not (string-match ,pv (or ,gv "")))
11444 `(string-match ,pv (or ,gv "")))
11445 (if str-p
11446 `(,po (or ,gv "") ,pv)
11447 `(,po (string-to-number (or ,gv ""))
11448 ,(string-to-number pv) ))))
11449 (t `(member ,tag tags-list)))
11450 mm (if minus (list 'not mm) mm)
11451 term rest)
11452 (push mm tagsmatcher))
11453 (push (if (> (length tagsmatcher) 1)
11454 (cons 'and tagsmatcher)
11455 (car tagsmatcher))
11456 orlist)
11457 (setq tagsmatcher nil))
11458 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11459 (setq tagsmatcher
11460 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11461 ;; Make the todo matcher
11462 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11463 (setq todomatcher t)
11464 (setq orterms (org-split-string todomatch "|") orlist nil)
11465 (while (setq term (pop orterms))
11466 (while (string-match re term)
11467 (setq minus (and (match-end 1)
11468 (equal (match-string 1 term) "-"))
11469 kwd (match-string 2 term)
11470 re-p (equal (string-to-char kwd) ?{)
11471 term (substring term (match-end 0))
11472 mm (if re-p
11473 `(string-match ,(substring kwd 1 -1) todo)
11474 (list 'equal 'todo kwd))
11475 mm (if minus (list 'not mm) mm))
11476 (push mm todomatcher))
11477 (push (if (> (length todomatcher) 1)
11478 (cons 'and todomatcher)
11479 (car todomatcher))
11480 orlist)
11481 (setq todomatcher nil))
11482 (setq todomatcher (if (> (length orlist) 1)
11483 (cons 'or orlist) (car orlist))))
11485 ;; Return the string and lisp forms of the matcher
11486 (setq matcher (if todomatcher
11487 (list 'and tagsmatcher todomatcher)
11488 tagsmatcher))
11489 (cons match0 matcher)))
11491 (defun org-op-to-function (op &optional stringp)
11492 "Turn an operator into the appropriate function."
11493 (setq op
11494 (cond
11495 ((equal op "<" ) '(< string< org-time<))
11496 ((equal op ">" ) '(> org-string> org-time>))
11497 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11498 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11499 ((member op '("=" "==")) '(= string= org-time=))
11500 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11501 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11503 (defun org<> (a b) (not (= a b)))
11504 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11505 (defun org-string>= (a b) (not (string< a b)))
11506 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11507 (defun org-string<> (a b) (not (string= a b)))
11508 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11509 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11510 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11511 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11512 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11513 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11514 (defun org-2ft (s)
11515 "Convert S to a floating point time.
11516 If S is already a number, just return it. If it is a string, parse
11517 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11518 (cond
11519 ((numberp s) s)
11520 ((stringp s)
11521 (condition-case nil
11522 (float-time (apply 'encode-time (org-parse-time-string s)))
11523 (error 0.)))
11524 (t 0.)))
11526 (defun org-time-today ()
11527 "Time in seconds today at 0:00.
11528 Returns the float number of seconds since the beginning of the
11529 epoch to the beginning of today (00:00)."
11530 (float-time (apply 'encode-time
11531 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11533 (defun org-matcher-time (s)
11534 "Interpret a time comparison value."
11535 (save-match-data
11536 (cond
11537 ((string= s "<now>") (float-time))
11538 ((string= s "<today>") (org-time-today))
11539 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11540 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11541 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11542 (+ (org-time-today)
11543 (* (string-to-number (match-string 1 s))
11544 (cdr (assoc (match-string 2 s)
11545 '(("d" . 86400.0) ("w" . 604800.0)
11546 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11547 (t (org-2ft s)))))
11549 (defun org-match-any-p (re list)
11550 "Does re match any element of list?"
11551 (setq list (mapcar (lambda (x) (string-match re x)) list))
11552 (delq nil list))
11554 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11555 (defvar org-tags-overlay (org-make-overlay 1 1))
11556 (org-detach-overlay org-tags-overlay)
11558 (defun org-get-local-tags-at (&optional pos)
11559 "Get a list of tags defined in the current headline."
11560 (org-get-tags-at pos 'local))
11562 (defun org-get-local-tags ()
11563 "Get a list of tags defined in the current headline."
11564 (org-get-tags-at nil 'local))
11566 (defun org-get-tags-at (&optional pos local)
11567 "Get a list of all headline tags applicable at POS.
11568 POS defaults to point. If tags are inherited, the list contains
11569 the targets in the same sequence as the headlines appear, i.e.
11570 the tags of the current headline come last.
11571 When LOCAL is non-nil, only return tags from the current headline,
11572 ignore inherited ones."
11573 (interactive)
11574 (if (and org-trust-scanner-tags
11575 (or (not pos) (equal pos (point)))
11576 (not local))
11577 org-scanner-tags
11578 (let (tags ltags lastpos parent)
11579 (save-excursion
11580 (save-restriction
11581 (widen)
11582 (goto-char (or pos (point)))
11583 (save-match-data
11584 (catch 'done
11585 (condition-case nil
11586 (progn
11587 (org-back-to-heading t)
11588 (while (not (equal lastpos (point)))
11589 (setq lastpos (point))
11590 (when (looking-at
11591 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11592 (setq ltags (org-split-string
11593 (org-match-string-no-properties 1) ":"))
11594 (when parent
11595 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11596 (setq tags (append
11597 (if parent
11598 (org-remove-uniherited-tags ltags)
11599 ltags)
11600 tags)))
11601 (or org-use-tag-inheritance (throw 'done t))
11602 (if local (throw 'done t))
11603 (or (org-up-heading-safe) (error nil))
11604 (setq parent t)))
11605 (error nil)))))
11606 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11608 (defun org-add-prop-inherited (s)
11609 (add-text-properties 0 (length s) '(inherited t) s)
11612 (defun org-toggle-tag (tag &optional onoff)
11613 "Toggle the tag TAG for the current line.
11614 If ONOFF is `on' or `off', don't toggle but set to this state."
11615 (let (res current)
11616 (save-excursion
11617 (org-back-to-heading t)
11618 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11619 (point-at-eol) t)
11620 (progn
11621 (setq current (match-string 1))
11622 (replace-match ""))
11623 (setq current ""))
11624 (setq current (nreverse (org-split-string current ":")))
11625 (cond
11626 ((eq onoff 'on)
11627 (setq res t)
11628 (or (member tag current) (push tag current)))
11629 ((eq onoff 'off)
11630 (or (not (member tag current)) (setq current (delete tag current))))
11631 (t (if (member tag current)
11632 (setq current (delete tag current))
11633 (setq res t)
11634 (push tag current))))
11635 (end-of-line 1)
11636 (if current
11637 (progn
11638 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11639 (org-set-tags nil t))
11640 (delete-horizontal-space))
11641 (run-hooks 'org-after-tags-change-hook))
11642 res))
11644 (defun org-align-tags-here (to-col)
11645 ;; Assumes that this is a headline
11646 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11647 (beginning-of-line 1)
11648 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11649 (< pos (match-beginning 2)))
11650 (progn
11651 (setq tags-l (- (match-end 2) (match-beginning 2)))
11652 (goto-char (match-beginning 1))
11653 (insert " ")
11654 (delete-region (point) (1+ (match-beginning 2)))
11655 (setq ncol (max (1+ (current-column))
11656 (1+ col)
11657 (if (> to-col 0)
11658 to-col
11659 (- (abs to-col) tags-l))))
11660 (setq p (point))
11661 (insert (make-string (- ncol (current-column)) ?\ ))
11662 (setq ncol (current-column))
11663 (when indent-tabs-mode (tabify p (point-at-eol)))
11664 (org-move-to-column (min ncol col) t))
11665 (goto-char pos))))
11667 (defun org-set-tags-command (&optional arg just-align)
11668 "Call the set-tags command for the current entry."
11669 (interactive "P")
11670 (if (org-on-heading-p)
11671 (org-set-tags arg just-align)
11672 (save-excursion
11673 (org-back-to-heading t)
11674 (org-set-tags arg just-align))))
11676 (defun org-set-tags-to (data)
11677 "Set the tags of the current entry to DATA, replacing the current tags.
11678 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11679 If DATA is nil or the empty string, any tags will be removed."
11680 (interactive "sTags: ")
11681 (setq data
11682 (cond
11683 ((eq data nil) "")
11684 ((equal data "") "")
11685 ((stringp data)
11686 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11687 ":"))
11688 ((listp data)
11689 (concat ":" (mapconcat 'identity data ":") ":"))
11690 (t nil)))
11691 (when data
11692 (save-excursion
11693 (org-back-to-heading t)
11694 (when (looking-at org-complex-heading-regexp)
11695 (if (match-end 5)
11696 (progn
11697 (goto-char (match-beginning 5))
11698 (insert data)
11699 (delete-region (point) (point-at-eol))
11700 (org-set-tags nil 'align))
11701 (goto-char (point-at-eol))
11702 (insert " " data)
11703 (org-set-tags nil 'align)))
11704 (beginning-of-line 1)
11705 (if (looking-at ".*?\\([ \t]+\\)$")
11706 (delete-region (match-beginning 1) (match-end 1))))))
11708 (defun org-set-tags (&optional arg just-align)
11709 "Set the tags for the current headline.
11710 With prefix ARG, realign all tags in headings in the current buffer."
11711 (interactive "P")
11712 (let* ((re (concat "^" outline-regexp))
11713 (current (org-get-tags-string))
11714 (col (current-column))
11715 (org-setting-tags t)
11716 table current-tags inherited-tags ; computed below when needed
11717 tags p0 c0 c1 rpl)
11718 (if arg
11719 (save-excursion
11720 (goto-char (point-min))
11721 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11722 (while (re-search-forward re nil t)
11723 (org-set-tags nil t)
11724 (end-of-line 1)))
11725 (message "All tags realigned to column %d" org-tags-column))
11726 (if just-align
11727 (setq tags current)
11728 ;; Get a new set of tags from the user
11729 (save-excursion
11730 (setq table (append org-tag-persistent-alist
11731 (or org-tag-alist (org-get-buffer-tags))
11732 (and org-complete-tags-always-offer-all-agenda-tags
11733 (org-global-tags-completion-table (org-agenda-files))))
11734 org-last-tags-completion-table table
11735 current-tags (org-split-string current ":")
11736 inherited-tags (nreverse
11737 (nthcdr (length current-tags)
11738 (nreverse (org-get-tags-at))))
11739 tags
11740 (if (or (eq t org-use-fast-tag-selection)
11741 (and org-use-fast-tag-selection
11742 (delq nil (mapcar 'cdr table))))
11743 (org-fast-tag-selection
11744 current-tags inherited-tags table
11745 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11746 (let ((org-add-colon-after-tag-completion t))
11747 (org-trim
11748 (org-without-partial-completion
11749 (org-icompleting-read "Tags: " 'org-tags-completion-function
11750 nil nil current 'org-tags-history)))))))
11751 (while (string-match "[-+&]+" tags)
11752 ;; No boolean logic, just a list
11753 (setq tags (replace-match ":" t t tags))))
11755 (if org-tags-sort-function
11756 (setq tags (mapconcat 'identity
11757 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11758 org-tags-sort-function) ":")))
11760 (if (string-match "\\`[\t ]*\\'" tags)
11761 (setq tags "")
11762 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11763 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11765 ;; Insert new tags at the correct column
11766 (beginning-of-line 1)
11767 (cond
11768 ((and (equal current "") (equal tags "")))
11769 ((re-search-forward
11770 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11771 (point-at-eol) t)
11772 (if (equal tags "")
11773 (setq rpl "")
11774 (goto-char (match-beginning 0))
11775 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11776 (1+ (point)) (point))
11777 c1 (max (1+ c0) (if (> org-tags-column 0)
11778 org-tags-column
11779 (- (- org-tags-column) (length tags))))
11780 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11781 (replace-match rpl t t)
11782 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11783 tags)
11784 (t (error "Tags alignment failed")))
11785 (org-move-to-column col)
11786 (unless just-align
11787 (run-hooks 'org-after-tags-change-hook)))))
11789 (defun org-change-tag-in-region (beg end tag off)
11790 "Add or remove TAG for each entry in the region.
11791 This works in the agenda, and also in an org-mode buffer."
11792 (interactive
11793 (list (region-beginning) (region-end)
11794 (let ((org-last-tags-completion-table
11795 (if (org-mode-p)
11796 (org-get-buffer-tags)
11797 (org-global-tags-completion-table))))
11798 (org-icompleting-read
11799 "Tag: " 'org-tags-completion-function nil nil nil
11800 'org-tags-history))
11801 (progn
11802 (message "[s]et or [r]emove? ")
11803 (equal (read-char-exclusive) ?r))))
11804 (if (fboundp 'deactivate-mark) (deactivate-mark))
11805 (let ((agendap (equal major-mode 'org-agenda-mode))
11806 l1 l2 m buf pos newhead (cnt 0))
11807 (goto-char end)
11808 (setq l2 (1- (org-current-line)))
11809 (goto-char beg)
11810 (setq l1 (org-current-line))
11811 (loop for l from l1 to l2 do
11812 (org-goto-line l)
11813 (setq m (get-text-property (point) 'org-hd-marker))
11814 (when (or (and (org-mode-p) (org-on-heading-p))
11815 (and agendap m))
11816 (setq buf (if agendap (marker-buffer m) (current-buffer))
11817 pos (if agendap m (point)))
11818 (with-current-buffer buf
11819 (save-excursion
11820 (save-restriction
11821 (goto-char pos)
11822 (setq cnt (1+ cnt))
11823 (org-toggle-tag tag (if off 'off 'on))
11824 (setq newhead (org-get-heading)))))
11825 (and agendap (org-agenda-change-all-lines newhead m))))
11826 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11828 (defun org-tags-completion-function (string predicate &optional flag)
11829 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11830 (confirm (lambda (x) (stringp (car x)))))
11831 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11832 (setq s1 (match-string 1 string)
11833 s2 (match-string 2 string))
11834 (setq s1 "" s2 string))
11835 (cond
11836 ((eq flag nil)
11837 ;; try completion
11838 (setq rtn (try-completion s2 ctable confirm))
11839 (if (stringp rtn)
11840 (setq rtn
11841 (concat s1 s2 (substring rtn (length s2))
11842 (if (and org-add-colon-after-tag-completion
11843 (assoc rtn ctable))
11844 ":" ""))))
11845 rtn)
11846 ((eq flag t)
11847 ;; all-completions
11848 (all-completions s2 ctable confirm)
11850 ((eq flag 'lambda)
11851 ;; exact match?
11852 (assoc s2 ctable)))
11855 (defun org-fast-tag-insert (kwd tags face &optional end)
11856 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11857 (insert (format "%-12s" (concat kwd ":"))
11858 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11859 (or end "")))
11861 (defun org-fast-tag-show-exit (flag)
11862 (save-excursion
11863 (org-goto-line 3)
11864 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11865 (replace-match ""))
11866 (when flag
11867 (end-of-line 1)
11868 (org-move-to-column (- (window-width) 19) t)
11869 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11871 (defun org-set-current-tags-overlay (current prefix)
11872 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11873 (if (featurep 'xemacs)
11874 (org-overlay-display org-tags-overlay (concat prefix s)
11875 'secondary-selection)
11876 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11877 (org-overlay-display org-tags-overlay (concat prefix s)))))
11879 (defvar org-last-tag-selection-key nil)
11880 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11881 "Fast tag selection with single keys.
11882 CURRENT is the current list of tags in the headline, INHERITED is the
11883 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11884 possibly with grouping information. TODO-TABLE is a similar table with
11885 TODO keywords, should these have keys assigned to them.
11886 If the keys are nil, a-z are automatically assigned.
11887 Returns the new tags string, or nil to not change the current settings."
11888 (let* ((fulltable (append table todo-table))
11889 (maxlen (apply 'max (mapcar
11890 (lambda (x)
11891 (if (stringp (car x)) (string-width (car x)) 0))
11892 fulltable)))
11893 (buf (current-buffer))
11894 (expert (eq org-fast-tag-selection-single-key 'expert))
11895 (buffer-tags nil)
11896 (fwidth (+ maxlen 3 1 3))
11897 (ncol (/ (- (window-width) 4) fwidth))
11898 (i-face 'org-done)
11899 (c-face 'org-todo)
11900 tg cnt e c char c1 c2 ntable tbl rtn
11901 ov-start ov-end ov-prefix
11902 (exit-after-next org-fast-tag-selection-single-key)
11903 (done-keywords org-done-keywords)
11904 groups ingroup)
11905 (save-excursion
11906 (beginning-of-line 1)
11907 (if (looking-at
11908 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11909 (setq ov-start (match-beginning 1)
11910 ov-end (match-end 1)
11911 ov-prefix "")
11912 (setq ov-start (1- (point-at-eol))
11913 ov-end (1+ ov-start))
11914 (skip-chars-forward "^\n\r")
11915 (setq ov-prefix
11916 (concat
11917 (buffer-substring (1- (point)) (point))
11918 (if (> (current-column) org-tags-column)
11920 (make-string (- org-tags-column (current-column)) ?\ ))))))
11921 (org-move-overlay org-tags-overlay ov-start ov-end)
11922 (save-window-excursion
11923 (if expert
11924 (set-buffer (get-buffer-create " *Org tags*"))
11925 (delete-other-windows)
11926 (split-window-vertically)
11927 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11928 (erase-buffer)
11929 (org-set-local 'org-done-keywords done-keywords)
11930 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11931 (org-fast-tag-insert "Current" current c-face "\n\n")
11932 (org-fast-tag-show-exit exit-after-next)
11933 (org-set-current-tags-overlay current ov-prefix)
11934 (setq tbl fulltable char ?a cnt 0)
11935 (while (setq e (pop tbl))
11936 (cond
11937 ((equal (car e) :startgroup)
11938 (push '() groups) (setq ingroup t)
11939 (when (not (= cnt 0))
11940 (setq cnt 0)
11941 (insert "\n"))
11942 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11943 ((equal (car e) :endgroup)
11944 (setq ingroup nil cnt 0)
11945 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11946 ((equal e '(:newline))
11947 (when (not (= cnt 0))
11948 (setq cnt 0)
11949 (insert "\n")
11950 (setq e (car tbl))
11951 (while (equal (car tbl) '(:newline))
11952 (insert "\n")
11953 (setq tbl (cdr tbl)))))
11955 (setq tg (copy-sequence (car e)) c2 nil)
11956 (if (cdr e)
11957 (setq c (cdr e))
11958 ;; automatically assign a character.
11959 (setq c1 (string-to-char
11960 (downcase (substring
11961 tg (if (= (string-to-char tg) ?@) 1 0)))))
11962 (if (or (rassoc c1 ntable) (rassoc c1 table))
11963 (while (or (rassoc char ntable) (rassoc char table))
11964 (setq char (1+ char)))
11965 (setq c2 c1))
11966 (setq c (or c2 char)))
11967 (if ingroup (push tg (car groups)))
11968 (setq tg (org-add-props tg nil 'face
11969 (cond
11970 ((not (assoc tg table))
11971 (org-get-todo-face tg))
11972 ((member tg current) c-face)
11973 ((member tg inherited) i-face)
11974 (t nil))))
11975 (if (and (= cnt 0) (not ingroup)) (insert " "))
11976 (insert "[" c "] " tg (make-string
11977 (- fwidth 4 (length tg)) ?\ ))
11978 (push (cons tg c) ntable)
11979 (when (= (setq cnt (1+ cnt)) ncol)
11980 (insert "\n")
11981 (if ingroup (insert " "))
11982 (setq cnt 0)))))
11983 (setq ntable (nreverse ntable))
11984 (insert "\n")
11985 (goto-char (point-min))
11986 (if (not expert) (org-fit-window-to-buffer))
11987 (setq rtn
11988 (catch 'exit
11989 (while t
11990 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11991 (if (not groups) "no " "")
11992 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11993 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11994 (setq org-last-tag-selection-key c)
11995 (cond
11996 ((= c ?\r) (throw 'exit t))
11997 ((= c ?!)
11998 (setq groups (not groups))
11999 (goto-char (point-min))
12000 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12001 ((= c ?\C-c)
12002 (if (not expert)
12003 (org-fast-tag-show-exit
12004 (setq exit-after-next (not exit-after-next)))
12005 (setq expert nil)
12006 (delete-other-windows)
12007 (split-window-vertically)
12008 (org-switch-to-buffer-other-window " *Org tags*")
12009 (org-fit-window-to-buffer)))
12010 ((or (= c ?\C-g)
12011 (and (= c ?q) (not (rassoc c ntable))))
12012 (org-detach-overlay org-tags-overlay)
12013 (setq quit-flag t))
12014 ((= c ?\ )
12015 (setq current nil)
12016 (if exit-after-next (setq exit-after-next 'now)))
12017 ((= c ?\t)
12018 (condition-case nil
12019 (setq tg (org-icompleting-read
12020 "Tag: "
12021 (or buffer-tags
12022 (with-current-buffer buf
12023 (org-get-buffer-tags)))))
12024 (quit (setq tg "")))
12025 (when (string-match "\\S-" tg)
12026 (add-to-list 'buffer-tags (list tg))
12027 (if (member tg current)
12028 (setq current (delete tg current))
12029 (push tg current)))
12030 (if exit-after-next (setq exit-after-next 'now)))
12031 ((setq e (rassoc c todo-table) tg (car e))
12032 (with-current-buffer buf
12033 (save-excursion (org-todo tg)))
12034 (if exit-after-next (setq exit-after-next 'now)))
12035 ((setq e (rassoc c ntable) tg (car e))
12036 (if (member tg current)
12037 (setq current (delete tg current))
12038 (loop for g in groups do
12039 (if (member tg g)
12040 (mapc (lambda (x)
12041 (setq current (delete x current)))
12042 g)))
12043 (push tg current))
12044 (if exit-after-next (setq exit-after-next 'now))))
12046 ;; Create a sorted list
12047 (setq current
12048 (sort current
12049 (lambda (a b)
12050 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12051 (if (eq exit-after-next 'now) (throw 'exit t))
12052 (goto-char (point-min))
12053 (beginning-of-line 2)
12054 (delete-region (point) (point-at-eol))
12055 (org-fast-tag-insert "Current" current c-face)
12056 (org-set-current-tags-overlay current ov-prefix)
12057 (while (re-search-forward
12058 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12059 (setq tg (match-string 1))
12060 (add-text-properties
12061 (match-beginning 1) (match-end 1)
12062 (list 'face
12063 (cond
12064 ((member tg current) c-face)
12065 ((member tg inherited) i-face)
12066 (t (get-text-property (match-beginning 1) 'face))))))
12067 (goto-char (point-min)))))
12068 (org-detach-overlay org-tags-overlay)
12069 (if rtn
12070 (mapconcat 'identity current ":")
12071 nil))))
12073 (defun org-get-tags-string ()
12074 "Get the TAGS string in the current headline."
12075 (unless (org-on-heading-p t)
12076 (error "Not on a heading"))
12077 (save-excursion
12078 (beginning-of-line 1)
12079 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12080 (org-match-string-no-properties 1)
12081 "")))
12083 (defun org-get-tags ()
12084 "Get the list of tags specified in the current headline."
12085 (org-split-string (org-get-tags-string) ":"))
12087 (defun org-get-buffer-tags ()
12088 "Get a table of all tags used in the buffer, for completion."
12089 (let (tags)
12090 (save-excursion
12091 (goto-char (point-min))
12092 (while (re-search-forward
12093 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12094 (when (equal (char-after (point-at-bol 0)) ?*)
12095 (mapc (lambda (x) (add-to-list 'tags x))
12096 (org-split-string (org-match-string-no-properties 1) ":")))))
12097 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12098 (mapcar 'list tags)))
12100 ;;;; The mapping API
12102 ;;;###autoload
12103 (defun org-map-entries (func &optional match scope &rest skip)
12104 "Call FUNC at each headline selected by MATCH in SCOPE.
12106 FUNC is a function or a lisp form. The function will be called without
12107 arguments, with the cursor positioned at the beginning of the headline.
12108 The return values of all calls to the function will be collected and
12109 returned as a list.
12111 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12112 does not need to preserve point. After evaluation, the cursor will be
12113 moved to the end of the line (presumably of the headline of the
12114 processed entry) and search continues from there. Under some
12115 circumstances, this may not produce the wanted results. For example,
12116 if you have removed (e.g. archived) the current (sub)tree it could
12117 mean that the next entry will be skipped entirely. In such cases, you
12118 can specify the position from where search should continue by making
12119 FUNC set the variable `org-map-continue-from' to the desired buffer
12120 position.
12122 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12123 Only headlines that are matched by this query will be considered during
12124 the iteration. When MATCH is nil or t, all headlines will be
12125 visited by the iteration.
12127 SCOPE determines the scope of this command. It can be any of:
12129 nil The current buffer, respecting the restriction if any
12130 tree The subtree started with the entry at point
12131 file The current buffer, without restriction
12132 file-with-archives
12133 The current buffer, and any archives associated with it
12134 agenda All agenda files
12135 agenda-with-archives
12136 All agenda files with any archive files associated with them
12137 \(file1 file2 ...)
12138 If this is a list, all files in the list will be scanned
12140 The remaining args are treated as settings for the skipping facilities of
12141 the scanner. The following items can be given here:
12143 archive skip trees with the archive tag.
12144 comment skip trees with the COMMENT keyword
12145 function or Emacs Lisp form:
12146 will be used as value for `org-agenda-skip-function', so whenever
12147 the function returns t, FUNC will not be called for that
12148 entry and search will continue from the point where the
12149 function leaves it.
12151 If your function needs to retrieve the tags including inherited tags
12152 at the *current* entry, you can use the value of the variable
12153 `org-scanner-tags' which will be much faster than getting the value
12154 with `org-get-tags-at'. If your function gets properties with
12155 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12156 to t around the call to `org-entry-properties' to get the same speedup.
12157 Note that if your function moves around to retrieve tags and properties at
12158 a *different* entry, you cannot use these techniques."
12159 (let* ((org-agenda-archives-mode nil) ; just to make sure
12160 (org-agenda-skip-archived-trees (memq 'archive skip))
12161 (org-agenda-skip-comment-trees (memq 'comment skip))
12162 (org-agenda-skip-function
12163 (car (org-delete-all '(comment archive) skip)))
12164 (org-tags-match-list-sublevels t)
12165 matcher file res
12166 org-todo-keywords-for-agenda
12167 org-done-keywords-for-agenda
12168 org-todo-keyword-alist-for-agenda
12169 org-drawers-for-agenda
12170 org-tag-alist-for-agenda)
12172 (cond
12173 ((eq match t) (setq matcher t))
12174 ((eq match nil) (setq matcher t))
12175 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12177 (save-excursion
12178 (save-restriction
12179 (when (eq scope 'tree)
12180 (org-back-to-heading t)
12181 (org-narrow-to-subtree)
12182 (setq scope nil))
12184 (if (not scope)
12185 (progn
12186 (org-prepare-agenda-buffers
12187 (list (buffer-file-name (current-buffer))))
12188 (setq res (org-scan-tags func matcher)))
12189 ;; Get the right scope
12190 (cond
12191 ((and scope (listp scope) (symbolp (car scope)))
12192 (setq scope (eval scope)))
12193 ((eq scope 'agenda)
12194 (setq scope (org-agenda-files t)))
12195 ((eq scope 'agenda-with-archives)
12196 (setq scope (org-agenda-files t))
12197 (setq scope (org-add-archive-files scope)))
12198 ((eq scope 'file)
12199 (setq scope (list (buffer-file-name))))
12200 ((eq scope 'file-with-archives)
12201 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12202 (org-prepare-agenda-buffers scope)
12203 (while (setq file (pop scope))
12204 (with-current-buffer (org-find-base-buffer-visiting file)
12205 (save-excursion
12206 (save-restriction
12207 (widen)
12208 (goto-char (point-min))
12209 (setq res (append res (org-scan-tags func matcher))))))))))
12210 res))
12212 ;;;; Properties
12214 ;;; Setting and retrieving properties
12216 (defconst org-special-properties
12217 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12218 "TIMESTAMP" "TIMESTAMP_IA")
12219 "The special properties valid in Org-mode.
12221 These are properties that are not defined in the property drawer,
12222 but in some other way.")
12224 (defconst org-default-properties
12225 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12226 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12227 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12228 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12229 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12230 "CLOCK_MODELINE_TOTAL" "STYLE")
12231 "Some properties that are used by Org-mode for various purposes.
12232 Being in this list makes sure that they are offered for completion.")
12234 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12235 "Regular expression matching the first line of a property drawer.")
12237 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12238 "Regular expression matching the first line of a property drawer.")
12240 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12241 "Regular expression matching the first line of a property drawer.")
12243 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12244 "Regular expression matching the first line of a property drawer.")
12246 (defconst org-property-drawer-re
12247 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12248 org-property-end-re "\\)\n?")
12249 "Matches an entire property drawer.")
12251 (defconst org-clock-drawer-re
12252 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12253 org-property-end-re "\\)\n?")
12254 "Matches an entire clock drawer.")
12256 (defun org-property-action ()
12257 "Do an action on properties."
12258 (interactive)
12259 (let (c)
12260 (org-at-property-p)
12261 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12262 (setq c (read-char-exclusive))
12263 (cond
12264 ((equal c ?s)
12265 (call-interactively 'org-set-property))
12266 ((equal c ?d)
12267 (call-interactively 'org-delete-property))
12268 ((equal c ?D)
12269 (call-interactively 'org-delete-property-globally))
12270 ((equal c ?c)
12271 (call-interactively 'org-compute-property-at-point))
12272 (t (error "No such property action %c" c)))))
12274 (defun org-set-effort (&optional value)
12275 "Set the effort property of the current entry.
12276 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12277 allowed value."
12278 (interactive "P")
12279 (if (equal value 0) (setq value 10))
12280 (let* ((completion-ignore-case t)
12281 (prop org-effort-property)
12282 (cur (org-entry-get nil prop))
12283 (allowed (org-property-get-allowed-values nil prop 'table))
12284 (existing (mapcar 'list (org-property-values prop)))
12286 (val (cond
12287 ((stringp value) value)
12288 ((and allowed (integerp value))
12289 (or (car (nth (1- value) allowed))
12290 (car (org-last allowed))))
12291 (allowed
12292 (message "Select 1-9,0, [RET%s]: %s"
12293 (if cur (concat "=" cur) "")
12294 (mapconcat 'car allowed " "))
12295 (setq rpl (read-char-exclusive))
12296 (if (equal rpl ?\r)
12298 (setq rpl (- rpl ?0))
12299 (if (equal rpl 0) (setq rpl 10))
12300 (if (and (> rpl 0) (<= rpl (length allowed)))
12301 (car (nth (1- rpl) allowed))
12302 (org-completing-read "Effort: " allowed nil))))
12304 (let (org-completion-use-ido org-completion-use-iswitchb)
12305 (org-completing-read
12306 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12307 (concat "[" cur "]") "")
12308 ": ")
12309 existing nil nil "" nil cur))))))
12310 (unless (equal (org-entry-get nil prop) val)
12311 (org-entry-put nil prop val))
12312 (message "%s is now %s" prop val)))
12314 (defun org-at-property-p ()
12315 "Is the cursor in a property line?"
12316 ;; FIXME: Does not check if we are actually in the drawer.
12317 ;; FIXME: also returns true on any drawers.....
12318 ;; This is used by C-c C-c for property action.
12319 (save-excursion
12320 (beginning-of-line 1)
12321 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12323 (defun org-get-property-block (&optional beg end force)
12324 "Return the (beg . end) range of the body of the property drawer.
12325 BEG and END can be beginning and end of subtree, if not given
12326 they will be found.
12327 If the drawer does not exist and FORCE is non-nil, create the drawer."
12328 (catch 'exit
12329 (save-excursion
12330 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12331 (end (or end (progn (outline-next-heading) (point)))))
12332 (goto-char beg)
12333 (if (re-search-forward org-property-start-re end t)
12334 (setq beg (1+ (match-end 0)))
12335 (if force
12336 (save-excursion
12337 (org-insert-property-drawer)
12338 (setq end (progn (outline-next-heading) (point))))
12339 (throw 'exit nil))
12340 (goto-char beg)
12341 (if (re-search-forward org-property-start-re end t)
12342 (setq beg (1+ (match-end 0)))))
12343 (if (re-search-forward org-property-end-re end t)
12344 (setq end (match-beginning 0))
12345 (or force (throw 'exit nil))
12346 (goto-char beg)
12347 (setq end beg)
12348 (org-indent-line-function)
12349 (insert ":END:\n"))
12350 (cons beg end)))))
12352 (defun org-entry-properties (&optional pom which)
12353 "Get all properties of the entry at point-or-marker POM.
12354 This includes the TODO keyword, the tags, time strings for deadline,
12355 scheduled, and clocking, and any additional properties defined in the
12356 entry. The return value is an alist, keys may occur multiple times
12357 if the property key was used several times.
12358 POM may also be nil, in which case the current entry is used.
12359 If WHICH is nil or `all', get all properties. If WHICH is
12360 `special' or `standard', only get that subclass."
12361 (setq which (or which 'all))
12362 (org-with-point-at pom
12363 (let ((clockstr (substring org-clock-string 0 -1))
12364 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12365 beg end range props sum-props key value string clocksum)
12366 (save-excursion
12367 (when (condition-case nil
12368 (and (org-mode-p) (org-back-to-heading t))
12369 (error nil))
12370 (setq beg (point))
12371 (setq sum-props (get-text-property (point) 'org-summaries))
12372 (setq clocksum (get-text-property (point) :org-clock-minutes))
12373 (outline-next-heading)
12374 (setq end (point))
12375 (when (memq which '(all special))
12376 ;; Get the special properties, like TODO and tags
12377 (goto-char beg)
12378 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12379 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12380 (when (looking-at org-priority-regexp)
12381 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12382 (when (and (setq value (org-get-tags-string))
12383 (string-match "\\S-" value))
12384 (push (cons "TAGS" value) props))
12385 (when (setq value (org-get-tags-at))
12386 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12387 props))
12388 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12389 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12390 string (if (equal key clockstr)
12391 (org-no-properties
12392 (org-trim
12393 (buffer-substring
12394 (match-beginning 3) (goto-char (point-at-eol)))))
12395 (substring (org-match-string-no-properties 3) 1 -1)))
12396 (unless key
12397 (if (= (char-after (match-beginning 3)) ?\[)
12398 (setq key "TIMESTAMP_IA")
12399 (setq key "TIMESTAMP")))
12400 (when (or (equal key clockstr) (not (assoc key props)))
12401 (push (cons key string) props)))
12405 (when (memq which '(all standard))
12406 ;; Get the standard properties, like :PROP: ...
12407 (setq range (org-get-property-block beg end))
12408 (when range
12409 (goto-char (car range))
12410 (while (re-search-forward
12411 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12412 (cdr range) t)
12413 (setq key (org-match-string-no-properties 1)
12414 value (org-trim (or (org-match-string-no-properties 2) "")))
12415 (unless (member key excluded)
12416 (push (cons key (or value "")) props)))))
12417 (if clocksum
12418 (push (cons "CLOCKSUM"
12419 (org-columns-number-to-string (/ (float clocksum) 60.)
12420 'add_times))
12421 props))
12422 (unless (assoc "CATEGORY" props)
12423 (setq value (or (org-get-category)
12424 (progn (org-refresh-category-properties)
12425 (org-get-category))))
12426 (push (cons "CATEGORY" value) props))
12427 (append sum-props (nreverse props)))))))
12429 (defun org-entry-get (pom property &optional inherit)
12430 "Get value of PROPERTY for entry at point-or-marker POM.
12431 If INHERIT is non-nil and the entry does not have the property,
12432 then also check higher levels of the hierarchy.
12433 If INHERIT is the symbol `selective', use inheritance only if the setting
12434 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12435 If the property is present but empty, the return value is the empty string.
12436 If the property is not present at all, nil is returned."
12437 (org-with-point-at pom
12438 (if (and inherit (if (eq inherit 'selective)
12439 (org-property-inherit-p property)
12441 (org-entry-get-with-inheritance property)
12442 (if (member property org-special-properties)
12443 ;; We need a special property. Use brute force, get all properties.
12444 (cdr (assoc property (org-entry-properties nil 'special)))
12445 (let ((range (org-get-property-block)))
12446 (if (and range
12447 (goto-char (car range))
12448 (re-search-forward
12449 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12450 (cdr range) t))
12451 ;; Found the property, return it.
12452 (if (match-end 1)
12453 (org-match-string-no-properties 1)
12454 "")))))))
12456 (defun org-property-or-variable-value (var &optional inherit)
12457 "Check if there is a property fixing the value of VAR.
12458 If yes, return this value. If not, return the current value of the variable."
12459 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12460 (if (and prop (stringp prop) (string-match "\\S-" prop))
12461 (read prop)
12462 (symbol-value var))))
12464 (defun org-entry-delete (pom property)
12465 "Delete the property PROPERTY from entry at point-or-marker POM."
12466 (org-with-point-at pom
12467 (if (member property org-special-properties)
12468 nil ; cannot delete these properties.
12469 (let ((range (org-get-property-block)))
12470 (if (and range
12471 (goto-char (car range))
12472 (re-search-forward
12473 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12474 (cdr range) t))
12475 (progn
12476 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12478 nil)))))
12480 ;; Multi-values properties are properties that contain multiple values
12481 ;; These values are assumed to be single words, separated by whitespace.
12482 (defun org-entry-add-to-multivalued-property (pom property value)
12483 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12484 (let* ((old (org-entry-get pom property))
12485 (values (and old (org-split-string old "[ \t]"))))
12486 (setq value (org-entry-protect-space value))
12487 (unless (member value values)
12488 (setq values (cons value values))
12489 (org-entry-put pom property
12490 (mapconcat 'identity values " ")))))
12492 (defun org-entry-remove-from-multivalued-property (pom property value)
12493 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12494 (let* ((old (org-entry-get pom property))
12495 (values (and old (org-split-string old "[ \t]"))))
12496 (setq value (org-entry-protect-space value))
12497 (when (member value values)
12498 (setq values (delete value values))
12499 (org-entry-put pom property
12500 (mapconcat 'identity values " ")))))
12502 (defun org-entry-member-in-multivalued-property (pom property value)
12503 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12504 (let* ((old (org-entry-get pom property))
12505 (values (and old (org-split-string old "[ \t]"))))
12506 (setq value (org-entry-protect-space value))
12507 (member value values)))
12509 (defun org-entry-get-multivalued-property (pom property)
12510 "Return a list of values in a multivalued property."
12511 (let* ((value (org-entry-get pom property))
12512 (values (and value (org-split-string value "[ \t]"))))
12513 (mapcar 'org-entry-restore-space values)))
12515 (defun org-entry-put-multivalued-property (pom property &rest values)
12516 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12517 VALUES should be a list of strings. Spaces will be protected."
12518 (org-entry-put pom property
12519 (mapconcat 'org-entry-protect-space values " "))
12520 (let* ((value (org-entry-get pom property))
12521 (values (and value (org-split-string value "[ \t]"))))
12522 (mapcar 'org-entry-restore-space values)))
12524 (defun org-entry-protect-space (s)
12525 "Protect spaces and newline in string S."
12526 (while (string-match " " s)
12527 (setq s (replace-match "%20" t t s)))
12528 (while (string-match "\n" s)
12529 (setq s (replace-match "%0A" t t s)))
12532 (defun org-entry-restore-space (s)
12533 "Restore spaces and newline in string S."
12534 (while (string-match "%20" s)
12535 (setq s (replace-match " " t t s)))
12536 (while (string-match "%0A" s)
12537 (setq s (replace-match "\n" t t s)))
12540 (defvar org-entry-property-inherited-from (make-marker)
12541 "Marker pointing to the entry from where a property was inherited.
12542 Each call to `org-entry-get-with-inheritance' will set this marker to the
12543 location of the entry where the inheritance search matched. If there was
12544 no match, the marker will point nowhere.
12545 Note that also `org-entry-get' calls this function, if the INHERIT flag
12546 is set.")
12548 (defun org-entry-get-with-inheritance (property)
12549 "Get entry property, and search higher levels if not present."
12550 (move-marker org-entry-property-inherited-from nil)
12551 (let (tmp)
12552 (save-excursion
12553 (save-restriction
12554 (widen)
12555 (catch 'ex
12556 (while t
12557 (when (setq tmp (org-entry-get nil property))
12558 (org-back-to-heading t)
12559 (move-marker org-entry-property-inherited-from (point))
12560 (throw 'ex tmp))
12561 (or (org-up-heading-safe) (throw 'ex nil)))))
12562 (or tmp
12563 (cdr (assoc property org-file-properties))
12564 (cdr (assoc property org-global-properties))
12565 (cdr (assoc property org-global-properties-fixed))))))
12567 (defvar org-property-changed-functions nil
12568 "Hook called when the value of a property has changed.
12569 Each hook function should accept two arguments, the name of the property
12570 and the new value.")
12572 (defun org-entry-put (pom property value)
12573 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12574 (org-with-point-at pom
12575 (org-back-to-heading t)
12576 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12577 range)
12578 (cond
12579 ((equal property "TODO")
12580 (when (and (stringp value) (string-match "\\S-" value)
12581 (not (member value org-todo-keywords-1)))
12582 (error "\"%s\" is not a valid TODO state" value))
12583 (if (or (not value)
12584 (not (string-match "\\S-" value)))
12585 (setq value 'none))
12586 (org-todo value)
12587 (org-set-tags nil 'align))
12588 ((equal property "PRIORITY")
12589 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12590 (string-to-char value) ?\ ))
12591 (org-set-tags nil 'align))
12592 ((equal property "SCHEDULED")
12593 (if (re-search-forward org-scheduled-time-regexp end t)
12594 (cond
12595 ((eq value 'earlier) (org-timestamp-change -1 'day))
12596 ((eq value 'later) (org-timestamp-change 1 'day))
12597 (t (call-interactively 'org-schedule)))
12598 (call-interactively 'org-schedule)))
12599 ((equal property "DEADLINE")
12600 (if (re-search-forward org-deadline-time-regexp end t)
12601 (cond
12602 ((eq value 'earlier) (org-timestamp-change -1 'day))
12603 ((eq value 'later) (org-timestamp-change 1 'day))
12604 (t (call-interactively 'org-deadline)))
12605 (call-interactively 'org-deadline)))
12606 ((member property org-special-properties)
12607 (error "The %s property can not yet be set with `org-entry-put'"
12608 property))
12609 (t ; a non-special property
12610 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12611 (setq range (org-get-property-block beg end 'force))
12612 (goto-char (car range))
12613 (if (re-search-forward
12614 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12615 (progn
12616 (delete-region (match-beginning 1) (match-end 1))
12617 (goto-char (match-beginning 1)))
12618 (goto-char (cdr range))
12619 (insert "\n")
12620 (backward-char 1)
12621 (org-indent-line-function)
12622 (insert ":" property ":"))
12623 (and value (insert " " value))
12624 (org-indent-line-function)))))
12625 (run-hook-with-args 'org-property-changed-functions property value)))
12627 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12628 "Get all property keys in the current buffer.
12629 With INCLUDE-SPECIALS, also list the special properties that reflect things
12630 like tags and TODO state.
12631 With INCLUDE-DEFAULTS, also include properties that has special meaning
12632 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12633 With INCLUDE-COLUMNS, also include property names given in COLUMN
12634 formats in the current buffer."
12635 (let (rtn range cfmt s p)
12636 (save-excursion
12637 (save-restriction
12638 (widen)
12639 (goto-char (point-min))
12640 (while (re-search-forward org-property-start-re nil t)
12641 (setq range (org-get-property-block))
12642 (goto-char (car range))
12643 (while (re-search-forward
12644 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12645 (cdr range) t)
12646 (add-to-list 'rtn (org-match-string-no-properties 1)))
12647 (outline-next-heading))))
12649 (when include-specials
12650 (setq rtn (append org-special-properties rtn)))
12652 (when include-defaults
12653 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12654 (add-to-list 'rtn org-effort-property))
12656 (when include-columns
12657 (save-excursion
12658 (save-restriction
12659 (widen)
12660 (goto-char (point-min))
12661 (while (re-search-forward
12662 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12663 nil t)
12664 (setq cfmt (match-string 2) s 0)
12665 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12666 cfmt s)
12667 (setq s (match-end 0)
12668 p (match-string 1 cfmt))
12669 (unless (or (equal p "ITEM")
12670 (member p org-special-properties))
12671 (add-to-list 'rtn (match-string 1 cfmt))))))))
12673 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12675 (defun org-property-values (key)
12676 "Return a list of all values of property KEY."
12677 (save-excursion
12678 (save-restriction
12679 (widen)
12680 (goto-char (point-min))
12681 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12682 values)
12683 (while (re-search-forward re nil t)
12684 (add-to-list 'values (org-trim (match-string 1))))
12685 (delete "" values)))))
12687 (defun org-insert-property-drawer ()
12688 "Insert a property drawer into the current entry."
12689 (interactive)
12690 (org-back-to-heading t)
12691 (looking-at outline-regexp)
12692 (let ((indent (if org-adapt-indentation
12693 (- (match-end 0)(match-beginning 0))
12695 (beg (point))
12696 (re (concat "^[ \t]*" org-keyword-time-regexp))
12697 end hiddenp)
12698 (outline-next-heading)
12699 (setq end (point))
12700 (goto-char beg)
12701 (while (re-search-forward re end t))
12702 (setq hiddenp (org-invisible-p))
12703 (end-of-line 1)
12704 (and (equal (char-after) ?\n) (forward-char 1))
12705 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12706 (if (member (match-string 1) '("CLOCK:" ":END:"))
12707 ;; just skip this line
12708 (beginning-of-line 2)
12709 ;; Drawer start, find the end
12710 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12711 (beginning-of-line 1)))
12712 (org-skip-over-state-notes)
12713 (skip-chars-backward " \t\n\r")
12714 (if (eq (char-before) ?*) (forward-char 1))
12715 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12716 (beginning-of-line 0)
12717 (org-indent-to-column indent)
12718 (beginning-of-line 2)
12719 (org-indent-to-column indent)
12720 (beginning-of-line 0)
12721 (if hiddenp
12722 (save-excursion
12723 (org-back-to-heading t)
12724 (hide-entry))
12725 (org-flag-drawer t))))
12727 (defun org-set-property (property value)
12728 "In the current entry, set PROPERTY to VALUE.
12729 When called interactively, this will prompt for a property name, offering
12730 completion on existing and default properties. And then it will prompt
12731 for a value, offering completion either on allowed values (via an inherited
12732 xxx_ALL property) or on existing values in other instances of this property
12733 in the current file."
12734 (interactive
12735 (let* ((completion-ignore-case t)
12736 (keys (org-buffer-property-keys nil t t))
12737 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12738 (prop (if (member prop0 keys)
12739 prop0
12740 (or (cdr (assoc (downcase prop0)
12741 (mapcar (lambda (x) (cons (downcase x) x))
12742 keys)))
12743 prop0)))
12744 (cur (org-entry-get nil prop))
12745 (allowed (org-property-get-allowed-values nil prop 'table))
12746 (existing (mapcar 'list (org-property-values prop)))
12747 (val (if allowed
12748 (org-completing-read "Value: " allowed nil
12749 (not (get-text-property 0 'org-unrestricted
12750 (caar allowed))))
12751 (let (org-completion-use-ido org-completion-use-iswitchb)
12752 (org-completing-read
12753 (concat "Value " (if (and cur (string-match "\\S-" cur))
12754 (concat "[" cur "]") "")
12755 ": ")
12756 existing nil nil "" nil cur)))))
12757 (list prop (if (equal val "") cur val))))
12758 (unless (equal (org-entry-get nil property) value)
12759 (org-entry-put nil property value)))
12761 (defun org-delete-property (property)
12762 "In the current entry, delete PROPERTY."
12763 (interactive
12764 (let* ((completion-ignore-case t)
12765 (prop (org-icompleting-read
12766 "Property: " (org-entry-properties nil 'standard))))
12767 (list prop)))
12768 (message "Property %s %s" property
12769 (if (org-entry-delete nil property)
12770 "deleted"
12771 "was not present in the entry")))
12773 (defun org-delete-property-globally (property)
12774 "Remove PROPERTY globally, from all entries."
12775 (interactive
12776 (let* ((completion-ignore-case t)
12777 (prop (org-icompleting-read
12778 "Globally remove property: "
12779 (mapcar 'list (org-buffer-property-keys)))))
12780 (list prop)))
12781 (save-excursion
12782 (save-restriction
12783 (widen)
12784 (goto-char (point-min))
12785 (let ((cnt 0))
12786 (while (re-search-forward
12787 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12788 nil t)
12789 (setq cnt (1+ cnt))
12790 (replace-match ""))
12791 (message "Property \"%s\" removed from %d entries" property cnt)))))
12793 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12795 (defun org-compute-property-at-point ()
12796 "Compute the property at point.
12797 This looks for an enclosing column format, extracts the operator and
12798 then applies it to the property in the column format's scope."
12799 (interactive)
12800 (unless (org-at-property-p)
12801 (error "Not at a property"))
12802 (let ((prop (org-match-string-no-properties 2)))
12803 (org-columns-get-format-and-top-level)
12804 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12805 (error "No operator defined for property %s" prop))
12806 (org-columns-compute prop)))
12808 (defvar org-property-allowed-value-functions nil
12809 "Hook for functions supplying allowed values for specific.
12810 The functions must take a single argument, the name of the property, and
12811 return a flat list of allowed values. If \":ETC\" is one of
12812 the values, this means that these values are intended as defaults for
12813 completion, but that other values should be allowed too.
12814 The functions must return nil if they are now responsible for this
12815 prioerty.")
12817 (defun org-property-get-allowed-values (pom property &optional table)
12818 "Get allowed values for the property PROPERTY.
12819 When TABLE is non-nil, return an alist that can directly be used for
12820 completion."
12821 (let (vals)
12822 (cond
12823 ((equal property "TODO")
12824 (setq vals (org-with-point-at pom
12825 (append org-todo-keywords-1 '("")))))
12826 ((equal property "PRIORITY")
12827 (let ((n org-lowest-priority))
12828 (while (>= n org-highest-priority)
12829 (push (char-to-string n) vals)
12830 (setq n (1- n)))))
12831 ((member property org-special-properties))
12832 ((setq vals (run-hook-with-args-until-success
12833 'org-property-allowed-value-functions property)))
12835 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12836 (when (and vals (string-match "\\S-" vals))
12837 (setq vals (car (read-from-string (concat "(" vals ")"))))
12838 (setq vals (mapcar (lambda (x)
12839 (cond ((stringp x) x)
12840 ((numberp x) (number-to-string x))
12841 ((symbolp x) (symbol-name x))
12842 (t "???")))
12843 vals)))))
12844 (when (member ":ETC" vals)
12845 (setq vals (remove ":ETC" vals))
12846 (org-add-props (car vals) '(org-unrestricted t)))
12847 (if table (mapcar 'list vals) vals)))
12849 (defun org-property-previous-allowed-value (&optional previous)
12850 "Switch to the next allowed value for this property."
12851 (interactive)
12852 (org-property-next-allowed-value t))
12854 (defun org-property-next-allowed-value (&optional previous)
12855 "Switch to the next allowed value for this property."
12856 (interactive)
12857 (unless (org-at-property-p)
12858 (error "Not at a property"))
12859 (let* ((key (match-string 2))
12860 (value (match-string 3))
12861 (allowed (or (org-property-get-allowed-values (point) key)
12862 (and (member value '("[ ]" "[-]" "[X]"))
12863 '("[ ]" "[X]"))))
12864 nval)
12865 (unless allowed
12866 (error "Allowed values for this property have not been defined"))
12867 (if previous (setq allowed (reverse allowed)))
12868 (if (member value allowed)
12869 (setq nval (car (cdr (member value allowed)))))
12870 (setq nval (or nval (car allowed)))
12871 (if (equal nval value)
12872 (error "Only one allowed value for this property"))
12873 (org-at-property-p)
12874 (replace-match (concat " :" key ": " nval) t t)
12875 (org-indent-line-function)
12876 (beginning-of-line 1)
12877 (skip-chars-forward " \t")
12878 (run-hook-with-args 'org-property-changed-functions key nval)))
12880 (defun org-find-entry-with-id (ident)
12881 "Locate the entry that contains the ID property with exact value IDENT.
12882 IDENT can be a string, a symbol or a number, this function will search for
12883 the string representation of it.
12884 Return the position where this entry starts, or nil if there is no such entry."
12885 (interactive "sID: ")
12886 (let ((id (cond
12887 ((stringp ident) ident)
12888 ((symbol-name ident) (symbol-name ident))
12889 ((numberp ident) (number-to-string ident))
12890 (t (error "IDENT %s must be a string, symbol or number" ident))))
12891 (case-fold-search nil))
12892 (save-excursion
12893 (save-restriction
12894 (widen)
12895 (goto-char (point-min))
12896 (when (re-search-forward
12897 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12898 nil t)
12899 (org-back-to-heading t)
12900 (point))))))
12902 ;;;; Timestamps
12904 (defvar org-last-changed-timestamp nil)
12905 (defvar org-last-inserted-timestamp nil
12906 "The last time stamp inserted with `org-insert-time-stamp'.")
12907 (defvar org-time-was-given) ; dynamically scoped parameter
12908 (defvar org-end-time-was-given) ; dynamically scoped parameter
12909 (defvar org-ts-what) ; dynamically scoped parameter
12911 (defun org-time-stamp (arg &optional inactive)
12912 "Prompt for a date/time and insert a time stamp.
12913 If the user specifies a time like HH:MM, or if this command is called
12914 with a prefix argument, the time stamp will contain date and time.
12915 Otherwise, only the date will be included. All parts of a date not
12916 specified by the user will be filled in from the current date/time.
12917 So if you press just return without typing anything, the time stamp
12918 will represent the current date/time. If there is already a timestamp
12919 at the cursor, it will be modified."
12920 (interactive "P")
12921 (let* ((ts nil)
12922 (default-time
12923 ;; Default time is either today, or, when entering a range,
12924 ;; the range start.
12925 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12926 (save-excursion
12927 (re-search-backward
12928 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12929 (- (point) 20) t)))
12930 (apply 'encode-time (org-parse-time-string (match-string 1)))
12931 (current-time)))
12932 (default-input (and ts (org-get-compact-tod ts)))
12933 org-time-was-given org-end-time-was-given time)
12934 (cond
12935 ((and (org-at-timestamp-p t)
12936 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12937 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12938 (insert "--")
12939 (setq time (let ((this-command this-command))
12940 (org-read-date arg 'totime nil nil
12941 default-time default-input)))
12942 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12943 ((org-at-timestamp-p t)
12944 (setq time (let ((this-command this-command))
12945 (org-read-date arg 'totime nil nil default-time default-input)))
12946 (when (org-at-timestamp-p t) ; just to get the match data
12947 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12948 (replace-match "")
12949 (setq org-last-changed-timestamp
12950 (org-insert-time-stamp
12951 time (or org-time-was-given arg)
12952 inactive nil nil (list org-end-time-was-given))))
12953 (message "Timestamp updated"))
12955 (setq time (let ((this-command this-command))
12956 (org-read-date arg 'totime nil nil default-time default-input)))
12957 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12958 nil nil (list org-end-time-was-given))))))
12960 ;; FIXME: can we use this for something else, like computing time differences?
12961 (defun org-get-compact-tod (s)
12962 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12963 (let* ((t1 (match-string 1 s))
12964 (h1 (string-to-number (match-string 2 s)))
12965 (m1 (string-to-number (match-string 3 s)))
12966 (t2 (and (match-end 4) (match-string 5 s)))
12967 (h2 (and t2 (string-to-number (match-string 6 s))))
12968 (m2 (and t2 (string-to-number (match-string 7 s))))
12969 dh dm)
12970 (if (not t2)
12972 (setq dh (- h2 h1) dm (- m2 m1))
12973 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12974 (concat t1 "+" (number-to-string dh)
12975 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12977 (defun org-time-stamp-inactive (&optional arg)
12978 "Insert an inactive time stamp.
12979 An inactive time stamp is enclosed in square brackets instead of angle
12980 brackets. It is inactive in the sense that it does not trigger agenda entries,
12981 does not link to the calendar and cannot be changed with the S-cursor keys.
12982 So these are more for recording a certain time/date."
12983 (interactive "P")
12984 (org-time-stamp arg 'inactive))
12986 (defvar org-date-ovl (org-make-overlay 1 1))
12987 (org-overlay-put org-date-ovl 'face 'org-warning)
12988 (org-detach-overlay org-date-ovl)
12990 (defvar org-ans1) ; dynamically scoped parameter
12991 (defvar org-ans2) ; dynamically scoped parameter
12993 (defvar org-plain-time-of-day-regexp) ; defined below
12995 (defvar org-overriding-default-time nil) ; dynamically scoped
12996 (defvar org-read-date-overlay nil)
12997 (defvar org-dcst nil) ; dynamically scoped
12998 (defvar org-read-date-history nil)
12999 (defvar org-read-date-final-answer nil)
13001 (defun org-read-date (&optional with-time to-time from-string prompt
13002 default-time default-input)
13003 "Read a date, possibly a time, and make things smooth for the user.
13004 The prompt will suggest to enter an ISO date, but you can also enter anything
13005 which will at least partially be understood by `parse-time-string'.
13006 Unrecognized parts of the date will default to the current day, month, year,
13007 hour and minute. If this command is called to replace a timestamp at point,
13008 of to enter the second timestamp of a range, the default time is taken from the
13009 existing stamp. For example,
13010 3-2-5 --> 2003-02-05
13011 feb 15 --> currentyear-02-15
13012 sep 12 9 --> 2009-09-12
13013 12:45 --> today 12:45
13014 22 sept 0:34 --> currentyear-09-22 0:34
13015 12 --> currentyear-currentmonth-12
13016 Fri --> nearest Friday (today or later)
13017 etc.
13019 Furthermore you can specify a relative date by giving, as the *first* thing
13020 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13021 change in days weeks, months, years.
13022 With a single plus or minus, the date is relative to today. With a double
13023 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13024 +4d --> four days from today
13025 +4 --> same as above
13026 +2w --> two weeks from today
13027 ++5 --> five days from default date
13029 The function understands only English month and weekday abbreviations,
13030 but this can be configured with the variables `parse-time-months' and
13031 `parse-time-weekdays'.
13033 While prompting, a calendar is popped up - you can also select the
13034 date with the mouse (button 1). The calendar shows a period of three
13035 months. To scroll it to other months, use the keys `>' and `<'.
13036 If you don't like the calendar, turn it off with
13037 \(setq org-read-date-popup-calendar nil)
13039 With optional argument TO-TIME, the date will immediately be converted
13040 to an internal time.
13041 With an optional argument WITH-TIME, the prompt will suggest to also
13042 insert a time. Note that when WITH-TIME is not set, you can still
13043 enter a time, and this function will inform the calling routine about
13044 this change. The calling routine may then choose to change the format
13045 used to insert the time stamp into the buffer to include the time.
13046 With optional argument FROM-STRING, read from this string instead from
13047 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13048 the time/date that is used for everything that is not specified by the
13049 user."
13050 (require 'parse-time)
13051 (let* ((org-time-stamp-rounding-minutes
13052 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13053 (org-dcst org-display-custom-times)
13054 (ct (org-current-time))
13055 (def (or org-overriding-default-time default-time ct))
13056 (defdecode (decode-time def))
13057 (dummy (progn
13058 (when (< (nth 2 defdecode) org-extend-today-until)
13059 (setcar (nthcdr 2 defdecode) -1)
13060 (setcar (nthcdr 1 defdecode) 59)
13061 (setq def (apply 'encode-time defdecode)
13062 defdecode (decode-time def)))))
13063 (calendar-frame-setup nil)
13064 (calendar-move-hook nil)
13065 (calendar-view-diary-initially-flag nil)
13066 (view-diary-entries-initially nil)
13067 (calendar-view-holidays-initially-flag nil)
13068 (view-calendar-holidays-initially nil)
13069 (timestr (format-time-string
13070 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13071 (prompt (concat (if prompt (concat prompt " ") "")
13072 (format "Date+time [%s]: " timestr)))
13073 ans (org-ans0 "") org-ans1 org-ans2 final)
13075 (cond
13076 (from-string (setq ans from-string))
13077 (org-read-date-popup-calendar
13078 (save-excursion
13079 (save-window-excursion
13080 (calendar)
13081 (calendar-forward-day (- (time-to-days def)
13082 (calendar-absolute-from-gregorian
13083 (calendar-current-date))))
13084 (org-eval-in-calendar nil t)
13085 (let* ((old-map (current-local-map))
13086 (map (copy-keymap calendar-mode-map))
13087 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13088 (org-defkey map (kbd "RET") 'org-calendar-select)
13089 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13090 'org-calendar-select-mouse)
13091 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13092 'org-calendar-select-mouse)
13093 (org-defkey minibuffer-local-map [(meta shift left)]
13094 (lambda () (interactive)
13095 (org-eval-in-calendar '(calendar-backward-month 1))))
13096 (org-defkey minibuffer-local-map [(meta shift right)]
13097 (lambda () (interactive)
13098 (org-eval-in-calendar '(calendar-forward-month 1))))
13099 (org-defkey minibuffer-local-map [(meta shift up)]
13100 (lambda () (interactive)
13101 (org-eval-in-calendar '(calendar-backward-year 1))))
13102 (org-defkey minibuffer-local-map [(meta shift down)]
13103 (lambda () (interactive)
13104 (org-eval-in-calendar '(calendar-forward-year 1))))
13105 (org-defkey minibuffer-local-map [?\e (shift left)]
13106 (lambda () (interactive)
13107 (org-eval-in-calendar '(calendar-backward-month 1))))
13108 (org-defkey minibuffer-local-map [?\e (shift right)]
13109 (lambda () (interactive)
13110 (org-eval-in-calendar '(calendar-forward-month 1))))
13111 (org-defkey minibuffer-local-map [?\e (shift up)]
13112 (lambda () (interactive)
13113 (org-eval-in-calendar '(calendar-backward-year 1))))
13114 (org-defkey minibuffer-local-map [?\e (shift down)]
13115 (lambda () (interactive)
13116 (org-eval-in-calendar '(calendar-forward-year 1))))
13117 (org-defkey minibuffer-local-map [(shift up)]
13118 (lambda () (interactive)
13119 (org-eval-in-calendar '(calendar-backward-week 1))))
13120 (org-defkey minibuffer-local-map [(shift down)]
13121 (lambda () (interactive)
13122 (org-eval-in-calendar '(calendar-forward-week 1))))
13123 (org-defkey minibuffer-local-map [(shift left)]
13124 (lambda () (interactive)
13125 (org-eval-in-calendar '(calendar-backward-day 1))))
13126 (org-defkey minibuffer-local-map [(shift right)]
13127 (lambda () (interactive)
13128 (org-eval-in-calendar '(calendar-forward-day 1))))
13129 (org-defkey minibuffer-local-map ">"
13130 (lambda () (interactive)
13131 (org-eval-in-calendar '(scroll-calendar-left 1))))
13132 (org-defkey minibuffer-local-map "<"
13133 (lambda () (interactive)
13134 (org-eval-in-calendar '(scroll-calendar-right 1))))
13135 (run-hooks 'org-read-date-minibuffer-setup-hook)
13136 (unwind-protect
13137 (progn
13138 (use-local-map map)
13139 (add-hook 'post-command-hook 'org-read-date-display)
13140 (setq org-ans0 (read-string prompt default-input
13141 'org-read-date-history nil))
13142 ;; org-ans0: from prompt
13143 ;; org-ans1: from mouse click
13144 ;; org-ans2: from calendar motion
13145 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13146 (remove-hook 'post-command-hook 'org-read-date-display)
13147 (use-local-map old-map)
13148 (when org-read-date-overlay
13149 (org-delete-overlay org-read-date-overlay)
13150 (setq org-read-date-overlay nil)))))))
13152 (t ; Naked prompt only
13153 (unwind-protect
13154 (setq ans (read-string prompt default-input
13155 'org-read-date-history timestr))
13156 (when org-read-date-overlay
13157 (org-delete-overlay org-read-date-overlay)
13158 (setq org-read-date-overlay nil)))))
13160 (setq final (org-read-date-analyze ans def defdecode))
13161 (setq org-read-date-final-answer ans)
13163 (if to-time
13164 (apply 'encode-time final)
13165 (if (and (boundp 'org-time-was-given) org-time-was-given)
13166 (format "%04d-%02d-%02d %02d:%02d"
13167 (nth 5 final) (nth 4 final) (nth 3 final)
13168 (nth 2 final) (nth 1 final))
13169 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13171 (defvar def)
13172 (defvar defdecode)
13173 (defvar with-time)
13174 (defvar org-read-date-analyze-futurep nil)
13175 (defun org-read-date-display ()
13176 "Display the current date prompt interpretation in the minibuffer."
13177 (when org-read-date-display-live
13178 (when org-read-date-overlay
13179 (org-delete-overlay org-read-date-overlay))
13180 (let ((p (point)))
13181 (end-of-line 1)
13182 (while (not (equal (buffer-substring
13183 (max (point-min) (- (point) 4)) (point))
13184 " "))
13185 (insert " "))
13186 (goto-char p))
13187 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13188 " " (or org-ans1 org-ans2)))
13189 (org-end-time-was-given nil)
13190 (f (org-read-date-analyze ans def defdecode))
13191 (fmts (if org-dcst
13192 org-time-stamp-custom-formats
13193 org-time-stamp-formats))
13194 (fmt (if (or with-time
13195 (and (boundp 'org-time-was-given) org-time-was-given))
13196 (cdr fmts)
13197 (car fmts)))
13198 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13199 (when (and org-end-time-was-given
13200 (string-match org-plain-time-of-day-regexp txt))
13201 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13202 org-end-time-was-given
13203 (substring txt (match-end 0)))))
13204 (when org-read-date-analyze-futurep
13205 (setq txt (concat txt " (=>F)")))
13206 (setq org-read-date-overlay
13207 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13208 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13210 (defun org-read-date-analyze (ans def defdecode)
13211 "Analyse the combined answer of the date prompt."
13212 ;; FIXME: cleanup and comment
13213 (let (delta deltan deltaw deltadef year month day
13214 hour minute second wday pm h2 m2 tl wday1
13215 iso-year iso-weekday iso-week iso-year iso-date futurep)
13216 (setq org-read-date-analyze-futurep nil)
13217 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13218 (setq ans "+0"))
13220 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13221 (setq ans (replace-match "" t t ans)
13222 deltan (car delta)
13223 deltaw (nth 1 delta)
13224 deltadef (nth 2 delta)))
13226 ;; Check if there is an iso week date in there
13227 ;; If yes, store the info and postpone interpreting it until the rest
13228 ;; of the parsing is done
13229 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13230 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13231 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13232 iso-week (string-to-number (match-string 2 ans)))
13233 (setq ans (replace-match "" t t ans)))
13235 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13236 (when (string-match
13237 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13238 (setq year (if (match-end 2)
13239 (string-to-number (match-string 2 ans))
13240 (string-to-number (format-time-string "%Y")))
13241 month (string-to-number (match-string 3 ans))
13242 day (string-to-number (match-string 4 ans)))
13243 (if (< year 100) (setq year (+ 2000 year)))
13244 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13245 t nil ans)))
13246 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13247 ;; If there is a time with am/pm, and *no* time without it, we convert
13248 ;; so that matching will be successful.
13249 (loop for i from 1 to 2 do ; twice, for end time as well
13250 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13251 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13252 (setq hour (string-to-number (match-string 1 ans))
13253 minute (if (match-end 3)
13254 (string-to-number (match-string 3 ans))
13256 pm (equal ?p
13257 (string-to-char (downcase (match-string 4 ans)))))
13258 (if (and (= hour 12) (not pm))
13259 (setq hour 0)
13260 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13261 (setq ans (replace-match (format "%02d:%02d" hour minute)
13262 t t ans))))
13264 ;; Check if a time range is given as a duration
13265 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13266 (setq hour (string-to-number (match-string 1 ans))
13267 h2 (+ hour (string-to-number (match-string 3 ans)))
13268 minute (string-to-number (match-string 2 ans))
13269 m2 (+ minute (if (match-end 5) (string-to-number
13270 (match-string 5 ans))0)))
13271 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13272 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13273 t t ans)))
13275 ;; Check if there is a time range
13276 (when (boundp 'org-end-time-was-given)
13277 (setq org-time-was-given nil)
13278 (when (and (string-match org-plain-time-of-day-regexp ans)
13279 (match-end 8))
13280 (setq org-end-time-was-given (match-string 8 ans))
13281 (setq ans (concat (substring ans 0 (match-beginning 7))
13282 (substring ans (match-end 7))))))
13284 (setq tl (parse-time-string ans)
13285 day (or (nth 3 tl) (nth 3 defdecode))
13286 month (or (nth 4 tl)
13287 (if (and org-read-date-prefer-future
13288 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13289 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13290 (nth 4 defdecode)))
13291 year (or (nth 5 tl)
13292 (if (and org-read-date-prefer-future
13293 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13294 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13295 (nth 5 defdecode)))
13296 hour (or (nth 2 tl) (nth 2 defdecode))
13297 minute (or (nth 1 tl) (nth 1 defdecode))
13298 second (or (nth 0 tl) 0)
13299 wday (nth 6 tl))
13301 (when (and (eq org-read-date-prefer-future 'time)
13302 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13303 (equal day (nth 3 defdecode))
13304 (equal month (nth 4 defdecode))
13305 (equal year (nth 5 defdecode))
13306 (nth 2 tl)
13307 (or (< (nth 2 tl) (nth 2 defdecode))
13308 (and (= (nth 2 tl) (nth 2 defdecode))
13309 (nth 1 tl)
13310 (< (nth 1 tl) (nth 1 defdecode)))))
13311 (setq day (1+ day)
13312 futurep t))
13314 ;; Special date definitions below
13315 (cond
13316 (iso-week
13317 ;; There was an iso week
13318 (setq futurep nil)
13319 (setq year (or iso-year year)
13320 day (or iso-weekday wday 1)
13321 wday nil ; to make sure that the trigger below does not match
13322 iso-date (calendar-gregorian-from-absolute
13323 (calendar-absolute-from-iso
13324 (list iso-week day year))))
13325 ; FIXME: Should we also push ISO weeks into the future?
13326 ; (when (and org-read-date-prefer-future
13327 ; (not iso-year)
13328 ; (< (calendar-absolute-from-gregorian iso-date)
13329 ; (time-to-days (current-time))))
13330 ; (setq year (1+ year)
13331 ; iso-date (calendar-gregorian-from-absolute
13332 ; (calendar-absolute-from-iso
13333 ; (list iso-week day year)))))
13334 (setq month (car iso-date)
13335 year (nth 2 iso-date)
13336 day (nth 1 iso-date)))
13337 (deltan
13338 (setq futurep nil)
13339 (unless deltadef
13340 (let ((now (decode-time (current-time))))
13341 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13342 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13343 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13344 ((equal deltaw "m") (setq month (+ month deltan)))
13345 ((equal deltaw "y") (setq year (+ year deltan)))))
13346 ((and wday (not (nth 3 tl)))
13347 (setq futurep nil)
13348 ;; Weekday was given, but no day, so pick that day in the week
13349 ;; on or after the derived date.
13350 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13351 (unless (equal wday wday1)
13352 (setq day (+ day (% (- wday wday1 -7) 7))))))
13353 (if (and (boundp 'org-time-was-given)
13354 (nth 2 tl))
13355 (setq org-time-was-given t))
13356 (if (< year 100) (setq year (+ 2000 year)))
13357 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13358 (setq org-read-date-analyze-futurep futurep)
13359 (list second minute hour day month year)))
13361 (defvar parse-time-weekdays)
13363 (defun org-read-date-get-relative (s today default)
13364 "Check string S for special relative date string.
13365 TODAY and DEFAULT are internal times, for today and for a default.
13366 Return shift list (N what def-flag)
13367 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13368 N is the number of WHATs to shift.
13369 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13370 the DEFAULT date rather than TODAY."
13371 (when (and
13372 (string-match
13373 (concat
13374 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13375 "\\([0-9]+\\)?"
13376 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13377 "\\([ \t]\\|$\\)") s)
13378 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13379 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13380 (string-to-char (substring (match-string 1 s) -1))
13381 ?+))
13382 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13383 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13384 (what (if (match-end 3) (match-string 3 s) "d"))
13385 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13386 (date (if rel default today))
13387 (wday (nth 6 (decode-time date)))
13388 delta)
13389 (if wday1
13390 (progn
13391 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13392 (if (= dir ?-) (setq delta (- delta 7)))
13393 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13394 (list delta "d" rel))
13395 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13397 (defun org-eval-in-calendar (form &optional keepdate)
13398 "Eval FORM in the calendar window and return to current window.
13399 Also, store the cursor date in variable org-ans2."
13400 (let ((sf (selected-frame))
13401 (sw (selected-window)))
13402 (select-window (get-buffer-window "*Calendar*" t))
13403 (eval form)
13404 (when (and (not keepdate) (calendar-cursor-to-date))
13405 (let* ((date (calendar-cursor-to-date))
13406 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13407 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13408 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13409 (select-window sw)
13410 (org-select-frame-set-input-focus sf)))
13412 (defun org-calendar-select ()
13413 "Return to `org-read-date' with the date currently selected.
13414 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13415 (interactive)
13416 (when (calendar-cursor-to-date)
13417 (let* ((date (calendar-cursor-to-date))
13418 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13419 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13420 (if (active-minibuffer-window) (exit-minibuffer))))
13422 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13423 "Insert a date stamp for the date given by the internal TIME.
13424 WITH-HM means, use the stamp format that includes the time of the day.
13425 INACTIVE means use square brackets instead of angular ones, so that the
13426 stamp will not contribute to the agenda.
13427 PRE and POST are optional strings to be inserted before and after the
13428 stamp.
13429 The command returns the inserted time stamp."
13430 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13431 stamp)
13432 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13433 (insert-before-markers (or pre ""))
13434 (insert-before-markers (setq stamp (format-time-string fmt time)))
13435 (when (listp extra)
13436 (setq extra (car extra))
13437 (if (and (stringp extra)
13438 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13439 (setq extra (format "-%02d:%02d"
13440 (string-to-number (match-string 1 extra))
13441 (string-to-number (match-string 2 extra))))
13442 (setq extra nil)))
13443 (when extra
13444 (backward-char 1)
13445 (insert-before-markers extra)
13446 (forward-char 1))
13447 (insert-before-markers (or post ""))
13448 (setq org-last-inserted-timestamp stamp)))
13450 (defun org-toggle-time-stamp-overlays ()
13451 "Toggle the use of custom time stamp formats."
13452 (interactive)
13453 (setq org-display-custom-times (not org-display-custom-times))
13454 (unless org-display-custom-times
13455 (let ((p (point-min)) (bmp (buffer-modified-p)))
13456 (while (setq p (next-single-property-change p 'display))
13457 (if (and (get-text-property p 'display)
13458 (eq (get-text-property p 'face) 'org-date))
13459 (remove-text-properties
13460 p (setq p (next-single-property-change p 'display))
13461 '(display t))))
13462 (set-buffer-modified-p bmp)))
13463 (if (featurep 'xemacs)
13464 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13465 (org-restart-font-lock)
13466 (setq org-table-may-need-update t)
13467 (if org-display-custom-times
13468 (message "Time stamps are overlayed with custom format")
13469 (message "Time stamp overlays removed")))
13471 (defun org-display-custom-time (beg end)
13472 "Overlay modified time stamp format over timestamp between BEG and END."
13473 (let* ((ts (buffer-substring beg end))
13474 t1 w1 with-hm tf time str w2 (off 0))
13475 (save-match-data
13476 (setq t1 (org-parse-time-string ts t))
13477 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13478 (setq off (- (match-end 0) (match-beginning 0)))))
13479 (setq end (- end off))
13480 (setq w1 (- end beg)
13481 with-hm (and (nth 1 t1) (nth 2 t1))
13482 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13483 time (org-fix-decoded-time t1)
13484 str (org-add-props
13485 (format-time-string
13486 (substring tf 1 -1) (apply 'encode-time time))
13487 nil 'mouse-face 'highlight)
13488 w2 (length str))
13489 (if (not (= w2 w1))
13490 (add-text-properties (1+ beg) (+ 2 beg)
13491 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13492 (if (featurep 'xemacs)
13493 (progn
13494 (put-text-property beg end 'invisible t)
13495 (put-text-property beg end 'end-glyph (make-glyph str)))
13496 (put-text-property beg end 'display str))))
13498 (defun org-translate-time (string)
13499 "Translate all timestamps in STRING to custom format.
13500 But do this only if the variable `org-display-custom-times' is set."
13501 (when org-display-custom-times
13502 (save-match-data
13503 (let* ((start 0)
13504 (re org-ts-regexp-both)
13505 t1 with-hm inactive tf time str beg end)
13506 (while (setq start (string-match re string start))
13507 (setq beg (match-beginning 0)
13508 end (match-end 0)
13509 t1 (save-match-data
13510 (org-parse-time-string (substring string beg end) t))
13511 with-hm (and (nth 1 t1) (nth 2 t1))
13512 inactive (equal (substring string beg (1+ beg)) "[")
13513 tf (funcall (if with-hm 'cdr 'car)
13514 org-time-stamp-custom-formats)
13515 time (org-fix-decoded-time t1)
13516 str (format-time-string
13517 (concat
13518 (if inactive "[" "<") (substring tf 1 -1)
13519 (if inactive "]" ">"))
13520 (apply 'encode-time time))
13521 string (replace-match str t t string)
13522 start (+ start (length str)))))))
13523 string)
13525 (defun org-fix-decoded-time (time)
13526 "Set 0 instead of nil for the first 6 elements of time.
13527 Don't touch the rest."
13528 (let ((n 0))
13529 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13531 (defun org-days-to-time (timestamp-string)
13532 "Difference between TIMESTAMP-STRING and now in days."
13533 (- (time-to-days (org-time-string-to-time timestamp-string))
13534 (time-to-days (current-time))))
13536 (defun org-deadline-close (timestamp-string &optional ndays)
13537 "Is the time in TIMESTAMP-STRING close to the current date?"
13538 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13539 (and (< (org-days-to-time timestamp-string) ndays)
13540 (not (org-entry-is-done-p))))
13542 (defun org-get-wdays (ts)
13543 "Get the deadline lead time appropriate for timestring TS."
13544 (cond
13545 ((<= org-deadline-warning-days 0)
13546 ;; 0 or negative, enforce this value no matter what
13547 (- org-deadline-warning-days))
13548 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13549 ;; lead time is specified.
13550 (floor (* (string-to-number (match-string 1 ts))
13551 (cdr (assoc (match-string 2 ts)
13552 '(("d" . 1) ("w" . 7)
13553 ("m" . 30.4) ("y" . 365.25)))))))
13554 ;; go for the default.
13555 (t org-deadline-warning-days)))
13557 (defun org-calendar-select-mouse (ev)
13558 "Return to `org-read-date' with the date currently selected.
13559 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13560 (interactive "e")
13561 (mouse-set-point ev)
13562 (when (calendar-cursor-to-date)
13563 (let* ((date (calendar-cursor-to-date))
13564 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13565 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13566 (if (active-minibuffer-window) (exit-minibuffer))))
13568 (defun org-check-deadlines (ndays)
13569 "Check if there are any deadlines due or past due.
13570 A deadline is considered due if it happens within `org-deadline-warning-days'
13571 days from today's date. If the deadline appears in an entry marked DONE,
13572 it is not shown. The prefix arg NDAYS can be used to test that many
13573 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13574 (interactive "P")
13575 (let* ((org-warn-days
13576 (cond
13577 ((equal ndays '(4)) 100000)
13578 (ndays (prefix-numeric-value ndays))
13579 (t (abs org-deadline-warning-days))))
13580 (case-fold-search nil)
13581 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13582 (callback
13583 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13585 (message "%d deadlines past-due or due within %d days"
13586 (org-occur regexp nil callback)
13587 org-warn-days)))
13589 (defun org-check-before-date (date)
13590 "Check if there are deadlines or scheduled entries before DATE."
13591 (interactive (list (org-read-date)))
13592 (let ((case-fold-search nil)
13593 (regexp (concat "\\<\\(" org-deadline-string
13594 "\\|" org-scheduled-string
13595 "\\) *<\\([^>]+\\)>"))
13596 (callback
13597 (lambda () (time-less-p
13598 (org-time-string-to-time (match-string 2))
13599 (org-time-string-to-time date)))))
13600 (message "%d entries before %s"
13601 (org-occur regexp nil callback) date)))
13603 (defun org-check-after-date (date)
13604 "Check if there are deadlines or scheduled entries after DATE."
13605 (interactive (list (org-read-date)))
13606 (let ((case-fold-search nil)
13607 (regexp (concat "\\<\\(" org-deadline-string
13608 "\\|" org-scheduled-string
13609 "\\) *<\\([^>]+\\)>"))
13610 (callback
13611 (lambda () (not
13612 (time-less-p
13613 (org-time-string-to-time (match-string 2))
13614 (org-time-string-to-time date))))))
13615 (message "%d entries after %s"
13616 (org-occur regexp nil callback) date)))
13618 (defun org-evaluate-time-range (&optional to-buffer)
13619 "Evaluate a time range by computing the difference between start and end.
13620 Normally the result is just printed in the echo area, but with prefix arg
13621 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13622 If the time range is actually in a table, the result is inserted into the
13623 next column.
13624 For time difference computation, a year is assumed to be exactly 365
13625 days in order to avoid rounding problems."
13626 (interactive "P")
13628 (org-clock-update-time-maybe)
13629 (save-excursion
13630 (unless (org-at-date-range-p t)
13631 (goto-char (point-at-bol))
13632 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13633 (if (not (org-at-date-range-p t))
13634 (error "Not at a time-stamp range, and none found in current line")))
13635 (let* ((ts1 (match-string 1))
13636 (ts2 (match-string 2))
13637 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13638 (match-end (match-end 0))
13639 (time1 (org-time-string-to-time ts1))
13640 (time2 (org-time-string-to-time ts2))
13641 (t1 (org-float-time time1))
13642 (t2 (org-float-time time2))
13643 (diff (abs (- t2 t1)))
13644 (negative (< (- t2 t1) 0))
13645 ;; (ys (floor (* 365 24 60 60)))
13646 (ds (* 24 60 60))
13647 (hs (* 60 60))
13648 (fy "%dy %dd %02d:%02d")
13649 (fy1 "%dy %dd")
13650 (fd "%dd %02d:%02d")
13651 (fd1 "%dd")
13652 (fh "%02d:%02d")
13653 y d h m align)
13654 (if havetime
13655 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13657 d (floor (/ diff ds)) diff (mod diff ds)
13658 h (floor (/ diff hs)) diff (mod diff hs)
13659 m (floor (/ diff 60)))
13660 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13662 d (floor (+ (/ diff ds) 0.5))
13663 h 0 m 0))
13664 (if (not to-buffer)
13665 (message "%s" (org-make-tdiff-string y d h m))
13666 (if (org-at-table-p)
13667 (progn
13668 (goto-char match-end)
13669 (setq align t)
13670 (and (looking-at " *|") (goto-char (match-end 0))))
13671 (goto-char match-end))
13672 (if (looking-at
13673 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13674 (replace-match ""))
13675 (if negative (insert " -"))
13676 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13677 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13678 (insert " " (format fh h m))))
13679 (if align (org-table-align))
13680 (message "Time difference inserted")))))
13682 (defun org-make-tdiff-string (y d h m)
13683 (let ((fmt "")
13684 (l nil))
13685 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13686 l (push y l)))
13687 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13688 l (push d l)))
13689 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13690 l (push h l)))
13691 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13692 l (push m l)))
13693 (apply 'format fmt (nreverse l))))
13695 (defun org-time-string-to-time (s)
13696 (apply 'encode-time (org-parse-time-string s)))
13697 (defun org-time-string-to-seconds (s)
13698 (org-float-time (org-time-string-to-time s)))
13700 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13701 "Convert a time stamp to an absolute day number.
13702 If there is a specifyer for a cyclic time stamp, get the closest date to
13703 DAYNR.
13704 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13705 the variable date is bound by the calendar when this is called."
13706 (cond
13707 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13708 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13709 daynr
13710 (+ daynr 1000)))
13711 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13712 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13713 (time-to-days (current-time))) (match-string 0 s)
13714 prefer show-all))
13715 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13717 (defun org-days-to-iso-week (days)
13718 "Return the iso week number."
13719 (require 'cal-iso)
13720 (car (calendar-iso-from-absolute days)))
13722 (defun org-small-year-to-year (year)
13723 "Convert 2-digit years into 4-digit years.
13724 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13725 The year 2000 cannot be abbreviated. Any year larger than 99
13726 is returned unchanged."
13727 (if (< year 38)
13728 (setq year (+ 2000 year))
13729 (if (< year 100)
13730 (setq year (+ 1900 year))))
13731 year)
13733 (defun org-time-from-absolute (d)
13734 "Return the time corresponding to date D.
13735 D may be an absolute day number, or a calendar-type list (month day year)."
13736 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13737 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13739 (defun org-calendar-holiday ()
13740 "List of holidays, for Diary display in Org-mode."
13741 (require 'holidays)
13742 (let ((hl (funcall
13743 (if (fboundp 'calendar-check-holidays)
13744 'calendar-check-holidays 'check-calendar-holidays) date)))
13745 (if hl (mapconcat 'identity hl "; "))))
13747 (defun org-diary-sexp-entry (sexp entry date)
13748 "Process a SEXP diary ENTRY for DATE."
13749 (require 'diary-lib)
13750 (let ((result (if calendar-debug-sexp
13751 (let ((stack-trace-on-error t))
13752 (eval (car (read-from-string sexp))))
13753 (condition-case nil
13754 (eval (car (read-from-string sexp)))
13755 (error
13756 (beep)
13757 (message "Bad sexp at line %d in %s: %s"
13758 (org-current-line)
13759 (buffer-file-name) sexp)
13760 (sleep-for 2))))))
13761 (cond ((stringp result) result)
13762 ((and (consp result)
13763 (stringp (cdr result))) (cdr result))
13764 (result entry)
13765 (t nil))))
13767 (defun org-diary-to-ical-string (frombuf)
13768 "Get iCalendar entries from diary entries in buffer FROMBUF.
13769 This uses the icalendar.el library."
13770 (let* ((tmpdir (if (featurep 'xemacs)
13771 (temp-directory)
13772 temporary-file-directory))
13773 (tmpfile (make-temp-name
13774 (expand-file-name "orgics" tmpdir)))
13775 buf rtn b e)
13776 (with-current-buffer frombuf
13777 (icalendar-export-region (point-min) (point-max) tmpfile)
13778 (setq buf (find-buffer-visiting tmpfile))
13779 (set-buffer buf)
13780 (goto-char (point-min))
13781 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13782 (setq b (match-beginning 0)))
13783 (goto-char (point-max))
13784 (if (re-search-backward "^END:VEVENT" nil t)
13785 (setq e (match-end 0)))
13786 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13787 (kill-buffer buf)
13788 (delete-file tmpfile)
13789 rtn))
13791 (defun org-closest-date (start current change prefer show-all)
13792 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13793 When PREFER is `past' return a date that is either CURRENT or past.
13794 When PREFER is `future', return a date that is either CURRENT or future.
13795 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13796 ;; Make the proper lists from the dates
13797 (catch 'exit
13798 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13799 dn dw sday cday n1 n2 n0
13800 d m y y1 y2 date1 date2 nmonths nm ny m2)
13802 (setq start (org-date-to-gregorian start)
13803 current (org-date-to-gregorian
13804 (if show-all
13805 current
13806 (time-to-days (current-time))))
13807 sday (calendar-absolute-from-gregorian start)
13808 cday (calendar-absolute-from-gregorian current))
13810 (if (<= cday sday) (throw 'exit sday))
13812 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13813 (setq dn (string-to-number (match-string 1 change))
13814 dw (cdr (assoc (match-string 2 change) a1)))
13815 (error "Invalid change specifyer: %s" change))
13816 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13817 (cond
13818 ((eq dw 'day)
13819 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13820 n2 (+ n1 dn)))
13821 ((eq dw 'year)
13822 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13823 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13824 (setq date1 (list m d y1)
13825 n1 (calendar-absolute-from-gregorian date1)
13826 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13827 n2 (calendar-absolute-from-gregorian date2)))
13828 ((eq dw 'month)
13829 ;; approx number of month between the two dates
13830 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13831 ;; How often does dn fit in there?
13832 (setq d (nth 1 start) m (car start) y (nth 2 start)
13833 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13834 m (+ m nm)
13835 ny (floor (/ m 12))
13836 y (+ y ny)
13837 m (- m (* ny 12)))
13838 (while (> m 12) (setq m (- m 12) y (1+ y)))
13839 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13840 (setq m2 (+ m dn) y2 y)
13841 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13842 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13843 (while (<= n2 cday)
13844 (setq n1 n2 m m2 y y2)
13845 (setq m2 (+ m dn) y2 y)
13846 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13847 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13848 ;; Make sure n1 is the earlier date
13849 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13850 (if show-all
13851 (cond
13852 ((eq prefer 'past) (if (= cday n2) n2 n1))
13853 ((eq prefer 'future) (if (= cday n1) n1 n2))
13854 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13855 (cond
13856 ((eq prefer 'past) (if (= cday n2) n2 n1))
13857 ((eq prefer 'future) (if (= cday n1) n1 n2))
13858 (t (if (= cday n1) n1 n2)))))))
13860 (defun org-date-to-gregorian (date)
13861 "Turn any specification of DATE into a gregorian date for the calendar."
13862 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13863 ((and (listp date) (= (length date) 3)) date)
13864 ((stringp date)
13865 (setq date (org-parse-time-string date))
13866 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13867 ((listp date)
13868 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13870 (defun org-parse-time-string (s &optional nodefault)
13871 "Parse the standard Org-mode time string.
13872 This should be a lot faster than the normal `parse-time-string'.
13873 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13874 hour and minute fields will be nil if not given."
13875 (if (string-match org-ts-regexp0 s)
13876 (list 0
13877 (if (or (match-beginning 8) (not nodefault))
13878 (string-to-number (or (match-string 8 s) "0")))
13879 (if (or (match-beginning 7) (not nodefault))
13880 (string-to-number (or (match-string 7 s) "0")))
13881 (string-to-number (match-string 4 s))
13882 (string-to-number (match-string 3 s))
13883 (string-to-number (match-string 2 s))
13884 nil nil nil)
13885 (error "Not a standard Org-mode time string: %s" s)))
13887 (defun org-timestamp-up (&optional arg)
13888 "Increase the date item at the cursor by one.
13889 If the cursor is on the year, change the year. If it is on the month or
13890 the day, change that.
13891 With prefix ARG, change by that many units."
13892 (interactive "p")
13893 (org-timestamp-change (prefix-numeric-value arg)))
13895 (defun org-timestamp-down (&optional arg)
13896 "Decrease the date item at the cursor by one.
13897 If the cursor is on the year, change the year. If it is on the month or
13898 the day, change that.
13899 With prefix ARG, change by that many units."
13900 (interactive "p")
13901 (org-timestamp-change (- (prefix-numeric-value arg))))
13903 (defun org-timestamp-up-day (&optional arg)
13904 "Increase the date in the time stamp by one day.
13905 With prefix ARG, change that many days."
13906 (interactive "p")
13907 (if (and (not (org-at-timestamp-p t))
13908 (org-on-heading-p))
13909 (org-todo 'up)
13910 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13912 (defun org-timestamp-down-day (&optional arg)
13913 "Decrease the date in the time stamp by one day.
13914 With prefix ARG, change that many days."
13915 (interactive "p")
13916 (if (and (not (org-at-timestamp-p t))
13917 (org-on-heading-p))
13918 (org-todo 'down)
13919 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13921 (defun org-at-timestamp-p (&optional inactive-ok)
13922 "Determine if the cursor is in or at a timestamp."
13923 (interactive)
13924 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13925 (pos (point))
13926 (ans (or (looking-at tsr)
13927 (save-excursion
13928 (skip-chars-backward "^[<\n\r\t")
13929 (if (> (point) (point-min)) (backward-char 1))
13930 (and (looking-at tsr)
13931 (> (- (match-end 0) pos) -1))))))
13932 (and ans
13933 (boundp 'org-ts-what)
13934 (setq org-ts-what
13935 (cond
13936 ((= pos (match-beginning 0)) 'bracket)
13937 ((= pos (1- (match-end 0))) 'bracket)
13938 ((org-pos-in-match-range pos 2) 'year)
13939 ((org-pos-in-match-range pos 3) 'month)
13940 ((org-pos-in-match-range pos 7) 'hour)
13941 ((org-pos-in-match-range pos 8) 'minute)
13942 ((or (org-pos-in-match-range pos 4)
13943 (org-pos-in-match-range pos 5)) 'day)
13944 ((and (> pos (or (match-end 8) (match-end 5)))
13945 (< pos (match-end 0)))
13946 (- pos (or (match-end 8) (match-end 5))))
13947 (t 'day))))
13948 ans))
13950 (defun org-toggle-timestamp-type ()
13951 "Toggle the type (<active> or [inactive]) of a time stamp."
13952 (interactive)
13953 (when (org-at-timestamp-p t)
13954 (let ((beg (match-beginning 0)) (end (match-end 0))
13955 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13956 (save-excursion
13957 (goto-char beg)
13958 (while (re-search-forward "[][<>]" end t)
13959 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13960 t t)))
13961 (message "Timestamp is now %sactive"
13962 (if (equal (char-after beg) ?<) "" "in")))))
13964 (defun org-timestamp-change (n &optional what)
13965 "Change the date in the time stamp at point.
13966 The date will be changed by N times WHAT. WHAT can be `day', `month',
13967 `year', `minute', `second'. If WHAT is not given, the cursor position
13968 in the timestamp determines what will be changed."
13969 (let ((pos (point))
13970 with-hm inactive
13971 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13972 org-ts-what
13973 extra rem
13974 ts time time0)
13975 (if (not (org-at-timestamp-p t))
13976 (error "Not at a timestamp"))
13977 (if (and (not what) (eq org-ts-what 'bracket))
13978 (org-toggle-timestamp-type)
13979 (if (and (not what) (not (eq org-ts-what 'day))
13980 org-display-custom-times
13981 (get-text-property (point) 'display)
13982 (not (get-text-property (1- (point)) 'display)))
13983 (setq org-ts-what 'day))
13984 (setq org-ts-what (or what org-ts-what)
13985 inactive (= (char-after (match-beginning 0)) ?\[)
13986 ts (match-string 0))
13987 (replace-match "")
13988 (if (string-match
13989 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13991 (setq extra (match-string 1 ts)))
13992 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13993 (setq with-hm t))
13994 (setq time0 (org-parse-time-string ts))
13995 (when (and (eq org-ts-what 'minute)
13996 (eq current-prefix-arg nil))
13997 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13998 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13999 (setcar (cdr time0) (+ (nth 1 time0)
14000 (if (> n 0) (- rem) (- dm rem))))))
14001 (setq time
14002 (encode-time (or (car time0) 0)
14003 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14004 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14005 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14006 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14007 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14008 (nthcdr 6 time0)))
14009 (when (and (member org-ts-what '(hour minute))
14010 extra
14011 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14012 (setq extra (org-modify-ts-extra
14013 extra
14014 (if (eq org-ts-what 'hour) 2 5)
14015 n dm)))
14016 (when (integerp org-ts-what)
14017 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14018 (if (eq what 'calendar)
14019 (let ((cal-date (org-get-date-from-calendar)))
14020 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14021 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14022 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14023 (setcar time0 (or (car time0) 0))
14024 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14025 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14026 (setq time (apply 'encode-time time0))))
14027 (setq org-last-changed-timestamp
14028 (org-insert-time-stamp time with-hm inactive nil nil extra))
14029 (org-clock-update-time-maybe)
14030 (goto-char pos)
14031 ;; Try to recenter the calendar window, if any
14032 (if (and org-calendar-follow-timestamp-change
14033 (get-buffer-window "*Calendar*" t)
14034 (memq org-ts-what '(day month year)))
14035 (org-recenter-calendar (time-to-days time))))))
14037 (defun org-modify-ts-extra (s pos n dm)
14038 "Change the different parts of the lead-time and repeat fields in timestamp."
14039 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14040 ng h m new rem)
14041 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14042 (cond
14043 ((or (org-pos-in-match-range pos 2)
14044 (org-pos-in-match-range pos 3))
14045 (setq m (string-to-number (match-string 3 s))
14046 h (string-to-number (match-string 2 s)))
14047 (if (org-pos-in-match-range pos 2)
14048 (setq h (+ h n))
14049 (setq n (* dm (org-no-warnings (signum n))))
14050 (when (not (= 0 (setq rem (% m dm))))
14051 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14052 (setq m (+ m n)))
14053 (if (< m 0) (setq m (+ m 60) h (1- h)))
14054 (if (> m 59) (setq m (- m 60) h (1+ h)))
14055 (setq h (min 24 (max 0 h)))
14056 (setq ng 1 new (format "-%02d:%02d" h m)))
14057 ((org-pos-in-match-range pos 6)
14058 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14059 ((org-pos-in-match-range pos 5)
14060 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14062 ((org-pos-in-match-range pos 9)
14063 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14064 ((org-pos-in-match-range pos 8)
14065 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14067 (when ng
14068 (setq s (concat
14069 (substring s 0 (match-beginning ng))
14071 (substring s (match-end ng))))))
14074 (defun org-recenter-calendar (date)
14075 "If the calendar is visible, recenter it to DATE."
14076 (let* ((win (selected-window))
14077 (cwin (get-buffer-window "*Calendar*" t))
14078 (calendar-move-hook nil))
14079 (when cwin
14080 (select-window cwin)
14081 (calendar-goto-date (if (listp date) date
14082 (calendar-gregorian-from-absolute date)))
14083 (select-window win))))
14085 (defun org-goto-calendar (&optional arg)
14086 "Go to the Emacs calendar at the current date.
14087 If there is a time stamp in the current line, go to that date.
14088 A prefix ARG can be used to force the current date."
14089 (interactive "P")
14090 (let ((tsr org-ts-regexp) diff
14091 (calendar-move-hook nil)
14092 (calendar-view-holidays-initially-flag nil)
14093 (view-calendar-holidays-initially nil)
14094 (calendar-view-diary-initially-flag nil)
14095 (view-diary-entries-initially nil))
14096 (if (or (org-at-timestamp-p)
14097 (save-excursion
14098 (beginning-of-line 1)
14099 (looking-at (concat ".*" tsr))))
14100 (let ((d1 (time-to-days (current-time)))
14101 (d2 (time-to-days
14102 (org-time-string-to-time (match-string 1)))))
14103 (setq diff (- d2 d1))))
14104 (calendar)
14105 (calendar-goto-today)
14106 (if (and diff (not arg)) (calendar-forward-day diff))))
14108 (defun org-get-date-from-calendar ()
14109 "Return a list (month day year) of date at point in calendar."
14110 (with-current-buffer "*Calendar*"
14111 (save-match-data
14112 (calendar-cursor-to-date))))
14114 (defun org-date-from-calendar ()
14115 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14116 If there is already a time stamp at the cursor position, update it."
14117 (interactive)
14118 (if (org-at-timestamp-p t)
14119 (org-timestamp-change 0 'calendar)
14120 (let ((cal-date (org-get-date-from-calendar)))
14121 (org-insert-time-stamp
14122 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14124 (defun org-minutes-to-hh:mm-string (m)
14125 "Compute H:MM from a number of minutes."
14126 (let ((h (/ m 60)))
14127 (setq m (- m (* 60 h)))
14128 (format org-time-clocksum-format h m)))
14130 (defun org-hh:mm-string-to-minutes (s)
14131 "Convert a string H:MM to a number of minutes.
14132 If the string is just a number, interpret it as minutes.
14133 In fact, the first hh:mm or number in the string will be taken,
14134 there can be extra stuff in the string.
14135 If no number is found, the return value is 0."
14136 (cond
14137 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14138 (+ (* (string-to-number (match-string 1 s)) 60)
14139 (string-to-number (match-string 2 s))))
14140 ((string-match "\\([0-9]+\\)" s)
14141 (string-to-number (match-string 1 s)))
14142 (t 0)))
14144 ;;;; Files
14146 (defun org-save-all-org-buffers ()
14147 "Save all Org-mode buffers without user confirmation."
14148 (interactive)
14149 (message "Saving all Org-mode buffers...")
14150 (save-some-buffers t 'org-mode-p)
14151 (when (featurep 'org-id) (org-id-locations-save))
14152 (message "Saving all Org-mode buffers... done"))
14154 (defun org-revert-all-org-buffers ()
14155 "Revert all Org-mode buffers.
14156 Prompt for confirmation when there are unsaved changes.
14157 Be sure you know what you are doing before letting this function
14158 overwrite your changes.
14160 This function is useful in a setup where one tracks org files
14161 with a version control system, to revert on one machine after pulling
14162 changes from another. I believe the procedure must be like this:
14164 1. M-x org-save-all-org-buffers
14165 2. Pull changes from the other machine, resolve conflicts
14166 3. M-x org-revert-all-org-buffers"
14167 (interactive)
14168 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14169 (error "Abort"))
14170 (save-excursion
14171 (save-window-excursion
14172 (mapc
14173 (lambda (b)
14174 (when (and (with-current-buffer b (org-mode-p))
14175 (with-current-buffer b buffer-file-name))
14176 (switch-to-buffer b)
14177 (revert-buffer t 'no-confirm)))
14178 (buffer-list))
14179 (when (and (featurep 'org-id) org-id-track-globally)
14180 (org-id-locations-load)))))
14182 ;;;; Agenda files
14184 ;;;###autoload
14185 (defun org-iswitchb (&optional arg)
14186 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14187 With a prefix argument, restrict available to files.
14188 With two prefix arguments, restrict available buffers to agenda files."
14189 (interactive "P")
14190 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14191 ((equal arg '(16)) (org-buffer-list 'agenda))
14192 (t (org-buffer-list)))))
14193 (switch-to-buffer
14194 (org-icompleting-read "Org buffer: "
14195 (mapcar 'list (mapcar 'buffer-name blist))
14196 nil t))))
14198 ;;;###autoload
14199 (defalias 'org-ido-switchb 'org-iswitchb)
14201 (defun org-buffer-list (&optional predicate exclude-tmp)
14202 "Return a list of Org buffers.
14203 PREDICATE can be `export', `files' or `agenda'.
14205 export restrict the list to Export buffers.
14206 files restrict the list to buffers visiting Org files.
14207 agenda restrict the list to buffers visiting agenda files.
14209 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14210 (let* ((bfn nil)
14211 (agenda-files (and (eq predicate 'agenda)
14212 (mapcar 'file-truename (org-agenda-files t))))
14213 (filter
14214 (cond
14215 ((eq predicate 'files)
14216 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14217 ((eq predicate 'export)
14218 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14219 ((eq predicate 'agenda)
14220 (lambda (b)
14221 (with-current-buffer b
14222 (and (eq major-mode 'org-mode)
14223 (setq bfn (buffer-file-name b))
14224 (member (file-truename bfn) agenda-files)))))
14225 (t (lambda (b) (with-current-buffer b
14226 (or (eq major-mode 'org-mode)
14227 (string-match "\*Org .*Export"
14228 (buffer-name b)))))))))
14229 (delq nil
14230 (mapcar
14231 (lambda(b)
14232 (if (and (funcall filter b)
14233 (or (not exclude-tmp)
14234 (not (string-match "tmp" (buffer-name b)))))
14236 nil))
14237 (buffer-list)))))
14239 (defun org-agenda-files (&optional unrestricted archives)
14240 "Get the list of agenda files.
14241 Optional UNRESTRICTED means return the full list even if a restriction
14242 is currently in place.
14243 When ARCHIVES is t, include all archive files hat are really being
14244 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14245 `org-agenda-archives-mode' is t."
14246 (let ((files
14247 (cond
14248 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14249 ((stringp org-agenda-files) (org-read-agenda-file-list))
14250 ((listp org-agenda-files) org-agenda-files)
14251 (t (error "Invalid value of `org-agenda-files'")))))
14252 (setq files (apply 'append
14253 (mapcar (lambda (f)
14254 (if (file-directory-p f)
14255 (directory-files
14256 f t org-agenda-file-regexp)
14257 (list f)))
14258 files)))
14259 (when org-agenda-skip-unavailable-files
14260 (setq files (delq nil
14261 (mapcar (function
14262 (lambda (file)
14263 (and (file-readable-p file) file)))
14264 files))))
14265 (when (or (eq archives t)
14266 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14267 (setq files (org-add-archive-files files)))
14268 files))
14270 (defun org-edit-agenda-file-list ()
14271 "Edit the list of agenda files.
14272 Depending on setup, this either uses customize to edit the variable
14273 `org-agenda-files', or it visits the file that is holding the list. In the
14274 latter case, the buffer is set up in a way that saving it automatically kills
14275 the buffer and restores the previous window configuration."
14276 (interactive)
14277 (if (stringp org-agenda-files)
14278 (let ((cw (current-window-configuration)))
14279 (find-file org-agenda-files)
14280 (org-set-local 'org-window-configuration cw)
14281 (org-add-hook 'after-save-hook
14282 (lambda ()
14283 (set-window-configuration
14284 (prog1 org-window-configuration
14285 (kill-buffer (current-buffer))))
14286 (org-install-agenda-files-menu)
14287 (message "New agenda file list installed"))
14288 nil 'local)
14289 (message "%s" (substitute-command-keys
14290 "Edit list and finish with \\[save-buffer]")))
14291 (customize-variable 'org-agenda-files)))
14293 (defun org-store-new-agenda-file-list (list)
14294 "Set new value for the agenda file list and save it correctly."
14295 (if (stringp org-agenda-files)
14296 (let ((f org-agenda-files) b)
14297 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14298 (with-temp-file f
14299 (insert (mapconcat 'identity list "\n") "\n")))
14300 (let ((org-mode-hook nil) (org-inhibit-startup t)
14301 (org-insert-mode-line-in-empty-file nil))
14302 (setq org-agenda-files list)
14303 (customize-save-variable 'org-agenda-files org-agenda-files))))
14305 (defun org-read-agenda-file-list ()
14306 "Read the list of agenda files from a file."
14307 (when (file-directory-p org-agenda-files)
14308 (error "`org-agenda-files' cannot be a single directory"))
14309 (when (stringp org-agenda-files)
14310 (with-temp-buffer
14311 (insert-file-contents org-agenda-files)
14312 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14315 ;;;###autoload
14316 (defun org-cycle-agenda-files ()
14317 "Cycle through the files in `org-agenda-files'.
14318 If the current buffer visits an agenda file, find the next one in the list.
14319 If the current buffer does not, find the first agenda file."
14320 (interactive)
14321 (let* ((fs (org-agenda-files t))
14322 (files (append fs (list (car fs))))
14323 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14324 file)
14325 (unless files (error "No agenda files"))
14326 (catch 'exit
14327 (while (setq file (pop files))
14328 (if (equal (file-truename file) tcf)
14329 (when (car files)
14330 (find-file (car files))
14331 (throw 'exit t))))
14332 (find-file (car fs)))
14333 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14335 (defun org-agenda-file-to-front (&optional to-end)
14336 "Move/add the current file to the top of the agenda file list.
14337 If the file is not present in the list, it is added to the front. If it is
14338 present, it is moved there. With optional argument TO-END, add/move to the
14339 end of the list."
14340 (interactive "P")
14341 (let ((org-agenda-skip-unavailable-files nil)
14342 (file-alist (mapcar (lambda (x)
14343 (cons (file-truename x) x))
14344 (org-agenda-files t)))
14345 (ctf (file-truename buffer-file-name))
14346 x had)
14347 (setq x (assoc ctf file-alist) had x)
14349 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14350 (if to-end
14351 (setq file-alist (append (delq x file-alist) (list x)))
14352 (setq file-alist (cons x (delq x file-alist))))
14353 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14354 (org-install-agenda-files-menu)
14355 (message "File %s to %s of agenda file list"
14356 (if had "moved" "added") (if to-end "end" "front"))))
14358 (defun org-remove-file (&optional file)
14359 "Remove current file from the list of files in variable `org-agenda-files'.
14360 These are the files which are being checked for agenda entries.
14361 Optional argument FILE means, use this file instead of the current."
14362 (interactive)
14363 (let* ((org-agenda-skip-unavailable-files nil)
14364 (file (or file buffer-file-name))
14365 (true-file (file-truename file))
14366 (afile (abbreviate-file-name file))
14367 (files (delq nil (mapcar
14368 (lambda (x)
14369 (if (equal true-file
14370 (file-truename x))
14371 nil x))
14372 (org-agenda-files t)))))
14373 (if (not (= (length files) (length (org-agenda-files t))))
14374 (progn
14375 (org-store-new-agenda-file-list files)
14376 (org-install-agenda-files-menu)
14377 (message "Removed file: %s" afile))
14378 (message "File was not in list: %s (not removed)" afile))))
14380 (defun org-file-menu-entry (file)
14381 (vector file (list 'find-file file) t))
14383 (defun org-check-agenda-file (file)
14384 "Make sure FILE exists. If not, ask user what to do."
14385 (when (not (file-exists-p file))
14386 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14387 (abbreviate-file-name file))
14388 (let ((r (downcase (read-char-exclusive))))
14389 (cond
14390 ((equal r ?r)
14391 (org-remove-file file)
14392 (throw 'nextfile t))
14393 (t (error "Abort"))))))
14395 (defun org-get-agenda-file-buffer (file)
14396 "Get a buffer visiting FILE. If the buffer needs to be created, add
14397 it to the list of buffers which might be released later."
14398 (let ((buf (org-find-base-buffer-visiting file)))
14399 (if buf
14400 buf ; just return it
14401 ;; Make a new buffer and remember it
14402 (setq buf (find-file-noselect file))
14403 (if buf (push buf org-agenda-new-buffers))
14404 buf)))
14406 (defun org-release-buffers (blist)
14407 "Release all buffers in list, asking the user for confirmation when needed.
14408 When a buffer is unmodified, it is just killed. When modified, it is saved
14409 \(if the user agrees) and then killed."
14410 (let (buf file)
14411 (while (setq buf (pop blist))
14412 (setq file (buffer-file-name buf))
14413 (when (and (buffer-modified-p buf)
14414 file
14415 (y-or-n-p (format "Save file %s? " file)))
14416 (with-current-buffer buf (save-buffer)))
14417 (kill-buffer buf))))
14419 (defun org-prepare-agenda-buffers (files)
14420 "Create buffers for all agenda files, protect archived trees and comments."
14421 (interactive)
14422 (let ((pa '(:org-archived t))
14423 (pc '(:org-comment t))
14424 (pall '(:org-archived t :org-comment t))
14425 (inhibit-read-only t)
14426 (rea (concat ":" org-archive-tag ":"))
14427 bmp file re)
14428 (save-excursion
14429 (save-restriction
14430 (while (setq file (pop files))
14431 (catch 'nextfile
14432 (if (bufferp file)
14433 (set-buffer file)
14434 (org-check-agenda-file file)
14435 (set-buffer (org-get-agenda-file-buffer file)))
14436 (widen)
14437 (setq bmp (buffer-modified-p))
14438 (org-refresh-category-properties)
14439 (setq org-todo-keywords-for-agenda
14440 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14441 (setq org-done-keywords-for-agenda
14442 (append org-done-keywords-for-agenda org-done-keywords))
14443 (setq org-todo-keyword-alist-for-agenda
14444 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14445 (setq org-drawers-for-agenda
14446 (append org-drawers-for-agenda org-drawers))
14447 (setq org-tag-alist-for-agenda
14448 (append org-tag-alist-for-agenda org-tag-alist))
14450 (save-excursion
14451 (remove-text-properties (point-min) (point-max) pall)
14452 (when org-agenda-skip-archived-trees
14453 (goto-char (point-min))
14454 (while (re-search-forward rea nil t)
14455 (if (org-on-heading-p t)
14456 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14457 (goto-char (point-min))
14458 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14459 (while (re-search-forward re nil t)
14460 (add-text-properties
14461 (match-beginning 0) (org-end-of-subtree t) pc)))
14462 (set-buffer-modified-p bmp)))))
14463 (setq org-todo-keyword-alist-for-agenda
14464 (org-uniquify org-todo-keyword-alist-for-agenda)
14465 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14467 ;;;; Embedded LaTeX
14469 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14470 "Keymap for the minor `org-cdlatex-mode'.")
14472 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14473 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14474 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14475 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14476 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14478 (defvar org-cdlatex-texmathp-advice-is-done nil
14479 "Flag remembering if we have applied the advice to texmathp already.")
14481 (define-minor-mode org-cdlatex-mode
14482 "Toggle the minor `org-cdlatex-mode'.
14483 This mode supports entering LaTeX environment and math in LaTeX fragments
14484 in Org-mode.
14485 \\{org-cdlatex-mode-map}"
14486 nil " OCDL" nil
14487 (when org-cdlatex-mode (require 'cdlatex))
14488 (unless org-cdlatex-texmathp-advice-is-done
14489 (setq org-cdlatex-texmathp-advice-is-done t)
14490 (defadvice texmathp (around org-math-always-on activate)
14491 "Always return t in org-mode buffers.
14492 This is because we want to insert math symbols without dollars even outside
14493 the LaTeX math segments. If Orgmode thinks that point is actually inside
14494 an embedded LaTeX fragment, let texmathp do its job.
14495 \\[org-cdlatex-mode-map]"
14496 (interactive)
14497 (let (p)
14498 (cond
14499 ((not (org-mode-p)) ad-do-it)
14500 ((eq this-command 'cdlatex-math-symbol)
14501 (setq ad-return-value t
14502 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14504 (let ((p (org-inside-LaTeX-fragment-p)))
14505 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14506 (setq ad-return-value t
14507 texmathp-why '("Org-mode embedded math" . 0))
14508 (if p ad-do-it)))))))))
14510 (defun turn-on-org-cdlatex ()
14511 "Unconditionally turn on `org-cdlatex-mode'."
14512 (org-cdlatex-mode 1))
14514 (defun org-inside-LaTeX-fragment-p ()
14515 "Test if point is inside a LaTeX fragment.
14516 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14517 sequence appearing also before point.
14518 Even though the matchers for math are configurable, this function assumes
14519 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14520 delimiters are skipped when they have been removed by customization.
14521 The return value is nil, or a cons cell with the delimiter and
14522 and the position of this delimiter.
14524 This function does a reasonably good job, but can locally be fooled by
14525 for example currency specifications. For example it will assume being in
14526 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14527 fragments that are properly closed, but during editing, we have to live
14528 with the uncertainty caused by missing closing delimiters. This function
14529 looks only before point, not after."
14530 (catch 'exit
14531 (let ((pos (point))
14532 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14533 (lim (progn
14534 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14535 (point)))
14536 dd-on str (start 0) m re)
14537 (goto-char pos)
14538 (when dodollar
14539 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14540 re (nth 1 (assoc "$" org-latex-regexps)))
14541 (while (string-match re str start)
14542 (cond
14543 ((= (match-end 0) (length str))
14544 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14545 ((= (match-end 0) (- (length str) 5))
14546 (throw 'exit nil))
14547 (t (setq start (match-end 0))))))
14548 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14549 (goto-char pos)
14550 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14551 (and (match-beginning 2) (throw 'exit nil))
14552 ;; count $$
14553 (while (re-search-backward "\\$\\$" lim t)
14554 (setq dd-on (not dd-on)))
14555 (goto-char pos)
14556 (if dd-on (cons "$$" m))))))
14558 (defun org-inside-latex-macro-p ()
14559 "Is point inside a LaTeX macro or its arguments?"
14560 (save-match-data
14561 (org-in-regexp
14562 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14564 (defun org-try-cdlatex-tab ()
14565 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14566 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14567 - inside a LaTeX fragment, or
14568 - after the first word in a line, where an abbreviation expansion could
14569 insert a LaTeX environment."
14570 (when org-cdlatex-mode
14571 (cond
14572 ((save-excursion
14573 (skip-chars-backward "a-zA-Z0-9*")
14574 (skip-chars-backward " \t")
14575 (bolp))
14576 (cdlatex-tab) t)
14577 ((org-inside-LaTeX-fragment-p)
14578 (cdlatex-tab) t)
14579 (t nil))))
14581 (defun org-cdlatex-underscore-caret (&optional arg)
14582 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14583 Revert to the normal definition outside of these fragments."
14584 (interactive "P")
14585 (if (org-inside-LaTeX-fragment-p)
14586 (call-interactively 'cdlatex-sub-superscript)
14587 (let (org-cdlatex-mode)
14588 (call-interactively (key-binding (vector last-input-event))))))
14590 (defun org-cdlatex-math-modify (&optional arg)
14591 "Execute `cdlatex-math-modify' in LaTeX fragments.
14592 Revert to the normal definition outside of these fragments."
14593 (interactive "P")
14594 (if (org-inside-LaTeX-fragment-p)
14595 (call-interactively 'cdlatex-math-modify)
14596 (let (org-cdlatex-mode)
14597 (call-interactively (key-binding (vector last-input-event))))))
14599 (defvar org-latex-fragment-image-overlays nil
14600 "List of overlays carrying the images of latex fragments.")
14601 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14603 (defun org-remove-latex-fragment-image-overlays ()
14604 "Remove all overlays with LaTeX fragment images in current buffer."
14605 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14606 (setq org-latex-fragment-image-overlays nil))
14608 (defun org-preview-latex-fragment (&optional subtree)
14609 "Preview the LaTeX fragment at point, or all locally or globally.
14610 If the cursor is in a LaTeX fragment, create the image and overlay
14611 it over the source code. If there is no fragment at point, display
14612 all fragments in the current text, from one headline to the next. With
14613 prefix SUBTREE, display all fragments in the current subtree. With a
14614 double prefix `C-u C-u', or when the cursor is before the first headline,
14615 display all fragments in the buffer.
14616 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14617 (interactive "P")
14618 (org-remove-latex-fragment-image-overlays)
14619 (save-excursion
14620 (save-restriction
14621 (let (beg end at msg)
14622 (cond
14623 ((or (equal subtree '(16))
14624 (not (save-excursion
14625 (re-search-backward (concat "^" outline-regexp) nil t))))
14626 (setq beg (point-min) end (point-max)
14627 msg "Creating images for buffer...%s"))
14628 ((equal subtree '(4))
14629 (org-back-to-heading)
14630 (setq beg (point) end (org-end-of-subtree t)
14631 msg "Creating images for subtree...%s"))
14633 (if (setq at (org-inside-LaTeX-fragment-p))
14634 (goto-char (max (point-min) (- (cdr at) 2)))
14635 (org-back-to-heading))
14636 (setq beg (point) end (progn (outline-next-heading) (point))
14637 msg (if at "Creating image...%s"
14638 "Creating images for entry...%s"))))
14639 (message msg "")
14640 (narrow-to-region beg end)
14641 (goto-char beg)
14642 (org-format-latex
14643 (concat "ltxpng/" (file-name-sans-extension
14644 (file-name-nondirectory
14645 buffer-file-name)))
14646 default-directory 'overlays msg at 'forbuffer)
14647 (message msg "done. Use `C-c C-c' to remove images.")))))
14649 (defvar org-latex-regexps
14650 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14651 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14652 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14653 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14654 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14655 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14656 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14657 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14658 "Regular expressions for matching embedded LaTeX.")
14660 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14661 "Replace LaTeX fragments with links to an image, and produce images.
14662 Some of the options can be changed using the variable
14663 `org-format-latex-options'."
14664 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14665 (let* ((prefixnodir (file-name-nondirectory prefix))
14666 (absprefix (expand-file-name prefix dir))
14667 (todir (file-name-directory absprefix))
14668 (opt org-format-latex-options)
14669 (matchers (plist-get opt :matchers))
14670 (re-list org-latex-regexps)
14671 (cnt 0) txt hash link beg end re e checkdir
14672 executables-checked
14673 m n block linkfile movefile ov)
14674 ;; Check the different regular expressions
14675 (while (setq e (pop re-list))
14676 (setq m (car e) re (nth 1 e) n (nth 2 e)
14677 block (if (nth 3 e) "\n\n" ""))
14678 (when (member m matchers)
14679 (goto-char (point-min))
14680 (while (re-search-forward re nil t)
14681 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14682 (not (get-text-property (match-beginning n)
14683 'org-protected))
14684 (or (not overlays)
14685 (not (eq (get-char-property (match-beginning n)
14686 'org-overlay-type)
14687 'org-latex-overlay))))
14688 (setq txt (match-string n)
14689 beg (match-beginning n) end (match-end n)
14690 cnt (1+ cnt))
14691 (let (print-length print-level) ; make sure full list is printed
14692 (setq hash (sha1 (prin1-to-string
14693 (list org-format-latex-header
14694 org-export-latex-packages-alist
14695 org-format-latex-options
14696 forbuffer txt)))
14697 linkfile (format "%s_%s.png" prefix hash)
14698 movefile (format "%s_%s.png" absprefix hash)))
14699 (setq link (concat block "[[file:" linkfile "]]" block))
14700 (if msg (message msg cnt))
14701 (goto-char beg)
14702 (unless checkdir ; make sure the directory exists
14703 (setq checkdir t)
14704 (or (file-directory-p todir) (make-directory todir)))
14706 (unless executables-checked
14707 (org-check-external-command
14708 "latex" "needed to convert LaTeX fragments to images")
14709 (org-check-external-command
14710 "dvipng" "needed to convert LaTeX fragments to images")
14711 (setq executables-checked t))
14713 (unless (file-exists-p movefile)
14714 (org-create-formula-image
14715 txt movefile opt forbuffer))
14716 (if overlays
14717 (progn
14718 (mapc (lambda (o)
14719 (if (eq (org-overlay-get o 'org-overlay-type)
14720 'org-latex-overlay)
14721 (org-delete-overlay o)))
14722 (org-overlays-in beg end))
14723 (setq ov (org-make-overlay beg end))
14724 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14725 (if (featurep 'xemacs)
14726 (progn
14727 (org-overlay-put ov 'invisible t)
14728 (org-overlay-put
14729 ov 'end-glyph
14730 (make-glyph (vector 'png :file movefile))))
14731 (org-overlay-put
14732 ov 'display
14733 (list 'image :type 'png :file movefile :ascent 'center)))
14734 (push ov org-latex-fragment-image-overlays)
14735 (goto-char end))
14736 (delete-region beg end)
14737 (insert link))))))))
14739 ;; This function borrows from Ganesh Swami's latex2png.el
14740 (defun org-create-formula-image (string tofile options buffer)
14741 "This calls dvipng."
14742 (require 'org-latex)
14743 (let* ((tmpdir (if (featurep 'xemacs)
14744 (temp-directory)
14745 temporary-file-directory))
14746 (texfilebase (make-temp-name
14747 (expand-file-name "orgtex" tmpdir)))
14748 (texfile (concat texfilebase ".tex"))
14749 (dvifile (concat texfilebase ".dvi"))
14750 (pngfile (concat texfilebase ".png"))
14751 (fnh (if (featurep 'xemacs)
14752 (font-height (get-face-font 'default))
14753 (face-attribute 'default :height nil)))
14754 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14755 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14756 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14757 "Black"))
14758 (bg (or (plist-get options (if buffer :background :html-background))
14759 "Transparent")))
14760 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14761 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14762 (with-temp-file texfile
14763 (insert org-format-latex-header
14764 (if org-export-latex-packages-alist
14765 (concat "\n"
14766 (mapconcat (lambda(p)
14767 (if (equal "" (car p))
14768 (format "\\usepackage{%s}" (cadr p))
14769 (format "\\usepackage[%s]{%s}"
14770 (car p) (cadr p))))
14771 org-export-latex-packages-alist "\n"))
14773 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14774 (let ((dir default-directory))
14775 (condition-case nil
14776 (progn
14777 (cd tmpdir)
14778 (call-process "latex" nil nil nil texfile))
14779 (error nil))
14780 (cd dir))
14781 (if (not (file-exists-p dvifile))
14782 (progn (message "Failed to create dvi file from %s" texfile) nil)
14783 (condition-case nil
14784 (call-process "dvipng" nil nil nil
14785 "-fg" fg "-bg" bg
14786 "-D" dpi
14787 ;;"-x" scale "-y" scale
14788 "-T" "tight"
14789 "-o" pngfile
14790 dvifile)
14791 (error nil))
14792 (if (not (file-exists-p pngfile))
14793 (progn (message "Failed to create png file from %s" texfile) nil)
14794 ;; Use the requested file name and clean up
14795 (copy-file pngfile tofile 'replace)
14796 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14797 (delete-file (concat texfilebase e)))
14798 pngfile))))
14800 (defun org-dvipng-color (attr)
14801 "Return an rgb color specification for dvipng."
14802 (apply 'format "rgb %s %s %s"
14803 (mapcar 'org-normalize-color
14804 (color-values (face-attribute 'default attr nil)))))
14806 (defun org-normalize-color (value)
14807 "Return string to be used as color value for an RGB component."
14808 (format "%g" (/ value 65535.0)))
14810 ;;;; Key bindings
14812 ;; Make `C-c C-x' a prefix key
14813 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14815 ;; TAB key with modifiers
14816 (org-defkey org-mode-map "\C-i" 'org-cycle)
14817 (org-defkey org-mode-map [(tab)] 'org-cycle)
14818 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14819 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14820 (org-defkey org-mode-map "\M-\t" 'org-complete)
14821 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14822 ;; The following line is necessary under Suse GNU/Linux
14823 (unless (featurep 'xemacs)
14824 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14825 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14826 (define-key org-mode-map [backtab] 'org-shifttab)
14828 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14829 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14830 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14832 ;; Cursor keys with modifiers
14833 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14834 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14835 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14836 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14838 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14839 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14840 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14841 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14843 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14844 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14845 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14846 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14848 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14849 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14851 ;;; Extra keys for tty access.
14852 ;; We only set them when really needed because otherwise the
14853 ;; menus don't show the simple keys
14855 (when (or org-use-extra-keys
14856 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14857 (not window-system))
14858 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14859 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14860 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14861 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14862 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14863 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14864 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14865 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14866 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14867 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14868 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14869 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14870 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14871 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14872 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14873 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14874 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14875 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14876 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14877 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14878 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14879 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14880 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14881 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14882 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14883 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14884 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14885 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14887 ;; All the other keys
14889 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14890 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14891 (if (boundp 'narrow-map)
14892 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14893 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14894 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14895 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14896 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14897 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14898 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14899 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14900 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14901 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14902 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14903 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14904 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14905 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14906 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14907 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14908 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14909 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14910 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14911 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14912 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14913 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14914 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14915 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14916 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14917 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14918 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14919 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14920 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14921 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14922 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14923 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14924 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14925 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14926 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14927 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14928 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14929 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14930 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14931 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14932 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14933 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14934 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14935 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14936 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14937 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14938 (org-defkey org-mode-map "\C-c^" 'org-sort)
14939 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14940 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14941 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14942 (org-defkey org-mode-map "\C-m" 'org-return)
14943 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14944 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14945 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14946 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14947 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14948 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14949 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14950 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14951 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14952 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14953 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14954 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14955 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14956 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14957 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14958 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14959 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14960 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14961 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14962 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14963 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14965 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14966 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14967 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14968 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14970 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14971 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14972 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14973 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14974 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14975 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14976 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14977 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14978 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14979 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14980 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14981 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14982 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14983 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14984 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14986 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14987 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14988 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14989 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14991 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14993 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14995 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14996 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14998 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15001 (when (featurep 'xemacs)
15002 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15005 (defconst org-speed-commands-default
15007 ("Outline Navigation")
15008 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15009 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15010 ("f" . (org-speed-move-safe 'org-forward-same-level))
15011 ("b" . (org-speed-move-safe 'org-backward-same-level))
15012 ("u" . (org-speed-move-safe 'outline-up-heading))
15013 ("j" . org-goto)
15014 ("g" . (org-refile t))
15015 ("Outline Visibility")
15016 ("c" . org-cycle)
15017 ("C" . org-shifttab)
15018 (" " . org-display-outline-path)
15019 ("Outline Structure Editing")
15020 ("U" . org-shiftmetaup)
15021 ("D" . org-shiftmetadown)
15022 ("r" . org-metaright)
15023 ("l" . org-metaleft)
15024 ("R" . org-shiftmetaright)
15025 ("L" . org-shiftmetaleft)
15026 ("i" . (progn (forward-char 1) (call-interactively
15027 'org-insert-heading-respect-content)))
15028 ("^" . org-sort)
15029 ("w" . org-refile)
15030 ("a" . org-archive-subtree-default-with-confirmation)
15031 ("." . outline-mark-subtree)
15032 ("Clock Commands")
15033 ("I" . org-clock-in)
15034 ("O" . org-clock-out)
15035 ("Meta Data Editing")
15036 ("t" . org-todo)
15037 ("0" . (org-priority ?\ ))
15038 ("1" . (org-priority ?A))
15039 ("2" . (org-priority ?B))
15040 ("3" . (org-priority ?C))
15041 (";" . org-set-tags-command)
15042 ("e" . org-set-effort)
15043 ("Agenda Views etc")
15044 ("v" . org-agenda)
15045 ("/" . org-sparse-tree)
15046 ("Misc")
15047 ("o" . org-open-at-point)
15048 ("?" . org-speed-command-help)
15050 "The default speed commands.")
15052 (defun org-print-speed-command (e)
15053 (if (> (length (car e)) 1)
15054 (progn
15055 (princ "\n")
15056 (princ (car e))
15057 (princ "\n")
15058 (princ (make-string (length (car e)) ?-))
15059 (princ "\n"))
15060 (princ (car e))
15061 (princ " ")
15062 (if (symbolp (cdr e))
15063 (princ (symbol-name (cdr e)))
15064 (prin1 (cdr e)))
15065 (princ "\n")))
15067 (defun org-speed-command-help ()
15068 "Show the available speed commands."
15069 (interactive)
15070 (if (not org-use-speed-commands)
15071 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15072 (with-output-to-temp-buffer "*Help*"
15073 (princ "User-defined Speed commands\n===========================\n")
15074 (mapc 'org-print-speed-command org-speed-commands-user)
15075 (princ "\n")
15076 (princ "Built-in Speed commands\n=======================\n")
15077 (mapc 'org-print-speed-command org-speed-commands-default))
15078 (with-current-buffer "*Help*"
15079 (setq truncate-lines t))))
15081 (defun org-speed-move-safe (cmd)
15082 "Execute CMD, but make sure that the cursor always ends up in a headline.
15083 If not, return to the original position and throw an error."
15084 (interactive)
15085 (let ((pos (point)))
15086 (call-interactively cmd)
15087 (unless (and (bolp) (org-on-heading-p))
15088 (goto-char pos)
15089 (error "Boundary reached while executing %s" cmd))))
15091 (defvar org-self-insert-command-undo-counter 0)
15093 (defvar org-table-auto-blank-field) ; defined in org-table.el
15094 (defvar org-speed-command nil)
15095 (defun org-self-insert-command (N)
15096 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15097 If the cursor is in a table looking at whitespace, the whitespace is
15098 overwritten, and the table is not marked as requiring realignment."
15099 (interactive "p")
15100 (cond
15101 ((and org-use-speed-commands
15102 (or (and (bolp) (looking-at outline-regexp))
15103 (and (functionp org-use-speed-commands)
15104 (funcall org-use-speed-commands)))
15105 (setq
15106 org-speed-command
15107 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15108 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15109 (cond
15110 ((commandp org-speed-command)
15111 (setq this-command org-speed-command)
15112 (call-interactively org-speed-command))
15113 ((functionp org-speed-command)
15114 (funcall org-speed-command))
15115 ((and org-speed-command (listp org-speed-command))
15116 (eval org-speed-command))
15117 (t (let (org-use-speed-commands)
15118 (call-interactively 'org-self-insert-command)))))
15119 ((and
15120 (org-table-p)
15121 (progn
15122 ;; check if we blank the field, and if that triggers align
15123 (and (featurep 'org-table) org-table-auto-blank-field
15124 (member last-command
15125 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15126 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15127 ;; got extra space, this field does not determine column width
15128 (let (org-table-may-need-update) (org-table-blank-field))
15129 ;; no extra space, this field may determine column width
15130 (org-table-blank-field)))
15132 (eq N 1)
15133 (looking-at "[^|\n]* |"))
15134 (let (org-table-may-need-update)
15135 (goto-char (1- (match-end 0)))
15136 (delete-backward-char 1)
15137 (goto-char (match-beginning 0))
15138 (self-insert-command N)))
15140 (setq org-table-may-need-update t)
15141 (self-insert-command N)
15142 (org-fix-tags-on-the-fly)
15143 (if org-self-insert-cluster-for-undo
15144 (if (not (eq last-command 'org-self-insert-command))
15145 (setq org-self-insert-command-undo-counter 1)
15146 (if (>= org-self-insert-command-undo-counter 20)
15147 (setq org-self-insert-command-undo-counter 1)
15148 (and (> org-self-insert-command-undo-counter 0)
15149 buffer-undo-list
15150 (not (cadr buffer-undo-list)) ; remove nil entry
15151 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15152 (setq org-self-insert-command-undo-counter
15153 (1+ org-self-insert-command-undo-counter))))))))
15155 (defun org-fix-tags-on-the-fly ()
15156 (when (and (equal (char-after (point-at-bol)) ?*)
15157 (org-on-heading-p))
15158 (org-align-tags-here org-tags-column)))
15160 (defun org-delete-backward-char (N)
15161 "Like `delete-backward-char', insert whitespace at field end in tables.
15162 When deleting backwards, in tables this function will insert whitespace in
15163 front of the next \"|\" separator, to keep the table aligned. The table will
15164 still be marked for re-alignment if the field did fill the entire column,
15165 because, in this case the deletion might narrow the column."
15166 (interactive "p")
15167 (if (and (org-table-p)
15168 (eq N 1)
15169 (string-match "|" (buffer-substring (point-at-bol) (point)))
15170 (looking-at ".*?|"))
15171 (let ((pos (point))
15172 (noalign (looking-at "[^|\n\r]* |"))
15173 (c org-table-may-need-update))
15174 (backward-delete-char N)
15175 (skip-chars-forward "^|")
15176 (insert " ")
15177 (goto-char (1- pos))
15178 ;; noalign: if there were two spaces at the end, this field
15179 ;; does not determine the width of the column.
15180 (if noalign (setq org-table-may-need-update c)))
15181 (backward-delete-char N)
15182 (org-fix-tags-on-the-fly)))
15184 (defun org-delete-char (N)
15185 "Like `delete-char', but insert whitespace at field end in tables.
15186 When deleting characters, in tables this function will insert whitespace in
15187 front of the next \"|\" separator, to keep the table aligned. The table will
15188 still be marked for re-alignment if the field did fill the entire column,
15189 because, in this case the deletion might narrow the column."
15190 (interactive "p")
15191 (if (and (org-table-p)
15192 (not (bolp))
15193 (not (= (char-after) ?|))
15194 (eq N 1))
15195 (if (looking-at ".*?|")
15196 (let ((pos (point))
15197 (noalign (looking-at "[^|\n\r]* |"))
15198 (c org-table-may-need-update))
15199 (replace-match (concat
15200 (substring (match-string 0) 1 -1)
15201 " |"))
15202 (goto-char pos)
15203 ;; noalign: if there were two spaces at the end, this field
15204 ;; does not determine the width of the column.
15205 (if noalign (setq org-table-may-need-update c)))
15206 (delete-char N))
15207 (delete-char N)
15208 (org-fix-tags-on-the-fly)))
15210 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15211 (put 'org-self-insert-command 'delete-selection t)
15212 (put 'orgtbl-self-insert-command 'delete-selection t)
15213 (put 'org-delete-char 'delete-selection 'supersede)
15214 (put 'org-delete-backward-char 'delete-selection 'supersede)
15215 (put 'org-yank 'delete-selection 'yank)
15217 ;; Make `flyspell-mode' delay after some commands
15218 (put 'org-self-insert-command 'flyspell-delayed t)
15219 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15220 (put 'org-delete-char 'flyspell-delayed t)
15221 (put 'org-delete-backward-char 'flyspell-delayed t)
15223 ;; Make pabbrev-mode expand after org-mode commands
15224 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15225 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15227 ;; How to do this: Measure non-white length of current string
15228 ;; If equal to column width, we should realign.
15230 (defun org-remap (map &rest commands)
15231 "In MAP, remap the functions given in COMMANDS.
15232 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15233 (let (new old)
15234 (while commands
15235 (setq old (pop commands) new (pop commands))
15236 (if (fboundp 'command-remapping)
15237 (org-defkey map (vector 'remap old) new)
15238 (substitute-key-definition old new map global-map)))))
15240 (when (eq org-enable-table-editor 'optimized)
15241 ;; If the user wants maximum table support, we need to hijack
15242 ;; some standard editing functions
15243 (org-remap org-mode-map
15244 'self-insert-command 'org-self-insert-command
15245 'delete-char 'org-delete-char
15246 'delete-backward-char 'org-delete-backward-char)
15247 (org-defkey org-mode-map "|" 'org-force-self-insert))
15249 (defvar org-ctrl-c-ctrl-c-hook nil
15250 "Hook for functions attaching themselves to `C-c C-c'.
15251 This can be used to add additional functionality to the C-c C-c key which
15252 executes context-dependent commands.
15253 Each function will be called with no arguments. The function must check
15254 if the context is appropriate for it to act. If yes, it should do its
15255 thing and then return a non-nil value. If the context is wrong,
15256 just do nothing and return nil.")
15258 (defvar org-tab-first-hook nil
15259 "Hook for functions to attach themselves to TAB.
15260 See `org-ctrl-c-ctrl-c-hook' for more information.
15261 This hook runs as the first action when TAB is pressed, even before
15262 `org-cycle' messes around with the `outline-regexp' to cater for
15263 inline tasks and plain list item folding.
15264 If any function in this hook returns t, not other actions like table
15265 field motion visibility cycling will be done.")
15267 (defvar org-tab-after-check-for-table-hook nil
15268 "Hook for functions to attach themselves to TAB.
15269 See `org-ctrl-c-ctrl-c-hook' for more information.
15270 This hook runs after it has been established that the cursor is not in a
15271 table, but before checking if the cursor is in a headline or if global cycling
15272 should be done.
15273 If any function in this hook returns t, not other actions like visibility
15274 cycling will be done.")
15276 (defvar org-tab-after-check-for-cycling-hook nil
15277 "Hook for functions to attach themselves to TAB.
15278 See `org-ctrl-c-ctrl-c-hook' for more information.
15279 This hook runs after it has been established that not table field motion and
15280 not visibility should be done because of current context. This is probably
15281 the place where a package like yasnippets can hook in.")
15283 (defvar org-tab-before-tab-emulation-hook nil
15284 "Hook for functions to attach themselves to TAB.
15285 See `org-ctrl-c-ctrl-c-hook' for more information.
15286 This hook runs after every other options for TAB have been exhausted, but
15287 before indentation and \t insertion takes place.")
15289 (defvar org-metaleft-hook nil
15290 "Hook for functions attaching themselves to `M-left'.
15291 See `org-ctrl-c-ctrl-c-hook' for more information.")
15292 (defvar org-metaright-hook nil
15293 "Hook for functions attaching themselves to `M-right'.
15294 See `org-ctrl-c-ctrl-c-hook' for more information.")
15295 (defvar org-metaup-hook nil
15296 "Hook for functions attaching themselves to `M-up'.
15297 See `org-ctrl-c-ctrl-c-hook' for more information.")
15298 (defvar org-metadown-hook nil
15299 "Hook for functions attaching themselves to `M-down'.
15300 See `org-ctrl-c-ctrl-c-hook' for more information.")
15301 (defvar org-shiftmetaleft-hook nil
15302 "Hook for functions attaching themselves to `M-S-left'.
15303 See `org-ctrl-c-ctrl-c-hook' for more information.")
15304 (defvar org-shiftmetaright-hook nil
15305 "Hook for functions attaching themselves to `M-S-right'.
15306 See `org-ctrl-c-ctrl-c-hook' for more information.")
15307 (defvar org-shiftmetaup-hook nil
15308 "Hook for functions attaching themselves to `M-S-up'.
15309 See `org-ctrl-c-ctrl-c-hook' for more information.")
15310 (defvar org-shiftmetadown-hook nil
15311 "Hook for functions attaching themselves to `M-S-down'.
15312 See `org-ctrl-c-ctrl-c-hook' for more information.")
15313 (defvar org-metareturn-hook nil
15314 "Hook for functions attaching themselves to `M-RET'.
15315 See `org-ctrl-c-ctrl-c-hook' for more information.")
15317 (defun org-modifier-cursor-error ()
15318 "Throw an error, a modified cursor command was applied in wrong context."
15319 (error "This command is active in special context like tables, headlines or items"))
15321 (defun org-shiftselect-error ()
15322 "Throw an error because Shift-Cursor command was applied in wrong context."
15323 (if (and (boundp 'shift-select-mode) shift-select-mode)
15324 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15325 (error "This command works only in special context like headlines or timestamps")))
15327 (defun org-call-for-shift-select (cmd)
15328 (let ((this-command-keys-shift-translated t))
15329 (call-interactively cmd)))
15331 (defun org-shifttab (&optional arg)
15332 "Global visibility cycling or move to previous table field.
15333 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15334 on context.
15335 See the individual commands for more information."
15336 (interactive "P")
15337 (cond
15338 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15339 ((integerp arg)
15340 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15341 (message "Content view to level: %d" arg)
15342 (org-content (prefix-numeric-value arg2))
15343 (setq org-cycle-global-status 'overview)))
15344 (t (call-interactively 'org-global-cycle))))
15346 (defun org-shiftmetaleft ()
15347 "Promote subtree or delete table column.
15348 Calls `org-promote-subtree', `org-outdent-item',
15349 or `org-table-delete-column', depending on context.
15350 See the individual commands for more information."
15351 (interactive)
15352 (cond
15353 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15354 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15355 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15356 ((org-at-item-p) (call-interactively 'org-outdent-item))
15357 (t (org-modifier-cursor-error))))
15359 (defun org-shiftmetaright ()
15360 "Demote subtree or insert table column.
15361 Calls `org-demote-subtree', `org-indent-item',
15362 or `org-table-insert-column', depending on context.
15363 See the individual commands for more information."
15364 (interactive)
15365 (cond
15366 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15367 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15368 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15369 ((org-at-item-p) (call-interactively 'org-indent-item))
15370 (t (org-modifier-cursor-error))))
15372 (defun org-shiftmetaup (&optional arg)
15373 "Move subtree up or kill table row.
15374 Calls `org-move-subtree-up' or `org-table-kill-row' or
15375 `org-move-item-up' depending on context. See the individual commands
15376 for more information."
15377 (interactive "P")
15378 (cond
15379 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15380 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15381 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15382 ((org-at-item-p) (call-interactively 'org-move-item-up))
15383 (t (org-modifier-cursor-error))))
15385 (defun org-shiftmetadown (&optional arg)
15386 "Move subtree down or insert table row.
15387 Calls `org-move-subtree-down' or `org-table-insert-row' or
15388 `org-move-item-down', depending on context. See the individual
15389 commands for more information."
15390 (interactive "P")
15391 (cond
15392 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15393 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15394 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15395 ((org-at-item-p) (call-interactively 'org-move-item-down))
15396 (t (org-modifier-cursor-error))))
15398 (defun org-metaleft (&optional arg)
15399 "Promote heading or move table column to left.
15400 Calls `org-do-promote' or `org-table-move-column', depending on context.
15401 With no specific context, calls the Emacs default `backward-word'.
15402 See the individual commands for more information."
15403 (interactive "P")
15404 (cond
15405 ((run-hook-with-args-until-success 'org-metaleft-hook))
15406 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15407 ((or (org-on-heading-p)
15408 (and (org-region-active-p)
15409 (save-excursion
15410 (goto-char (region-beginning))
15411 (org-on-heading-p))))
15412 (call-interactively 'org-do-promote))
15413 ((or (org-at-item-p)
15414 (and (org-region-active-p)
15415 (save-excursion
15416 (goto-char (region-beginning))
15417 (org-at-item-p))))
15418 (call-interactively 'org-outdent-item))
15419 (t (call-interactively 'backward-word))))
15421 (defun org-metaright (&optional arg)
15422 "Demote subtree or move table column to right.
15423 Calls `org-do-demote' or `org-table-move-column', depending on context.
15424 With no specific context, calls the Emacs default `forward-word'.
15425 See the individual commands for more information."
15426 (interactive "P")
15427 (cond
15428 ((run-hook-with-args-until-success 'org-metaright-hook))
15429 ((org-at-table-p) (call-interactively 'org-table-move-column))
15430 ((or (org-on-heading-p)
15431 (and (org-region-active-p)
15432 (save-excursion
15433 (goto-char (region-beginning))
15434 (org-on-heading-p))))
15435 (call-interactively 'org-do-demote))
15436 ((or (org-at-item-p)
15437 (and (org-region-active-p)
15438 (save-excursion
15439 (goto-char (region-beginning))
15440 (org-at-item-p))))
15441 (call-interactively 'org-indent-item))
15442 (t (call-interactively 'forward-word))))
15444 (defun org-metaup (&optional arg)
15445 "Move subtree up or move table row up.
15446 Calls `org-move-subtree-up' or `org-table-move-row' or
15447 `org-move-item-up', depending on context. See the individual commands
15448 for more information."
15449 (interactive "P")
15450 (cond
15451 ((run-hook-with-args-until-success 'org-metaup-hook))
15452 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15453 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15454 ((org-at-item-p) (call-interactively 'org-move-item-up))
15455 (t (transpose-lines 1) (beginning-of-line -1))))
15457 (defun org-metadown (&optional arg)
15458 "Move subtree down or move table row down.
15459 Calls `org-move-subtree-down' or `org-table-move-row' or
15460 `org-move-item-down', depending on context. See the individual
15461 commands for more information."
15462 (interactive "P")
15463 (cond
15464 ((run-hook-with-args-until-success 'org-metadown-hook))
15465 ((org-at-table-p) (call-interactively 'org-table-move-row))
15466 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15467 ((org-at-item-p) (call-interactively 'org-move-item-down))
15468 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15470 (defun org-shiftup (&optional arg)
15471 "Increase item in timestamp or increase priority of current headline.
15472 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15473 depending on context. See the individual commands for more information."
15474 (interactive "P")
15475 (cond
15476 ((and org-support-shift-select (org-region-active-p))
15477 (org-call-for-shift-select 'previous-line))
15478 ((org-at-timestamp-p t)
15479 (call-interactively (if org-edit-timestamp-down-means-later
15480 'org-timestamp-down 'org-timestamp-up)))
15481 ((and (not (eq org-support-shift-select 'always))
15482 org-enable-priority-commands
15483 (org-on-heading-p))
15484 (call-interactively 'org-priority-up))
15485 ((and (not org-support-shift-select) (org-at-item-p))
15486 (call-interactively 'org-previous-item))
15487 ((org-clocktable-try-shift 'up arg))
15488 (org-support-shift-select
15489 (org-call-for-shift-select 'previous-line))
15490 (t (org-shiftselect-error))))
15492 (defun org-shiftdown (&optional arg)
15493 "Decrease item in timestamp or decrease priority of current headline.
15494 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15495 depending on context. See the individual commands for more information."
15496 (interactive "P")
15497 (cond
15498 ((and org-support-shift-select (org-region-active-p))
15499 (org-call-for-shift-select 'next-line))
15500 ((org-at-timestamp-p t)
15501 (call-interactively (if org-edit-timestamp-down-means-later
15502 'org-timestamp-up 'org-timestamp-down)))
15503 ((and (not (eq org-support-shift-select 'always))
15504 org-enable-priority-commands
15505 (org-on-heading-p))
15506 (call-interactively 'org-priority-down))
15507 ((and (not org-support-shift-select) (org-at-item-p))
15508 (call-interactively 'org-next-item))
15509 ((org-clocktable-try-shift 'down arg))
15510 (org-support-shift-select
15511 (org-call-for-shift-select 'next-line))
15512 (t (org-shiftselect-error))))
15514 (defun org-shiftright (&optional arg)
15515 "Cycle the thing at point or in the current line, depending on context.
15516 Depending on context, this does one of the following:
15518 - switch a timestamp at point one day into the future
15519 - on a headline, switch to the next TODO keyword.
15520 - on an item, switch entire list to the next bullet type
15521 - on a property line, switch to the next allowed value
15522 - on a clocktable definition line, move time block into the future"
15523 (interactive "P")
15524 (cond
15525 ((and org-support-shift-select (org-region-active-p))
15526 (org-call-for-shift-select 'forward-char))
15527 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15528 ((and (not (eq org-support-shift-select 'always))
15529 (org-on-heading-p))
15530 (let ((org-inhibit-logging
15531 (not org-treat-S-cursor-todo-selection-as-state-change))
15532 (org-inhibit-blocking
15533 (not org-treat-S-cursor-todo-selection-as-state-change)))
15534 (org-call-with-arg 'org-todo 'right)))
15535 ((or (and org-support-shift-select
15536 (not (eq org-support-shift-select 'always))
15537 (org-at-item-bullet-p))
15538 (and (not org-support-shift-select) (org-at-item-p)))
15539 (org-call-with-arg 'org-cycle-list-bullet nil))
15540 ((and (not (eq org-support-shift-select 'always))
15541 (org-at-property-p))
15542 (call-interactively 'org-property-next-allowed-value))
15543 ((org-clocktable-try-shift 'right arg))
15544 (org-support-shift-select
15545 (org-call-for-shift-select 'forward-char))
15546 (t (org-shiftselect-error))))
15548 (defun org-shiftleft (&optional arg)
15549 "Cycle the thing at point or in the current line, depending on context.
15550 Depending on context, this does one of the following:
15552 - switch a timestamp at point one day into the past
15553 - on a headline, switch to the previous TODO keyword.
15554 - on an item, switch entire list to the previous bullet type
15555 - on a property line, switch to the previous allowed value
15556 - on a clocktable definition line, move time block into the past"
15557 (interactive "P")
15558 (cond
15559 ((and org-support-shift-select (org-region-active-p))
15560 (org-call-for-shift-select 'backward-char))
15561 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15562 ((and (not (eq org-support-shift-select 'always))
15563 (org-on-heading-p))
15564 (let ((org-inhibit-logging
15565 (not org-treat-S-cursor-todo-selection-as-state-change))
15566 (org-inhibit-blocking
15567 (not org-treat-S-cursor-todo-selection-as-state-change)))
15568 (org-call-with-arg 'org-todo 'left)))
15569 ((or (and org-support-shift-select
15570 (not (eq org-support-shift-select 'always))
15571 (org-at-item-bullet-p))
15572 (and (not org-support-shift-select) (org-at-item-p)))
15573 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15574 ((and (not (eq org-support-shift-select 'always))
15575 (org-at-property-p))
15576 (call-interactively 'org-property-previous-allowed-value))
15577 ((org-clocktable-try-shift 'left arg))
15578 (org-support-shift-select
15579 (org-call-for-shift-select 'backward-char))
15580 (t (org-shiftselect-error))))
15582 (defun org-shiftcontrolright ()
15583 "Switch to next TODO set."
15584 (interactive)
15585 (cond
15586 ((and org-support-shift-select (org-region-active-p))
15587 (org-call-for-shift-select 'forward-word))
15588 ((and (not (eq org-support-shift-select 'always))
15589 (org-on-heading-p))
15590 (org-call-with-arg 'org-todo 'nextset))
15591 (org-support-shift-select
15592 (org-call-for-shift-select 'forward-word))
15593 (t (org-shiftselect-error))))
15595 (defun org-shiftcontrolleft ()
15596 "Switch to previous TODO set."
15597 (interactive)
15598 (cond
15599 ((and org-support-shift-select (org-region-active-p))
15600 (org-call-for-shift-select 'backward-word))
15601 ((and (not (eq org-support-shift-select 'always))
15602 (org-on-heading-p))
15603 (org-call-with-arg 'org-todo 'previousset))
15604 (org-support-shift-select
15605 (org-call-for-shift-select 'backward-word))
15606 (t (org-shiftselect-error))))
15608 (defun org-ctrl-c-ret ()
15609 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15610 (interactive)
15611 (cond
15612 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15613 (t (call-interactively 'org-insert-heading))))
15615 (defun org-copy-special ()
15616 "Copy region in table or copy current subtree.
15617 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15618 See the individual commands for more information."
15619 (interactive)
15620 (call-interactively
15621 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15623 (defun org-cut-special ()
15624 "Cut region in table or cut current subtree.
15625 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15626 See the individual commands for more information."
15627 (interactive)
15628 (call-interactively
15629 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15631 (defun org-paste-special (arg)
15632 "Paste rectangular region into table, or past subtree relative to level.
15633 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15634 See the individual commands for more information."
15635 (interactive "P")
15636 (if (org-at-table-p)
15637 (org-table-paste-rectangle)
15638 (org-paste-subtree arg)))
15640 (defun org-edit-special ()
15641 "Call a special editor for the stuff at point.
15642 When at a table, call the formula editor with `org-table-edit-formulas'.
15643 When at the first line of an src example, call `org-edit-src-code'.
15644 When in an #+include line, visit the include file. Otherwise call
15645 `ffap' to visit the file at point."
15646 (interactive)
15647 (cond
15648 ((org-at-table-p)
15649 (call-interactively 'org-table-edit-formulas))
15650 ((save-excursion
15651 (beginning-of-line 1)
15652 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15653 (find-file (org-trim (match-string 1))))
15654 ((org-edit-src-code))
15655 ((org-edit-fixed-width-region))
15656 (t (call-interactively 'ffap))))
15659 (defun org-ctrl-c-ctrl-c (&optional arg)
15660 "Set tags in headline, or update according to changed information at point.
15662 This command does many different things, depending on context:
15664 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15665 this is what we do.
15667 - If the cursor is on a statistics cookie, update it.
15669 - If the cursor is in a headline, prompt for tags and insert them
15670 into the current line, aligned to `org-tags-column'. When called
15671 with prefix arg, realign all tags in the current buffer.
15673 - If the cursor is in one of the special #+KEYWORD lines, this
15674 triggers scanning the buffer for these lines and updating the
15675 information.
15677 - If the cursor is inside a table, realign the table. This command
15678 works even if the automatic table editor has been turned off.
15680 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15681 the entire table.
15683 - If the cursor is at a footnote reference or definition, jump to
15684 the corresponding definition or references, respectively.
15686 - If the cursor is a the beginning of a dynamic block, update it.
15688 - If the cursor is inside a table created by the table.el package,
15689 activate that table.
15691 - If the current buffer is a remember buffer, close note and file
15692 it. A prefix argument of 1 files to the default location
15693 without further interaction. A prefix argument of 2 files to
15694 the currently clocking task.
15696 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15697 links in this buffer.
15699 - If the cursor is on a numbered item in a plain list, renumber the
15700 ordered list.
15702 - If the cursor is on a checkbox, toggle it."
15703 (interactive "P")
15704 (let ((org-enable-table-editor t))
15705 (cond
15706 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15707 org-occur-highlights
15708 org-latex-fragment-image-overlays)
15709 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15710 (org-remove-occur-highlights)
15711 (org-remove-latex-fragment-image-overlays)
15712 (message "Temporary highlights/overlays removed from current buffer"))
15713 ((and (local-variable-p 'org-finish-function (current-buffer))
15714 (fboundp org-finish-function))
15715 (funcall org-finish-function))
15716 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15717 ((org-at-property-p)
15718 (call-interactively 'org-property-action))
15719 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15720 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15721 (or (org-on-heading-p) (org-at-item-p)))
15722 (call-interactively 'org-update-statistics-cookies))
15723 ((org-on-heading-p) (call-interactively 'org-set-tags))
15724 ((org-at-table.el-p)
15725 (require 'table)
15726 (beginning-of-line 1)
15727 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15728 (call-interactively 'table-recognize-table))
15729 ((org-at-table-p)
15730 (org-table-maybe-eval-formula)
15731 (if arg
15732 (call-interactively 'org-table-recalculate)
15733 (org-table-maybe-recalculate-line))
15734 (call-interactively 'org-table-align))
15735 ((or (org-footnote-at-reference-p)
15736 (org-footnote-at-definition-p))
15737 (call-interactively 'org-footnote-action))
15738 ((org-at-item-checkbox-p)
15739 (call-interactively 'org-toggle-checkbox))
15740 ((org-at-item-p)
15741 (if arg
15742 (call-interactively 'org-toggle-checkbox)
15743 (call-interactively 'org-maybe-renumber-ordered-list)))
15744 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15745 ;; Dynamic block
15746 (beginning-of-line 1)
15747 (save-excursion (org-update-dblock)))
15748 ((save-excursion
15749 (beginning-of-line 1)
15750 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15751 (cond
15752 ((equal (match-string 1) "TBLFM")
15753 ;; Recalculate the table before this line
15754 (save-excursion
15755 (beginning-of-line 1)
15756 (skip-chars-backward " \r\n\t")
15757 (if (org-at-table-p)
15758 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15760 ; (org-set-regexps-and-options)
15761 ; (org-restart-font-lock)
15762 (let ((org-inhibit-startup t)) (org-mode-restart))
15763 (message "Local setup has been refreshed"))))
15764 ((org-clock-update-time-maybe))
15765 (t (error "C-c C-c can do nothing useful at this location")))))
15767 (defun org-mode-restart ()
15768 "Restart Org-mode, to scan again for special lines.
15769 Also updates the keyword regular expressions."
15770 (interactive)
15771 (org-mode)
15772 (message "Org-mode restarted"))
15774 (defun org-kill-note-or-show-branches ()
15775 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15776 (interactive)
15777 (if (not org-finish-function)
15778 (call-interactively 'show-branches)
15779 (let ((org-note-abort t))
15780 (funcall org-finish-function))))
15782 (defun org-return (&optional indent)
15783 "Goto next table row or insert a newline.
15784 Calls `org-table-next-row' or `newline', depending on context.
15785 See the individual commands for more information."
15786 (interactive)
15787 (cond
15788 ((bobp) (if indent (newline-and-indent) (newline)))
15789 ((org-at-table-p)
15790 (org-table-justify-field-maybe)
15791 (call-interactively 'org-table-next-row))
15792 ((and org-return-follows-link
15793 (eq (get-text-property (point) 'face) 'org-link))
15794 (call-interactively 'org-open-at-point))
15795 ((and (org-at-heading-p)
15796 (looking-at
15797 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15798 (org-show-entry)
15799 (end-of-line 1)
15800 (newline))
15801 (t (if indent (newline-and-indent) (newline)))))
15803 (defun org-return-indent ()
15804 "Goto next table row or insert a newline and indent.
15805 Calls `org-table-next-row' or `newline-and-indent', depending on
15806 context. See the individual commands for more information."
15807 (interactive)
15808 (org-return t))
15810 (defun org-ctrl-c-star ()
15811 "Compute table, or change heading status of lines.
15812 Calls `org-table-recalculate' or `org-toggle-heading',
15813 depending on context."
15814 (interactive)
15815 (cond
15816 ((org-at-table-p)
15817 (call-interactively 'org-table-recalculate))
15819 ;; Convert all lines in region to list items
15820 (call-interactively 'org-toggle-heading))))
15822 (defun org-ctrl-c-minus ()
15823 "Insert separator line in table or modify bullet status of line.
15824 Also turns a plain line or a region of lines into list items.
15825 Calls `org-table-insert-hline', `org-toggle-item', or
15826 `org-cycle-list-bullet', depending on context."
15827 (interactive)
15828 (cond
15829 ((org-at-table-p)
15830 (call-interactively 'org-table-insert-hline))
15831 ((org-region-active-p)
15832 (call-interactively 'org-toggle-item))
15833 ((org-in-item-p)
15834 (call-interactively 'org-cycle-list-bullet))
15836 (call-interactively 'org-toggle-item))))
15838 (defun org-toggle-item ()
15839 "Convert headings or normal lines to items, items to normal lines.
15840 If there is no active region, only the current line is considered.
15842 If the first line in the region is a headline, convert all headlines to items.
15844 If the first line in the region is an item, convert all items to normal lines.
15846 If the first line is normal text, add an item bullet to each line."
15847 (interactive)
15848 (let (l2 l beg end)
15849 (if (org-region-active-p)
15850 (setq beg (region-beginning) end (region-end))
15851 (setq beg (point-at-bol)
15852 end (min (1+ (point-at-eol)) (point-max))))
15853 (save-excursion
15854 (goto-char end)
15855 (setq l2 (org-current-line))
15856 (goto-char beg)
15857 (beginning-of-line 1)
15858 (setq l (1- (org-current-line)))
15859 (if (org-at-item-p)
15860 ;; We already have items, de-itemize
15861 (while (< (setq l (1+ l)) l2)
15862 (when (org-at-item-p)
15863 (goto-char (match-beginning 2))
15864 (delete-region (match-beginning 2) (match-end 2))
15865 (and (looking-at "[ \t]+") (replace-match "")))
15866 (beginning-of-line 2))
15867 (if (org-on-heading-p)
15868 ;; Headings, convert to items
15869 (while (< (setq l (1+ l)) l2)
15870 (if (looking-at org-outline-regexp)
15871 (replace-match "- " t t))
15872 (beginning-of-line 2))
15873 ;; normal lines, turn them into items
15874 (while (< (setq l (1+ l)) l2)
15875 (unless (org-at-item-p)
15876 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15877 (replace-match "\\1- \\2")))
15878 (beginning-of-line 2)))))))
15880 (defun org-toggle-heading (&optional nstars)
15881 "Convert headings to normal text, or items or text to headings.
15882 If there is no active region, only the current line is considered.
15884 If the first line is a heading, remove the stars from all headlines
15885 in the region.
15887 If the first line is a plain list item, turn all plain list items
15888 into headings.
15890 If the first line is a normal line, turn each and every line in the
15891 region into a heading.
15893 When converting a line into a heading, the number of stars is chosen
15894 such that the lines become children of the current entry. However,
15895 when a prefix argument is given, its value determines the number of
15896 stars to add."
15897 (interactive "P")
15898 (let (l2 l itemp beg end)
15899 (if (org-region-active-p)
15900 (setq beg (region-beginning) end (region-end))
15901 (setq beg (point-at-bol)
15902 end (min (1+ (point-at-eol)) (point-max))))
15903 (save-excursion
15904 (goto-char end)
15905 (setq l2 (org-current-line))
15906 (goto-char beg)
15907 (beginning-of-line 1)
15908 (setq l (1- (org-current-line)))
15909 (if (org-on-heading-p)
15910 ;; We already have headlines, de-star them
15911 (while (< (setq l (1+ l)) l2)
15912 (when (org-on-heading-p t)
15913 (and (looking-at outline-regexp) (replace-match "")))
15914 (beginning-of-line 2))
15915 (setq itemp (org-at-item-p))
15916 (let* ((stars
15917 (if nstars
15918 (make-string (prefix-numeric-value current-prefix-arg)
15920 (save-excursion
15921 (if (re-search-backward org-complex-heading-regexp nil t)
15922 (match-string 1) ""))))
15923 (add-stars (cond (nstars "")
15924 ((equal stars "") "*")
15925 (org-odd-levels-only "**")
15926 (t "*")))
15927 (rpl (concat stars add-stars " ")))
15928 (while (< (setq l (1+ l)) l2)
15929 (if itemp
15930 (and (org-at-item-p) (replace-match rpl t t))
15931 (unless (org-on-heading-p)
15932 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15933 (replace-match (concat rpl (match-string 2))))))
15934 (beginning-of-line 2)))))))
15936 (defun org-meta-return (&optional arg)
15937 "Insert a new heading or wrap a region in a table.
15938 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15939 See the individual commands for more information."
15940 (interactive "P")
15941 (cond
15942 ((run-hook-with-args-until-success 'org-metareturn-hook))
15943 ((org-at-table-p)
15944 (call-interactively 'org-table-wrap-region))
15945 (t (call-interactively 'org-insert-heading))))
15947 ;;; Menu entries
15949 ;; Define the Org-mode menus
15950 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15951 '("Tbl"
15952 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15953 ["Next Field" org-cycle (org-at-table-p)]
15954 ["Previous Field" org-shifttab (org-at-table-p)]
15955 ["Next Row" org-return (org-at-table-p)]
15956 "--"
15957 ["Blank Field" org-table-blank-field (org-at-table-p)]
15958 ["Edit Field" org-table-edit-field (org-at-table-p)]
15959 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15960 "--"
15961 ("Column"
15962 ["Move Column Left" org-metaleft (org-at-table-p)]
15963 ["Move Column Right" org-metaright (org-at-table-p)]
15964 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15965 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15966 ("Row"
15967 ["Move Row Up" org-metaup (org-at-table-p)]
15968 ["Move Row Down" org-metadown (org-at-table-p)]
15969 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15970 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15971 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15972 "--"
15973 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15974 ("Rectangle"
15975 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15976 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15977 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15978 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15979 "--"
15980 ("Calculate"
15981 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15982 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15983 ["Edit Formulas" org-edit-special (org-at-table-p)]
15984 "--"
15985 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15986 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15987 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15988 "--"
15989 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15990 "--"
15991 ["Sum Column/Rectangle" org-table-sum
15992 (or (org-at-table-p) (org-region-active-p))]
15993 ["Which Column?" org-table-current-column (org-at-table-p)])
15994 ["Debug Formulas"
15995 org-table-toggle-formula-debugger
15996 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15997 ["Show Col/Row Numbers"
15998 org-table-toggle-coordinate-overlays
15999 :style toggle
16000 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16001 "--"
16002 ["Create" org-table-create (and (not (org-at-table-p))
16003 org-enable-table-editor)]
16004 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16005 ["Import from File" org-table-import (not (org-at-table-p))]
16006 ["Export to File" org-table-export (org-at-table-p)]
16007 "--"
16008 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16010 (easy-menu-define org-org-menu org-mode-map "Org menu"
16011 '("Org"
16012 ("Show/Hide"
16013 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16014 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16015 ["Sparse Tree..." org-sparse-tree t]
16016 ["Reveal Context" org-reveal t]
16017 ["Show All" show-all t]
16018 "--"
16019 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16020 "--"
16021 ["New Heading" org-insert-heading t]
16022 ("Navigate Headings"
16023 ["Up" outline-up-heading t]
16024 ["Next" outline-next-visible-heading t]
16025 ["Previous" outline-previous-visible-heading t]
16026 ["Next Same Level" outline-forward-same-level t]
16027 ["Previous Same Level" outline-backward-same-level t]
16028 "--"
16029 ["Jump" org-goto t])
16030 ("Edit Structure"
16031 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16032 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16033 "--"
16034 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16035 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16036 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16037 "--"
16038 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16039 "--"
16040 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16041 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16042 ["Demote Heading" org-metaright (not (org-at-table-p))]
16043 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16044 "--"
16045 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16046 "--"
16047 ["Convert to odd levels" org-convert-to-odd-levels t]
16048 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16049 ("Editing"
16050 ["Emphasis..." org-emphasize t]
16051 ["Edit Source Example" org-edit-special t]
16052 "--"
16053 ["Footnote new/jump" org-footnote-action t]
16054 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16055 ("Archive"
16056 ["Archive (default method)" org-archive-subtree-default t]
16057 "--"
16058 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16059 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16060 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16062 "--"
16063 ("Hyperlinks"
16064 ["Store Link (Global)" org-store-link t]
16065 ["Find existing link to here" org-occur-link-in-agenda-files t]
16066 ["Insert Link" org-insert-link t]
16067 ["Follow Link" org-open-at-point t]
16068 "--"
16069 ["Next link" org-next-link t]
16070 ["Previous link" org-previous-link t]
16071 "--"
16072 ["Descriptive Links"
16073 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16074 :style radio
16075 :selected (member '(org-link) buffer-invisibility-spec)]
16076 ["Literal Links"
16077 (progn
16078 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16079 :style radio
16080 :selected (not (member '(org-link) buffer-invisibility-spec))])
16081 "--"
16082 ("TODO Lists"
16083 ["TODO/DONE/-" org-todo t]
16084 ("Select keyword"
16085 ["Next keyword" org-shiftright (org-on-heading-p)]
16086 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16087 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16088 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16089 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16090 ["Show TODO Tree" org-show-todo-tree t]
16091 ["Global TODO list" org-todo-list t]
16092 "--"
16093 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16094 :selected org-enforce-todo-dependencies :style toggle :active t]
16095 "Settings for tree at point"
16096 ["Do Children sequentially" org-toggle-ordered-property :style radio
16097 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16098 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16099 ["Do Children parallel" org-toggle-ordered-property :style radio
16100 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16101 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16102 "--"
16103 ["Set Priority" org-priority t]
16104 ["Priority Up" org-shiftup t]
16105 ["Priority Down" org-shiftdown t]
16106 "--"
16107 ["Get news from all feeds" org-feed-update-all t]
16108 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16109 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16110 ("TAGS and Properties"
16111 ["Set Tags" org-set-tags-command t]
16112 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16113 "--"
16114 ["Set property" org-set-property t]
16115 ["Column view of properties" org-columns t]
16116 ["Insert Column View DBlock" org-insert-columns-dblock t])
16117 ("Dates and Scheduling"
16118 ["Timestamp" org-time-stamp t]
16119 ["Timestamp (inactive)" org-time-stamp-inactive t]
16120 ("Change Date"
16121 ["1 Day Later" org-shiftright t]
16122 ["1 Day Earlier" org-shiftleft t]
16123 ["1 ... Later" org-shiftup t]
16124 ["1 ... Earlier" org-shiftdown t])
16125 ["Compute Time Range" org-evaluate-time-range t]
16126 ["Schedule Item" org-schedule t]
16127 ["Deadline" org-deadline t]
16128 "--"
16129 ["Custom time format" org-toggle-time-stamp-overlays
16130 :style radio :selected org-display-custom-times]
16131 "--"
16132 ["Goto Calendar" org-goto-calendar t]
16133 ["Date from Calendar" org-date-from-calendar t]
16134 "--"
16135 ["Start/Restart Timer" org-timer-start t]
16136 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16137 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16138 ["Insert Timer String" org-timer t]
16139 ["Insert Timer Item" org-timer-item t])
16140 ("Logging work"
16141 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16142 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16143 ["Clock out" org-clock-out t]
16144 ["Clock cancel" org-clock-cancel t]
16145 "--"
16146 ["Mark as default task" org-clock-mark-default-task t]
16147 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16148 ["Goto running clock" org-clock-goto t]
16149 "--"
16150 ["Display times" org-clock-display t]
16151 ["Create clock table" org-clock-report t]
16152 "--"
16153 ["Record DONE time"
16154 (progn (setq org-log-done (not org-log-done))
16155 (message "Switching to %s will %s record a timestamp"
16156 (car org-done-keywords)
16157 (if org-log-done "automatically" "not")))
16158 :style toggle :selected org-log-done])
16159 "--"
16160 ["Agenda Command..." org-agenda t]
16161 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16162 ("File List for Agenda")
16163 ("Special views current file"
16164 ["TODO Tree" org-show-todo-tree t]
16165 ["Check Deadlines" org-check-deadlines t]
16166 ["Timeline" org-timeline t]
16167 ["Tags/Property tree" org-match-sparse-tree t])
16168 "--"
16169 ["Export/Publish..." org-export t]
16170 ("LaTeX"
16171 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16172 :selected org-cdlatex-mode]
16173 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16174 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16175 ["Modify math symbol" org-cdlatex-math-modify
16176 (org-inside-LaTeX-fragment-p)]
16177 ["Insert citation" org-reftex-citation t]
16178 "--"
16179 ["Export LaTeX fragments as images"
16180 (if (featurep 'org-exp)
16181 (setq org-export-with-LaTeX-fragments
16182 (not org-export-with-LaTeX-fragments))
16183 (require 'org-exp))
16184 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16185 org-export-with-LaTeX-fragments)]
16186 "--"
16187 ["Template for BEAMER" org-beamer-settings-template t])
16188 "--"
16189 ("MobileOrg"
16190 ["Push Files and Views" org-mobile-push t]
16191 ["Get Captured and Flagged" org-mobile-pull t]
16192 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16193 "--"
16194 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16195 "--"
16196 ("Documentation"
16197 ["Show Version" org-version t]
16198 ["Info Documentation" org-info t])
16199 ("Customize"
16200 ["Browse Org Group" org-customize t]
16201 "--"
16202 ["Expand This Menu" org-create-customize-menu
16203 (fboundp 'customize-menu-create)])
16204 ["Send bug report" org-submit-bug-report t]
16205 "--"
16206 ("Refresh/Reload"
16207 ["Refresh setup current buffer" org-mode-restart t]
16208 ["Reload Org (after update)" org-reload t]
16209 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16212 (defun org-info (&optional node)
16213 "Read documentation for Org-mode in the info system.
16214 With optional NODE, go directly to that node."
16215 (interactive)
16216 (info (format "(org)%s" (or node ""))))
16218 ;;;###autoload
16219 (defun org-submit-bug-report ()
16220 "Submit a bug report on Org-mode via mail.
16222 Don't hesitate to report any problems or inaccurate documentation.
16224 If you don't have setup sending mail from (X)Emacs, please copy the
16225 output buffer into your mail program, as it gives us important
16226 information about your Org-mode version and configuration."
16227 (interactive)
16228 (require 'reporter)
16229 (org-load-modules-maybe)
16230 (org-require-autoloaded-modules)
16231 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16232 (reporter-submit-bug-report
16233 "emacs-orgmode@gnu.org"
16234 (org-version)
16235 (let (list)
16236 (save-window-excursion
16237 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16238 (delete-other-windows)
16239 (erase-buffer)
16240 (insert "You are about to submit a bug report to the Org-mode mailing list.
16242 We would like to add your full Org-mode and Outline configuration to the
16243 bug report. This greatly simplifies the work of the maintainer and
16244 other experts on the mailing list.
16246 HOWEVER, some variables you have customized may contain private
16247 information. The names of customers, colleagues, or friends, might
16248 appear in the form of file names, tags, todo states, or search strings.
16249 If you answer yes to the prompt, you might want to check and remove
16250 such private information before sending the email.")
16251 (add-text-properties (point-min) (point-max) '(face org-warning))
16252 (when (yes-or-no-p "Include your Org-mode configuration ")
16253 (mapatoms
16254 (lambda (v)
16255 (and (boundp v)
16256 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16257 (or (and (symbol-value v)
16258 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16259 (and
16260 (get v 'custom-type) (get v 'standard-value)
16261 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16262 (push v list)))))
16263 (kill-buffer (get-buffer "*Warn about privacy*"))
16264 list))
16265 nil nil
16266 "Remember to cover the basics, that is, what you expected to happen and
16267 what in fact did happen. You don't know how to make a good report? See
16269 http://orgmode.org/manual/Feedback.html#Feedback
16271 Your bug report will be posted to the Org-mode mailing list.
16272 ------------------------------------------------------------------------")
16273 (save-excursion
16274 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16275 (replace-match "\\1Bug: \\3 [\\2]")))))
16278 (defun org-install-agenda-files-menu ()
16279 (let ((bl (buffer-list)))
16280 (save-excursion
16281 (while bl
16282 (set-buffer (pop bl))
16283 (if (org-mode-p) (setq bl nil)))
16284 (when (org-mode-p)
16285 (easy-menu-change
16286 '("Org") "File List for Agenda"
16287 (append
16288 (list
16289 ["Edit File List" (org-edit-agenda-file-list) t]
16290 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16291 ["Remove Current File from List" org-remove-file t]
16292 ["Cycle through agenda files" org-cycle-agenda-files t]
16293 ["Occur in all agenda files" org-occur-in-agenda-files t]
16294 "--")
16295 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16297 ;;;; Documentation
16299 ;;;###autoload
16300 (defun org-require-autoloaded-modules ()
16301 (interactive)
16302 (mapc 'require
16303 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16304 org-docbook org-exp org-html org-icalendar
16305 org-id org-latex
16306 org-publish org-remember org-table
16307 org-timer org-xoxo)))
16309 ;;;###autoload
16310 (defun org-reload (&optional uncompiled)
16311 "Reload all org lisp files.
16312 With prefix arg UNCOMPILED, load the uncompiled versions."
16313 (interactive "P")
16314 (require 'find-func)
16315 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16316 (dir-org (file-name-directory (org-find-library-name "org")))
16317 (dir-org-contrib (ignore-errors
16318 (file-name-directory
16319 (org-find-library-name "org-contribdir"))))
16320 (files
16321 (append (directory-files dir-org t file-re)
16322 (and dir-org-contrib
16323 (directory-files dir-org-contrib t file-re))))
16324 (remove-re (concat (if (featurep 'xemacs)
16325 "org-colview" "org-colview-xemacs")
16326 "\\'")))
16327 (setq files (mapcar 'file-name-sans-extension files))
16328 (setq files (mapcar
16329 (lambda (x) (if (string-match remove-re x) nil x))
16330 files))
16331 (setq files (delq nil files))
16332 (mapc
16333 (lambda (f)
16334 (when (featurep (intern (file-name-nondirectory f)))
16335 (if (and (not uncompiled)
16336 (file-exists-p (concat f ".elc")))
16337 (load (concat f ".elc") nil nil t)
16338 (load (concat f ".el") nil nil t))))
16339 files))
16340 (org-version))
16342 ;;;###autoload
16343 (defun org-customize ()
16344 "Call the customize function with org as argument."
16345 (interactive)
16346 (org-load-modules-maybe)
16347 (org-require-autoloaded-modules)
16348 (customize-browse 'org))
16350 (defun org-create-customize-menu ()
16351 "Create a full customization menu for Org-mode, insert it into the menu."
16352 (interactive)
16353 (org-load-modules-maybe)
16354 (org-require-autoloaded-modules)
16355 (if (fboundp 'customize-menu-create)
16356 (progn
16357 (easy-menu-change
16358 '("Org") "Customize"
16359 `(["Browse Org group" org-customize t]
16360 "--"
16361 ,(customize-menu-create 'org)
16362 ["Set" Custom-set t]
16363 ["Save" Custom-save t]
16364 ["Reset to Current" Custom-reset-current t]
16365 ["Reset to Saved" Custom-reset-saved t]
16366 ["Reset to Standard Settings" Custom-reset-standard t]))
16367 (message "\"Org\"-menu now contains full customization menu"))
16368 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16370 ;;;; Miscellaneous stuff
16372 ;;; Generally useful functions
16374 (defun org-get-at-bol (property)
16375 "Get text property PROPERTY at beginning of line."
16376 (get-text-property (point-at-bol) property))
16378 (defun org-find-text-property-in-string (prop s)
16379 "Return the first non-nil value of property PROP in string S."
16380 (or (get-text-property 0 prop s)
16381 (get-text-property (or (next-single-property-change 0 prop s) 0)
16382 prop s)))
16384 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16385 "Display the given MESSAGE as a warning."
16386 (if (fboundp 'display-warning)
16387 (display-warning 'org message
16388 (if (featurep 'xemacs)
16389 'warning
16390 :warning))
16391 (let ((buf (get-buffer-create "*Org warnings*")))
16392 (with-current-buffer buf
16393 (goto-char (point-max))
16394 (insert "Warning (Org): " message)
16395 (unless (bolp)
16396 (newline)))
16397 (display-buffer buf)
16398 (sit-for 0))))
16400 (defun org-in-commented-line ()
16401 "Is point in a line starting with `#'?"
16402 (equal (char-after (point-at-bol)) ?#))
16404 (defun org-in-verbatim-emphasis ()
16405 (save-match-data
16406 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16408 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16409 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16410 (if (and marker (marker-buffer marker)
16411 (buffer-live-p (marker-buffer marker)))
16412 (progn
16413 (switch-to-buffer (marker-buffer marker))
16414 (if (or (> marker (point-max)) (< marker (point-min)))
16415 (widen))
16416 (goto-char marker)
16417 (org-show-context 'org-goto))
16418 (if bookmark
16419 (bookmark-jump bookmark)
16420 (error "Cannot find location"))))
16422 (defun org-quote-csv-field (s)
16423 "Quote field for inclusion in CSV material."
16424 (if (string-match "[\",]" s)
16425 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16428 (defun org-plist-delete (plist property)
16429 "Delete PROPERTY from PLIST.
16430 This is in contrast to merely setting it to 0."
16431 (let (p)
16432 (while plist
16433 (if (not (eq property (car plist)))
16434 (setq p (plist-put p (car plist) (nth 1 plist))))
16435 (setq plist (cddr plist)))
16438 (defun org-force-self-insert (N)
16439 "Needed to enforce self-insert under remapping."
16440 (interactive "p")
16441 (self-insert-command N))
16443 (defun org-string-width (s)
16444 "Compute width of string, ignoring invisible characters.
16445 This ignores character with invisibility property `org-link', and also
16446 characters with property `org-cwidth', because these will become invisible
16447 upon the next fontification round."
16448 (let (b l)
16449 (when (or (eq t buffer-invisibility-spec)
16450 (assq 'org-link buffer-invisibility-spec))
16451 (while (setq b (text-property-any 0 (length s)
16452 'invisible 'org-link s))
16453 (setq s (concat (substring s 0 b)
16454 (substring s (or (next-single-property-change
16455 b 'invisible s) (length s)))))))
16456 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16457 (setq s (concat (substring s 0 b)
16458 (substring s (or (next-single-property-change
16459 b 'org-cwidth s) (length s))))))
16460 (setq l (string-width s) b -1)
16461 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16462 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16465 (defun org-get-indentation (&optional line)
16466 "Get the indentation of the current line, interpreting tabs.
16467 When LINE is given, assume it represents a line and compute its indentation."
16468 (if line
16469 (if (string-match "^ *" (org-remove-tabs line))
16470 (match-end 0))
16471 (save-excursion
16472 (beginning-of-line 1)
16473 (skip-chars-forward " \t")
16474 (current-column))))
16476 (defun org-remove-tabs (s &optional width)
16477 "Replace tabulators in S with spaces.
16478 Assumes that s is a single line, starting in column 0."
16479 (setq width (or width tab-width))
16480 (while (string-match "\t" s)
16481 (setq s (replace-match
16482 (make-string
16483 (- (* width (/ (+ (match-beginning 0) width) width))
16484 (match-beginning 0)) ?\ )
16485 t t s)))
16488 (defun org-fix-indentation (line ind)
16489 "Fix indentation in LINE.
16490 IND is a cons cell with target and minimum indentation.
16491 If the current indentation in LINE is smaller than the minimum,
16492 leave it alone. If it is larger than ind, set it to the target."
16493 (let* ((l (org-remove-tabs line))
16494 (i (org-get-indentation l))
16495 (i1 (car ind)) (i2 (cdr ind)))
16496 (if (>= i i2) (setq l (substring line i2)))
16497 (if (> i1 0)
16498 (concat (make-string i1 ?\ ) l)
16499 l)))
16501 (defun org-remove-indentation (code &optional n)
16502 "Remove the maximum common indentation from the lines in CODE.
16503 N may optionally be the number of spaces to remove."
16504 (with-temp-buffer
16505 (insert code)
16506 (org-do-remove-indentation n)
16507 (buffer-string)))
16509 (defun org-do-remove-indentation (&optional n)
16510 "Remove the maximum common indentation from the buffer."
16511 (untabify (point-min) (point-max))
16512 (let ((min 10000) re)
16513 (if n
16514 (setq min n)
16515 (goto-char (point-min))
16516 (while (re-search-forward "^ *[^ \n]" nil t)
16517 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16518 (unless (or (= min 0) (= min 10000))
16519 (setq re (format "^ \\{%d\\}" min))
16520 (goto-char (point-min))
16521 (while (re-search-forward re nil t)
16522 (replace-match "")
16523 (end-of-line 1))
16524 min)))
16526 (defun org-fill-template (template alist)
16527 "Find each %key of ALIST in TEMPLATE and replace it."
16528 (let ((case-fold-search nil)
16529 entry key value)
16530 (setq alist (sort (copy-sequence alist)
16531 (lambda (a b) (< (length (car a)) (length (car b))))))
16532 (while (setq entry (pop alist))
16533 (setq template
16534 (replace-regexp-in-string
16535 (concat "%" (regexp-quote (car entry)))
16536 (cdr entry) template t t)))
16537 template))
16539 (defun org-base-buffer (buffer)
16540 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16541 (if (not buffer)
16542 buffer
16543 (or (buffer-base-buffer buffer)
16544 buffer)))
16546 (defun org-trim (s)
16547 "Remove whitespace at beginning and end of string."
16548 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16549 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16552 (defun org-wrap (string &optional width lines)
16553 "Wrap string to either a number of lines, or a width in characters.
16554 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16555 that costs. If there is a word longer than WIDTH, the text is actually
16556 wrapped to the length of that word.
16557 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16558 many lines, whatever width that takes.
16559 The return value is a list of lines, without newlines at the end."
16560 (let* ((words (org-split-string string "[ \t\n]+"))
16561 (maxword (apply 'max (mapcar 'org-string-width words)))
16562 w ll)
16563 (cond (width
16564 (org-do-wrap words (max maxword width)))
16565 (lines
16566 (setq w maxword)
16567 (setq ll (org-do-wrap words maxword))
16568 (if (<= (length ll) lines)
16570 (setq ll words)
16571 (while (> (length ll) lines)
16572 (setq w (1+ w))
16573 (setq ll (org-do-wrap words w)))
16574 ll))
16575 (t (error "Cannot wrap this")))))
16577 (defun org-do-wrap (words width)
16578 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16579 (let (lines line)
16580 (while words
16581 (setq line (pop words))
16582 (while (and words (< (+ (length line) (length (car words))) width))
16583 (setq line (concat line " " (pop words))))
16584 (setq lines (push line lines)))
16585 (nreverse lines)))
16587 (defun org-split-string (string &optional separators)
16588 "Splits STRING into substrings at SEPARATORS.
16589 No empty strings are returned if there are matches at the beginning
16590 and end of string."
16591 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16592 (start 0)
16593 notfirst
16594 (list nil))
16595 (while (and (string-match rexp string
16596 (if (and notfirst
16597 (= start (match-beginning 0))
16598 (< start (length string)))
16599 (1+ start) start))
16600 (< (match-beginning 0) (length string)))
16601 (setq notfirst t)
16602 (or (eq (match-beginning 0) 0)
16603 (and (eq (match-beginning 0) (match-end 0))
16604 (eq (match-beginning 0) start))
16605 (setq list
16606 (cons (substring string start (match-beginning 0))
16607 list)))
16608 (setq start (match-end 0)))
16609 (or (eq start (length string))
16610 (setq list
16611 (cons (substring string start)
16612 list)))
16613 (nreverse list)))
16615 (defun org-quote-vert (s)
16616 "Replace \"|\" with \"\\vert\"."
16617 (while (string-match "|" s)
16618 (setq s (replace-match "\\vert" t t s)))
16621 (defun org-uuidgen-p (s)
16622 "Is S an ID created by UUIDGEN?"
16623 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16625 (defun org-context ()
16626 "Return a list of contexts of the current cursor position.
16627 If several contexts apply, all are returned.
16628 Each context entry is a list with a symbol naming the context, and
16629 two positions indicating start and end of the context. Possible
16630 contexts are:
16632 :headline anywhere in a headline
16633 :headline-stars on the leading stars in a headline
16634 :todo-keyword on a TODO keyword (including DONE) in a headline
16635 :tags on the TAGS in a headline
16636 :priority on the priority cookie in a headline
16637 :item on the first line of a plain list item
16638 :item-bullet on the bullet/number of a plain list item
16639 :checkbox on the checkbox in a plain list item
16640 :table in an org-mode table
16641 :table-special on a special filed in a table
16642 :table-table in a table.el table
16643 :link on a hyperlink
16644 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16645 :target on a <<target>>
16646 :radio-target on a <<<radio-target>>>
16647 :latex-fragment on a LaTeX fragment
16648 :latex-preview on a LaTeX fragment with overlayed preview image
16650 This function expects the position to be visible because it uses font-lock
16651 faces as a help to recognize the following contexts: :table-special, :link,
16652 and :keyword."
16653 (let* ((f (get-text-property (point) 'face))
16654 (faces (if (listp f) f (list f)))
16655 (p (point)) clist o)
16656 ;; First the large context
16657 (cond
16658 ((org-on-heading-p t)
16659 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16660 (when (progn
16661 (beginning-of-line 1)
16662 (looking-at org-todo-line-tags-regexp))
16663 (push (org-point-in-group p 1 :headline-stars) clist)
16664 (push (org-point-in-group p 2 :todo-keyword) clist)
16665 (push (org-point-in-group p 4 :tags) clist))
16666 (goto-char p)
16667 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16668 (if (looking-at "\\[#[A-Z0-9]\\]")
16669 (push (org-point-in-group p 0 :priority) clist)))
16671 ((org-at-item-p)
16672 (push (org-point-in-group p 2 :item-bullet) clist)
16673 (push (list :item (point-at-bol)
16674 (save-excursion (org-end-of-item) (point)))
16675 clist)
16676 (and (org-at-item-checkbox-p)
16677 (push (org-point-in-group p 0 :checkbox) clist)))
16679 ((org-at-table-p)
16680 (push (list :table (org-table-begin) (org-table-end)) clist)
16681 (if (memq 'org-formula faces)
16682 (push (list :table-special
16683 (previous-single-property-change p 'face)
16684 (next-single-property-change p 'face)) clist)))
16685 ((org-at-table-p 'any)
16686 (push (list :table-table) clist)))
16687 (goto-char p)
16689 ;; Now the small context
16690 (cond
16691 ((org-at-timestamp-p)
16692 (push (org-point-in-group p 0 :timestamp) clist))
16693 ((memq 'org-link faces)
16694 (push (list :link
16695 (previous-single-property-change p 'face)
16696 (next-single-property-change p 'face)) clist))
16697 ((memq 'org-special-keyword faces)
16698 (push (list :keyword
16699 (previous-single-property-change p 'face)
16700 (next-single-property-change p 'face)) clist))
16701 ((org-on-target-p)
16702 (push (org-point-in-group p 0 :target) clist)
16703 (goto-char (1- (match-beginning 0)))
16704 (if (looking-at org-radio-target-regexp)
16705 (push (org-point-in-group p 0 :radio-target) clist))
16706 (goto-char p))
16707 ((setq o (car (delq nil
16708 (mapcar
16709 (lambda (x)
16710 (if (memq x org-latex-fragment-image-overlays) x))
16711 (org-overlays-at (point))))))
16712 (push (list :latex-fragment
16713 (org-overlay-start o) (org-overlay-end o)) clist)
16714 (push (list :latex-preview
16715 (org-overlay-start o) (org-overlay-end o)) clist))
16716 ((org-inside-LaTeX-fragment-p)
16717 ;; FIXME: positions wrong.
16718 (push (list :latex-fragment (point) (point)) clist)))
16720 (setq clist (nreverse (delq nil clist)))
16721 clist))
16723 ;; FIXME: Compare with at-regexp-p Do we need both?
16724 (defun org-in-regexp (re &optional nlines visually)
16725 "Check if point is inside a match of regexp.
16726 Normally only the current line is checked, but you can include NLINES extra
16727 lines both before and after point into the search.
16728 If VISUALLY is set, require that the cursor is not after the match but
16729 really on, so that the block visually is on the match."
16730 (catch 'exit
16731 (let ((pos (point))
16732 (eol (point-at-eol (+ 1 (or nlines 0))))
16733 (inc (if visually 1 0)))
16734 (save-excursion
16735 (beginning-of-line (- 1 (or nlines 0)))
16736 (while (re-search-forward re eol t)
16737 (if (and (<= (match-beginning 0) pos)
16738 (>= (+ inc (match-end 0)) pos))
16739 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16741 (defun org-at-regexp-p (regexp)
16742 "Is point inside a match of REGEXP in the current line?"
16743 (catch 'exit
16744 (save-excursion
16745 (let ((pos (point)) (end (point-at-eol)))
16746 (beginning-of-line 1)
16747 (while (re-search-forward regexp end t)
16748 (if (and (<= (match-beginning 0) pos)
16749 (>= (match-end 0) pos))
16750 (throw 'exit t)))
16751 nil))))
16753 (defun org-occur-in-agenda-files (regexp &optional nlines)
16754 "Call `multi-occur' with buffers for all agenda files."
16755 (interactive "sOrg-files matching: \np")
16756 (let* ((files (org-agenda-files))
16757 (tnames (mapcar 'file-truename files))
16758 (extra org-agenda-text-search-extra-files)
16760 (when (eq (car extra) 'agenda-archives)
16761 (setq extra (cdr extra))
16762 (setq files (org-add-archive-files files)))
16763 (while (setq f (pop extra))
16764 (unless (member (file-truename f) tnames)
16765 (add-to-list 'files f 'append)
16766 (add-to-list 'tnames (file-truename f) 'append)))
16767 (multi-occur
16768 (mapcar (lambda (x)
16769 (with-current-buffer
16770 (or (get-file-buffer x) (find-file-noselect x))
16771 (widen)
16772 (current-buffer)))
16773 files)
16774 regexp)))
16776 (if (boundp 'occur-mode-find-occurrence-hook)
16777 ;; Emacs 23
16778 (add-hook 'occur-mode-find-occurrence-hook
16779 (lambda ()
16780 (when (org-mode-p)
16781 (org-reveal))))
16782 ;; Emacs 22
16783 (defadvice occur-mode-goto-occurrence
16784 (after org-occur-reveal activate)
16785 (and (org-mode-p) (org-reveal)))
16786 (defadvice occur-mode-goto-occurrence-other-window
16787 (after org-occur-reveal activate)
16788 (and (org-mode-p) (org-reveal)))
16789 (defadvice occur-mode-display-occurrence
16790 (after org-occur-reveal activate)
16791 (when (org-mode-p)
16792 (let ((pos (occur-mode-find-occurrence)))
16793 (with-current-buffer (marker-buffer pos)
16794 (save-excursion
16795 (goto-char pos)
16796 (org-reveal)))))))
16798 (defun org-occur-link-in-agenda-files ()
16799 "Create a link and search for it in the agendas.
16800 The link is not stored in `org-stored-links', it is just created
16801 for the search purpose."
16802 (interactive)
16803 (let ((link (condition-case nil
16804 (org-store-link nil)
16805 (error "Unable to create a link to here"))))
16806 (org-occur-in-agenda-files (regexp-quote link))))
16808 (defun org-uniquify (list)
16809 "Remove duplicate elements from LIST."
16810 (let (res)
16811 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16812 res))
16814 (defun org-delete-all (elts list)
16815 "Remove all elements in ELTS from LIST."
16816 (while elts
16817 (setq list (delete (pop elts) list)))
16818 list)
16820 (defun org-back-over-empty-lines ()
16821 "Move backwards over whitespace, to the beginning of the first empty line.
16822 Returns the number of empty lines passed."
16823 (let ((pos (point)))
16824 (skip-chars-backward " \t\n\r")
16825 (beginning-of-line 2)
16826 (goto-char (min (point) pos))
16827 (count-lines (point) pos)))
16829 (defun org-skip-whitespace ()
16830 (skip-chars-forward " \t\n\r"))
16832 (defun org-point-in-group (point group &optional context)
16833 "Check if POINT is in match-group GROUP.
16834 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16835 match. If the match group does ot exist or point is not inside it,
16836 return nil."
16837 (and (match-beginning group)
16838 (>= point (match-beginning group))
16839 (<= point (match-end group))
16840 (if context
16841 (list context (match-beginning group) (match-end group))
16842 t)))
16844 (defun org-switch-to-buffer-other-window (&rest args)
16845 "Switch to buffer in a second window on the current frame.
16846 In particular, do not allow pop-up frames."
16847 (let (pop-up-frames special-display-buffer-names special-display-regexps
16848 special-display-function)
16849 (apply 'switch-to-buffer-other-window args)))
16851 (defun org-combine-plists (&rest plists)
16852 "Create a single property list from all plists in PLISTS.
16853 The process starts by copying the first list, and then setting properties
16854 from the other lists. Settings in the last list are the most significant
16855 ones and overrule settings in the other lists."
16856 (let ((rtn (copy-sequence (pop plists)))
16857 p v ls)
16858 (while plists
16859 (setq ls (pop plists))
16860 (while ls
16861 (setq p (pop ls) v (pop ls))
16862 (setq rtn (plist-put rtn p v))))
16863 rtn))
16865 (defun org-move-line-down (arg)
16866 "Move the current line down. With prefix argument, move it past ARG lines."
16867 (interactive "p")
16868 (let ((col (current-column))
16869 beg end pos)
16870 (beginning-of-line 1) (setq beg (point))
16871 (beginning-of-line 2) (setq end (point))
16872 (beginning-of-line (+ 1 arg))
16873 (setq pos (move-marker (make-marker) (point)))
16874 (insert (delete-and-extract-region beg end))
16875 (goto-char pos)
16876 (org-move-to-column col)))
16878 (defun org-move-line-up (arg)
16879 "Move the current line up. With prefix argument, move it past ARG lines."
16880 (interactive "p")
16881 (let ((col (current-column))
16882 beg end pos)
16883 (beginning-of-line 1) (setq beg (point))
16884 (beginning-of-line 2) (setq end (point))
16885 (beginning-of-line (- arg))
16886 (setq pos (move-marker (make-marker) (point)))
16887 (insert (delete-and-extract-region beg end))
16888 (goto-char pos)
16889 (org-move-to-column col)))
16891 (defun org-replace-escapes (string table)
16892 "Replace %-escapes in STRING with values in TABLE.
16893 TABLE is an association list with keys like \"%a\" and string values.
16894 The sequences in STRING may contain normal field width and padding information,
16895 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16896 so values can contain further %-escapes if they are define later in TABLE."
16897 (let ((case-fold-search nil)
16898 e re rpl)
16899 (while (setq e (pop table))
16900 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16901 (while (string-match re string)
16902 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16903 (cdr e)))
16904 (setq string (replace-match rpl t t string))))
16905 string))
16908 (defun org-sublist (list start end)
16909 "Return a section of LIST, from START to END.
16910 Counting starts at 1."
16911 (let (rtn (c start))
16912 (setq list (nthcdr (1- start) list))
16913 (while (and list (<= c end))
16914 (push (pop list) rtn)
16915 (setq c (1+ c)))
16916 (nreverse rtn)))
16918 (defun org-find-base-buffer-visiting (file)
16919 "Like `find-buffer-visiting' but always return the base buffer and
16920 not an indirect buffer."
16921 (let ((buf (or (get-file-buffer file)
16922 (find-buffer-visiting file))))
16923 (if buf
16924 (or (buffer-base-buffer buf) buf)
16925 nil)))
16927 (defun org-image-file-name-regexp (&optional extensions)
16928 "Return regexp matching the file names of images.
16929 If EXTENSIONS is given, only match these."
16930 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16931 (image-file-name-regexp)
16932 (let ((image-file-name-extensions
16933 (or extensions
16934 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16935 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16936 (concat "\\."
16937 (regexp-opt (nconc (mapcar 'upcase
16938 image-file-name-extensions)
16939 image-file-name-extensions)
16941 "\\'"))))
16943 (defun org-file-image-p (file &optional extensions)
16944 "Return non-nil if FILE is an image."
16945 (save-match-data
16946 (string-match (org-image-file-name-regexp extensions) file)))
16948 (defun org-get-cursor-date ()
16949 "Return the date at cursor in as a time.
16950 This works in the calendar and in the agenda, anywhere else it just
16951 returns the current time."
16952 (let (date day defd)
16953 (cond
16954 ((eq major-mode 'calendar-mode)
16955 (setq date (calendar-cursor-to-date)
16956 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16957 ((eq major-mode 'org-agenda-mode)
16958 (setq day (get-text-property (point) 'day))
16959 (if day
16960 (setq date (calendar-gregorian-from-absolute day)
16961 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16962 (nth 2 date))))))
16963 (or defd (current-time))))
16965 (defvar org-agenda-action-marker (make-marker)
16966 "Marker pointing to the entry for the next agenda action.")
16968 (defun org-mark-entry-for-agenda-action ()
16969 "Mark the current entry as target of an agenda action.
16970 Agenda actions are actions executed from the agenda with the key `k',
16971 which make use of the date at the cursor."
16972 (interactive)
16973 (move-marker org-agenda-action-marker
16974 (save-excursion (org-back-to-heading t) (point))
16975 (current-buffer))
16976 (message
16977 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16979 ;;; Paragraph filling stuff.
16980 ;; We want this to be just right, so use the full arsenal.
16982 (defun org-indent-line-function ()
16983 "Indent line like previous, but further if previous was headline or item."
16984 (interactive)
16985 (let* ((pos (point))
16986 (itemp (org-at-item-p))
16987 (case-fold-search t)
16988 (org-drawer-regexp (or org-drawer-regexp "\000"))
16989 column bpos bcol tpos tcol bullet btype bullet-type)
16990 ;; Find the previous relevant line
16991 (beginning-of-line 1)
16992 (cond
16993 ((looking-at "#") (setq column 0))
16994 ((looking-at "\\*+ ") (setq column 0))
16995 ((and (looking-at "[ \t]*:END:")
16996 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16997 (save-excursion
16998 (goto-char (1- (match-beginning 1)))
16999 (setq column (current-column))))
17000 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17001 (save-excursion
17002 (re-search-backward
17003 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17004 (setq column (org-get-indentation (match-string 0))))
17006 (beginning-of-line 0)
17007 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17008 (not (looking-at "[ \t]*:END:"))
17009 (not (looking-at org-drawer-regexp)))
17010 (beginning-of-line 0))
17011 (cond
17012 ((looking-at "\\*+[ \t]+")
17013 (if (not org-adapt-indentation)
17014 (setq column 0)
17015 (goto-char (match-end 0))
17016 (setq column (current-column))))
17017 ((looking-at org-drawer-regexp)
17018 (goto-char (1- (match-beginning 1)))
17019 (setq column (current-column)))
17020 ((looking-at "\\([ \t]*\\):END:")
17021 (goto-char (match-end 1))
17022 (setq column (current-column)))
17023 ((org-in-item-p)
17024 (org-beginning-of-item)
17025 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17026 (setq bpos (match-beginning 1) tpos (match-end 0)
17027 bcol (progn (goto-char bpos) (current-column))
17028 tcol (progn (goto-char tpos) (current-column))
17029 bullet (match-string 1)
17030 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17031 (if (> tcol (+ bcol org-description-max-indent))
17032 (setq tcol (+ bcol 5)))
17033 (if (not itemp)
17034 (setq column tcol)
17035 (goto-char pos)
17036 (beginning-of-line 1)
17037 (if (looking-at "\\S-")
17038 (progn
17039 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17040 (setq bullet (match-string 1)
17041 btype (if (string-match "[0-9]" bullet) "n" bullet))
17042 (setq column (if (equal btype bullet-type) bcol tcol)))
17043 (setq column (org-get-indentation)))))
17044 (t (setq column (org-get-indentation))))))
17045 (goto-char pos)
17046 (if (<= (current-column) (current-indentation))
17047 (org-indent-line-to column)
17048 (save-excursion (org-indent-line-to column)))
17049 (setq column (current-column))
17050 (beginning-of-line 1)
17051 (if (looking-at
17052 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17053 (replace-match (concat (match-string 1)
17054 (format org-property-format
17055 (match-string 2) (match-string 3)))
17056 t t))
17057 (org-move-to-column column)))
17059 (defun org-set-autofill-regexps ()
17060 (interactive)
17061 ;; In the paragraph separator we include headlines, because filling
17062 ;; text in a line directly attached to a headline would otherwise
17063 ;; fill the headline as well.
17064 (org-set-local 'comment-start-skip "^#+[ \t]*")
17065 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17066 ;; The paragraph starter includes hand-formatted lists.
17067 (org-set-local
17068 'paragraph-start
17069 (concat
17070 "\f" "\\|"
17071 "[ ]*$" "\\|"
17072 "\\*+ " "\\|"
17073 "[ \t]*#" "\\|"
17074 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17075 "[ \t]*[:|]" "\\|"
17076 "\\$\\$" "\\|"
17077 "\\\\\\(begin\\|end\\|[][]\\)"))
17078 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17079 ;; But only if the user has not turned off tables or fixed-width regions
17080 (org-set-local
17081 'auto-fill-inhibit-regexp
17082 (concat "\\*+ \\|#\\+"
17083 "\\|[ \t]*" org-keyword-time-regexp
17084 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17085 (concat
17086 "\\|[ \t]*["
17087 (if org-enable-table-editor "|" "")
17088 (if org-enable-fixed-width-editor ":" "")
17089 "]"))))
17090 ;; We use our own fill-paragraph function, to make sure that tables
17091 ;; and fixed-width regions are not wrapped. That function will pass
17092 ;; through to `fill-paragraph' when appropriate.
17093 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17094 ; Adaptive filling: To get full control, first make sure that
17095 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17096 (org-set-local 'adaptive-fill-regexp "\000")
17097 (org-set-local 'adaptive-fill-function
17098 'org-adaptive-fill-function)
17099 (org-set-local
17100 'align-mode-rules-list
17101 '((org-in-buffer-settings
17102 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17103 (modes . '(org-mode))))))
17105 (defun org-fill-paragraph (&optional justify)
17106 "Re-align a table, pass through to fill-paragraph if no table."
17107 (let ((table-p (org-at-table-p))
17108 (table.el-p (org-at-table.el-p)))
17109 (cond ((and (equal (char-after (point-at-bol)) ?*)
17110 (save-excursion (goto-char (point-at-bol))
17111 (looking-at outline-regexp)))
17112 t) ; skip headlines
17113 (table.el-p t) ; skip table.el tables
17114 (table-p (org-table-align) t) ; align org-mode tables
17115 (t nil)))) ; call paragraph-fill
17117 ;; For reference, this is the default value of adaptive-fill-regexp
17118 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17120 (defun org-adaptive-fill-function ()
17121 "Return a fill prefix for org-mode files.
17122 In particular, this makes sure hanging paragraphs for hand-formatted lists
17123 work correctly."
17124 (cond ((looking-at "#[ \t]+")
17125 (match-string 0))
17126 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17127 (save-excursion
17128 (if (> (match-end 1) (+ (match-beginning 1)
17129 org-description-max-indent))
17130 (goto-char (+ (match-beginning 1) 5))
17131 (goto-char (match-end 0)))
17132 (make-string (current-column) ?\ )))
17133 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17134 (save-excursion
17135 (goto-char (match-end 0))
17136 (make-string (current-column) ?\ )))
17137 (t nil)))
17139 ;;; Other stuff.
17141 (defun org-toggle-fixed-width-section (arg)
17142 "Toggle the fixed-width export.
17143 If there is no active region, the QUOTE keyword at the current headline is
17144 inserted or removed. When present, it causes the text between this headline
17145 and the next to be exported as fixed-width text, and unmodified.
17146 If there is an active region, this command adds or removes a colon as the
17147 first character of this line. If the first character of a line is a colon,
17148 this line is also exported in fixed-width font."
17149 (interactive "P")
17150 (let* ((cc 0)
17151 (regionp (org-region-active-p))
17152 (beg (if regionp (region-beginning) (point)))
17153 (end (if regionp (region-end)))
17154 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17155 (case-fold-search nil)
17156 (re "[ \t]*\\(: \\)")
17157 off)
17158 (if regionp
17159 (save-excursion
17160 (goto-char beg)
17161 (setq cc (current-column))
17162 (beginning-of-line 1)
17163 (setq off (looking-at re))
17164 (while (> nlines 0)
17165 (setq nlines (1- nlines))
17166 (beginning-of-line 1)
17167 (cond
17168 (arg
17169 (org-move-to-column cc t)
17170 (insert ": \n")
17171 (forward-line -1))
17172 ((and off (looking-at re))
17173 (replace-match "" t t nil 1))
17174 ((not off) (org-move-to-column cc t) (insert ": ")))
17175 (forward-line 1)))
17176 (save-excursion
17177 (org-back-to-heading)
17178 (if (looking-at (concat outline-regexp
17179 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17180 (replace-match "" t t nil 1)
17181 (if (looking-at outline-regexp)
17182 (progn
17183 (goto-char (match-end 0))
17184 (insert org-quote-string " "))))))))
17186 (defun org-reftex-citation ()
17187 "Use reftex-citation to insert a citation into the buffer.
17188 This looks for a line like
17190 #+BIBLIOGRAPHY: foo plain option:-d
17192 and derives from it that foo.bib is the bibliography file relevant
17193 for this document. It then installs the necessary environment for RefTeX
17194 to work in this buffer and calls `reftex-citation' to insert a citation
17195 into the buffer.
17197 Export of such citations to both LaTeX and HTML is handled by the contributed
17198 package org-exp-bibtex by Taru Karttunen."
17199 (interactive)
17200 (let ((reftex-docstruct-symbol 'rds)
17201 (reftex-cite-format "\\cite{%l}")
17202 rds bib)
17203 (save-excursion
17204 (save-restriction
17205 (widen)
17206 (let ((case-fold-search t)
17207 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17208 (if (not (save-excursion
17209 (or (re-search-forward re nil t)
17210 (re-search-backward re nil t))))
17211 (error "No bibliography defined in file")
17212 (setq bib (concat (match-string 1) ".bib")
17213 rds (list (list 'bib bib)))))))
17214 (call-interactively 'reftex-citation)))
17216 ;;;; Functions extending outline functionality
17218 (defun org-beginning-of-line (&optional arg)
17219 "Go to the beginning of the current line. If that is invisible, continue
17220 to a visible line beginning. This makes the function of C-a more intuitive.
17221 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17222 first attempt, and only move to after the tags when the cursor is already
17223 beyond the end of the headline."
17224 (interactive "P")
17225 (let ((pos (point))
17226 (special (if (consp org-special-ctrl-a/e)
17227 (car org-special-ctrl-a/e)
17228 org-special-ctrl-a/e))
17229 refpos)
17230 (if (org-bound-and-true-p line-move-visual)
17231 (beginning-of-visual-line 1)
17232 (beginning-of-line 1))
17233 (if (and arg (fboundp 'move-beginning-of-line))
17234 (call-interactively 'move-beginning-of-line)
17235 (if (bobp)
17237 (backward-char 1)
17238 (if (org-invisible-p)
17239 (while (and (not (bobp)) (org-invisible-p))
17240 (backward-char 1)
17241 (beginning-of-line 1))
17242 (forward-char 1))))
17243 (when special
17244 (cond
17245 ((and (looking-at org-complex-heading-regexp)
17246 (= (char-after (match-end 1)) ?\ ))
17247 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17248 (point-at-eol)))
17249 (goto-char
17250 (if (eq special t)
17251 (cond ((> pos refpos) refpos)
17252 ((= pos (point)) refpos)
17253 (t (point)))
17254 (cond ((> pos (point)) (point))
17255 ((not (eq last-command this-command)) (point))
17256 (t refpos)))))
17257 ((org-at-item-p)
17258 (goto-char
17259 (if (eq special t)
17260 (cond ((> pos (match-end 4)) (match-end 4))
17261 ((= pos (point)) (match-end 4))
17262 (t (point)))
17263 (cond ((> pos (point)) (point))
17264 ((not (eq last-command this-command)) (point))
17265 (t (match-end 4))))))))
17266 (org-no-warnings
17267 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17269 (defun org-end-of-line (&optional arg)
17270 "Go to the end of the line.
17271 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17272 first attempt, and only move to after the tags when the cursor is already
17273 beyond the end of the headline."
17274 (interactive "P")
17275 (let ((special (if (consp org-special-ctrl-a/e)
17276 (cdr org-special-ctrl-a/e)
17277 org-special-ctrl-a/e)))
17278 (if (or (not special)
17279 (not (org-on-heading-p))
17280 arg)
17281 (call-interactively
17282 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17283 ((fboundp 'move-end-of-line) 'move-end-of-line)
17284 (t 'end-of-line)))
17285 (let ((pos (point)))
17286 (beginning-of-line 1)
17287 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17288 (if (eq special t)
17289 (if (or (< pos (match-beginning 1))
17290 (= pos (match-end 0)))
17291 (goto-char (match-beginning 1))
17292 (goto-char (match-end 0)))
17293 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17294 (goto-char (match-end 0))
17295 (goto-char (match-beginning 1))))
17296 (call-interactively (if (fboundp 'move-end-of-line)
17297 'move-end-of-line
17298 'end-of-line)))))
17299 (org-no-warnings
17300 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17302 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17303 (define-key org-mode-map "\C-e" 'org-end-of-line)
17304 (define-key org-mode-map [home] 'org-beginning-of-line)
17305 (define-key org-mode-map [end] 'org-end-of-line)
17307 (defun org-backward-sentence (&optional arg)
17308 "Go to beginning of sentence, or beginning of table field.
17309 This will call `backward-sentence' or `org-table-beginning-of-field',
17310 depending on context."
17311 (interactive "P")
17312 (cond
17313 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17314 (t (call-interactively 'backward-sentence))))
17316 (defun org-forward-sentence (&optional arg)
17317 "Go to end of sentence, or end of table field.
17318 This will call `forward-sentence' or `org-table-end-of-field',
17319 depending on context."
17320 (interactive "P")
17321 (cond
17322 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17323 (t (call-interactively 'forward-sentence))))
17325 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17326 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17328 (defun org-kill-line (&optional arg)
17329 "Kill line, to tags or end of line."
17330 (interactive "P")
17331 (cond
17332 ((or (not org-special-ctrl-k)
17333 (bolp)
17334 (not (org-on-heading-p)))
17335 (call-interactively 'kill-line))
17336 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17337 (kill-region (point) (match-beginning 1))
17338 (org-set-tags nil t))
17339 (t (kill-region (point) (point-at-eol)))))
17341 (define-key org-mode-map "\C-k" 'org-kill-line)
17343 (defun org-yank (&optional arg)
17344 "Yank. If the kill is a subtree, treat it specially.
17345 This command will look at the current kill and check if is a single
17346 subtree, or a series of subtrees[1]. If it passes the test, and if the
17347 cursor is at the beginning of a line or after the stars of a currently
17348 empty headline, then the yank is handled specially. How exactly depends
17349 on the value of the following variables, both set by default.
17351 org-yank-folded-subtrees
17352 When set, the subtree(s) will be folded after insertion, but only
17353 if doing so would now swallow text after the yanked text.
17355 org-yank-adjusted-subtrees
17356 When set, the subtree will be promoted or demoted in order to
17357 fit into the local outline tree structure, which means that the level
17358 will be adjusted so that it becomes the smaller one of the two
17359 *visible* surrounding headings.
17361 Any prefix to this command will cause `yank' to be called directly with
17362 no special treatment. In particular, a simple `C-u' prefix will just
17363 plainly yank the text as it is.
17365 \[1] The test checks if the first non-white line is a heading
17366 and if there are no other headings with fewer stars."
17367 (interactive "P")
17368 (org-yank-generic 'yank arg))
17370 (defun org-yank-generic (command arg)
17371 "Perform some yank-like command.
17373 This function implements the behavior described in the `org-yank'
17374 documentation. However, it has been generalized to work for any
17375 interactive command with similar behavior."
17377 ;; pretend to be command COMMAND
17378 (setq this-command command)
17380 (if arg
17381 (call-interactively command)
17383 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17384 (and (org-kill-is-subtree-p)
17385 (or (bolp)
17386 (and (looking-at "[ \t]*$")
17387 (string-match
17388 "\\`\\*+\\'"
17389 (buffer-substring (point-at-bol) (point)))))))
17390 swallowp)
17391 (cond
17392 ((and subtreep org-yank-folded-subtrees)
17393 (let ((beg (point))
17394 end)
17395 (if (and subtreep org-yank-adjusted-subtrees)
17396 (org-paste-subtree nil nil 'for-yank)
17397 (call-interactively command))
17399 (setq end (point))
17400 (goto-char beg)
17401 (when (and (bolp) subtreep
17402 (not (setq swallowp
17403 (org-yank-folding-would-swallow-text beg end))))
17404 (or (looking-at outline-regexp)
17405 (re-search-forward (concat "^" outline-regexp) end t))
17406 (while (and (< (point) end) (looking-at outline-regexp))
17407 (hide-subtree)
17408 (org-cycle-show-empty-lines 'folded)
17409 (condition-case nil
17410 (outline-forward-same-level 1)
17411 (error (goto-char end)))))
17412 (when swallowp
17413 (message
17414 "Inserted text not folded because that would swallow text"))
17416 (goto-char end)
17417 (skip-chars-forward " \t\n\r")
17418 (beginning-of-line 1)
17419 (push-mark beg 'nomsg)))
17420 ((and subtreep org-yank-adjusted-subtrees)
17421 (let ((beg (point-at-bol)))
17422 (org-paste-subtree nil nil 'for-yank)
17423 (push-mark beg 'nomsg)))
17425 (call-interactively command))))))
17427 (defun org-yank-folding-would-swallow-text (beg end)
17428 "Would hide-subtree at BEG swallow any text after END?"
17429 (let (level)
17430 (save-excursion
17431 (goto-char beg)
17432 (when (or (looking-at outline-regexp)
17433 (re-search-forward (concat "^" outline-regexp) end t))
17434 (setq level (org-outline-level)))
17435 (goto-char end)
17436 (skip-chars-forward " \t\r\n\v\f")
17437 (if (or (eobp)
17438 (and (bolp) (looking-at org-outline-regexp)
17439 (<= (org-outline-level) level)))
17440 nil ; Nothing would be swallowed
17441 t)))) ; something would swallow
17443 (define-key org-mode-map "\C-y" 'org-yank)
17445 (defun org-invisible-p ()
17446 "Check if point is at a character currently not visible."
17447 ;; Early versions of noutline don't have `outline-invisible-p'.
17448 (if (fboundp 'outline-invisible-p)
17449 (outline-invisible-p)
17450 (get-char-property (point) 'invisible)))
17452 (defun org-invisible-p2 ()
17453 "Check if point is at a character currently not visible."
17454 (save-excursion
17455 (if (and (eolp) (not (bobp))) (backward-char 1))
17456 ;; Early versions of noutline don't have `outline-invisible-p'.
17457 (if (fboundp 'outline-invisible-p)
17458 (outline-invisible-p)
17459 (get-char-property (point) 'invisible))))
17461 (defun org-back-to-heading (&optional invisible-ok)
17462 "Call `outline-back-to-heading', but provide a better error message."
17463 (condition-case nil
17464 (outline-back-to-heading invisible-ok)
17465 (error (error "Before first headline at position %d in buffer %s"
17466 (point) (current-buffer)))))
17468 (defun org-before-first-heading-p ()
17469 "Before first heading?"
17470 (save-excursion
17471 (null (re-search-backward "^\\*+ " nil t))))
17473 (defun org-on-heading-p (&optional ignored)
17474 (outline-on-heading-p t))
17475 (defun org-at-heading-p (&optional ignored)
17476 (outline-on-heading-p t))
17478 (defun org-at-heading-or-item-p ()
17479 (or (org-on-heading-p) (org-at-item-p)))
17481 (defun org-on-target-p ()
17482 (or (org-in-regexp org-radio-target-regexp)
17483 (org-in-regexp org-target-regexp)))
17485 (defun org-up-heading-all (arg)
17486 "Move to the heading line of which the present line is a subheading.
17487 This function considers both visible and invisible heading lines.
17488 With argument, move up ARG levels."
17489 (if (fboundp 'outline-up-heading-all)
17490 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17491 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17493 (defun org-up-heading-safe ()
17494 "Move to the heading line of which the present line is a subheading.
17495 This version will not throw an error. It will return the level of the
17496 headline found, or nil if no higher level is found.
17498 Also, this function will be a lot faster than `outline-up-heading',
17499 because it relies on stars being the outline starters. This can really
17500 make a significant difference in outlines with very many siblings."
17501 (let (start-level re)
17502 (org-back-to-heading t)
17503 (setq start-level (funcall outline-level))
17504 (if (equal start-level 1)
17506 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17507 (if (re-search-backward re nil t)
17508 (funcall outline-level)))))
17510 (defun org-first-sibling-p ()
17511 "Is this heading the first child of its parents?"
17512 (interactive)
17513 (let ((re (concat "^" outline-regexp))
17514 level l)
17515 (unless (org-at-heading-p t)
17516 (error "Not at a heading"))
17517 (setq level (funcall outline-level))
17518 (save-excursion
17519 (if (not (re-search-backward re nil t))
17521 (setq l (funcall outline-level))
17522 (< l level)))))
17524 (defun org-goto-sibling (&optional previous)
17525 "Goto the next sibling, even if it is invisible.
17526 When PREVIOUS is set, go to the previous sibling instead. Returns t
17527 when a sibling was found. When none is found, return nil and don't
17528 move point."
17529 (let ((fun (if previous 're-search-backward 're-search-forward))
17530 (pos (point))
17531 (re (concat "^" outline-regexp))
17532 level l)
17533 (when (condition-case nil (org-back-to-heading t) (error nil))
17534 (setq level (funcall outline-level))
17535 (catch 'exit
17536 (or previous (forward-char 1))
17537 (while (funcall fun re nil t)
17538 (setq l (funcall outline-level))
17539 (when (< l level) (goto-char pos) (throw 'exit nil))
17540 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17541 (goto-char pos)
17542 nil))))
17544 (defun org-show-siblings ()
17545 "Show all siblings of the current headline."
17546 (save-excursion
17547 (while (org-goto-sibling) (org-flag-heading nil)))
17548 (save-excursion
17549 (while (org-goto-sibling 'previous)
17550 (org-flag-heading nil))))
17552 (defun org-show-hidden-entry ()
17553 "Show an entry where even the heading is hidden."
17554 (save-excursion
17555 (org-show-entry)))
17557 (defun org-flag-heading (flag &optional entry)
17558 "Flag the current heading. FLAG non-nil means make invisible.
17559 When ENTRY is non-nil, show the entire entry."
17560 (save-excursion
17561 (org-back-to-heading t)
17562 ;; Check if we should show the entire entry
17563 (if entry
17564 (progn
17565 (org-show-entry)
17566 (save-excursion
17567 (and (outline-next-heading)
17568 (org-flag-heading nil))))
17569 (outline-flag-region (max (point-min) (1- (point)))
17570 (save-excursion (outline-end-of-heading) (point))
17571 flag))))
17573 (defun org-get-next-sibling ()
17574 "Move to next heading of the same level, and return point.
17575 If there is no such heading, return nil.
17576 This is like outline-next-sibling, but invisible headings are ok."
17577 (let ((level (funcall outline-level)))
17578 (outline-next-heading)
17579 (while (and (not (eobp)) (> (funcall outline-level) level))
17580 (outline-next-heading))
17581 (if (or (eobp) (< (funcall outline-level) level))
17583 (point))))
17585 (defun org-get-last-sibling ()
17586 "Move to previous heading of the same level, and return point.
17587 If there is no such heading, return nil."
17588 (let ((opoint (point))
17589 (level (funcall outline-level)))
17590 (outline-previous-heading)
17591 (when (and (/= (point) opoint) (outline-on-heading-p t))
17592 (while (and (> (funcall outline-level) level)
17593 (not (bobp)))
17594 (outline-previous-heading))
17595 (if (< (funcall outline-level) level)
17597 (point)))))
17599 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17600 ;; This contains an exact copy of the original function, but it uses
17601 ;; `org-back-to-heading', to make it work also in invisible
17602 ;; trees. And is uses an invisible-OK argument.
17603 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17604 ;; Furthermore, when used inside Org, finding the end of a large subtree
17605 ;; with many children and grandchildren etc, this can be much faster
17606 ;; than the outline version.
17607 (org-back-to-heading invisible-OK)
17608 (let ((first t)
17609 (level (funcall outline-level)))
17610 (if (and (org-mode-p) (< level 1000))
17611 ;; A true heading (not a plain list item), in Org-mode
17612 ;; This means we can easily find the end by looking
17613 ;; only for the right number of stars. Using a regexp to do
17614 ;; this is so much faster than using a Lisp loop.
17615 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17616 (forward-char 1)
17617 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17618 ;; something else, do it the slow way
17619 (while (and (not (eobp))
17620 (or first (> (funcall outline-level) level)))
17621 (setq first nil)
17622 (outline-next-heading)))
17623 (unless to-heading
17624 (if (memq (preceding-char) '(?\n ?\^M))
17625 (progn
17626 ;; Go to end of line before heading
17627 (forward-char -1)
17628 (if (memq (preceding-char) '(?\n ?\^M))
17629 ;; leave blank line before heading
17630 (forward-char -1))))))
17631 (point))
17633 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17634 "Use Org version in org-mode, for dramatic speed-up."
17635 (if (eq major-mode 'org-mode)
17636 (progn
17637 (org-end-of-subtree nil t)
17638 (unless (eobp) (backward-char 1)))
17639 ad-do-it))
17641 (defun org-forward-same-level (arg &optional invisible-ok)
17642 "Move forward to the arg'th subheading at same level as this one.
17643 Stop at the first and last subheadings of a superior heading."
17644 (interactive "p")
17645 (org-back-to-heading invisible-ok)
17646 (org-on-heading-p)
17647 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17648 (re (format "^\\*\\{1,%d\\} " level))
17650 (forward-char 1)
17651 (while (> arg 0)
17652 (while (and (re-search-forward re nil 'move)
17653 (setq l (- (match-end 0) (match-beginning 0) 1))
17654 (= l level)
17655 (not invisible-ok)
17656 (progn (backward-char 1) (org-invisible-p)))
17657 (if (< l level) (setq arg 1)))
17658 (setq arg (1- arg)))
17659 (beginning-of-line 1)))
17661 (defun org-backward-same-level (arg &optional invisible-ok)
17662 "Move backward to the arg'th subheading at same level as this one.
17663 Stop at the first and last subheadings of a superior heading."
17664 (interactive "p")
17665 (org-back-to-heading)
17666 (org-on-heading-p)
17667 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17668 (re (format "^\\*\\{1,%d\\} " level))
17670 (while (> arg 0)
17671 (while (and (re-search-backward re nil 'move)
17672 (setq l (- (match-end 0) (match-beginning 0) 1))
17673 (= l level)
17674 (not invisible-ok)
17675 (org-invisible-p))
17676 (if (< l level) (setq arg 1)))
17677 (setq arg (1- arg)))))
17679 (defun org-show-subtree ()
17680 "Show everything after this heading at deeper levels."
17681 (outline-flag-region
17682 (point)
17683 (save-excursion
17684 (org-end-of-subtree t t))
17685 nil))
17687 (defun org-show-entry ()
17688 "Show the body directly following this heading.
17689 Show the heading too, if it is currently invisible."
17690 (interactive)
17691 (save-excursion
17692 (condition-case nil
17693 (progn
17694 (org-back-to-heading t)
17695 (outline-flag-region
17696 (max (point-min) (1- (point)))
17697 (save-excursion
17698 (if (re-search-forward
17699 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17700 (match-beginning 1)
17701 (point-max)))
17702 nil)
17703 (org-cycle-hide-drawers 'children))
17704 (error nil))))
17706 (defun org-make-options-regexp (kwds &optional extra)
17707 "Make a regular expression for keyword lines."
17708 (concat
17710 "#?[ \t]*\\+\\("
17711 (mapconcat 'regexp-quote kwds "\\|")
17712 (if extra (concat "\\|" extra))
17713 "\\):[ \t]*"
17714 "\\(.*\\)"))
17716 ;; Make isearch reveal the necessary context
17717 (defun org-isearch-end ()
17718 "Reveal context after isearch exits."
17719 (when isearch-success ; only if search was successful
17720 (if (featurep 'xemacs)
17721 ;; Under XEmacs, the hook is run in the correct place,
17722 ;; we directly show the context.
17723 (org-show-context 'isearch)
17724 ;; In Emacs the hook runs *before* restoring the overlays.
17725 ;; So we have to use a one-time post-command-hook to do this.
17726 ;; (Emacs 22 has a special variable, see function `org-mode')
17727 (unless (and (boundp 'isearch-mode-end-hook-quit)
17728 isearch-mode-end-hook-quit)
17729 ;; Only when the isearch was not quitted.
17730 (org-add-hook 'post-command-hook 'org-isearch-post-command
17731 'append 'local)))))
17733 (defun org-isearch-post-command ()
17734 "Remove self from hook, and show context."
17735 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17736 (org-show-context 'isearch))
17739 ;;;; Integration with and fixes for other packages
17741 ;;; Imenu support
17743 (defvar org-imenu-markers nil
17744 "All markers currently used by Imenu.")
17745 (make-variable-buffer-local 'org-imenu-markers)
17747 (defun org-imenu-new-marker (&optional pos)
17748 "Return a new marker for use by Imenu, and remember the marker."
17749 (let ((m (make-marker)))
17750 (move-marker m (or pos (point)))
17751 (push m org-imenu-markers)
17754 (defun org-imenu-get-tree ()
17755 "Produce the index for Imenu."
17756 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17757 (setq org-imenu-markers nil)
17758 (let* ((n org-imenu-depth)
17759 (re (concat "^" outline-regexp))
17760 (subs (make-vector (1+ n) nil))
17761 (last-level 0)
17762 m level head)
17763 (save-excursion
17764 (save-restriction
17765 (widen)
17766 (goto-char (point-max))
17767 (while (re-search-backward re nil t)
17768 (setq level (org-reduced-level (funcall outline-level)))
17769 (when (<= level n)
17770 (looking-at org-complex-heading-regexp)
17771 (setq head (org-link-display-format
17772 (org-match-string-no-properties 4))
17773 m (org-imenu-new-marker))
17774 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17775 (if (>= level last-level)
17776 (push (cons head m) (aref subs level))
17777 (push (cons head (aref subs (1+ level))) (aref subs level))
17778 (loop for i from (1+ level) to n do (aset subs i nil)))
17779 (setq last-level level)))))
17780 (aref subs 1)))
17782 (eval-after-load "imenu"
17783 '(progn
17784 (add-hook 'imenu-after-jump-hook
17785 (lambda ()
17786 (if (eq major-mode 'org-mode)
17787 (org-show-context 'org-goto))))))
17789 (defun org-link-display-format (link)
17790 "Replace a link with either the description, or the link target
17791 if no description is present"
17792 (save-match-data
17793 (if (string-match org-bracket-link-analytic-regexp link)
17794 (replace-match (if (match-end 5)
17795 (match-string 5 link)
17796 (concat (match-string 1 link)
17797 (match-string 3 link)))
17798 nil t link)
17799 link)))
17801 ;; Speedbar support
17803 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17804 "Overlay marking the agenda restriction line in speedbar.")
17805 (org-overlay-put org-speedbar-restriction-lock-overlay
17806 'face 'org-agenda-restriction-lock)
17807 (org-overlay-put org-speedbar-restriction-lock-overlay
17808 'help-echo "Agendas are currently limited to this item.")
17809 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17811 (defun org-speedbar-set-agenda-restriction ()
17812 "Restrict future agenda commands to the location at point in speedbar.
17813 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17814 (interactive)
17815 (require 'org-agenda)
17816 (let (p m tp np dir txt)
17817 (cond
17818 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17819 'org-imenu t))
17820 (setq m (get-text-property p 'org-imenu-marker))
17821 (with-current-buffer (marker-buffer m)
17822 (goto-char m)
17823 (org-agenda-set-restriction-lock 'subtree)))
17824 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17825 'speedbar-function 'speedbar-find-file))
17826 (setq tp (previous-single-property-change
17827 (1+ p) 'speedbar-function)
17828 np (next-single-property-change
17829 tp 'speedbar-function)
17830 dir (speedbar-line-directory)
17831 txt (buffer-substring-no-properties (or tp (point-min))
17832 (or np (point-max))))
17833 (with-current-buffer (find-file-noselect
17834 (let ((default-directory dir))
17835 (expand-file-name txt)))
17836 (unless (org-mode-p)
17837 (error "Cannot restrict to non-Org-mode file"))
17838 (org-agenda-set-restriction-lock 'file)))
17839 (t (error "Don't know how to restrict Org-mode's agenda")))
17840 (org-move-overlay org-speedbar-restriction-lock-overlay
17841 (point-at-bol) (point-at-eol))
17842 (setq current-prefix-arg nil)
17843 (org-agenda-maybe-redo)))
17845 (eval-after-load "speedbar"
17846 '(progn
17847 (speedbar-add-supported-extension ".org")
17848 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17849 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17850 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17851 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17852 (add-hook 'speedbar-visiting-tag-hook
17853 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17856 ;;; Fixes and Hacks for problems with other packages
17858 ;; Make flyspell not check words in links, to not mess up our keymap
17859 (defun org-mode-flyspell-verify ()
17860 "Don't let flyspell put overlays at active buttons."
17861 (and (not (get-text-property (point) 'keymap))
17862 (not (get-text-property (point) 'org-no-flyspell))))
17864 (defun org-remove-flyspell-overlays-in (beg end)
17865 "Remove flyspell overlays in region."
17866 (and (org-bound-and-true-p flyspell-mode)
17867 (fboundp 'flyspell-delete-region-overlays)
17868 (flyspell-delete-region-overlays beg end))
17869 (add-text-properties beg end '(org-no-flyspell t)))
17871 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17872 (eval-after-load "bookmark"
17873 '(if (boundp 'bookmark-after-jump-hook)
17874 ;; We can use the hook
17875 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17876 ;; Hook not available, use advice
17877 (defadvice bookmark-jump (after org-make-visible activate)
17878 "Make the position visible."
17879 (org-bookmark-jump-unhide))))
17881 ;; Make sure saveplace shows the location if it was hidden
17882 (eval-after-load "saveplace"
17883 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17884 "Make the position visible."
17885 (org-bookmark-jump-unhide)))
17887 ;; Make sure ecb shows the location if it was hidden
17888 (eval-after-load "ecb"
17889 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17890 "Make hierarchy visible when jumping into location from ECB tree buffer."
17891 (if (eq major-mode 'org-mode)
17892 (org-show-context))))
17894 (defun org-bookmark-jump-unhide ()
17895 "Unhide the current position, to show the bookmark location."
17896 (and (org-mode-p)
17897 (or (org-invisible-p)
17898 (save-excursion (goto-char (max (point-min) (1- (point))))
17899 (org-invisible-p)))
17900 (org-show-context 'bookmark-jump)))
17902 ;; Make session.el ignore our circular variable
17903 (eval-after-load "session"
17904 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17906 ;;;; Experimental code
17908 (defun org-closed-in-range ()
17909 "Sparse tree of items closed in a certain time range.
17910 Still experimental, may disappear in the future."
17911 (interactive)
17912 ;; Get the time interval from the user.
17913 (let* ((time1 (org-float-time
17914 (org-read-date nil 'to-time nil "Starting date: ")))
17915 (time2 (org-float-time
17916 (org-read-date nil 'to-time nil "End date:")))
17917 ;; callback function
17918 (callback (lambda ()
17919 (let ((time
17920 (org-float-time
17921 (apply 'encode-time
17922 (org-parse-time-string
17923 (match-string 1))))))
17924 ;; check if time in interval
17925 (and (>= time time1) (<= time time2))))))
17926 ;; make tree, check each match with the callback
17927 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17929 ;;;; Finish up
17931 (provide 'org)
17933 (run-hooks 'org-load-hook)
17935 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17937 ;;; org.el ends here