Match TODO keywords case-sensitively
[org-mode.git] / lisp / org.el
blob74fa3b6c7c272829321d9d3d3aa58240020312e5
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.
2075 In fact, it is not a good idea to change the `state' entry, because
2076 agenda log mode depends on the format of these entries."
2077 :group 'org-todo
2078 :group 'org-progress
2079 :type '(list :greedy t
2080 (cons (const :tag "Heading when closing an item" done) string)
2081 (cons (const :tag
2082 "Heading when changing todo state (todo sequence only)"
2083 state) string)
2084 (cons (const :tag "Heading when just taking a note" note) string)
2085 (cons (const :tag "Heading when clocking out" clock-out) string)
2086 (cons (const :tag "Heading when rescheduling" reschedule) string)
2087 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2089 (unless (assq 'note org-log-note-headings)
2090 (push '(note . "%t") org-log-note-headings))
2092 (defcustom org-log-into-drawer nil
2093 "Non-nil means, insert state change notes and time stamps into a drawer.
2094 When nil, state changes notes will be inserted after the headline and
2095 any scheduling and clock lines, but not inside a drawer.
2097 The value of this variable should be the name of the drawer to use.
2098 LOGBOOK is proposed at the default drawer for this purpose, you can
2099 also set this to a string to define the drawer of your choice.
2101 A value of t is also allowed, representing \"LOGBOOK\".
2103 If this variable is set, `org-log-state-notes-insert-after-drawers'
2104 will be ignored.
2106 You can set the property LOG_INTO_DRAWER to overrule this setting for
2107 a subtree."
2108 :group 'org-todo
2109 :group 'org-progress
2110 :type '(choice
2111 (const :tag "Not into a drawer" nil)
2112 (const :tag "LOGBOOK" t)
2113 (string :tag "Other")))
2115 (if (fboundp 'defvaralias)
2116 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2118 (defun org-log-into-drawer ()
2119 "Return the value of `org-log-into-drawer', but let properties overrule.
2120 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2121 used instead of the default value."
2122 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2123 (cond
2124 ((or (not p) (equal p "nil")) org-log-into-drawer)
2125 ((equal p "t") "LOGBOOK")
2126 (t p))))
2128 (defcustom org-log-state-notes-insert-after-drawers nil
2129 "Non-nil means, insert state change notes after any drawers in entry.
2130 Only the drawers that *immediately* follow the headline and the
2131 deadline/scheduled line are skipped.
2132 When nil, insert notes right after the heading and perhaps the line
2133 with deadline/scheduling if present.
2135 This variable will have no effect if `org-log-into-drawer' is
2136 set."
2137 :group 'org-todo
2138 :group 'org-progress
2139 :type 'boolean)
2141 (defcustom org-log-states-order-reversed t
2142 "Non-nil means, the latest state change note will be directly after heading.
2143 When nil, the notes will be orderer according to time."
2144 :group 'org-todo
2145 :group 'org-progress
2146 :type 'boolean)
2148 (defcustom org-log-repeat 'time
2149 "Non-nil means, record moving through the DONE state when triggering repeat.
2150 An auto-repeating task is immediately switched back to TODO when
2151 marked DONE. If you are not logging state changes (by adding \"@\"
2152 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2153 record a closing note, there will be no record of the task moving
2154 through DONE. This variable forces taking a note anyway.
2156 nil Don't force a record
2157 time Record a time stamp
2158 note Record a note
2160 This option can also be set with on a per-file-basis with
2162 #+STARTUP: logrepeat
2163 #+STARTUP: lognoterepeat
2164 #+STARTUP: nologrepeat
2166 You can have local logging settings for a subtree by setting the LOGGING
2167 property to one or more of these keywords."
2168 :group 'org-todo
2169 :group 'org-progress
2170 :type '(choice
2171 (const :tag "Don't force a record" nil)
2172 (const :tag "Force recording the DONE state" time)
2173 (const :tag "Force recording a note with the DONE state" note)))
2176 (defgroup org-priorities nil
2177 "Priorities in Org-mode."
2178 :tag "Org Priorities"
2179 :group 'org-todo)
2181 (defcustom org-enable-priority-commands t
2182 "Non-nil means, priority commands are active.
2183 When nil, these commands will be disabled, so that you never accidentally
2184 set a priority."
2185 :group 'org-priorities
2186 :type 'boolean)
2188 (defcustom org-highest-priority ?A
2189 "The highest priority of TODO items. A character like ?A, ?B etc.
2190 Must have a smaller ASCII number than `org-lowest-priority'."
2191 :group 'org-priorities
2192 :type 'character)
2194 (defcustom org-lowest-priority ?C
2195 "The lowest priority of TODO items. A character like ?A, ?B etc.
2196 Must have a larger ASCII number than `org-highest-priority'."
2197 :group 'org-priorities
2198 :type 'character)
2200 (defcustom org-default-priority ?B
2201 "The default priority of TODO items.
2202 This is the priority an item get if no explicit priority is given."
2203 :group 'org-priorities
2204 :type 'character)
2206 (defcustom org-priority-start-cycle-with-default t
2207 "Non-nil means, start with default priority when starting to cycle.
2208 When this is nil, the first step in the cycle will be (depending on the
2209 command used) one higher or lower that the default priority."
2210 :group 'org-priorities
2211 :type 'boolean)
2213 (defgroup org-time nil
2214 "Options concerning time stamps and deadlines in Org-mode."
2215 :tag "Org Time"
2216 :group 'org)
2218 (defcustom org-insert-labeled-timestamps-at-point nil
2219 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2220 When nil, these labeled time stamps are forces into the second line of an
2221 entry, just after the headline. When scheduling from the global TODO list,
2222 the time stamp will always be forced into the second line."
2223 :group 'org-time
2224 :type 'boolean)
2226 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2227 "Formats for `format-time-string' which are used for time stamps.
2228 It is not recommended to change this constant.")
2230 (defcustom org-time-stamp-rounding-minutes '(0 5)
2231 "Number of minutes to round time stamps to.
2232 These are two values, the first applies when first creating a time stamp.
2233 The second applies when changing it with the commands `S-up' and `S-down'.
2234 When changing the time stamp, this means that it will change in steps
2235 of N minutes, as given by the second value.
2237 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2238 numbers should be factors of 60, so for example 5, 10, 15.
2240 When this is larger than 1, you can still force an exact time-stamp by using
2241 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2242 and by using a prefix arg to `S-up/down' to specify the exact number
2243 of minutes to shift."
2244 :group 'org-time
2245 :get '(lambda (var) ; Make sure all entries have 5 elements
2246 (if (integerp (default-value var))
2247 (list (default-value var) 5)
2248 (default-value var)))
2249 :type '(list
2250 (integer :tag "when inserting times")
2251 (integer :tag "when modifying times")))
2253 ;; Normalize old customizations of this variable.
2254 (when (integerp org-time-stamp-rounding-minutes)
2255 (setq org-time-stamp-rounding-minutes
2256 (list org-time-stamp-rounding-minutes
2257 org-time-stamp-rounding-minutes)))
2259 (defcustom org-display-custom-times nil
2260 "Non-nil means, overlay custom formats over all time stamps.
2261 The formats are defined through the variable `org-time-stamp-custom-formats'.
2262 To turn this on on a per-file basis, insert anywhere in the file:
2263 #+STARTUP: customtime"
2264 :group 'org-time
2265 :set 'set-default
2266 :type 'sexp)
2267 (make-variable-buffer-local 'org-display-custom-times)
2269 (defcustom org-time-stamp-custom-formats
2270 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2271 "Custom formats for time stamps. See `format-time-string' for the syntax.
2272 These are overlayed over the default ISO format if the variable
2273 `org-display-custom-times' is set. Time like %H:%M should be at the
2274 end of the second format. The custom formats are also honored by export
2275 commands, if custom time display is turned on at the time of export."
2276 :group 'org-time
2277 :type 'sexp)
2279 (defun org-time-stamp-format (&optional long inactive)
2280 "Get the right format for a time string."
2281 (let ((f (if long (cdr org-time-stamp-formats)
2282 (car org-time-stamp-formats))))
2283 (if inactive
2284 (concat "[" (substring f 1 -1) "]")
2285 f)))
2287 (defcustom org-time-clocksum-format "%d:%02d"
2288 "The format string used when creating CLOCKSUM lines, or when
2289 org-mode generates a time duration."
2290 :group 'org-time
2291 :type 'string)
2293 (defcustom org-time-clocksum-use-fractional nil
2294 "If non-nil, \\[org-clock-display] uses fractional times.
2295 org-mode generates a time duration."
2296 :group 'org-time
2297 :type 'boolean)
2299 (defcustom org-time-clocksum-fractional-format "%.2f"
2300 "The format string used when creating CLOCKSUM lines, or when
2301 org-mode generates a time duration."
2302 :group 'org-time
2303 :type 'string)
2305 (defcustom org-deadline-warning-days 14
2306 "No. of days before expiration during which a deadline becomes active.
2307 This variable governs the display in sparse trees and in the agenda.
2308 When 0 or negative, it means use this number (the absolute value of it)
2309 even if a deadline has a different individual lead time specified.
2311 Custom commands can set this variable in the options section."
2312 :group 'org-time
2313 :group 'org-agenda-daily/weekly
2314 :type 'integer)
2316 (defcustom org-read-date-prefer-future t
2317 "Non-nil means, assume future for incomplete date input from user.
2318 This affects the following situations:
2319 1. The user gives a month but not a year.
2320 For example, if it is april and you enter \"feb 2\", this will be read
2321 as feb 2, *next* year. \"May 5\", however, will be this year.
2322 2. The user gives a day, but no month.
2323 For example, if today is the 15th, and you enter \"3\", Org-mode will
2324 read this as the third of *next* month. However, if you enter \"17\",
2325 it will be considered as *this* month.
2327 If you set this variable to the symbol `time', then also the following
2328 will work:
2330 3. If the user gives a time, but no day. If the time is before now,
2331 to will be interpreted as tomorrow.
2333 Currently none of this works for ISO week specifications.
2335 When this option is nil, the current day, month and year will always be
2336 used as defaults."
2337 :group 'org-time
2338 :type '(choice
2339 (const :tag "Never" nil)
2340 (const :tag "Check month and day" t)
2341 (const :tag "Check month, day, and time" time)))
2343 (defcustom org-read-date-display-live t
2344 "Non-nil means, display current interpretation of date prompt live.
2345 This display will be in an overlay, in the minibuffer."
2346 :group 'org-time
2347 :type 'boolean)
2349 (defcustom org-read-date-popup-calendar t
2350 "Non-nil means, pop up a calendar when prompting for a date.
2351 In the calendar, the date can be selected with mouse-1. However, the
2352 minibuffer will also be active, and you can simply enter the date as well.
2353 When nil, only the minibuffer will be available."
2354 :group 'org-time
2355 :type 'boolean)
2356 (if (fboundp 'defvaralias)
2357 (defvaralias 'org-popup-calendar-for-date-prompt
2358 'org-read-date-popup-calendar))
2360 (defcustom org-read-date-minibuffer-setup-hook nil
2361 "Hook to be used to set up keys for the date/time interface.
2362 Add key definitions to `minibuffer-local-map', which will be a temporary
2363 copy."
2364 :group 'org-time
2365 :type 'hook)
2367 (defcustom org-extend-today-until 0
2368 "The hour when your day really ends. Must be an integer.
2369 This has influence for the following applications:
2370 - When switching the agenda to \"today\". It it is still earlier than
2371 the time given here, the day recognized as TODAY is actually yesterday.
2372 - When a date is read from the user and it is still before the time given
2373 here, the current date and time will be assumed to be yesterday, 23:59.
2374 Also, timestamps inserted in remember templates follow this rule.
2376 IMPORTANT: This is a feature whose implementation is and likely will
2377 remain incomplete. Really, it is only here because past midnight seems to
2378 be the favorite working time of John Wiegley :-)"
2379 :group 'org-time
2380 :type 'integer)
2382 (defcustom org-edit-timestamp-down-means-later nil
2383 "Non-nil means, S-down will increase the time in a time stamp.
2384 When nil, S-up will increase."
2385 :group 'org-time
2386 :type 'boolean)
2388 (defcustom org-calendar-follow-timestamp-change t
2389 "Non-nil means, make the calendar window follow timestamp changes.
2390 When a timestamp is modified and the calendar window is visible, it will be
2391 moved to the new date."
2392 :group 'org-time
2393 :type 'boolean)
2395 (defgroup org-tags nil
2396 "Options concerning tags in Org-mode."
2397 :tag "Org Tags"
2398 :group 'org)
2400 (defcustom org-tag-alist nil
2401 "List of tags allowed in Org-mode files.
2402 When this list is nil, Org-mode will base TAG input on what is already in the
2403 buffer.
2404 The value of this variable is an alist, the car of each entry must be a
2405 keyword as a string, the cdr may be a character that is used to select
2406 that tag through the fast-tag-selection interface.
2407 See the manual for details."
2408 :group 'org-tags
2409 :type '(repeat
2410 (choice
2411 (cons (string :tag "Tag name")
2412 (character :tag "Access char"))
2413 (list :tag "Start radio group"
2414 (const :startgroup)
2415 (option (string :tag "Group description")))
2416 (list :tag "End radio group"
2417 (const :endgroup)
2418 (option (string :tag "Group description")))
2419 (const :tag "New line" (:newline)))))
2421 (defcustom org-tag-persistent-alist nil
2422 "List of tags that will always appear in all Org-mode files.
2423 This is in addition to any in buffer settings or customizations
2424 of `org-tag-alist'.
2425 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2426 The value of this variable is an alist, the car of each entry must be a
2427 keyword as a string, the cdr may be a character that is used to select
2428 that tag through the fast-tag-selection interface.
2429 See the manual for details.
2430 To disable these tags on a per-file basis, insert anywhere in the file:
2431 #+STARTUP: noptag"
2432 :group 'org-tags
2433 :type '(repeat
2434 (choice
2435 (cons (string :tag "Tag name")
2436 (character :tag "Access char"))
2437 (const :tag "Start radio group" (:startgroup))
2438 (const :tag "End radio group" (:endgroup))
2439 (const :tag "New line" (:newline)))))
2441 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2442 "If non-nil, always offer completion for all tags of all agenda files.
2443 Instead of customizing this variable directly, you might want to
2444 set it locally for remember buffers, because there no list of
2445 tags in that file can be created dynamically (there are none).
2447 (add-hook 'org-remember-mode-hook
2448 (lambda ()
2449 (set (make-local-variable
2450 'org-complete-tags-always-offer-all-agenda-tags)
2451 t)))"
2452 :group 'org-tags
2453 :type 'boolean)
2455 (defvar org-file-tags nil
2456 "List of tags that can be inherited by all entries in the file.
2457 The tags will be inherited if the variable `org-use-tag-inheritance'
2458 says they should be.
2459 This variable is populated from #+FILETAGS lines.")
2461 (defcustom org-use-fast-tag-selection 'auto
2462 "Non-nil means, use fast tag selection scheme.
2463 This is a special interface to select and deselect tags with single keys.
2464 When nil, fast selection is never used.
2465 When the symbol `auto', fast selection is used if and only if selection
2466 characters for tags have been configured, either through the variable
2467 `org-tag-alist' or through a #+TAGS line in the buffer.
2468 When t, fast selection is always used and selection keys are assigned
2469 automatically if necessary."
2470 :group 'org-tags
2471 :type '(choice
2472 (const :tag "Always" t)
2473 (const :tag "Never" nil)
2474 (const :tag "When selection characters are configured" 'auto)))
2476 (defcustom org-fast-tag-selection-single-key nil
2477 "Non-nil means, fast tag selection exits after first change.
2478 When nil, you have to press RET to exit it.
2479 During fast tag selection, you can toggle this flag with `C-c'.
2480 This variable can also have the value `expert'. In this case, the window
2481 displaying the tags menu is not even shown, until you press C-c again."
2482 :group 'org-tags
2483 :type '(choice
2484 (const :tag "No" nil)
2485 (const :tag "Yes" t)
2486 (const :tag "Expert" expert)))
2488 (defvar org-fast-tag-selection-include-todo nil
2489 "Non-nil means, fast tags selection interface will also offer TODO states.
2490 This is an undocumented feature, you should not rely on it.")
2492 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2493 "The column to which tags should be indented in a headline.
2494 If this number is positive, it specifies the column. If it is negative,
2495 it means that the tags should be flushright to that column. For example,
2496 -80 works well for a normal 80 character screen."
2497 :group 'org-tags
2498 :type 'integer)
2500 (defcustom org-auto-align-tags t
2501 "Non-nil means, realign tags after pro/demotion of TODO state change.
2502 These operations change the length of a headline and therefore shift
2503 the tags around. With this options turned on, after each such operation
2504 the tags are again aligned to `org-tags-column'."
2505 :group 'org-tags
2506 :type 'boolean)
2508 (defcustom org-use-tag-inheritance t
2509 "Non-nil means, tags in levels apply also for sublevels.
2510 When nil, only the tags directly given in a specific line apply there.
2511 This may also be a list of tags that should be inherited, or a regexp that
2512 matches tags that should be inherited. Additional control is possible
2513 with the variable `org-tags-exclude-from-inheritance' which gives an
2514 explicit list of tags to be excluded from inheritance., even if the value of
2515 `org-use-tag-inheritance' would select it for inheritance.
2517 If this option is t, a match early-on in a tree can lead to a large
2518 number of matches in the subtree when constructing the agenda or creating
2519 a sparse tree. If you only want to see the first match in a tree during
2520 a search, check out the variable `org-tags-match-list-sublevels'."
2521 :group 'org-tags
2522 :type '(choice
2523 (const :tag "Not" nil)
2524 (const :tag "Always" t)
2525 (repeat :tag "Specific tags" (string :tag "Tag"))
2526 (regexp :tag "Tags matched by regexp")))
2528 (defcustom org-tags-exclude-from-inheritance nil
2529 "List of tags that should never be inherited.
2530 This is a way to exclude a few tags from inheritance. For way to do
2531 the opposite, to actively allow inheritance for selected tags,
2532 see the variable `org-use-tag-inheritance'."
2533 :group 'org-tags
2534 :type '(repeat (string :tag "Tag")))
2536 (defun org-tag-inherit-p (tag)
2537 "Check if TAG is one that should be inherited."
2538 (cond
2539 ((member tag org-tags-exclude-from-inheritance) nil)
2540 ((eq org-use-tag-inheritance t) t)
2541 ((not org-use-tag-inheritance) nil)
2542 ((stringp org-use-tag-inheritance)
2543 (string-match org-use-tag-inheritance tag))
2544 ((listp org-use-tag-inheritance)
2545 (member tag org-use-tag-inheritance))
2546 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2548 (defcustom org-tags-match-list-sublevels t
2549 "Non-nil means list also sublevels of headlines matching a search.
2550 This variable applies to tags/property searches, and also to stuck
2551 projects because this search is based on a tags match as well.
2553 When set to the symbol `indented', sublevels are indented with
2554 leading dots.
2556 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2557 the sublevels of a headline matching a tag search often also match
2558 the same search. Listing all of them can create very long lists.
2559 Setting this variable to nil causes subtrees of a match to be skipped.
2561 This variable is semi-obsolete and probably should always be true. It
2562 is better to limit inheritance to certain tags using the variables
2563 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2564 :group 'org-tags
2565 :type '(choice
2566 (const :tag "No, don't list them" nil)
2567 (const :tag "Yes, do list them" t)
2568 (const :tag "List them, indented with leading dots" indented)))
2570 (defcustom org-tags-sort-function nil
2571 "When set, tags are sorted using this function as a comparator"
2572 :group 'org-tags
2573 :type '(choice
2574 (const :tag "No sorting" nil)
2575 (const :tag "Alphabetical" string<)
2576 (const :tag "Reverse alphabetical" string>)
2577 (function :tag "Custom function" nil)))
2579 (defvar org-tags-history nil
2580 "History of minibuffer reads for tags.")
2581 (defvar org-last-tags-completion-table nil
2582 "The last used completion table for tags.")
2583 (defvar org-after-tags-change-hook nil
2584 "Hook that is run after the tags in a line have changed.")
2586 (defgroup org-properties nil
2587 "Options concerning properties in Org-mode."
2588 :tag "Org Properties"
2589 :group 'org)
2591 (defcustom org-property-format "%-10s %s"
2592 "How property key/value pairs should be formatted by `indent-line'.
2593 When `indent-line' hits a property definition, it will format the line
2594 according to this format, mainly to make sure that the values are
2595 lined-up with respect to each other."
2596 :group 'org-properties
2597 :type 'string)
2599 (defcustom org-use-property-inheritance nil
2600 "Non-nil means, properties apply also for sublevels.
2602 This setting is chiefly used during property searches. Turning it on can
2603 cause significant overhead when doing a search, which is why it is not
2604 on by default.
2606 When nil, only the properties directly given in the current entry count.
2607 When t, every property is inherited. The value may also be a list of
2608 properties that should have inheritance, or a regular expression matching
2609 properties that should be inherited.
2611 However, note that some special properties use inheritance under special
2612 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2613 and the properties ending in \"_ALL\" when they are used as descriptor
2614 for valid values of a property.
2616 Note for programmers:
2617 When querying an entry with `org-entry-get', you can control if inheritance
2618 should be used. By default, `org-entry-get' looks only at the local
2619 properties. You can request inheritance by setting the inherit argument
2620 to t (to force inheritance) or to `selective' (to respect the setting
2621 in this variable)."
2622 :group 'org-properties
2623 :type '(choice
2624 (const :tag "Not" nil)
2625 (const :tag "Always" t)
2626 (repeat :tag "Specific properties" (string :tag "Property"))
2627 (regexp :tag "Properties matched by regexp")))
2629 (defun org-property-inherit-p (property)
2630 "Check if PROPERTY is one that should be inherited."
2631 (cond
2632 ((eq org-use-property-inheritance t) t)
2633 ((not org-use-property-inheritance) nil)
2634 ((stringp org-use-property-inheritance)
2635 (string-match org-use-property-inheritance property))
2636 ((listp org-use-property-inheritance)
2637 (member property org-use-property-inheritance))
2638 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2640 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2641 "The default column format, if no other format has been defined.
2642 This variable can be set on the per-file basis by inserting a line
2644 #+COLUMNS: %25ITEM ....."
2645 :group 'org-properties
2646 :type 'string)
2648 (defcustom org-columns-ellipses ".."
2649 "The ellipses to be used when a field in column view is truncated.
2650 When this is the empty string, as many characters as possible are shown,
2651 but then there will be no visual indication that the field has been truncated.
2652 When this is a string of length N, the last N characters of a truncated
2653 field are replaced by this string. If the column is narrower than the
2654 ellipses string, only part of the ellipses string will be shown."
2655 :group 'org-properties
2656 :type 'string)
2658 (defcustom org-columns-modify-value-for-display-function nil
2659 "Function that modifies values for display in column view.
2660 For example, it can be used to cut out a certain part from a time stamp.
2661 The function must take 2 arguments:
2663 column-title The title of the column (*not* the property name)
2664 value The value that should be modified.
2666 The function should return the value that should be displayed,
2667 or nil if the normal value should be used."
2668 :group 'org-properties
2669 :type 'function)
2671 (defcustom org-effort-property "Effort"
2672 "The property that is being used to keep track of effort estimates.
2673 Effort estimates given in this property need to have the format H:MM."
2674 :group 'org-properties
2675 :group 'org-progress
2676 :type '(string :tag "Property"))
2678 (defconst org-global-properties-fixed
2679 '(("VISIBILITY_ALL" . "folded children content all")
2680 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2681 "List of property/value pairs that can be inherited by any entry.
2683 These are fixed values, for the preset properties. The user variable
2684 that can be used to add to this list is `org-global-properties'.
2686 The entries in this list are cons cells where the car is a property
2687 name and cdr is a string with the value. If the value represents
2688 multiple items like an \"_ALL\" property, separate the items by
2689 spaces.")
2691 (defcustom org-global-properties nil
2692 "List of property/value pairs that can be inherited by any entry.
2694 This list will be combined with the constant `org-global-properties-fixed'.
2696 The entries in this list are cons cells where the car is a property
2697 name and cdr is a string with the value.
2699 You can set buffer-local values for the same purpose in the variable
2700 `org-file-properties' this by adding lines like
2702 #+PROPERTY: NAME VALUE"
2703 :group 'org-properties
2704 :type '(repeat
2705 (cons (string :tag "Property")
2706 (string :tag "Value"))))
2708 (defvar org-file-properties nil
2709 "List of property/value pairs that can be inherited by any entry.
2710 Valid for the current buffer.
2711 This variable is populated from #+PROPERTY lines.")
2712 (make-variable-buffer-local 'org-file-properties)
2714 (defgroup org-agenda nil
2715 "Options concerning agenda views in Org-mode."
2716 :tag "Org Agenda"
2717 :group 'org)
2719 (defvar org-category nil
2720 "Variable used by org files to set a category for agenda display.
2721 Such files should use a file variable to set it, for example
2723 # -*- mode: org; org-category: \"ELisp\"
2725 or contain a special line
2727 #+CATEGORY: ELisp
2729 If the file does not specify a category, then file's base name
2730 is used instead.")
2731 (make-variable-buffer-local 'org-category)
2732 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2734 (defcustom org-agenda-files nil
2735 "The files to be used for agenda display.
2736 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2737 \\[org-remove-file]. You can also use customize to edit the list.
2739 If an entry is a directory, all files in that directory that are matched by
2740 `org-agenda-file-regexp' will be part of the file list.
2742 If the value of the variable is not a list but a single file name, then
2743 the list of agenda files is actually stored and maintained in that file, one
2744 agenda file per line."
2745 :group 'org-agenda
2746 :type '(choice
2747 (repeat :tag "List of files and directories" file)
2748 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2750 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2751 "Regular expression to match files for `org-agenda-files'.
2752 If any element in the list in that variable contains a directory instead
2753 of a normal file, all files in that directory that are matched by this
2754 regular expression will be included."
2755 :group 'org-agenda
2756 :type 'regexp)
2758 (defcustom org-agenda-text-search-extra-files nil
2759 "List of extra files to be searched by text search commands.
2760 These files will be search in addition to the agenda files by the
2761 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2762 Note that these files will only be searched for text search commands,
2763 not for the other agenda views like todo lists, tag searches or the weekly
2764 agenda. This variable is intended to list notes and possibly archive files
2765 that should also be searched by these two commands.
2766 In fact, if the first element in the list is the symbol `agenda-archives',
2767 than all archive files of all agenda files will be added to the search
2768 scope."
2769 :group 'org-agenda
2770 :type '(set :greedy t
2771 (const :tag "Agenda Archives" agenda-archives)
2772 (repeat :inline t (file))))
2774 (if (fboundp 'defvaralias)
2775 (defvaralias 'org-agenda-multi-occur-extra-files
2776 'org-agenda-text-search-extra-files))
2778 (defcustom org-agenda-skip-unavailable-files nil
2779 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2780 A nil value means to remove them, after a query, from the list."
2781 :group 'org-agenda
2782 :type 'boolean)
2784 (defcustom org-calendar-to-agenda-key [?c]
2785 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2786 The command `org-calendar-goto-agenda' will be bound to this key. The
2787 default is the character `c' because then `c' can be used to switch back and
2788 forth between agenda and calendar."
2789 :group 'org-agenda
2790 :type 'sexp)
2792 (defcustom org-calendar-agenda-action-key [?k]
2793 "The key to be installed in `calendar-mode-map' for agenda-action.
2794 The command `org-agenda-action' will be bound to this key. The
2795 default is the character `k' because we use the same key in the agenda."
2796 :group 'org-agenda
2797 :type 'sexp)
2799 (defcustom org-calendar-insert-diary-entry-key [?i]
2800 "The key to be installed in `calendar-mode-map' for adding diary entries.
2801 This option is irrelevant until `org-agenda-diary-file' has been configured
2802 to point to an Org-mode file. When that is the case, the command
2803 `org-agenda-diary-entry' will be bound to the key given here, by default
2804 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2805 if you want to continue doing this, you need to change this to a different
2806 key."
2807 :group 'org-agenda
2808 :type 'sexp)
2810 (defcustom org-agenda-diary-file 'diary-file
2811 "File to which to add new entries with the `i' key in agenda and calendar.
2812 When this is the symbol `diary-file', the functionality in the Emacs
2813 calendar will be used to add entries to the `diary-file'. But when this
2814 points to a file, `org-agenda-diary-entry' will be used instead."
2815 :group 'org-agenda
2816 :type '(choice
2817 (const :tag "The standard Emacs diary file" diary-file)
2818 (file :tag "Special Org file diary entries")))
2820 (eval-after-load "calendar"
2821 '(progn
2822 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2823 'org-calendar-goto-agenda)
2824 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2825 'org-agenda-action)
2826 (add-hook 'calendar-mode-hook
2827 (lambda ()
2828 (unless (eq org-agenda-diary-file 'diary-file)
2829 (define-key calendar-mode-map
2830 org-calendar-insert-diary-entry-key
2831 'org-agenda-diary-entry))))))
2833 (defgroup org-latex nil
2834 "Options for embedding LaTeX code into Org-mode."
2835 :tag "Org LaTeX"
2836 :group 'org)
2838 (defcustom org-format-latex-options
2839 '(:foreground default :background default :scale 1.0
2840 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2841 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2842 "Options for creating images from LaTeX fragments.
2843 This is a property list with the following properties:
2844 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2845 `default' means use the foreground of the default face.
2846 :background the background color, or \"Transparent\".
2847 `default' means use the background of the default face.
2848 :scale a scaling factor for the size of the images.
2849 :html-foreground, :html-background, :html-scale
2850 the same numbers for HTML export.
2851 :matchers a list indicating which matchers should be used to
2852 find LaTeX fragments. Valid members of this list are:
2853 \"begin\" find environments
2854 \"$1\" find single characters surrounded by $.$
2855 \"$\" find math expressions surrounded by $...$
2856 \"$$\" find math expressions surrounded by $$....$$
2857 \"\\(\" find math expressions surrounded by \\(...\\)
2858 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2859 :group 'org-latex
2860 :type 'plist)
2862 (defcustom org-format-latex-header "\\documentclass{article}
2863 \\usepackage{amssymb}
2864 \\usepackage[usenames]{color}
2865 \\usepackage{amsmath}
2866 \\usepackage{latexsym}
2867 \\usepackage[mathscr]{eucal}
2868 \\pagestyle{empty} % do not remove
2869 % The settings below are copied from fullpage.sty
2870 \\setlength{\\textwidth}{\\paperwidth}
2871 \\addtolength{\\textwidth}{-3cm}
2872 \\setlength{\\oddsidemargin}{1.5cm}
2873 \\addtolength{\\oddsidemargin}{-2.54cm}
2874 \\setlength{\\evensidemargin}{\\oddsidemargin}
2875 \\setlength{\\textheight}{\\paperheight}
2876 \\addtolength{\\textheight}{-\\headheight}
2877 \\addtolength{\\textheight}{-\\headsep}
2878 \\addtolength{\\textheight}{-\\footskip}
2879 \\addtolength{\\textheight}{-3cm}
2880 \\setlength{\\topmargin}{1.5cm}
2881 \\addtolength{\\topmargin}{-2.54cm}"
2882 "The document header used for processing LaTeX fragments.
2883 It is imperative that this header make sure that no page number
2884 appears on the page."
2885 :group 'org-latex
2886 :type 'string)
2888 ;; The following variable is defined here because is it also used
2889 ;; when formatting latex fragments. Originally it was part of the
2890 ;; LaTeX exporter, which is why the name includes "export".
2891 (defcustom org-export-latex-packages-alist nil
2892 "Alist of packages to be inserted in the header.
2893 Each cell is of the format \( \"option\" . \"package\" \)."
2894 :group 'org-export-latex
2895 :type '(repeat
2896 (list
2897 (string :tag "option")
2898 (string :tag "package"))))
2900 (defgroup org-font-lock nil
2901 "Font-lock settings for highlighting in Org-mode."
2902 :tag "Org Font Lock"
2903 :group 'org)
2905 (defcustom org-level-color-stars-only nil
2906 "Non-nil means fontify only the stars in each headline.
2907 When nil, the entire headline is fontified.
2908 Changing it requires restart of `font-lock-mode' to become effective
2909 also in regions already fontified."
2910 :group 'org-font-lock
2911 :type 'boolean)
2913 (defcustom org-hide-leading-stars nil
2914 "Non-nil means, hide the first N-1 stars in a headline.
2915 This works by using the face `org-hide' for these stars. This
2916 face is white for a light background, and black for a dark
2917 background. You may have to customize the face `org-hide' to
2918 make this work.
2919 Changing it requires restart of `font-lock-mode' to become effective
2920 also in regions already fontified.
2921 You may also set this on a per-file basis by adding one of the following
2922 lines to the buffer:
2924 #+STARTUP: hidestars
2925 #+STARTUP: showstars"
2926 :group 'org-font-lock
2927 :type 'boolean)
2929 (defcustom org-fontify-done-headline nil
2930 "Non-nil means, change the face of a headline if it is marked DONE.
2931 Normally, only the TODO/DONE keyword indicates the state of a headline.
2932 When this is non-nil, the headline after the keyword is set to the
2933 `org-headline-done' as an additional indication."
2934 :group 'org-font-lock
2935 :type 'boolean)
2937 (defcustom org-fontify-emphasized-text t
2938 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2939 Changing this variable requires a restart of Emacs to take effect."
2940 :group 'org-font-lock
2941 :type 'boolean)
2943 (defcustom org-fontify-whole-heading-line nil
2944 "Non-nil means fontify the whole line for headings.
2945 This is useful when setting a background color for the
2946 org-level-* faces."
2947 :group 'org-font-lock
2948 :type 'boolean)
2950 (defcustom org-highlight-latex-fragments-and-specials nil
2951 "Non-nil means, fontify what is treated specially by the exporters."
2952 :group 'org-font-lock
2953 :type 'boolean)
2955 (defcustom org-hide-emphasis-markers nil
2956 "Non-nil mean font-lock should hide the emphasis marker characters."
2957 :group 'org-font-lock
2958 :type 'boolean)
2960 (defvar org-emph-re nil
2961 "Regular expression for matching emphasis.")
2962 (defvar org-verbatim-re nil
2963 "Regular expression for matching verbatim text.")
2964 (defvar org-emphasis-regexp-components) ; defined just below
2965 (defvar org-emphasis-alist) ; defined just below
2966 (defun org-set-emph-re (var val)
2967 "Set variable and compute the emphasis regular expression."
2968 (set var val)
2969 (when (and (boundp 'org-emphasis-alist)
2970 (boundp 'org-emphasis-regexp-components)
2971 org-emphasis-alist org-emphasis-regexp-components)
2972 (let* ((e org-emphasis-regexp-components)
2973 (pre (car e))
2974 (post (nth 1 e))
2975 (border (nth 2 e))
2976 (body (nth 3 e))
2977 (nl (nth 4 e))
2978 (body1 (concat body "*?"))
2979 (markers (mapconcat 'car org-emphasis-alist ""))
2980 (vmarkers (mapconcat
2981 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2982 org-emphasis-alist "")))
2983 ;; make sure special characters appear at the right position in the class
2984 (if (string-match "\\^" markers)
2985 (setq markers (concat (replace-match "" t t markers) "^")))
2986 (if (string-match "-" markers)
2987 (setq markers (concat (replace-match "" t t markers) "-")))
2988 (if (string-match "\\^" vmarkers)
2989 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2990 (if (string-match "-" vmarkers)
2991 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2992 (if (> nl 0)
2993 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2994 (int-to-string nl) "\\}")))
2995 ;; Make the regexp
2996 (setq org-emph-re
2997 (concat "\\([" pre "]\\|^\\)"
2998 "\\("
2999 "\\([" markers "]\\)"
3000 "\\("
3001 "[^" border "]\\|"
3002 "[^" border "]"
3003 body1
3004 "[^" border "]"
3005 "\\)"
3006 "\\3\\)"
3007 "\\([" post "]\\|$\\)"))
3008 (setq org-verbatim-re
3009 (concat "\\([" pre "]\\|^\\)"
3010 "\\("
3011 "\\([" vmarkers "]\\)"
3012 "\\("
3013 "[^" border "]\\|"
3014 "[^" border "]"
3015 body1
3016 "[^" border "]"
3017 "\\)"
3018 "\\3\\)"
3019 "\\([" post "]\\|$\\)")))))
3021 (defcustom org-emphasis-regexp-components
3022 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3023 "Components used to build the regular expression for emphasis.
3024 This is a list with 6 entries. Terminology: In an emphasis string
3025 like \" *strong word* \", we call the initial space PREMATCH, the final
3026 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3027 and \"trong wor\" is the body. The different components in this variable
3028 specify what is allowed/forbidden in each part:
3030 pre Chars allowed as prematch. Beginning of line will be allowed too.
3031 post Chars allowed as postmatch. End of line will be allowed too.
3032 border The chars *forbidden* as border characters.
3033 body-regexp A regexp like \".\" to match a body character. Don't use
3034 non-shy groups here, and don't allow newline here.
3035 newline The maximum number of newlines allowed in an emphasis exp.
3037 Use customize to modify this, or restart Emacs after changing it."
3038 :group 'org-font-lock
3039 :set 'org-set-emph-re
3040 :type '(list
3041 (sexp :tag "Allowed chars in pre ")
3042 (sexp :tag "Allowed chars in post ")
3043 (sexp :tag "Forbidden chars in border ")
3044 (sexp :tag "Regexp for body ")
3045 (integer :tag "number of newlines allowed")
3046 (option (boolean :tag "Please ignore this button"))))
3048 (defcustom org-emphasis-alist
3049 `(("*" bold "<b>" "</b>")
3050 ("/" italic "<i>" "</i>")
3051 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3052 ("=" org-code "<code>" "</code>" verbatim)
3053 ("~" org-verbatim "<code>" "</code>" verbatim)
3054 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3055 "<del>" "</del>")
3057 "Special syntax for emphasized text.
3058 Text starting and ending with a special character will be emphasized, for
3059 example *bold*, _underlined_ and /italic/. This variable sets the marker
3060 characters, the face to be used by font-lock for highlighting in Org-mode
3061 Emacs buffers, and the HTML tags to be used for this.
3062 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3063 Use customize to modify this, or restart Emacs after changing it."
3064 :group 'org-font-lock
3065 :set 'org-set-emph-re
3066 :type '(repeat
3067 (list
3068 (string :tag "Marker character")
3069 (choice
3070 (face :tag "Font-lock-face")
3071 (plist :tag "Face property list"))
3072 (string :tag "HTML start tag")
3073 (string :tag "HTML end tag")
3074 (option (const verbatim)))))
3076 (defvar org-protecting-blocks
3077 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3078 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3079 This is needed for font-lock setup.")
3081 ;;; Miscellaneous options
3083 (defgroup org-completion nil
3084 "Completion in Org-mode."
3085 :tag "Org Completion"
3086 :group 'org)
3088 (defcustom org-completion-use-ido nil
3089 "Non-nil means, use ido completion wherever possible.
3090 Note that `ido-mode' must be active for this variable to be relevant.
3091 If you decide to turn this variable on, you might well want to turn off
3092 `org-outline-path-complete-in-steps'.
3093 See also `org-completion-use-iswitchb'."
3094 :group 'org-completion
3095 :type 'boolean)
3097 (defcustom org-completion-use-iswitchb nil
3098 "Non-nil means, use iswitchb completion wherever possible.
3099 Note that `iswitchb-mode' must be active for this variable to be relevant.
3100 If you decide to turn this variable on, you might well want to turn off
3101 `org-outline-path-complete-in-steps'.
3102 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3103 :group 'org-completion
3104 :type 'boolean)
3106 (defcustom org-completion-fallback-command 'hippie-expand
3107 "The expansion command called by \\[org-complete] in normal context.
3108 Normal means, no org-mode-specific context."
3109 :group 'org-completion
3110 :type 'function)
3112 ;;; Functions and variables from their packages
3113 ;; Declared here to avoid compiler warnings
3115 ;; XEmacs only
3116 (defvar outline-mode-menu-heading)
3117 (defvar outline-mode-menu-show)
3118 (defvar outline-mode-menu-hide)
3119 (defvar zmacs-regions) ; XEmacs regions
3121 ;; Emacs only
3122 (defvar mark-active)
3124 ;; Various packages
3125 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3126 (declare-function calendar-forward-day "cal-move" (arg))
3127 (declare-function calendar-goto-date "cal-move" (date))
3128 (declare-function calendar-goto-today "cal-move" ())
3129 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3130 (defvar calc-embedded-close-formula)
3131 (defvar calc-embedded-open-formula)
3132 (declare-function cdlatex-tab "ext:cdlatex" ())
3133 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3134 (defvar font-lock-unfontify-region-function)
3135 (declare-function iswitchb-read-buffer "iswitchb"
3136 (prompt &optional default require-match start matches-set))
3137 (defvar iswitchb-temp-buflist)
3138 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3139 (defvar org-agenda-tags-todo-honor-ignore-options)
3140 (declare-function org-agenda-skip "org-agenda" ())
3141 (declare-function
3142 org-format-agenda-item "org-agenda"
3143 (extra txt &optional category tags dotime noprefix remove-re habitp))
3144 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3145 (declare-function org-agenda-change-all-lines "org-agenda"
3146 (newhead hdmarker &optional fixface just-this))
3147 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3148 (declare-function org-agenda-maybe-redo "org-agenda" ())
3149 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3150 (beg end))
3151 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3152 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3153 "org-agenda" (&optional end))
3154 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3155 (declare-function org-indent-mode "org-indent" (&optional arg))
3156 (declare-function parse-time-string "parse-time" (string))
3157 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3158 (defvar remember-data-file)
3159 (defvar texmathp-why)
3160 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3161 (declare-function table--at-cell-p "table" (position &optional object at-column))
3163 (defvar w3m-current-url)
3164 (defvar w3m-current-title)
3166 (defvar org-latex-regexps)
3168 ;;; Autoload and prepare some org modules
3170 ;; Some table stuff that needs to be defined here, because it is used
3171 ;; by the functions setting up org-mode or checking for table context.
3173 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3174 "Detects an org-type or table-type table.")
3175 (defconst org-table-line-regexp "^[ \t]*|"
3176 "Detects an org-type table line.")
3177 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3178 "Detects an org-type table line.")
3179 (defconst org-table-hline-regexp "^[ \t]*|-"
3180 "Detects an org-type table hline.")
3181 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3182 "Detects a table-type table hline.")
3183 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3184 "Searching from within a table (any type) this finds the first line
3185 outside the table.")
3187 ;; Autoload the functions in org-table.el that are needed by functions here.
3189 (eval-and-compile
3190 (org-autoload "org-table"
3191 '(org-table-align org-table-begin org-table-blank-field
3192 org-table-convert org-table-convert-region org-table-copy-down
3193 org-table-copy-region org-table-create
3194 org-table-create-or-convert-from-region
3195 org-table-create-with-table.el org-table-current-dline
3196 org-table-cut-region org-table-delete-column org-table-edit-field
3197 org-table-edit-formulas org-table-end org-table-eval-formula
3198 org-table-export org-table-field-info
3199 org-table-get-stored-formulas org-table-goto-column
3200 org-table-hline-and-move org-table-import org-table-insert-column
3201 org-table-insert-hline org-table-insert-row org-table-iterate
3202 org-table-justify-field-maybe org-table-kill-row
3203 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3204 org-table-move-column org-table-move-column-left
3205 org-table-move-column-right org-table-move-row
3206 org-table-move-row-down org-table-move-row-up
3207 org-table-next-field org-table-next-row org-table-paste-rectangle
3208 org-table-previous-field org-table-recalculate
3209 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3210 org-table-toggle-coordinate-overlays
3211 org-table-toggle-formula-debugger org-table-wrap-region
3212 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3214 (defun org-at-table-p (&optional table-type)
3215 "Return t if the cursor is inside an org-type table.
3216 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3217 (if org-enable-table-editor
3218 (save-excursion
3219 (beginning-of-line 1)
3220 (looking-at (if table-type org-table-any-line-regexp
3221 org-table-line-regexp)))
3222 nil))
3223 (defsubst org-table-p () (org-at-table-p))
3225 (defun org-at-table.el-p ()
3226 "Return t if and only if we are at a table.el table."
3227 (and (org-at-table-p 'any)
3228 (save-excursion
3229 (goto-char (org-table-begin 'any))
3230 (looking-at org-table1-hline-regexp))))
3231 (defun org-table-recognize-table.el ()
3232 "If there is a table.el table nearby, recognize it and move into it."
3233 (if org-table-tab-recognizes-table.el
3234 (if (org-at-table.el-p)
3235 (progn
3236 (beginning-of-line 1)
3237 (if (looking-at org-table-dataline-regexp)
3239 (if (looking-at org-table1-hline-regexp)
3240 (progn
3241 (beginning-of-line 2)
3242 (if (looking-at org-table-any-border-regexp)
3243 (beginning-of-line -1)))))
3244 (if (re-search-forward "|" (org-table-end t) t)
3245 (progn
3246 (require 'table)
3247 (if (table--at-cell-p (point))
3249 (message "recognizing table.el table...")
3250 (table-recognize-table)
3251 (message "recognizing table.el table...done")))
3252 (error "This should not happen..."))
3254 nil)
3255 nil))
3257 (defun org-at-table-hline-p ()
3258 "Return t if the cursor is inside a hline in a table."
3259 (if org-enable-table-editor
3260 (save-excursion
3261 (beginning-of-line 1)
3262 (looking-at org-table-hline-regexp))
3263 nil))
3265 (defvar org-table-clean-did-remove-column nil)
3267 (defun org-table-map-tables (function)
3268 "Apply FUNCTION to the start of all tables in the buffer."
3269 (save-excursion
3270 (save-restriction
3271 (widen)
3272 (goto-char (point-min))
3273 (while (re-search-forward org-table-any-line-regexp nil t)
3274 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3275 (beginning-of-line 1)
3276 (when (looking-at org-table-line-regexp)
3277 (save-excursion (funcall function))
3278 (or (looking-at org-table-line-regexp)
3279 (forward-char 1)))
3280 (re-search-forward org-table-any-border-regexp nil 1))))
3281 (message "Mapping tables: done"))
3283 ;; Declare and autoload functions from org-exp.el & Co
3285 (declare-function org-default-export-plist "org-exp")
3286 (declare-function org-infile-export-plist "org-exp")
3287 (declare-function org-get-current-options "org-exp")
3288 (eval-and-compile
3289 (org-autoload "org-exp"
3290 '(org-export org-export-visible
3291 org-insert-export-options-template
3292 org-table-clean-before-export))
3293 (org-autoload "org-ascii"
3294 '(org-export-as-ascii org-export-ascii-preprocess
3295 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3296 org-export-region-as-ascii))
3297 (org-autoload "org-latex"
3298 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3299 org-replace-region-by-latex org-export-region-as-latex
3300 org-export-as-latex org-export-as-pdf
3301 org-export-as-pdf-and-open))
3302 (org-autoload "org-html"
3303 '(org-export-as-html-and-open
3304 org-export-as-html-batch org-export-as-html-to-buffer
3305 org-replace-region-by-html org-export-region-as-html
3306 org-export-as-html))
3307 (org-autoload "org-docbook"
3308 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3309 org-replace-region-by-docbook org-export-region-as-docbook
3310 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3311 org-export-as-docbook))
3312 (org-autoload "org-icalendar"
3313 '(org-export-icalendar-this-file
3314 org-export-icalendar-all-agenda-files
3315 org-export-icalendar-combine-agenda-files))
3316 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3317 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3319 ;; Declare and autoload functions from org-agenda.el
3321 (eval-and-compile
3322 (org-autoload "org-agenda"
3323 '(org-agenda org-agenda-list org-search-view
3324 org-todo-list org-tags-view org-agenda-list-stuck-projects
3325 org-diary org-agenda-to-appt
3326 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3328 ;; Autoload org-remember
3330 (eval-and-compile
3331 (org-autoload "org-remember"
3332 '(org-remember-insinuate org-remember-annotation
3333 org-remember-apply-template org-remember org-remember-handler)))
3335 ;; Autoload org-clock.el
3338 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3339 (beg end))
3340 (declare-function org-clock-update-mode-line "org-clock" ())
3341 (declare-function org-resolve-clocks "org-clock"
3342 (&optional also-non-dangling-p prompt last-valid))
3343 (defvar org-clock-start-time)
3344 (defvar org-clock-marker (make-marker)
3345 "Marker recording the last clock-in.")
3346 (defvar org-clock-hd-marker (make-marker)
3347 "Marker recording the last clock-in, but the headline position.")
3348 (defvar org-clock-heading ""
3349 "The heading of the current clock entry.")
3350 (defun org-clock-is-active ()
3351 "Return non-nil if clock is currently running.
3352 The return value is actually the clock marker."
3353 (marker-buffer org-clock-marker))
3355 (eval-and-compile
3356 (org-autoload
3357 "org-clock"
3358 '(org-clock-in org-clock-out org-clock-cancel
3359 org-clock-goto org-clock-sum org-clock-display
3360 org-clock-remove-overlays org-clock-report
3361 org-clocktable-shift org-dblock-write:clocktable
3362 org-get-clocktable org-resolve-clocks)))
3364 (defun org-clock-update-time-maybe ()
3365 "If this is a CLOCK line, update it and return t.
3366 Otherwise, return nil."
3367 (interactive)
3368 (save-excursion
3369 (beginning-of-line 1)
3370 (skip-chars-forward " \t")
3371 (when (looking-at org-clock-string)
3372 (let ((re (concat "[ \t]*" org-clock-string
3373 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3374 "\\([ \t]*=>.*\\)?\\)?"))
3375 ts te h m s neg)
3376 (cond
3377 ((not (looking-at re))
3378 nil)
3379 ((not (match-end 2))
3380 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3381 (> org-clock-marker (point))
3382 (<= org-clock-marker (point-at-eol)))
3383 ;; The clock is running here
3384 (setq org-clock-start-time
3385 (apply 'encode-time
3386 (org-parse-time-string (match-string 1))))
3387 (org-clock-update-mode-line)))
3389 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3390 (end-of-line 1)
3391 (setq ts (match-string 1)
3392 te (match-string 3))
3393 (setq s (- (org-float-time
3394 (apply 'encode-time (org-parse-time-string te)))
3395 (org-float-time
3396 (apply 'encode-time (org-parse-time-string ts))))
3397 neg (< s 0)
3398 s (abs s)
3399 h (floor (/ s 3600))
3400 s (- s (* 3600 h))
3401 m (floor (/ s 60))
3402 s (- s (* 60 s)))
3403 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3404 t))))))
3406 (defun org-check-running-clock ()
3407 "Check if the current buffer contains the running clock.
3408 If yes, offer to stop it and to save the buffer with the changes."
3409 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3410 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3411 (buffer-name))))
3412 (org-clock-out)
3413 (when (y-or-n-p "Save changed buffer?")
3414 (save-buffer))))
3416 (defun org-clocktable-try-shift (dir n)
3417 "Check if this line starts a clock table, if yes, shift the time block."
3418 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3419 (org-clocktable-shift dir n)))
3421 ;; Autoload org-timer.el
3423 (eval-and-compile
3424 (org-autoload
3425 "org-timer"
3426 '(org-timer-start org-timer org-timer-item
3427 org-timer-change-times-in-region
3428 org-timer-set-timer
3429 org-timer-reset-timers
3430 org-timer-show-remaining-time)))
3432 ;; Autoload org-feed.el
3434 (eval-and-compile
3435 (org-autoload
3436 "org-feed"
3437 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3440 ;; Autoload org-indent.el
3442 ;; Define the variable already here, to make sure we have it.
3443 (defvar org-indent-mode nil
3444 "Non-nil if Org-Indent mode is enabled.
3445 Use the command `org-indent-mode' to change this variable.")
3447 (eval-and-compile
3448 (org-autoload
3449 "org-indent"
3450 '(org-indent-mode)))
3452 ;; Autoload org-mobile.el
3454 (eval-and-compile
3455 (org-autoload
3456 "org-mobile"
3457 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3459 ;; Autoload archiving code
3460 ;; The stuff that is needed for cycling and tags has to be defined here.
3462 (defgroup org-archive nil
3463 "Options concerning archiving in Org-mode."
3464 :tag "Org Archive"
3465 :group 'org-structure)
3467 (defcustom org-archive-location "%s_archive::"
3468 "The location where subtrees should be archived.
3470 The value of this variable is a string, consisting of two parts,
3471 separated by a double-colon. The first part is a filename and
3472 the second part is a headline.
3474 When the filename is omitted, archiving happens in the same file.
3475 %s in the filename will be replaced by the current file
3476 name (without the directory part). Archiving to a different file
3477 is useful to keep archived entries from contributing to the
3478 Org-mode Agenda.
3480 The archived entries will be filed as subtrees of the specified
3481 headline. When the headline is omitted, the subtrees are simply
3482 filed away at the end of the file, as top-level entries. Also in
3483 the heading you can use %s to represent the file name, this can be
3484 useful when using the same archive for a number of different files.
3486 Here are a few examples:
3487 \"%s_archive::\"
3488 If the current file is Projects.org, archive in file
3489 Projects.org_archive, as top-level trees. This is the default.
3491 \"::* Archived Tasks\"
3492 Archive in the current file, under the top-level headline
3493 \"* Archived Tasks\".
3495 \"~/org/archive.org::\"
3496 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3498 \"~/org/archive.org::From %s\"
3499 Archive in file ~/org/archive.org (absolute path), under headlines
3500 \"From FILENAME\" where file name is the current file name.
3502 \"basement::** Finished Tasks\"
3503 Archive in file ./basement (relative path), as level 3 trees
3504 below the level 2 heading \"** Finished Tasks\".
3506 You may set this option on a per-file basis by adding to the buffer a
3507 line like
3509 #+ARCHIVE: basement::** Finished Tasks
3511 You may also define it locally for a subtree by setting an ARCHIVE property
3512 in the entry. If such a property is found in an entry, or anywhere up
3513 the hierarchy, it will be used."
3514 :group 'org-archive
3515 :type 'string)
3517 (defcustom org-archive-tag "ARCHIVE"
3518 "The tag that marks a subtree as archived.
3519 An archived subtree does not open during visibility cycling, and does
3520 not contribute to the agenda listings.
3521 After changing this, font-lock must be restarted in the relevant buffers to
3522 get the proper fontification."
3523 :group 'org-archive
3524 :group 'org-keywords
3525 :type 'string)
3527 (defcustom org-agenda-skip-archived-trees t
3528 "Non-nil means, the agenda will skip any items located in archived trees.
3529 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3530 variable is no longer recommended, you should leave it at the value t.
3531 Instead, use the key `v' to cycle the archives-mode in the agenda."
3532 :group 'org-archive
3533 :group 'org-agenda-skip
3534 :type 'boolean)
3536 (defcustom org-columns-skip-archived-trees t
3537 "Non-nil means, ignore archived trees when creating column view."
3538 :group 'org-archive
3539 :group 'org-properties
3540 :type 'boolean)
3542 (defcustom org-cycle-open-archived-trees nil
3543 "Non-nil means, `org-cycle' will open archived trees.
3544 An archived tree is a tree marked with the tag ARCHIVE.
3545 When nil, archived trees will stay folded. You can still open them with
3546 normal outline commands like `show-all', but not with the cycling commands."
3547 :group 'org-archive
3548 :group 'org-cycle
3549 :type 'boolean)
3551 (defcustom org-sparse-tree-open-archived-trees nil
3552 "Non-nil means sparse tree construction shows matches in archived trees.
3553 When nil, matches in these trees are highlighted, but the trees are kept in
3554 collapsed state."
3555 :group 'org-archive
3556 :group 'org-sparse-trees
3557 :type 'boolean)
3559 (defun org-cycle-hide-archived-subtrees (state)
3560 "Re-hide all archived subtrees after a visibility state change."
3561 (when (and (not org-cycle-open-archived-trees)
3562 (not (memq state '(overview folded))))
3563 (save-excursion
3564 (let* ((globalp (memq state '(contents all)))
3565 (beg (if globalp (point-min) (point)))
3566 (end (if globalp (point-max) (org-end-of-subtree t))))
3567 (org-hide-archived-subtrees beg end)
3568 (goto-char beg)
3569 (if (looking-at (concat ".*:" org-archive-tag ":"))
3570 (message "%s" (substitute-command-keys
3571 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3573 (defun org-force-cycle-archived ()
3574 "Cycle subtree even if it is archived."
3575 (interactive)
3576 (setq this-command 'org-cycle)
3577 (let ((org-cycle-open-archived-trees t))
3578 (call-interactively 'org-cycle)))
3580 (defun org-hide-archived-subtrees (beg end)
3581 "Re-hide all archived subtrees after a visibility state change."
3582 (save-excursion
3583 (let* ((re (concat ":" org-archive-tag ":")))
3584 (goto-char beg)
3585 (while (re-search-forward re end t)
3586 (and (org-on-heading-p) (org-flag-subtree t))
3587 (org-end-of-subtree t)))))
3589 (defun org-flag-subtree (flag)
3590 (save-excursion
3591 (org-back-to-heading t)
3592 (outline-end-of-heading)
3593 (outline-flag-region (point)
3594 (progn (org-end-of-subtree t) (point))
3595 flag)))
3597 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3599 (eval-and-compile
3600 (org-autoload "org-archive"
3601 '(org-add-archive-files org-archive-subtree
3602 org-archive-to-archive-sibling org-toggle-archive-tag
3603 org-archive-subtree-default
3604 org-archive-subtree-default-with-confirmation)))
3606 ;; Autoload Column View Code
3608 (declare-function org-columns-number-to-string "org-colview")
3609 (declare-function org-columns-get-format-and-top-level "org-colview")
3610 (declare-function org-columns-compute "org-colview")
3612 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3613 '(org-columns-number-to-string org-columns-get-format-and-top-level
3614 org-columns-compute org-agenda-columns org-columns-remove-overlays
3615 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3617 ;; Autoload ID code
3619 (declare-function org-id-store-link "org-id")
3620 (declare-function org-id-locations-load "org-id")
3621 (declare-function org-id-locations-save "org-id")
3622 (defvar org-id-track-globally)
3623 (org-autoload "org-id"
3624 '(org-id-get-create org-id-new org-id-copy org-id-get
3625 org-id-get-with-outline-path-completion
3626 org-id-get-with-outline-drilling
3627 org-id-goto org-id-find org-id-store-link))
3629 ;; Autoload Plotting Code
3631 (org-autoload "org-plot"
3632 '(org-plot/gnuplot))
3634 ;;; Variables for pre-computed regular expressions, all buffer local
3636 (defvar org-drawer-regexp nil
3637 "Matches first line of a hidden block.")
3638 (make-variable-buffer-local 'org-drawer-regexp)
3639 (defvar org-todo-regexp nil
3640 "Matches any of the TODO state keywords.")
3641 (make-variable-buffer-local 'org-todo-regexp)
3642 (defvar org-not-done-regexp nil
3643 "Matches any of the TODO state keywords except the last one.")
3644 (make-variable-buffer-local 'org-not-done-regexp)
3645 (defvar org-not-done-heading-regexp nil
3646 "Matches a TODO headline that is not done.")
3647 (make-variable-buffer-local 'org-not-done-regexp)
3648 (defvar org-todo-line-regexp nil
3649 "Matches a headline and puts TODO state into group 2 if present.")
3650 (make-variable-buffer-local 'org-todo-line-regexp)
3651 (defvar org-complex-heading-regexp nil
3652 "Matches a headline and puts everything into groups:
3653 group 1: the stars
3654 group 2: The todo keyword, maybe
3655 group 3: Priority cookie
3656 group 4: True headline
3657 group 5: Tags")
3658 (make-variable-buffer-local 'org-complex-heading-regexp)
3659 (defvar org-complex-heading-regexp-format nil)
3660 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3661 (defvar org-todo-line-tags-regexp nil
3662 "Matches a headline and puts TODO state into group 2 if present.
3663 Also put tags into group 4 if tags are present.")
3664 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3665 (defvar org-nl-done-regexp nil
3666 "Matches newline followed by a headline with the DONE keyword.")
3667 (make-variable-buffer-local 'org-nl-done-regexp)
3668 (defvar org-looking-at-done-regexp nil
3669 "Matches the DONE keyword a point.")
3670 (make-variable-buffer-local 'org-looking-at-done-regexp)
3671 (defvar org-ds-keyword-length 12
3672 "Maximum length of the Deadline and SCHEDULED keywords.")
3673 (make-variable-buffer-local 'org-ds-keyword-length)
3674 (defvar org-deadline-regexp nil
3675 "Matches the DEADLINE keyword.")
3676 (make-variable-buffer-local 'org-deadline-regexp)
3677 (defvar org-deadline-time-regexp nil
3678 "Matches the DEADLINE keyword together with a time stamp.")
3679 (make-variable-buffer-local 'org-deadline-time-regexp)
3680 (defvar org-deadline-line-regexp nil
3681 "Matches the DEADLINE keyword and the rest of the line.")
3682 (make-variable-buffer-local 'org-deadline-line-regexp)
3683 (defvar org-scheduled-regexp nil
3684 "Matches the SCHEDULED keyword.")
3685 (make-variable-buffer-local 'org-scheduled-regexp)
3686 (defvar org-scheduled-time-regexp nil
3687 "Matches the SCHEDULED keyword together with a time stamp.")
3688 (make-variable-buffer-local 'org-scheduled-time-regexp)
3689 (defvar org-closed-time-regexp nil
3690 "Matches the CLOSED keyword together with a time stamp.")
3691 (make-variable-buffer-local 'org-closed-time-regexp)
3693 (defvar org-keyword-time-regexp nil
3694 "Matches any of the 4 keywords, together with the time stamp.")
3695 (make-variable-buffer-local 'org-keyword-time-regexp)
3696 (defvar org-keyword-time-not-clock-regexp nil
3697 "Matches any of the 3 keywords, together with the time stamp.")
3698 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3699 (defvar org-maybe-keyword-time-regexp nil
3700 "Matches a timestamp, possibly preceeded by a keyword.")
3701 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3702 (defvar org-planning-or-clock-line-re nil
3703 "Matches a line with planning or clock info.")
3704 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3706 (defconst org-plain-time-of-day-regexp
3707 (concat
3708 "\\(\\<[012]?[0-9]"
3709 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3710 "\\(--?"
3711 "\\(\\<[012]?[0-9]"
3712 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3713 "\\)?")
3714 "Regular expression to match a plain time or time range.
3715 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3716 groups carry important information:
3717 0 the full match
3718 1 the first time, range or not
3719 8 the second time, if it is a range.")
3721 (defconst org-plain-time-extension-regexp
3722 (concat
3723 "\\(\\<[012]?[0-9]"
3724 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3725 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3726 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3727 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3728 groups carry important information:
3729 0 the full match
3730 7 hours of duration
3731 9 minutes of duration")
3733 (defconst org-stamp-time-of-day-regexp
3734 (concat
3735 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3736 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3737 "\\(--?"
3738 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3739 "Regular expression to match a timestamp time or time range.
3740 After a match, the following groups carry important information:
3741 0 the full match
3742 1 date plus weekday, for back referencing to make sure both times are on the same day
3743 2 the first time, range or not
3744 4 the second time, if it is a range.")
3746 (defconst org-startup-options
3747 '(("fold" org-startup-folded t)
3748 ("overview" org-startup-folded t)
3749 ("nofold" org-startup-folded nil)
3750 ("showall" org-startup-folded nil)
3751 ("showeverything" org-startup-folded showeverything)
3752 ("content" org-startup-folded content)
3753 ("indent" org-startup-indented t)
3754 ("noindent" org-startup-indented nil)
3755 ("hidestars" org-hide-leading-stars t)
3756 ("showstars" org-hide-leading-stars nil)
3757 ("odd" org-odd-levels-only t)
3758 ("oddeven" org-odd-levels-only nil)
3759 ("align" org-startup-align-all-tables t)
3760 ("noalign" org-startup-align-all-tables nil)
3761 ("customtime" org-display-custom-times t)
3762 ("logdone" org-log-done time)
3763 ("lognotedone" org-log-done note)
3764 ("nologdone" org-log-done nil)
3765 ("lognoteclock-out" org-log-note-clock-out t)
3766 ("nolognoteclock-out" org-log-note-clock-out nil)
3767 ("logrepeat" org-log-repeat state)
3768 ("lognoterepeat" org-log-repeat note)
3769 ("nologrepeat" org-log-repeat nil)
3770 ("logreschedule" org-log-reschedule time)
3771 ("lognotereschedule" org-log-reschedule note)
3772 ("nologreschedule" org-log-reschedule nil)
3773 ("logredeadline" org-log-redeadline time)
3774 ("lognoteredeadline" org-log-redeadline note)
3775 ("nologredeadline" org-log-redeadline nil)
3776 ("fninline" org-footnote-define-inline t)
3777 ("nofninline" org-footnote-define-inline nil)
3778 ("fnlocal" org-footnote-section nil)
3779 ("fnauto" org-footnote-auto-label t)
3780 ("fnprompt" org-footnote-auto-label nil)
3781 ("fnconfirm" org-footnote-auto-label confirm)
3782 ("fnplain" org-footnote-auto-label plain)
3783 ("fnadjust" org-footnote-auto-adjust t)
3784 ("nofnadjust" org-footnote-auto-adjust nil)
3785 ("constcgs" constants-unit-system cgs)
3786 ("constSI" constants-unit-system SI)
3787 ("noptag" org-tag-persistent-alist nil)
3788 ("hideblocks" org-hide-block-startup t)
3789 ("nohideblocks" org-hide-block-startup nil)
3790 ("beamer" org-startup-with-beamer-mode t))
3791 "Variable associated with STARTUP options for org-mode.
3792 Each element is a list of three items: The startup options as written
3793 in the #+STARTUP line, the corresponding variable, and the value to
3794 set this variable to if the option is found. An optional forth element PUSH
3795 means to push this value onto the list in the variable.")
3797 (defun org-set-regexps-and-options ()
3798 "Precompute regular expressions for current buffer."
3799 (when (org-mode-p)
3800 (org-set-local 'org-todo-kwd-alist nil)
3801 (org-set-local 'org-todo-key-alist nil)
3802 (org-set-local 'org-todo-key-trigger nil)
3803 (org-set-local 'org-todo-keywords-1 nil)
3804 (org-set-local 'org-done-keywords nil)
3805 (org-set-local 'org-todo-heads nil)
3806 (org-set-local 'org-todo-sets nil)
3807 (org-set-local 'org-todo-log-states nil)
3808 (org-set-local 'org-file-properties nil)
3809 (org-set-local 'org-file-tags nil)
3810 (let ((re (org-make-options-regexp
3811 '("CATEGORY" "TODO" "COLUMNS"
3812 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3813 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3814 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3815 (splitre "[ \t]+")
3816 kwds kws0 kwsa key log value cat arch tags const links hw dws
3817 tail sep kws1 prio props ftags drawers beamer-p
3818 ext-setup-or-nil setup-contents (start 0))
3819 (save-excursion
3820 (save-restriction
3821 (widen)
3822 (goto-char (point-min))
3823 (while (or (and ext-setup-or-nil
3824 (string-match re ext-setup-or-nil start)
3825 (setq start (match-end 0)))
3826 (and (setq ext-setup-or-nil nil start 0)
3827 (re-search-forward re nil t)))
3828 (setq key (upcase (match-string 1 ext-setup-or-nil))
3829 value (org-match-string-no-properties 2 ext-setup-or-nil))
3830 (cond
3831 ((equal key "CATEGORY")
3832 (if (string-match "[ \t]+$" value)
3833 (setq value (replace-match "" t t value)))
3834 (setq cat value))
3835 ((member key '("SEQ_TODO" "TODO"))
3836 (push (cons 'sequence (org-split-string value splitre)) kwds))
3837 ((equal key "TYP_TODO")
3838 (push (cons 'type (org-split-string value splitre)) kwds))
3839 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3840 ;; general TODO-like setup
3841 (push (cons (intern (downcase (match-string 1 key)))
3842 (org-split-string value splitre)) kwds))
3843 ((equal key "TAGS")
3844 (setq tags (append tags (if tags '("\\n") nil)
3845 (org-split-string value splitre))))
3846 ((equal key "COLUMNS")
3847 (org-set-local 'org-columns-default-format value))
3848 ((equal key "LINK")
3849 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3850 (push (cons (match-string 1 value)
3851 (org-trim (match-string 2 value)))
3852 links)))
3853 ((equal key "PRIORITIES")
3854 (setq prio (org-split-string value " +")))
3855 ((equal key "PROPERTY")
3856 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3857 (push (cons (match-string 1 value) (match-string 2 value))
3858 props)))
3859 ((equal key "FILETAGS")
3860 (when (string-match "\\S-" value)
3861 (setq ftags
3862 (append
3863 ftags
3864 (apply 'append
3865 (mapcar (lambda (x) (org-split-string x ":"))
3866 (org-split-string value)))))))
3867 ((equal key "DRAWERS")
3868 (setq drawers (org-split-string value splitre)))
3869 ((equal key "CONSTANTS")
3870 (setq const (append const (org-split-string value splitre))))
3871 ((equal key "STARTUP")
3872 (let ((opts (org-split-string value splitre))
3873 l var val)
3874 (while (setq l (pop opts))
3875 (when (setq l (assoc l org-startup-options))
3876 (setq var (nth 1 l) val (nth 2 l))
3877 (if (not (nth 3 l))
3878 (set (make-local-variable var) val)
3879 (if (not (listp (symbol-value var)))
3880 (set (make-local-variable var) nil))
3881 (set (make-local-variable var) (symbol-value var))
3882 (add-to-list var val))))))
3883 ((equal key "ARCHIVE")
3884 (string-match " *$" value)
3885 (setq arch (replace-match "" t t value))
3886 (remove-text-properties 0 (length arch)
3887 '(face t fontified t) arch))
3888 ((equal key "LATEX_CLASS")
3889 (setq beamer-p (equal value "beamer")))
3890 ((equal key "SETUPFILE")
3891 (setq setup-contents (org-file-contents
3892 (expand-file-name
3893 (org-remove-double-quotes value))
3894 'noerror))
3895 (if (not ext-setup-or-nil)
3896 (setq ext-setup-or-nil setup-contents start 0)
3897 (setq ext-setup-or-nil
3898 (concat (substring ext-setup-or-nil 0 start)
3899 "\n" setup-contents "\n"
3900 (substring ext-setup-or-nil start)))))
3901 ))))
3902 (when cat
3903 (org-set-local 'org-category (intern cat))
3904 (push (cons "CATEGORY" cat) props))
3905 (when prio
3906 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3907 (setq prio (mapcar 'string-to-char prio))
3908 (org-set-local 'org-highest-priority (nth 0 prio))
3909 (org-set-local 'org-lowest-priority (nth 1 prio))
3910 (org-set-local 'org-default-priority (nth 2 prio)))
3911 (and props (org-set-local 'org-file-properties (nreverse props)))
3912 (and ftags (org-set-local 'org-file-tags
3913 (mapcar 'org-add-prop-inherited ftags)))
3914 (and drawers (org-set-local 'org-drawers drawers))
3915 (and arch (org-set-local 'org-archive-location arch))
3916 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3917 ;; Process the TODO keywords
3918 (unless kwds
3919 ;; Use the global values as if they had been given locally.
3920 (setq kwds (default-value 'org-todo-keywords))
3921 (if (stringp (car kwds))
3922 (setq kwds (list (cons org-todo-interpretation
3923 (default-value 'org-todo-keywords)))))
3924 (setq kwds (reverse kwds)))
3925 (setq kwds (nreverse kwds))
3926 (let (inter kws kw)
3927 (while (setq kws (pop kwds))
3928 (let ((kws (or
3929 (run-hook-with-args-until-success
3930 'org-todo-setup-filter-hook kws)
3931 kws)))
3932 (setq inter (pop kws) sep (member "|" kws)
3933 kws0 (delete "|" (copy-sequence kws))
3934 kwsa nil
3935 kws1 (mapcar
3936 (lambda (x)
3937 ;; 1 2
3938 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3939 (progn
3940 (setq kw (match-string 1 x)
3941 key (and (match-end 2) (match-string 2 x))
3942 log (org-extract-log-state-settings x))
3943 (push (cons kw (and key (string-to-char key))) kwsa)
3944 (and log (push log org-todo-log-states))
3946 (error "Invalid TODO keyword %s" x)))
3947 kws0)
3948 kwsa (if kwsa (append '((:startgroup))
3949 (nreverse kwsa)
3950 '((:endgroup))))
3951 hw (car kws1)
3952 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3953 tail (list inter hw (car dws) (org-last dws))))
3954 (add-to-list 'org-todo-heads hw 'append)
3955 (push kws1 org-todo-sets)
3956 (setq org-done-keywords (append org-done-keywords dws nil))
3957 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3958 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3959 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3960 (setq org-todo-sets (nreverse org-todo-sets)
3961 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3962 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3963 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3964 ;; Process the constants
3965 (when const
3966 (let (e cst)
3967 (while (setq e (pop const))
3968 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3969 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3970 (setq org-table-formula-constants-local cst)))
3972 ;; Process the tags.
3973 (when tags
3974 (let (e tgs)
3975 (while (setq e (pop tags))
3976 (cond
3977 ((equal e "{") (push '(:startgroup) tgs))
3978 ((equal e "}") (push '(:endgroup) tgs))
3979 ((equal e "\\n") (push '(:newline) tgs))
3980 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3981 (push (cons (match-string 1 e)
3982 (string-to-char (match-string 2 e)))
3983 tgs))
3984 (t (push (list e) tgs))))
3985 (org-set-local 'org-tag-alist nil)
3986 (while (setq e (pop tgs))
3987 (or (and (stringp (car e))
3988 (assoc (car e) org-tag-alist))
3989 (push e org-tag-alist)))))
3991 ;; Compute the regular expressions and other local variables
3992 (if (not org-done-keywords)
3993 (setq org-done-keywords (and org-todo-keywords-1
3994 (list (org-last org-todo-keywords-1)))))
3995 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3996 (length org-scheduled-string)
3997 (length org-clock-string)
3998 (length org-closed-string)))
3999 org-drawer-regexp
4000 (concat "^[ \t]*:\\("
4001 (mapconcat 'regexp-quote org-drawers "\\|")
4002 "\\):[ \t]*$")
4003 org-not-done-keywords
4004 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4005 org-todo-regexp
4006 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4007 "\\|") "\\)\\>")
4008 org-not-done-regexp
4009 (concat "\\<\\("
4010 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4011 "\\)\\>")
4012 org-not-done-heading-regexp
4013 (concat "^\\(\\*+\\)[ \t]+\\("
4014 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4015 "\\)\\>")
4016 org-todo-line-regexp
4017 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4018 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4019 "\\)\\>\\)?[ \t]*\\(.*\\)")
4020 org-complex-heading-regexp
4021 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4022 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4023 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4024 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4025 org-complex-heading-regexp-format
4026 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4027 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4028 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4029 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4030 org-nl-done-regexp
4031 (concat "\n\\*+[ \t]+"
4032 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4033 "\\)" "\\>")
4034 org-todo-line-tags-regexp
4035 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4036 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4037 (org-re
4038 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4039 org-looking-at-done-regexp
4040 (concat "^" "\\(?:"
4041 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4042 "\\>")
4043 org-deadline-regexp (concat "\\<" org-deadline-string)
4044 org-deadline-time-regexp
4045 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4046 org-deadline-line-regexp
4047 (concat "\\<\\(" org-deadline-string "\\).*")
4048 org-scheduled-regexp
4049 (concat "\\<" org-scheduled-string)
4050 org-scheduled-time-regexp
4051 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4052 org-closed-time-regexp
4053 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4054 org-keyword-time-regexp
4055 (concat "\\<\\(" org-scheduled-string
4056 "\\|" org-deadline-string
4057 "\\|" org-closed-string
4058 "\\|" org-clock-string "\\)"
4059 " *[[<]\\([^]>]+\\)[]>]")
4060 org-keyword-time-not-clock-regexp
4061 (concat "\\<\\(" org-scheduled-string
4062 "\\|" org-deadline-string
4063 "\\|" org-closed-string
4064 "\\)"
4065 " *[[<]\\([^]>]+\\)[]>]")
4066 org-maybe-keyword-time-regexp
4067 (concat "\\(\\<\\(" org-scheduled-string
4068 "\\|" org-deadline-string
4069 "\\|" org-closed-string
4070 "\\|" org-clock-string "\\)\\)?"
4071 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4072 org-planning-or-clock-line-re
4073 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4074 "\\|" org-deadline-string
4075 "\\|" org-closed-string "\\|" org-clock-string
4076 "\\)\\>\\)")
4078 (org-compute-latex-and-specials-regexp)
4079 (org-set-font-lock-defaults))))
4081 (defun org-file-contents (file &optional noerror)
4082 "Return the contents of FILE, as a string."
4083 (if (or (not file)
4084 (not (file-readable-p file)))
4085 (if noerror
4086 (progn
4087 (message "Cannot read file %s" file)
4088 (ding) (sit-for 2)
4090 (error "Cannot read file %s" file))
4091 (with-temp-buffer
4092 (insert-file-contents file)
4093 (buffer-string))))
4095 (defun org-extract-log-state-settings (x)
4096 "Extract the log state setting from a TODO keyword string.
4097 This will extract info from a string like \"WAIT(w@/!)\"."
4098 (let (kw key log1 log2)
4099 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4100 (setq kw (match-string 1 x)
4101 key (and (match-end 2) (match-string 2 x))
4102 log1 (and (match-end 3) (match-string 3 x))
4103 log2 (and (match-end 4) (match-string 4 x)))
4104 (and (or log1 log2)
4105 (list kw
4106 (and log1 (if (equal log1 "!") 'time 'note))
4107 (and log2 (if (equal log2 "!") 'time 'note)))))))
4109 (defun org-remove-keyword-keys (list)
4110 "Remove a pair of parenthesis at the end of each string in LIST."
4111 (mapcar (lambda (x)
4112 (if (string-match "(.*)$" x)
4113 (substring x 0 (match-beginning 0))
4115 list))
4117 ;; FIXME: this could be done much better, using second characters etc.
4118 (defun org-assign-fast-keys (alist)
4119 "Assign fast keys to a keyword-key alist.
4120 Respect keys that are already there."
4121 (let (new e k c c1 c2 (char ?a))
4122 (while (setq e (pop alist))
4123 (cond
4124 ((equal e '(:startgroup)) (push e new))
4125 ((equal e '(:endgroup)) (push e new))
4126 ((equal e '(:newline)) (push e new))
4128 (setq k (car e) c2 nil)
4129 (if (cdr e)
4130 (setq c (cdr e))
4131 ;; automatically assign a character.
4132 (setq c1 (string-to-char
4133 (downcase (substring
4134 k (if (= (string-to-char k) ?@) 1 0)))))
4135 (if (or (rassoc c1 new) (rassoc c1 alist))
4136 (while (or (rassoc char new) (rassoc char alist))
4137 (setq char (1+ char)))
4138 (setq c2 c1))
4139 (setq c (or c2 char)))
4140 (push (cons k c) new))))
4141 (nreverse new)))
4143 ;;; Some variables used in various places
4145 (defvar org-window-configuration nil
4146 "Used in various places to store a window configuration.")
4147 (defvar org-selected-window nil
4148 "Used in various places to store a window configuration.")
4149 (defvar org-finish-function nil
4150 "Function to be called when `C-c C-c' is used.
4151 This is for getting out of special buffers like remember.")
4154 ;; FIXME: Occasionally check by commenting these, to make sure
4155 ;; no other functions uses these, forgetting to let-bind them.
4156 (defvar entry)
4157 (defvar last-state)
4158 (defvar date)
4160 ;; Defined somewhere in this file, but used before definition.
4161 (defvar org-html-entities)
4162 (defvar org-struct-menu)
4163 (defvar org-org-menu)
4164 (defvar org-tbl-menu)
4166 ;;;; Define the Org-mode
4168 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4169 (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."))
4172 ;; We use a before-change function to check if a table might need
4173 ;; an update.
4174 (defvar org-table-may-need-update t
4175 "Indicates that a table might need an update.
4176 This variable is set by `org-before-change-function'.
4177 `org-table-align' sets it back to nil.")
4178 (defun org-before-change-function (beg end)
4179 "Every change indicates that a table might need an update."
4180 (setq org-table-may-need-update t))
4181 (defvar org-mode-map)
4182 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4183 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4184 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4185 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4186 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4187 (defvar org-table-buffer-is-an nil)
4188 (defconst org-outline-regexp "\\*+ ")
4190 ;;;###autoload
4191 (define-derived-mode org-mode outline-mode "Org"
4192 "Outline-based notes management and organizer, alias
4193 \"Carsten's outline-mode for keeping track of everything.\"
4195 Org-mode develops organizational tasks around a NOTES file which
4196 contains information about projects as plain text. Org-mode is
4197 implemented on top of outline-mode, which is ideal to keep the content
4198 of large files well structured. It supports ToDo items, deadlines and
4199 time stamps, which magically appear in the diary listing of the Emacs
4200 calendar. Tables are easily created with a built-in table editor.
4201 Plain text URL-like links connect to websites, emails (VM), Usenet
4202 messages (Gnus), BBDB entries, and any files related to the project.
4203 For printing and sharing of notes, an Org-mode file (or a part of it)
4204 can be exported as a structured ASCII or HTML file.
4206 The following commands are available:
4208 \\{org-mode-map}"
4210 ;; Get rid of Outline menus, they are not needed
4211 ;; Need to do this here because define-derived-mode sets up
4212 ;; the keymap so late. Still, it is a waste to call this each time
4213 ;; we switch another buffer into org-mode.
4214 (if (featurep 'xemacs)
4215 (when (boundp 'outline-mode-menu-heading)
4216 ;; Assume this is Greg's port, it used easymenu
4217 (easy-menu-remove outline-mode-menu-heading)
4218 (easy-menu-remove outline-mode-menu-show)
4219 (easy-menu-remove outline-mode-menu-hide))
4220 (define-key org-mode-map [menu-bar headings] 'undefined)
4221 (define-key org-mode-map [menu-bar hide] 'undefined)
4222 (define-key org-mode-map [menu-bar show] 'undefined))
4224 (org-load-modules-maybe)
4225 (easy-menu-add org-org-menu)
4226 (easy-menu-add org-tbl-menu)
4227 (org-install-agenda-files-menu)
4228 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4229 (org-add-to-invisibility-spec '(org-cwidth))
4230 (org-add-to-invisibility-spec '(org-hide-block . t))
4231 (when (featurep 'xemacs)
4232 (org-set-local 'line-move-ignore-invisible t))
4233 (org-set-local 'outline-regexp org-outline-regexp)
4234 (org-set-local 'outline-level 'org-outline-level)
4235 (when (and org-ellipsis
4236 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4237 (fboundp 'make-glyph-code))
4238 (unless org-display-table
4239 (setq org-display-table (make-display-table)))
4240 (set-display-table-slot
4241 org-display-table 4
4242 (vconcat (mapcar
4243 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4244 org-ellipsis)))
4245 (if (stringp org-ellipsis) org-ellipsis "..."))))
4246 (setq buffer-display-table org-display-table))
4247 (org-set-regexps-and-options)
4248 (when (and org-tag-faces (not org-tags-special-faces-re))
4249 ;; tag faces set outside customize.... force initialization.
4250 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4251 ;; Calc embedded
4252 (org-set-local 'calc-embedded-open-mode "# ")
4253 (modify-syntax-entry ?# "<")
4254 (modify-syntax-entry ?@ "w")
4255 (if org-startup-truncated (setq truncate-lines t))
4256 (org-set-local 'font-lock-unfontify-region-function
4257 'org-unfontify-region)
4258 ;; Activate before-change-function
4259 (org-set-local 'org-table-may-need-update t)
4260 (org-add-hook 'before-change-functions 'org-before-change-function nil
4261 'local)
4262 ;; Check for running clock before killing a buffer
4263 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4264 ;; Paragraphs and auto-filling
4265 (org-set-autofill-regexps)
4266 (setq indent-line-function 'org-indent-line-function)
4267 (org-update-radio-target-regexp)
4268 ;; Make sure dependence stuff works reliably, even for users who set it
4269 ;; too late :-(
4270 (if org-enforce-todo-dependencies
4271 (add-hook 'org-blocker-hook
4272 'org-block-todo-from-children-or-siblings-or-parent)
4273 (remove-hook 'org-blocker-hook
4274 'org-block-todo-from-children-or-siblings-or-parent))
4275 (if org-enforce-todo-checkbox-dependencies
4276 (add-hook 'org-blocker-hook
4277 'org-block-todo-from-checkboxes)
4278 (remove-hook 'org-blocker-hook
4279 'org-block-todo-from-checkboxes))
4281 ;; Comment characters
4282 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4283 (org-set-local 'comment-padding " ")
4285 ;; Align options lines
4286 (org-set-local
4287 'align-mode-rules-list
4288 '((org-in-buffer-settings
4289 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4290 (modes . '(org-mode)))))
4292 ;; Imenu
4293 (org-set-local 'imenu-create-index-function
4294 'org-imenu-get-tree)
4296 ;; Make isearch reveal context
4297 (if (or (featurep 'xemacs)
4298 (not (boundp 'outline-isearch-open-invisible-function)))
4299 ;; Emacs 21 and XEmacs make use of the hook
4300 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4301 ;; Emacs 22 deals with this through a special variable
4302 (org-set-local 'outline-isearch-open-invisible-function
4303 (lambda (&rest ignore) (org-show-context 'isearch))))
4305 ;; Turn on org-beamer-mode?
4306 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4308 ;; If empty file that did not turn on org-mode automatically, make it to.
4309 (if (and org-insert-mode-line-in-empty-file
4310 (interactive-p)
4311 (= (point-min) (point-max)))
4312 (insert "# -*- mode: org -*-\n\n"))
4313 (unless org-inhibit-startup
4314 (when org-startup-align-all-tables
4315 (let ((bmp (buffer-modified-p)))
4316 (org-table-map-tables 'org-table-align)
4317 (set-buffer-modified-p bmp)))
4318 (when org-startup-indented
4319 (require 'org-indent)
4320 (org-indent-mode 1))
4321 (unless org-inhibit-startup-visibility-stuff
4322 (org-set-startup-visibility))))
4324 (when (fboundp 'abbrev-table-put)
4325 (abbrev-table-put org-mode-abbrev-table
4326 :parents (list text-mode-abbrev-table)))
4328 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4330 (defun org-current-time ()
4331 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4332 (if (> (car org-time-stamp-rounding-minutes) 1)
4333 (let ((r (car org-time-stamp-rounding-minutes))
4334 (time (decode-time)))
4335 (apply 'encode-time
4336 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4337 (nthcdr 2 time))))
4338 (current-time)))
4340 ;;;; Font-Lock stuff, including the activators
4342 (defvar org-mouse-map (make-sparse-keymap))
4343 (org-defkey org-mouse-map
4344 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4345 (org-defkey org-mouse-map
4346 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4347 (when org-mouse-1-follows-link
4348 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4349 (when org-tab-follows-link
4350 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4351 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4353 (require 'font-lock)
4355 (defconst org-non-link-chars "]\t\n\r<>")
4356 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4357 "shell" "elisp"))
4358 (defvar org-link-types-re nil
4359 "Matches a link that has a url-like prefix like \"http:\"")
4360 (defvar org-link-re-with-space nil
4361 "Matches a link with spaces, optional angular brackets around it.")
4362 (defvar org-link-re-with-space2 nil
4363 "Matches a link with spaces, optional angular brackets around it.")
4364 (defvar org-link-re-with-space3 nil
4365 "Matches a link with spaces, only for internal part in bracket links.")
4366 (defvar org-angle-link-re nil
4367 "Matches link with angular brackets, spaces are allowed.")
4368 (defvar org-plain-link-re nil
4369 "Matches plain link, without spaces.")
4370 (defvar org-bracket-link-regexp nil
4371 "Matches a link in double brackets.")
4372 (defvar org-bracket-link-analytic-regexp nil
4373 "Regular expression used to analyze links.
4374 Here is what the match groups contain after a match:
4375 1: http:
4376 2: http
4377 3: path
4378 4: [desc]
4379 5: desc")
4380 (defvar org-bracket-link-analytic-regexp++ nil
4381 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4382 (defvar org-any-link-re nil
4383 "Regular expression matching any link.")
4385 (defun org-make-link-regexps ()
4386 "Update the link regular expressions.
4387 This should be called after the variable `org-link-types' has changed."
4388 (setq org-link-types-re
4389 (concat
4390 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4391 org-link-re-with-space
4392 (concat
4393 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4394 "\\([^" org-non-link-chars " ]"
4395 "[^" org-non-link-chars "]*"
4396 "[^" org-non-link-chars " ]\\)>?")
4397 org-link-re-with-space2
4398 (concat
4399 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4400 "\\([^" org-non-link-chars " ]"
4401 "[^\t\n\r]*"
4402 "[^" org-non-link-chars " ]\\)>?")
4403 org-link-re-with-space3
4404 (concat
4405 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4406 "\\([^" org-non-link-chars " ]"
4407 "[^\t\n\r]*\\)")
4408 org-angle-link-re
4409 (concat
4410 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4411 "\\([^" org-non-link-chars " ]"
4412 "[^" org-non-link-chars "]*"
4413 "\\)>")
4414 org-plain-link-re
4415 (concat
4416 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4417 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4418 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4419 org-bracket-link-regexp
4420 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4421 org-bracket-link-analytic-regexp
4422 (concat
4423 "\\[\\["
4424 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4425 "\\([^]]+\\)"
4426 "\\]"
4427 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4428 "\\]")
4429 org-bracket-link-analytic-regexp++
4430 (concat
4431 "\\[\\["
4432 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4433 "\\([^]]+\\)"
4434 "\\]"
4435 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4436 "\\]")
4437 org-any-link-re
4438 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4439 org-angle-link-re "\\)\\|\\("
4440 org-plain-link-re "\\)")))
4442 (org-make-link-regexps)
4444 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4445 "Regular expression for fast time stamp matching.")
4446 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4447 "Regular expression for fast time stamp matching.")
4448 (defconst org-ts-regexp0 "\\(\\([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 This one does not require the space after the date, so it can be used
4451 on a string that terminates immediately after the date.")
4452 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4453 "Regular expression matching time strings for analysis.")
4454 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4455 "Regular expression matching time stamps, with groups.")
4456 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4457 "Regular expression matching time stamps (also [..]), with groups.")
4458 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4459 "Regular expression matching a time stamp range.")
4460 (defconst org-tr-regexp-both
4461 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4462 "Regular expression matching a time stamp range.")
4463 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4464 org-ts-regexp "\\)?")
4465 "Regular expression matching a time stamp or time stamp range.")
4466 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4467 org-ts-regexp-both "\\)?")
4468 "Regular expression matching a time stamp or time stamp range.
4469 The time stamps may be either active or inactive.")
4471 (defvar org-emph-face nil)
4473 (defun org-do-emphasis-faces (limit)
4474 "Run through the buffer and add overlays to links."
4475 (let (rtn a)
4476 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4477 (if (not (= (char-after (match-beginning 3))
4478 (char-after (match-beginning 4))))
4479 (progn
4480 (setq rtn t)
4481 (setq a (assoc (match-string 3) org-emphasis-alist))
4482 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4483 'face
4484 (nth 1 a))
4485 (and (nth 4 a)
4486 (org-remove-flyspell-overlays-in
4487 (match-beginning 0) (match-end 0)))
4488 (add-text-properties (match-beginning 2) (match-end 2)
4489 '(font-lock-multiline t))
4490 (when org-hide-emphasis-markers
4491 (add-text-properties (match-end 4) (match-beginning 5)
4492 '(invisible org-link))
4493 (add-text-properties (match-beginning 3) (match-end 3)
4494 '(invisible org-link)))))
4495 (backward-char 1))
4496 rtn))
4498 (defun org-emphasize (&optional char)
4499 "Insert or change an emphasis, i.e. a font like bold or italic.
4500 If there is an active region, change that region to a new emphasis.
4501 If there is no region, just insert the marker characters and position
4502 the cursor between them.
4503 CHAR should be either the marker character, or the first character of the
4504 HTML tag associated with that emphasis. If CHAR is a space, the means
4505 to remove the emphasis of the selected region.
4506 If char is not given (for example in an interactive call) it
4507 will be prompted for."
4508 (interactive)
4509 (let ((eal org-emphasis-alist) e det
4510 (erc org-emphasis-regexp-components)
4511 (prompt "")
4512 (string "") beg end move tag c s)
4513 (if (org-region-active-p)
4514 (setq beg (region-beginning) end (region-end)
4515 string (buffer-substring beg end))
4516 (setq move t))
4518 (while (setq e (pop eal))
4519 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4520 c (aref tag 0))
4521 (push (cons c (string-to-char (car e))) det)
4522 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4523 (substring tag 1)))))
4524 (setq det (nreverse det))
4525 (unless char
4526 (message "%s" (concat "Emphasis marker or tag:" prompt))
4527 (setq char (read-char-exclusive)))
4528 (setq char (or (cdr (assoc char det)) char))
4529 (if (equal char ?\ )
4530 (setq s "" move nil)
4531 (unless (assoc (char-to-string char) org-emphasis-alist)
4532 (error "No such emphasis marker: \"%c\"" char))
4533 (setq s (char-to-string char)))
4534 (while (and (> (length string) 1)
4535 (equal (substring string 0 1) (substring string -1))
4536 (assoc (substring string 0 1) org-emphasis-alist))
4537 (setq string (substring string 1 -1)))
4538 (setq string (concat s string s))
4539 (if beg (delete-region beg end))
4540 (unless (or (bolp)
4541 (string-match (concat "[" (nth 0 erc) "\n]")
4542 (char-to-string (char-before (point)))))
4543 (insert " "))
4544 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4545 (char-to-string (char-after (point))))
4546 (insert " ") (backward-char 1))
4547 (insert string)
4548 (and move (backward-char 1))))
4550 (defconst org-nonsticky-props
4551 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4553 (defsubst org-rear-nonsticky-at (pos)
4554 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4556 (defun org-activate-plain-links (limit)
4557 "Run through the buffer and add overlays to links."
4558 (catch 'exit
4559 (let (f)
4560 (if (re-search-forward org-plain-link-re limit t)
4561 (progn
4562 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4563 (setq f (get-text-property (match-beginning 0) 'face))
4564 (if (or (eq f 'org-tag)
4565 (and (listp f) (memq 'org-tag f)))
4567 (add-text-properties (match-beginning 0) (match-end 0)
4568 (list 'mouse-face 'highlight
4569 'face 'org-link
4570 'keymap org-mouse-map))
4571 (org-rear-nonsticky-at (match-end 0)))
4572 t)))))
4574 (defun org-activate-code (limit)
4575 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4576 (progn
4577 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4578 (remove-text-properties (match-beginning 0) (match-end 0)
4579 '(display t invisible t intangible t))
4580 t)))
4582 (defun org-fontify-meta-lines-and-blocks (limit)
4583 "Fontify #+ lines and blocks, in the correct ways."
4584 (let ((case-fold-search t))
4585 (if (re-search-forward
4586 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4587 limit t)
4588 (let ((beg (match-beginning 0))
4589 (beg1 (line-beginning-position 2))
4590 (dc1 (downcase (match-string 2)))
4591 (dc3 (downcase (match-string 3)))
4592 end end1 quoting block-type)
4593 (cond
4594 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4595 ;; a single line of backend-specific content
4596 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4597 (remove-text-properties (match-beginning 0) (match-end 0)
4598 '(display t invisible t intangible t))
4599 (add-text-properties (match-beginning 1) (match-end 3)
4600 '(font-lock-fontified t face org-meta-line))
4601 (add-text-properties (match-beginning 6) (match-end 6)
4602 '(font-lock-fontified t face org-block))
4604 ((and (match-end 4) (equal dc3 "begin"))
4605 ;; Truely a block
4606 (setq block-type (downcase (match-string 5))
4607 quoting (member block-type org-protecting-blocks))
4608 (when (re-search-forward
4609 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4610 nil t) ;; on purpose, we look further than LIMIT
4611 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4612 (when quoting
4613 (remove-text-properties beg end
4614 '(display t invisible t intangible t)))
4615 (add-text-properties
4616 beg end
4617 '(font-lock-fontified t font-lock-multiline t))
4618 (add-text-properties beg beg1 '(face org-meta-line))
4619 (add-text-properties end1 end '(face org-meta-line))
4620 (cond
4621 (quoting
4622 (add-text-properties beg1 end1 '(face org-block)))
4623 ((string= block-type "quote")
4624 (add-text-properties beg1 end1 '(face org-quote)))
4625 ((string= block-type "verse")
4626 (add-text-properties beg1 end1 '(face org-verse))))
4628 ((not (member (char-after beg) '(?\ ?\t)))
4629 ;; just any other in-buffer setting, but not indented
4630 (add-text-properties
4631 beg (match-end 0)
4632 '(font-lock-fontified t face org-meta-line))
4634 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4635 "orgtbl:" "tblfm:" "tblname:"))
4636 (and (match-end 4) (equal dc3 "attr")))
4637 (add-text-properties
4638 beg (match-end 0)
4639 '(font-lock-fontified t face org-meta-line))
4641 ((member dc3 '(" " ""))
4642 (add-text-properties
4643 beg (match-end 0)
4644 '(font-lock-fontified t face font-lock-comment-face)))
4645 (t nil))))))
4647 (defun org-activate-angle-links (limit)
4648 "Run through the buffer and add overlays to links."
4649 (if (re-search-forward org-angle-link-re limit t)
4650 (progn
4651 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4652 (add-text-properties (match-beginning 0) (match-end 0)
4653 (list 'mouse-face 'highlight
4654 'keymap org-mouse-map))
4655 (org-rear-nonsticky-at (match-end 0))
4656 t)))
4658 (defun org-activate-footnote-links (limit)
4659 "Run through the buffer and add overlays to links."
4660 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4661 limit t)
4662 (progn
4663 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4664 (add-text-properties (match-beginning 2) (match-end 2)
4665 (list 'mouse-face 'highlight
4666 'keymap org-mouse-map
4667 'help-echo
4668 (if (= (point-at-bol) (match-beginning 2))
4669 "Footnote definition"
4670 "Footnote reference")
4672 (org-rear-nonsticky-at (match-end 2))
4673 t)))
4675 (defun org-activate-bracket-links (limit)
4676 "Run through the buffer and add overlays to bracketed links."
4677 (if (re-search-forward org-bracket-link-regexp limit t)
4678 (let* ((help (concat "LINK: "
4679 (org-match-string-no-properties 1)))
4680 ;; FIXME: above we should remove the escapes.
4681 ;; but that requires another match, protecting match data,
4682 ;; a lot of overhead for font-lock.
4683 (ip (org-maybe-intangible
4684 (list 'invisible 'org-link
4685 'keymap org-mouse-map 'mouse-face 'highlight
4686 'font-lock-multiline t 'help-echo help)))
4687 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4688 'font-lock-multiline t 'help-echo help)))
4689 ;; We need to remove the invisible property here. Table narrowing
4690 ;; may have made some of this invisible.
4691 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4692 (remove-text-properties (match-beginning 0) (match-end 0)
4693 '(invisible nil))
4694 (if (match-end 3)
4695 (progn
4696 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4697 (org-rear-nonsticky-at (match-beginning 3))
4698 (add-text-properties (match-beginning 3) (match-end 3) vp)
4699 (org-rear-nonsticky-at (match-end 3))
4700 (add-text-properties (match-end 3) (match-end 0) ip)
4701 (org-rear-nonsticky-at (match-end 0)))
4702 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4703 (org-rear-nonsticky-at (match-beginning 1))
4704 (add-text-properties (match-beginning 1) (match-end 1) vp)
4705 (org-rear-nonsticky-at (match-end 1))
4706 (add-text-properties (match-end 1) (match-end 0) ip)
4707 (org-rear-nonsticky-at (match-end 0)))
4708 t)))
4710 (defun org-activate-dates (limit)
4711 "Run through the buffer and add overlays to dates."
4712 (if (re-search-forward org-tsr-regexp-both limit t)
4713 (progn
4714 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4715 (add-text-properties (match-beginning 0) (match-end 0)
4716 (list 'mouse-face 'highlight
4717 'keymap org-mouse-map))
4718 (org-rear-nonsticky-at (match-end 0))
4719 (when org-display-custom-times
4720 (if (match-end 3)
4721 (org-display-custom-time (match-beginning 3) (match-end 3)))
4722 (org-display-custom-time (match-beginning 1) (match-end 1)))
4723 t)))
4725 (defvar org-target-link-regexp nil
4726 "Regular expression matching radio targets in plain text.")
4727 (make-variable-buffer-local 'org-target-link-regexp)
4728 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4729 "Regular expression matching a link target.")
4730 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4731 "Regular expression matching a radio target.")
4732 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4733 "Regular expression matching any target.")
4735 (defun org-activate-target-links (limit)
4736 "Run through the buffer and add overlays to target matches."
4737 (when org-target-link-regexp
4738 (let ((case-fold-search t))
4739 (if (re-search-forward org-target-link-regexp limit t)
4740 (progn
4741 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4742 (add-text-properties (match-beginning 0) (match-end 0)
4743 (list 'mouse-face 'highlight
4744 'keymap org-mouse-map
4745 'help-echo "Radio target link"
4746 'org-linked-text t))
4747 (org-rear-nonsticky-at (match-end 0))
4748 t)))))
4750 (defun org-update-radio-target-regexp ()
4751 "Find all radio targets in this file and update the regular expression."
4752 (interactive)
4753 (when (memq 'radio org-activate-links)
4754 (setq org-target-link-regexp
4755 (org-make-target-link-regexp (org-all-targets 'radio)))
4756 (org-restart-font-lock)))
4758 (defun org-hide-wide-columns (limit)
4759 (let (s e)
4760 (setq s (text-property-any (point) (or limit (point-max))
4761 'org-cwidth t))
4762 (when s
4763 (setq e (next-single-property-change s 'org-cwidth))
4764 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4765 (goto-char e)
4766 t)))
4768 (defvar org-latex-and-specials-regexp nil
4769 "Regular expression for highlighting export special stuff.")
4770 (defvar org-match-substring-regexp)
4771 (defvar org-match-substring-with-braces-regexp)
4773 ;; This should be with the exporter code, but we also use if for font-locking
4774 (defconst org-export-html-special-string-regexps
4775 '(("\\\\-" . "&shy;")
4776 ("---\\([^-]\\)" . "&mdash;\\1")
4777 ("--\\([^-]\\)" . "&ndash;\\1")
4778 ("\\.\\.\\." . "&hellip;"))
4779 "Regular expressions for special string conversion.")
4782 (defun org-compute-latex-and-specials-regexp ()
4783 "Compute regular expression for stuff treated specially by exporters."
4784 (if (not org-highlight-latex-fragments-and-specials)
4785 (org-set-local 'org-latex-and-specials-regexp nil)
4786 (require 'org-exp)
4787 (let*
4788 ((matchers (plist-get org-format-latex-options :matchers))
4789 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4790 org-latex-regexps)))
4791 (options (org-combine-plists (org-default-export-plist)
4792 (org-infile-export-plist)))
4793 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4794 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4795 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4796 (org-export-html-expand (plist-get options :expand-quoted-html))
4797 (org-export-with-special-strings (plist-get options :special-strings))
4798 (re-sub
4799 (cond
4800 ((equal org-export-with-sub-superscripts '{})
4801 (list org-match-substring-with-braces-regexp))
4802 (org-export-with-sub-superscripts
4803 (list org-match-substring-regexp))
4804 (t nil)))
4805 (re-latex
4806 (if org-export-with-LaTeX-fragments
4807 (mapcar (lambda (x) (nth 1 x)) latexs)))
4808 (re-macros
4809 (if org-export-with-TeX-macros
4810 (list (concat "\\\\"
4811 (regexp-opt
4812 (append (mapcar 'car org-html-entities)
4813 (if (boundp 'org-latex-entities)
4814 (mapcar (lambda (x)
4815 (or (car-safe x) x))
4816 org-latex-entities)
4817 nil))
4818 'words))) ; FIXME
4820 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4821 (re-special (if org-export-with-special-strings
4822 (mapcar (lambda (x) (car x))
4823 org-export-html-special-string-regexps)))
4824 (re-rest
4825 (delq nil
4826 (list
4827 (if org-export-html-expand "@<[^>\n]+>")
4828 ))))
4829 (org-set-local
4830 'org-latex-and-specials-regexp
4831 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4832 re-rest) "\\|")))))
4834 (defun org-do-latex-and-special-faces (limit)
4835 "Run through the buffer and add overlays to links."
4836 (when org-latex-and-specials-regexp
4837 (let (rtn d)
4838 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4839 limit t))
4840 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4841 'face))
4842 '(org-code org-verbatim underline)))
4843 (progn
4844 (setq rtn t
4845 d (cond ((member (char-after (1+ (match-beginning 0)))
4846 '(?_ ?^)) 1)
4847 (t 0)))
4848 (font-lock-prepend-text-property
4849 (+ d (match-beginning 0)) (match-end 0)
4850 'face 'org-latex-and-export-specials)
4851 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4852 '(font-lock-multiline t)))))
4853 rtn)))
4855 (defun org-restart-font-lock ()
4856 "Restart font-lock-mode, to force refontification."
4857 (when (and (boundp 'font-lock-mode) font-lock-mode)
4858 (font-lock-mode -1)
4859 (font-lock-mode 1)))
4861 (defun org-all-targets (&optional radio)
4862 "Return a list of all targets in this file.
4863 With optional argument RADIO, only find radio targets."
4864 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4865 rtn)
4866 (save-excursion
4867 (goto-char (point-min))
4868 (while (re-search-forward re nil t)
4869 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4870 rtn)))
4872 (defun org-make-target-link-regexp (targets)
4873 "Make regular expression matching all strings in TARGETS.
4874 The regular expression finds the targets also if there is a line break
4875 between words."
4876 (and targets
4877 (concat
4878 "\\<\\("
4879 (mapconcat
4880 (lambda (x)
4881 (while (string-match " +" x)
4882 (setq x (replace-match "\\s-+" t t x)))
4884 targets
4885 "\\|")
4886 "\\)\\>")))
4888 (defun org-activate-tags (limit)
4889 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4890 (progn
4891 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4892 (add-text-properties (match-beginning 1) (match-end 1)
4893 (list 'mouse-face 'highlight
4894 'keymap org-mouse-map))
4895 (org-rear-nonsticky-at (match-end 1))
4896 t)))
4898 (defun org-outline-level ()
4899 "Compute the outline level of the heading at point.
4900 This function assumes that the cursor is at the beginning of a line matched
4901 by outline-regexp. Otherwise it returns garbage.
4902 If this is called at a normal headline, the level is the number of stars.
4903 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4904 For plain list items, if they are matched by `outline-regexp', this returns
4905 1000 plus the line indentation."
4906 (save-excursion
4907 (looking-at outline-regexp)
4908 (if (match-beginning 1)
4909 (+ (org-get-string-indentation (match-string 1)) 1000)
4910 (1- (- (match-end 0) (match-beginning 0))))))
4912 (defvar org-font-lock-keywords nil)
4914 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4915 "Regular expression matching a property line.")
4917 (defvar org-font-lock-hook nil
4918 "Functions to be called for special font lock stuff.")
4920 (defun org-font-lock-hook (limit)
4921 (run-hook-with-args 'org-font-lock-hook limit))
4923 (defun org-set-font-lock-defaults ()
4924 (let* ((em org-fontify-emphasized-text)
4925 (lk org-activate-links)
4926 (org-font-lock-extra-keywords
4927 (list
4928 ;; Call the hook
4929 '(org-font-lock-hook)
4930 ;; Headlines
4931 `(,(if org-fontify-whole-heading-line
4932 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4933 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4934 (1 (org-get-level-face 1))
4935 (2 (org-get-level-face 2))
4936 (3 (org-get-level-face 3)))
4937 ;; Table lines
4938 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4939 (1 'org-table t))
4940 ;; Table internals
4941 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4942 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4943 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4944 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4945 ;; Drawers
4946 (list org-drawer-regexp '(0 'org-special-keyword t))
4947 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4948 ;; Properties
4949 (list org-property-re
4950 '(1 'org-special-keyword t)
4951 '(3 'org-property-value t))
4952 ;; Links
4953 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4954 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4955 (if (memq 'plain lk) '(org-activate-plain-links))
4956 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4957 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4958 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4959 (if (memq 'footnote lk) '(org-activate-footnote-links
4960 (2 'org-footnote t)))
4961 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4962 '(org-hide-wide-columns (0 nil append))
4963 ;; TODO lines
4964 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4965 '(1 (org-get-todo-face 1) t))
4966 ;; DONE
4967 (if org-fontify-done-headline
4968 (list (concat "^[*]+ +\\<\\("
4969 (mapconcat 'regexp-quote org-done-keywords "\\|")
4970 "\\)\\(.*\\)")
4971 '(2 'org-headline-done t))
4972 nil)
4973 ;; Priorities
4974 '(org-font-lock-add-priority-faces)
4975 ;; Tags
4976 '(org-font-lock-add-tag-faces)
4977 ;; Special keywords
4978 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4979 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4980 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4981 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4982 ;; Emphasis
4983 (if em
4984 (if (featurep 'xemacs)
4985 '(org-do-emphasis-faces (0 nil append))
4986 '(org-do-emphasis-faces)))
4987 ;; Checkboxes
4988 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4989 2 'org-checkbox prepend)
4990 (if org-provide-checkbox-statistics
4991 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4992 (0 (org-get-checkbox-statistics-face) t)))
4993 ;; Description list items
4994 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4995 2 'bold prepend)
4996 ;; ARCHIVEd headings
4997 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4998 '(1 'org-archived prepend))
4999 ;; Specials
5000 '(org-do-latex-and-special-faces)
5001 ;; Code
5002 '(org-activate-code (1 'org-code t))
5003 ;; COMMENT
5004 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5005 "\\|" org-quote-string "\\)\\>")
5006 '(1 'org-special-keyword t))
5007 '("^#.*" (0 'font-lock-comment-face t))
5008 ;; Blocks and meta lines
5009 '(org-fontify-meta-lines-and-blocks)
5011 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5012 ;; Now set the full font-lock-keywords
5013 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5014 (org-set-local 'font-lock-defaults
5015 '(org-font-lock-keywords t nil nil backward-paragraph))
5016 (kill-local-variable 'font-lock-keywords) nil))
5018 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5019 "Fontify string S like in Org-mode"
5020 (with-temp-buffer
5021 (insert s)
5022 (let ((org-odd-levels-only odd-levels))
5023 (org-mode)
5024 (font-lock-fontify-buffer)
5025 (buffer-string))))
5027 (defvar org-m nil)
5028 (defvar org-l nil)
5029 (defvar org-f nil)
5030 (defun org-get-level-face (n)
5031 "Get the right face for match N in font-lock matching of headlines."
5032 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5033 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5034 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5035 (cond
5036 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5037 ((eq n 2) org-f)
5038 (t (if org-level-color-stars-only nil org-f))))
5040 (defun org-get-todo-face (kwd)
5041 "Get the right face for a TODO keyword KWD.
5042 If KWD is a number, get the corresponding match group."
5043 (if (numberp kwd) (setq kwd (match-string kwd)))
5044 (or (cdr (assoc kwd org-todo-keyword-faces))
5045 (and (member kwd org-done-keywords) 'org-done)
5046 'org-todo))
5048 (defun org-font-lock-add-tag-faces (limit)
5049 "Add the special tag faces."
5050 (when (and org-tag-faces org-tags-special-faces-re)
5051 (while (re-search-forward org-tags-special-faces-re limit t)
5052 (add-text-properties (match-beginning 1) (match-end 1)
5053 (list 'face (org-get-tag-face 1)
5054 'font-lock-fontified t))
5055 (backward-char 1))))
5057 (defun org-font-lock-add-priority-faces (limit)
5058 "Add the special priority faces."
5059 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5060 (add-text-properties
5061 (match-beginning 0) (match-end 0)
5062 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5063 org-priority-faces))
5064 'org-special-keyword)
5065 'font-lock-fontified t))))
5067 (defun org-get-tag-face (kwd)
5068 "Get the right face for a TODO keyword KWD.
5069 If KWD is a number, get the corresponding match group."
5070 (if (numberp kwd) (setq kwd (match-string kwd)))
5071 (or (cdr (assoc kwd org-tag-faces))
5072 'org-tag))
5074 (defun org-unfontify-region (beg end &optional maybe_loudly)
5075 "Remove fontification and activation overlays from links."
5076 (font-lock-default-unfontify-region beg end)
5077 (let* ((buffer-undo-list t)
5078 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5079 (inhibit-modification-hooks t)
5080 deactivate-mark buffer-file-name buffer-file-truename)
5081 (remove-text-properties
5082 beg end
5083 (if org-indent-mode
5084 ;; also remove line-prefix and wrap-prefix properties
5085 '(mouse-face t keymap t org-linked-text t
5086 invisible t intangible t
5087 line-prefix t wrap-prefix t
5088 org-no-flyspell t)
5089 '(mouse-face t keymap t org-linked-text t
5090 invisible t intangible t
5091 org-no-flyspell t)))))
5093 ;;;; Visibility cycling, including org-goto and indirect buffer
5095 ;;; Cycling
5097 (defvar org-cycle-global-status nil)
5098 (make-variable-buffer-local 'org-cycle-global-status)
5099 (defvar org-cycle-subtree-status nil)
5100 (make-variable-buffer-local 'org-cycle-subtree-status)
5102 ;;;###autoload
5104 (defvar org-inlinetask-min-level)
5106 (defun org-cycle (&optional arg)
5107 "TAB-action and visibility cycling for Org-mode.
5109 This is the command invoked in Org-mode by the TAB key. Its main purpose
5110 is outline visibility cycling, but it also invokes other actions
5111 in special contexts.
5113 - When this function is called with a prefix argument, rotate the entire
5114 buffer through 3 states (global cycling)
5115 1. OVERVIEW: Show only top-level headlines.
5116 2. CONTENTS: Show all headlines of all levels, but no body text.
5117 3. SHOW ALL: Show everything.
5118 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5119 determined by the variable `org-startup-folded', and by any VISIBILITY
5120 properties in the buffer.
5121 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5122 including any drawers.
5124 - When inside a table, re-align the table and move to the next field.
5126 - When point is at the beginning of a headline, rotate the subtree started
5127 by this line through 3 different states (local cycling)
5128 1. FOLDED: Only the main headline is shown.
5129 2. CHILDREN: The main headline and the direct children are shown.
5130 From this state, you can move to one of the children
5131 and zoom in further.
5132 3. SUBTREE: Show the entire subtree, including body text.
5133 If there is no subtree, switch directly from CHILDREN to FOLDED.
5135 - When there is a numeric prefix, go up to a heading with level ARG, do
5136 a `show-subtree' and return to the previous cursor position. If ARG
5137 is negative, go up that many levels.
5139 - When point is not at the beginning of a headline, execute the global
5140 binding for TAB, which is re-indenting the line. See the option
5141 `org-cycle-emulate-tab' for details.
5143 - Special case: if point is at the beginning of the buffer and there is
5144 no headline in line 1, this function will act as if called with prefix arg.
5145 But only if also the variable `org-cycle-global-at-bob' is t."
5146 (interactive "P")
5147 (org-load-modules-maybe)
5148 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5149 (and org-cycle-level-after-item/entry-creation
5150 (or (org-cycle-level)
5151 (org-cycle-item-indentation))))
5152 (let* ((limit-level
5153 (or org-cycle-max-level
5154 (and (boundp 'org-inlinetask-min-level)
5155 org-inlinetask-min-level
5156 (1- org-inlinetask-min-level))))
5157 (nstars (and limit-level
5158 (if org-odd-levels-only
5159 (and limit-level (1- (* limit-level 2)))
5160 limit-level)))
5161 (outline-regexp
5162 (cond
5163 ((not (org-mode-p)) outline-regexp)
5164 ((or (eq org-cycle-include-plain-lists 'integrate)
5165 (and org-cycle-include-plain-lists (org-at-item-p)))
5166 (concat "\\(?:\\*"
5167 (if nstars (format "\\{1,%d\\}" nstars) "+")
5168 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5169 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5170 (bob-special (and org-cycle-global-at-bob (bobp)
5171 (not (looking-at outline-regexp))))
5172 (org-cycle-hook
5173 (if bob-special
5174 (delq 'org-optimize-window-after-visibility-change
5175 (copy-sequence org-cycle-hook))
5176 org-cycle-hook))
5177 (pos (point)))
5179 (if (or bob-special (equal arg '(4)))
5180 ;; special case: use global cycling
5181 (setq arg t))
5183 (cond
5185 ((equal arg '(16))
5186 (org-set-startup-visibility)
5187 (message "Startup visibility, plus VISIBILITY properties"))
5189 ((equal arg '(64))
5190 (show-all)
5191 (message "Entire buffer visible, including drawers"))
5193 ((org-at-table-p 'any)
5194 ;; Enter the table or move to the next field in the table
5195 (or (org-table-recognize-table.el)
5196 (progn
5197 (if arg (org-table-edit-field t)
5198 (org-table-justify-field-maybe)
5199 (call-interactively 'org-table-next-field)))))
5201 ((run-hook-with-args-until-success
5202 'org-tab-after-check-for-table-hook))
5204 ((eq arg t) ;; Global cycling
5205 (org-cycle-internal-global))
5207 ((and org-drawers org-drawer-regexp
5208 (save-excursion
5209 (beginning-of-line 1)
5210 (looking-at org-drawer-regexp)))
5211 ;; Toggle block visibility
5212 (org-flag-drawer
5213 (not (get-char-property (match-end 0) 'invisible))))
5215 ((integerp arg)
5216 ;; Show-subtree, ARG levels up from here.
5217 (save-excursion
5218 (org-back-to-heading)
5219 (outline-up-heading (if (< arg 0) (- arg)
5220 (- (funcall outline-level) arg)))
5221 (org-show-subtree)))
5223 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5224 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5226 (org-cycle-internal-local))
5228 ;; TAB emulation and template completion
5229 (buffer-read-only (org-back-to-heading))
5231 ((run-hook-with-args-until-success
5232 'org-tab-after-check-for-cycling-hook))
5234 ((org-try-structure-completion))
5236 ((org-try-cdlatex-tab))
5238 ((run-hook-with-args-until-success
5239 'org-tab-before-tab-emulation-hook))
5241 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5242 (or (not (bolp))
5243 (not (looking-at outline-regexp))))
5244 (call-interactively (global-key-binding "\t")))
5246 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5247 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5248 (or (and (eq org-cycle-emulate-tab 'white)
5249 (= (match-end 0) (point-at-eol)))
5250 (and (eq org-cycle-emulate-tab 'whitestart)
5251 (>= (match-end 0) pos))))
5253 (eq org-cycle-emulate-tab t))
5254 (call-interactively (global-key-binding "\t")))
5256 (t (save-excursion
5257 (org-back-to-heading)
5258 (org-cycle)))))))
5260 (defun org-cycle-internal-global ()
5261 "Do the global cycling action."
5262 (cond
5263 ((and (eq last-command this-command)
5264 (eq org-cycle-global-status 'overview))
5265 ;; We just created the overview - now do table of contents
5266 ;; This can be slow in very large buffers, so indicate action
5267 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5268 (message "CONTENTS...")
5269 (org-content)
5270 (message "CONTENTS...done")
5271 (setq org-cycle-global-status 'contents)
5272 (run-hook-with-args 'org-cycle-hook 'contents))
5274 ((and (eq last-command this-command)
5275 (eq org-cycle-global-status 'contents))
5276 ;; We just showed the table of contents - now show everything
5277 (run-hook-with-args 'org-pre-cycle-hook 'all)
5278 (show-all)
5279 (message "SHOW ALL")
5280 (setq org-cycle-global-status 'all)
5281 (run-hook-with-args 'org-cycle-hook 'all))
5284 ;; Default action: go to overview
5285 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5286 (org-overview)
5287 (message "OVERVIEW")
5288 (setq org-cycle-global-status 'overview)
5289 (run-hook-with-args 'org-cycle-hook 'overview))))
5291 (defun org-cycle-internal-local ()
5292 "Do the local cycling action."
5293 (org-back-to-heading)
5294 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5295 ;; First, some boundaries
5296 (save-excursion
5297 (org-back-to-heading)
5298 (setq level (funcall outline-level))
5299 (save-excursion
5300 (beginning-of-line 2)
5301 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5302 ; XEmacs does not have `next-single-char-property-change'
5303 ; I'm not sure about Emacs 21.
5304 (while (and (not (eobp)) ;; this is like `next-line'
5305 (get-char-property (1- (point)) 'invisible))
5306 (beginning-of-line 2))
5307 (while (and (not (eobp)) ;; this is like `next-line'
5308 (get-char-property (1- (point)) 'invisible))
5309 (goto-char (next-single-char-property-change (point) 'invisible))
5310 ;;;??? (or (bolp) (beginning-of-line 2))))
5311 (and (eolp) (beginning-of-line 2))))
5312 (setq eol (point)))
5313 (outline-end-of-heading) (setq eoh (point))
5314 (save-excursion
5315 (outline-next-heading)
5316 (setq has-children (and (org-at-heading-p t)
5317 (> (funcall outline-level) level))))
5318 (org-end-of-subtree t)
5319 (unless (eobp)
5320 (skip-chars-forward " \t\n")
5321 (beginning-of-line 1) ; in case this is an item
5323 (setq eos (if (eobp) (point) (1- (point)))))
5324 ;; Find out what to do next and set `this-command'
5325 (cond
5326 ((= eos eoh)
5327 ;; Nothing is hidden behind this heading
5328 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5329 (message "EMPTY ENTRY")
5330 (setq org-cycle-subtree-status nil)
5331 (save-excursion
5332 (goto-char eos)
5333 (outline-next-heading)
5334 (if (org-invisible-p) (org-flag-heading nil))))
5335 ((and (or (>= eol eos)
5336 (not (string-match "\\S-" (buffer-substring eol eos))))
5337 (or has-children
5338 (not (setq children-skipped
5339 org-cycle-skip-children-state-if-no-children))))
5340 ;; Entire subtree is hidden in one line: children view
5341 (run-hook-with-args 'org-pre-cycle-hook 'children)
5342 (org-show-entry)
5343 (show-children)
5344 (message "CHILDREN")
5345 (save-excursion
5346 (goto-char eos)
5347 (outline-next-heading)
5348 (if (org-invisible-p) (org-flag-heading nil)))
5349 (setq org-cycle-subtree-status 'children)
5350 (run-hook-with-args 'org-cycle-hook 'children))
5351 ((or children-skipped
5352 (and (eq last-command this-command)
5353 (eq org-cycle-subtree-status 'children)))
5354 ;; We just showed the children, or no children are there,
5355 ;; now show everything.
5356 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5357 (org-show-subtree)
5358 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5359 (setq org-cycle-subtree-status 'subtree)
5360 (run-hook-with-args 'org-cycle-hook 'subtree))
5362 ;; Default action: hide the subtree.
5363 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5364 (hide-subtree)
5365 (message "FOLDED")
5366 (setq org-cycle-subtree-status 'folded)
5367 (run-hook-with-args 'org-cycle-hook 'folded)))))
5369 ;;;###autoload
5370 (defun org-global-cycle (&optional arg)
5371 "Cycle the global visibility. For details see `org-cycle'.
5372 With C-u prefix arg, switch to startup visibility.
5373 With a numeric prefix, show all headlines up to that level."
5374 (interactive "P")
5375 (let ((org-cycle-include-plain-lists
5376 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5377 (cond
5378 ((integerp arg)
5379 (show-all)
5380 (hide-sublevels arg)
5381 (setq org-cycle-global-status 'contents))
5382 ((equal arg '(4))
5383 (org-set-startup-visibility)
5384 (message "Startup visibility, plus VISIBILITY properties."))
5386 (org-cycle '(4))))))
5388 (defun org-set-startup-visibility ()
5389 "Set the visibility required by startup options and properties."
5390 (cond
5391 ((eq org-startup-folded t)
5392 (org-cycle '(4)))
5393 ((eq org-startup-folded 'content)
5394 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5395 (org-cycle '(4)) (org-cycle '(4)))))
5396 (unless (eq org-startup-folded 'showeverything)
5397 (if org-hide-block-startup (org-hide-block-all))
5398 (org-set-visibility-according-to-property 'no-cleanup)
5399 (org-cycle-hide-archived-subtrees 'all)
5400 (org-cycle-hide-drawers 'all)
5401 (org-cycle-show-empty-lines 'all)))
5403 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5404 "Switch subtree visibilities according to :VISIBILITY: property."
5405 (interactive)
5406 (let (org-show-entry-below state)
5407 (save-excursion
5408 (goto-char (point-min))
5409 (while (re-search-forward
5410 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5411 nil t)
5412 (setq state (match-string 1))
5413 (save-excursion
5414 (org-back-to-heading t)
5415 (hide-subtree)
5416 (org-reveal)
5417 (cond
5418 ((equal state '("fold" "folded"))
5419 (hide-subtree))
5420 ((equal state "children")
5421 (org-show-hidden-entry)
5422 (show-children))
5423 ((equal state "content")
5424 (save-excursion
5425 (save-restriction
5426 (org-narrow-to-subtree)
5427 (org-content))))
5428 ((member state '("all" "showall"))
5429 (show-subtree)))))
5430 (unless no-cleanup
5431 (org-cycle-hide-archived-subtrees 'all)
5432 (org-cycle-hide-drawers 'all)
5433 (org-cycle-show-empty-lines 'all)))))
5435 (defun org-overview ()
5436 "Switch to overview mode, showing only top-level headlines.
5437 Really, this shows all headlines with level equal or greater than the level
5438 of the first headline in the buffer. This is important, because if the
5439 first headline is not level one, then (hide-sublevels 1) gives confusing
5440 results."
5441 (interactive)
5442 (let ((level (save-excursion
5443 (goto-char (point-min))
5444 (if (re-search-forward (concat "^" outline-regexp) nil t)
5445 (progn
5446 (goto-char (match-beginning 0))
5447 (funcall outline-level))))))
5448 (and level (hide-sublevels level))))
5450 (defun org-content (&optional arg)
5451 "Show all headlines in the buffer, like a table of contents.
5452 With numerical argument N, show content up to level N."
5453 (interactive "P")
5454 (save-excursion
5455 ;; Visit all headings and show their offspring
5456 (and (integerp arg) (org-overview))
5457 (goto-char (point-max))
5458 (catch 'exit
5459 (while (and (progn (condition-case nil
5460 (outline-previous-visible-heading 1)
5461 (error (goto-char (point-min))))
5463 (looking-at outline-regexp))
5464 (if (integerp arg)
5465 (show-children (1- arg))
5466 (show-branches))
5467 (if (bobp) (throw 'exit nil))))))
5470 (defun org-optimize-window-after-visibility-change (state)
5471 "Adjust the window after a change in outline visibility.
5472 This function is the default value of the hook `org-cycle-hook'."
5473 (when (get-buffer-window (current-buffer))
5474 (cond
5475 ((eq state 'content) nil)
5476 ((eq state 'all) nil)
5477 ((eq state 'folded) nil)
5478 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5479 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5481 (defun org-remove-empty-overlays-at (pos)
5482 "Remove outline overlays that do not contain non-white stuff."
5483 (mapc
5484 (lambda (o)
5485 (and (eq 'outline (org-overlay-get o 'invisible))
5486 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5487 (org-overlay-end o))))
5488 (org-delete-overlay o)))
5489 (org-overlays-at pos)))
5491 (defun org-clean-visibility-after-subtree-move ()
5492 "Fix visibility issues after moving a subtree."
5493 ;; First, find a reasonable region to look at:
5494 ;; Start two siblings above, end three below
5495 (let* ((beg (save-excursion
5496 (and (org-get-last-sibling)
5497 (org-get-last-sibling))
5498 (point)))
5499 (end (save-excursion
5500 (and (org-get-next-sibling)
5501 (org-get-next-sibling)
5502 (org-get-next-sibling))
5503 (if (org-at-heading-p)
5504 (point-at-eol)
5505 (point))))
5506 (level (looking-at "\\*+"))
5507 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5508 (save-excursion
5509 (save-restriction
5510 (narrow-to-region beg end)
5511 (when re
5512 ;; Properly fold already folded siblings
5513 (goto-char (point-min))
5514 (while (re-search-forward re nil t)
5515 (if (and (not (org-invisible-p))
5516 (save-excursion
5517 (goto-char (point-at-eol)) (org-invisible-p)))
5518 (hide-entry))))
5519 (org-cycle-show-empty-lines 'overview)
5520 (org-cycle-hide-drawers 'overview)))))
5522 (defun org-cycle-show-empty-lines (state)
5523 "Show empty lines above all visible headlines.
5524 The region to be covered depends on STATE when called through
5525 `org-cycle-hook'. Lisp program can use t for STATE to get the
5526 entire buffer covered. Note that an empty line is only shown if there
5527 are at least `org-cycle-separator-lines' empty lines before the headline."
5528 (when (not (= org-cycle-separator-lines 0))
5529 (save-excursion
5530 (let* ((n (abs org-cycle-separator-lines))
5531 (re (cond
5532 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5533 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5534 (t (let ((ns (number-to-string (- n 2))))
5535 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5536 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5537 beg end b e)
5538 (cond
5539 ((memq state '(overview contents t))
5540 (setq beg (point-min) end (point-max)))
5541 ((memq state '(children folded))
5542 (setq beg (point) end (progn (org-end-of-subtree t t)
5543 (beginning-of-line 2)
5544 (point)))))
5545 (when beg
5546 (goto-char beg)
5547 (while (re-search-forward re end t)
5548 (unless (get-char-property (match-end 1) 'invisible)
5549 (setq e (match-end 1))
5550 (if (< org-cycle-separator-lines 0)
5551 (setq b (save-excursion
5552 (goto-char (match-beginning 0))
5553 (org-back-over-empty-lines)
5554 (if (save-excursion
5555 (goto-char (max (point-min) (1- (point))))
5556 (org-on-heading-p))
5557 (1- (point))
5558 (point))))
5559 (setq b (match-beginning 1)))
5560 (outline-flag-region b e nil)))))))
5561 ;; Never hide empty lines at the end of the file.
5562 (save-excursion
5563 (goto-char (point-max))
5564 (outline-previous-heading)
5565 (outline-end-of-heading)
5566 (if (and (looking-at "[ \t\n]+")
5567 (= (match-end 0) (point-max)))
5568 (outline-flag-region (point) (match-end 0) nil))))
5570 (defun org-show-empty-lines-in-parent ()
5571 "Move to the parent and re-show empty lines before visible headlines."
5572 (save-excursion
5573 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5574 (org-cycle-show-empty-lines context))))
5576 (defun org-files-list ()
5577 "Return `org-agenda-files' list, plus all open org-mode files.
5578 This is useful for operations that need to scan all of a user's
5579 open and agenda-wise Org files."
5580 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5581 (dolist (buf (buffer-list))
5582 (with-current-buffer buf
5583 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5584 (let ((file (expand-file-name (buffer-file-name))))
5585 (unless (member file files)
5586 (push file files))))))
5587 files))
5589 (defsubst org-entry-beginning-position ()
5590 "Return the beginning position of the current entry."
5591 (save-excursion (outline-back-to-heading t) (point)))
5593 (defsubst org-entry-end-position ()
5594 "Return the end position of the current entry."
5595 (save-excursion (outline-next-heading) (point)))
5597 (defun org-cycle-hide-drawers (state)
5598 "Re-hide all drawers after a visibility state change."
5599 (when (and (org-mode-p)
5600 (not (memq state '(overview folded contents))))
5601 (save-excursion
5602 (let* ((globalp (memq state '(contents all)))
5603 (beg (if globalp (point-min) (point)))
5604 (end (if globalp (point-max)
5605 (if (eq state 'children)
5606 (save-excursion (outline-next-heading) (point))
5607 (org-end-of-subtree t)))))
5608 (goto-char beg)
5609 (while (re-search-forward org-drawer-regexp end t)
5610 (org-flag-drawer t))))))
5612 (defun org-flag-drawer (flag)
5613 (save-excursion
5614 (beginning-of-line 1)
5615 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5616 (let ((b (match-end 0))
5617 (outline-regexp org-outline-regexp))
5618 (if (re-search-forward
5619 "^[ \t]*:END:"
5620 (save-excursion (outline-next-heading) (point)) t)
5621 (outline-flag-region b (point-at-eol) flag)
5622 (error ":END: line missing at position %s" b))))))
5624 (defun org-subtree-end-visible-p ()
5625 "Is the end of the current subtree visible?"
5626 (pos-visible-in-window-p
5627 (save-excursion (org-end-of-subtree t) (point))))
5629 (defun org-first-headline-recenter (&optional N)
5630 "Move cursor to the first headline and recenter the headline.
5631 Optional argument N means, put the headline into the Nth line of the window."
5632 (goto-char (point-min))
5633 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5634 (beginning-of-line)
5635 (recenter (prefix-numeric-value N))))
5637 ;;; Saving and restoring visibility
5639 (defun org-outline-overlay-data (&optional use-markers)
5640 "Return a list of the locations of all outline overlays.
5641 The are overlays with the `invisible' property value `outline'.
5642 The return valus is a list of cons cells, with start and stop
5643 positions for each overlay.
5644 If USE-MARKERS is set, return the positions as markers."
5645 (let (beg end)
5646 (save-excursion
5647 (save-restriction
5648 (widen)
5649 (delq nil
5650 (mapcar (lambda (o)
5651 (when (eq (org-overlay-get o 'invisible) 'outline)
5652 (setq beg (org-overlay-start o)
5653 end (org-overlay-end o))
5654 (and beg end (> end beg)
5655 (if use-markers
5656 (cons (move-marker (make-marker) beg)
5657 (move-marker (make-marker) end))
5658 (cons beg end)))))
5659 (org-overlays-in (point-min) (point-max))))))))
5661 (defun org-set-outline-overlay-data (data)
5662 "Create visibility overlays for all positions in DATA.
5663 DATA should have been made by `org-outline-overlay-data'."
5664 (let (o)
5665 (save-excursion
5666 (save-restriction
5667 (widen)
5668 (show-all)
5669 (mapc (lambda (c)
5670 (setq o (org-make-overlay (car c) (cdr c)))
5671 (org-overlay-put o 'invisible 'outline))
5672 data)))))
5674 (defmacro org-save-outline-visibility (use-markers &rest body)
5675 "Save and restore outline visibility around BODY.
5676 If USE-MARKERS is non-nil, use markers for the positions.
5677 This means that the buffer may change while running BODY,
5678 but it also means that the buffer should stay alive
5679 during the operation, because otherwise all these markers will
5680 point nowhere."
5681 `(let ((data (org-outline-overlay-data ,use-markers)))
5682 (unwind-protect
5683 (progn
5684 ,@body
5685 (org-set-outline-overlay-data data))
5686 (when ,use-markers
5687 (mapc (lambda (c)
5688 (and (markerp (car c)) (move-marker (car c) nil))
5689 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5690 data)))))
5693 ;;; Folding of blocks
5695 (defconst org-block-regexp
5697 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5698 "Regular expression for hiding blocks.")
5700 (defvar org-hide-block-overlays nil
5701 "Overlays hiding blocks.")
5702 (make-variable-buffer-local 'org-hide-block-overlays)
5704 (defun org-block-map (function &optional start end)
5705 "Call func at the head of all source blocks in the current
5706 buffer. Optional arguments START and END can be used to limit
5707 the range."
5708 (let ((start (or start (point-min)))
5709 (end (or end (point-max))))
5710 (save-excursion
5711 (goto-char start)
5712 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5713 (save-excursion
5714 (save-match-data
5715 (goto-char (match-beginning 0))
5716 (funcall function)))))))
5718 (defun org-hide-block-toggle-all ()
5719 "Toggle the visibility of all blocks in the current buffer."
5720 (org-block-map #'org-hide-block-toggle))
5722 (defun org-hide-block-all ()
5723 "Fold all blocks in the current buffer."
5724 (interactive)
5725 (org-show-block-all)
5726 (org-block-map #'org-hide-block-toggle-maybe))
5728 (defun org-show-block-all ()
5729 "Unfold all blocks in the current buffer."
5730 (mapc 'org-delete-overlay org-hide-block-overlays)
5731 (setq org-hide-block-overlays nil))
5733 (defun org-hide-block-toggle-maybe ()
5734 "Toggle visibility of block at point."
5735 (interactive)
5736 (let ((case-fold-search t))
5737 (if (save-excursion
5738 (beginning-of-line 1)
5739 (looking-at org-block-regexp))
5740 (progn (org-hide-block-toggle)
5741 t) ;; to signal that we took action
5742 nil))) ;; to signal that we did not
5744 (defun org-hide-block-toggle (&optional force)
5745 "Toggle the visibility of the current block."
5746 (interactive)
5747 (save-excursion
5748 (beginning-of-line)
5749 (if (re-search-forward org-block-regexp nil t)
5750 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5751 (end (match-end 0)) ;; end of entire body
5753 (if (memq t (mapcar (lambda (overlay)
5754 (eq (org-overlay-get overlay 'invisible)
5755 'org-hide-block))
5756 (org-overlays-at start)))
5757 (if (or (not force) (eq force 'off))
5758 (mapc (lambda (ov)
5759 (when (member ov org-hide-block-overlays)
5760 (setq org-hide-block-overlays
5761 (delq ov org-hide-block-overlays)))
5762 (when (eq (org-overlay-get ov 'invisible)
5763 'org-hide-block)
5764 (org-delete-overlay ov)))
5765 (org-overlays-at start)))
5766 (setq ov (org-make-overlay start end))
5767 (org-overlay-put ov 'invisible 'org-hide-block)
5768 ;; make the block accessible to isearch
5769 (org-overlay-put
5770 ov 'isearch-open-invisible
5771 (lambda (ov)
5772 (when (member ov org-hide-block-overlays)
5773 (setq org-hide-block-overlays
5774 (delq ov org-hide-block-overlays)))
5775 (when (eq (org-overlay-get ov 'invisible)
5776 'org-hide-block)
5777 (org-delete-overlay ov))))
5778 (push ov org-hide-block-overlays)))
5779 (error "Not looking at a source block"))))
5781 ;; org-tab-after-check-for-cycling-hook
5782 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5783 ;; Remove overlays when changing major mode
5784 (add-hook 'org-mode-hook
5785 (lambda () (org-add-hook 'change-major-mode-hook
5786 'org-show-block-all 'append 'local)))
5788 ;;; Org-goto
5790 (defvar org-goto-window-configuration nil)
5791 (defvar org-goto-marker nil)
5792 (defvar org-goto-map
5793 (let ((map (make-sparse-keymap)))
5794 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5795 (while (setq cmd (pop cmds))
5796 (substitute-key-definition cmd cmd map global-map)))
5797 (suppress-keymap map)
5798 (org-defkey map "\C-m" 'org-goto-ret)
5799 (org-defkey map [(return)] 'org-goto-ret)
5800 (org-defkey map [(left)] 'org-goto-left)
5801 (org-defkey map [(right)] 'org-goto-right)
5802 (org-defkey map [(control ?g)] 'org-goto-quit)
5803 (org-defkey map "\C-i" 'org-cycle)
5804 (org-defkey map [(tab)] 'org-cycle)
5805 (org-defkey map [(down)] 'outline-next-visible-heading)
5806 (org-defkey map [(up)] 'outline-previous-visible-heading)
5807 (if org-goto-auto-isearch
5808 (if (fboundp 'define-key-after)
5809 (define-key-after map [t] 'org-goto-local-auto-isearch)
5810 nil)
5811 (org-defkey map "q" 'org-goto-quit)
5812 (org-defkey map "n" 'outline-next-visible-heading)
5813 (org-defkey map "p" 'outline-previous-visible-heading)
5814 (org-defkey map "f" 'outline-forward-same-level)
5815 (org-defkey map "b" 'outline-backward-same-level)
5816 (org-defkey map "u" 'outline-up-heading))
5817 (org-defkey map "/" 'org-occur)
5818 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5819 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5820 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5821 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5822 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5823 map))
5825 (defconst org-goto-help
5826 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5827 RET=jump to location [Q]uit and return to previous location
5828 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5830 (defvar org-goto-start-pos) ; dynamically scoped parameter
5832 ;; FIXME: Docstring does not mention both interfaces
5833 (defun org-goto (&optional alternative-interface)
5834 "Look up a different location in the current file, keeping current visibility.
5836 When you want look-up or go to a different location in a document, the
5837 fastest way is often to fold the entire buffer and then dive into the tree.
5838 This method has the disadvantage, that the previous location will be folded,
5839 which may not be what you want.
5841 This command works around this by showing a copy of the current buffer
5842 in an indirect buffer, in overview mode. You can dive into the tree in
5843 that copy, use org-occur and incremental search to find a location.
5844 When pressing RET or `Q', the command returns to the original buffer in
5845 which the visibility is still unchanged. After RET is will also jump to
5846 the location selected in the indirect buffer and expose the
5847 the headline hierarchy above."
5848 (interactive "P")
5849 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5850 (org-refile-use-outline-path t)
5851 (org-refile-target-verify-function nil)
5852 (interface
5853 (if (not alternative-interface)
5854 org-goto-interface
5855 (if (eq org-goto-interface 'outline)
5856 'outline-path-completion
5857 'outline)))
5858 (org-goto-start-pos (point))
5859 (selected-point
5860 (if (eq interface 'outline)
5861 (car (org-get-location (current-buffer) org-goto-help))
5862 (nth 3 (org-refile-get-location "Goto: ")))))
5863 (if selected-point
5864 (progn
5865 (org-mark-ring-push org-goto-start-pos)
5866 (goto-char selected-point)
5867 (if (or (org-invisible-p) (org-invisible-p2))
5868 (org-show-context 'org-goto)))
5869 (message "Quit"))))
5871 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5872 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5873 (defvar org-goto-local-auto-isearch-map) ; defined below
5875 (defun org-get-location (buf help)
5876 "Let the user select a location in the Org-mode buffer BUF.
5877 This function uses a recursive edit. It returns the selected position
5878 or nil."
5879 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5880 (isearch-hide-immediately nil)
5881 (isearch-search-fun-function
5882 (lambda () 'org-goto-local-search-headings))
5883 (org-goto-selected-point org-goto-exit-command))
5884 (save-excursion
5885 (save-window-excursion
5886 (delete-other-windows)
5887 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5888 (switch-to-buffer
5889 (condition-case nil
5890 (make-indirect-buffer (current-buffer) "*org-goto*")
5891 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5892 (with-output-to-temp-buffer "*Help*"
5893 (princ help))
5894 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5895 (setq buffer-read-only nil)
5896 (let ((org-startup-truncated t)
5897 (org-startup-folded nil)
5898 (org-startup-align-all-tables nil))
5899 (org-mode)
5900 (org-overview))
5901 (setq buffer-read-only t)
5902 (if (and (boundp 'org-goto-start-pos)
5903 (integer-or-marker-p org-goto-start-pos))
5904 (let ((org-show-hierarchy-above t)
5905 (org-show-siblings t)
5906 (org-show-following-heading t))
5907 (goto-char org-goto-start-pos)
5908 (and (org-invisible-p) (org-show-context)))
5909 (goto-char (point-min)))
5910 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5911 (message "Select location and press RET")
5912 (use-local-map org-goto-map)
5913 (recursive-edit)
5915 (kill-buffer "*org-goto*")
5916 (cons org-goto-selected-point org-goto-exit-command)))
5918 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5919 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5920 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5921 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5923 (defun org-goto-local-search-headings (string bound noerror)
5924 "Search and make sure that any matches are in headlines."
5925 (catch 'return
5926 (while (if isearch-forward
5927 (search-forward string bound noerror)
5928 (search-backward string bound noerror))
5929 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5930 (and (member :headline context)
5931 (not (member :tags context))))
5932 (throw 'return (point))))))
5934 (defun org-goto-local-auto-isearch ()
5935 "Start isearch."
5936 (interactive)
5937 (goto-char (point-min))
5938 (let ((keys (this-command-keys)))
5939 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5940 (isearch-mode t)
5941 (isearch-process-search-char (string-to-char keys)))))
5943 (defun org-goto-ret (&optional arg)
5944 "Finish `org-goto' by going to the new location."
5945 (interactive "P")
5946 (setq org-goto-selected-point (point)
5947 org-goto-exit-command 'return)
5948 (throw 'exit nil))
5950 (defun org-goto-left ()
5951 "Finish `org-goto' by going to the new location."
5952 (interactive)
5953 (if (org-on-heading-p)
5954 (progn
5955 (beginning-of-line 1)
5956 (setq org-goto-selected-point (point)
5957 org-goto-exit-command 'left)
5958 (throw 'exit nil))
5959 (error "Not on a heading")))
5961 (defun org-goto-right ()
5962 "Finish `org-goto' by going to the new location."
5963 (interactive)
5964 (if (org-on-heading-p)
5965 (progn
5966 (setq org-goto-selected-point (point)
5967 org-goto-exit-command 'right)
5968 (throw 'exit nil))
5969 (error "Not on a heading")))
5971 (defun org-goto-quit ()
5972 "Finish `org-goto' without cursor motion."
5973 (interactive)
5974 (setq org-goto-selected-point nil)
5975 (setq org-goto-exit-command 'quit)
5976 (throw 'exit nil))
5978 ;;; Indirect buffer display of subtrees
5980 (defvar org-indirect-dedicated-frame nil
5981 "This is the frame being used for indirect tree display.")
5982 (defvar org-last-indirect-buffer nil)
5984 (defun org-tree-to-indirect-buffer (&optional arg)
5985 "Create indirect buffer and narrow it to current subtree.
5986 With numerical prefix ARG, go up to this level and then take that tree.
5987 If ARG is negative, go up that many levels.
5988 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5989 indirect buffer previously made with this command, to avoid proliferation of
5990 indirect buffers. However, when you call the command with a `C-u' prefix, or
5991 when `org-indirect-buffer-display' is `new-frame', the last buffer
5992 is kept so that you can work with several indirect buffers at the same time.
5993 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5994 requests that a new frame be made for the new buffer, so that the dedicated
5995 frame is not changed."
5996 (interactive "P")
5997 (let ((cbuf (current-buffer))
5998 (cwin (selected-window))
5999 (pos (point))
6000 beg end level heading ibuf)
6001 (save-excursion
6002 (org-back-to-heading t)
6003 (when (numberp arg)
6004 (setq level (org-outline-level))
6005 (if (< arg 0) (setq arg (+ level arg)))
6006 (while (> (setq level (org-outline-level)) arg)
6007 (outline-up-heading 1 t)))
6008 (setq beg (point)
6009 heading (org-get-heading))
6010 (org-end-of-subtree t t) (setq end (point)))
6011 (if (and (buffer-live-p org-last-indirect-buffer)
6012 (not (eq org-indirect-buffer-display 'new-frame))
6013 (not arg))
6014 (kill-buffer org-last-indirect-buffer))
6015 (setq ibuf (org-get-indirect-buffer cbuf)
6016 org-last-indirect-buffer ibuf)
6017 (cond
6018 ((or (eq org-indirect-buffer-display 'new-frame)
6019 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6020 (select-frame (make-frame))
6021 (delete-other-windows)
6022 (switch-to-buffer ibuf)
6023 (org-set-frame-title heading))
6024 ((eq org-indirect-buffer-display 'dedicated-frame)
6025 (raise-frame
6026 (select-frame (or (and org-indirect-dedicated-frame
6027 (frame-live-p org-indirect-dedicated-frame)
6028 org-indirect-dedicated-frame)
6029 (setq org-indirect-dedicated-frame (make-frame)))))
6030 (delete-other-windows)
6031 (switch-to-buffer ibuf)
6032 (org-set-frame-title (concat "Indirect: " heading)))
6033 ((eq org-indirect-buffer-display 'current-window)
6034 (switch-to-buffer ibuf))
6035 ((eq org-indirect-buffer-display 'other-window)
6036 (pop-to-buffer ibuf))
6037 (t (error "Invalid value")))
6038 (if (featurep 'xemacs)
6039 (save-excursion (org-mode) (turn-on-font-lock)))
6040 (narrow-to-region beg end)
6041 (show-all)
6042 (goto-char pos)
6043 (and (window-live-p cwin) (select-window cwin))))
6045 (defun org-get-indirect-buffer (&optional buffer)
6046 (setq buffer (or buffer (current-buffer)))
6047 (let ((n 1) (base (buffer-name buffer)) bname)
6048 (while (buffer-live-p
6049 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6050 (setq n (1+ n)))
6051 (condition-case nil
6052 (make-indirect-buffer buffer bname 'clone)
6053 (error (make-indirect-buffer buffer bname)))))
6055 (defun org-set-frame-title (title)
6056 "Set the title of the current frame to the string TITLE."
6057 ;; FIXME: how to name a single frame in XEmacs???
6058 (unless (featurep 'xemacs)
6059 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6061 ;;;; Structure editing
6063 ;;; Inserting headlines
6065 (defun org-previous-line-empty-p ()
6066 (save-excursion
6067 (and (not (bobp))
6068 (or (beginning-of-line 0) t)
6069 (save-match-data
6070 (looking-at "[ \t]*$")))))
6072 (defun org-insert-heading (&optional force-heading)
6073 "Insert a new heading or item with same depth at point.
6074 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6075 If point is at the beginning of a headline, insert a sibling before the
6076 current headline. If point is not at the beginning, do not split the line,
6077 but create the new headline after the current line."
6078 (interactive "P")
6079 (if (or (= (buffer-size) 0)
6080 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
6081 (org-on-heading-p))))
6082 (not (org-in-item-p))))
6083 (insert "\n* ")
6084 (when (or force-heading (not (org-insert-item)))
6085 (let* ((empty-line-p nil)
6086 (head (save-excursion
6087 (condition-case nil
6088 (progn
6089 (org-back-to-heading)
6090 (setq empty-line-p (org-previous-line-empty-p))
6091 (match-string 0))
6092 (error "*"))))
6093 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6094 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6095 pos hide-previous previous-pos)
6096 (cond
6097 ((and (org-on-heading-p) (bolp)
6098 (or (bobp)
6099 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6100 ;; insert before the current line
6101 (open-line (if blank 2 1)))
6102 ((and (bolp)
6103 (not org-insert-heading-respect-content)
6104 (or (bobp)
6105 (save-excursion
6106 (backward-char 1) (not (org-invisible-p)))))
6107 ;; insert right here
6108 nil)
6110 ;; somewhere in the line
6111 (save-excursion
6112 (setq previous-pos (point-at-bol))
6113 (end-of-line)
6114 (setq hide-previous (org-invisible-p)))
6115 (and org-insert-heading-respect-content (org-show-subtree))
6116 (let ((split
6117 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6118 (save-excursion
6119 (let ((p (point)))
6120 (goto-char (point-at-bol))
6121 (and (looking-at org-complex-heading-regexp)
6122 (> p (match-beginning 4)))))))
6123 tags pos)
6124 (cond
6125 (org-insert-heading-respect-content
6126 (org-end-of-subtree nil t)
6127 (or (bolp) (newline))
6128 (or (org-previous-line-empty-p)
6129 (and blank (newline)))
6130 (open-line 1))
6131 ((org-on-heading-p)
6132 (when hide-previous
6133 (show-children)
6134 (org-show-entry))
6135 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6136 (setq tags (and (match-end 2) (match-string 2)))
6137 (and (match-end 1)
6138 (delete-region (match-beginning 1) (match-end 1)))
6139 (setq pos (point-at-bol))
6140 (or split (end-of-line 1))
6141 (delete-horizontal-space)
6142 (newline (if blank 2 1))
6143 (when tags
6144 (save-excursion
6145 (goto-char pos)
6146 (end-of-line 1)
6147 (insert " " tags)
6148 (org-set-tags nil 'align))))
6150 (or split (end-of-line 1))
6151 (newline (if blank 2 1)))))))
6152 (insert head) (just-one-space)
6153 (setq pos (point))
6154 (end-of-line 1)
6155 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6156 (when (and org-insert-heading-respect-content hide-previous)
6157 (save-excursion
6158 (goto-char previous-pos)
6159 (hide-subtree)))
6160 (run-hooks 'org-insert-heading-hook)))))
6162 (defun org-get-heading (&optional no-tags)
6163 "Return the heading of the current entry, without the stars."
6164 (save-excursion
6165 (org-back-to-heading t)
6166 (if (looking-at
6167 (if no-tags
6168 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6169 "\\*+[ \t]+\\([^\r\n]*\\)"))
6170 (match-string 1) "")))
6172 (defun org-heading-components ()
6173 "Return the components of the current heading.
6174 This is a list with the following elements:
6175 - the level as an integer
6176 - the reduced level, different if `org-odd-levels-only' is set.
6177 - the TODO keyword, or nil
6178 - the priority character, like ?A, or nil if no priority is given
6179 - the headline text itself, or the tags string if no headline text
6180 - the tags string, or nil."
6181 (save-excursion
6182 (org-back-to-heading t)
6183 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6184 (list (length (match-string 1))
6185 (org-reduced-level (length (match-string 1)))
6186 (org-match-string-no-properties 2)
6187 (and (match-end 3) (aref (match-string 3) 2))
6188 (org-match-string-no-properties 4)
6189 (org-match-string-no-properties 5)))))
6191 (defun org-get-entry ()
6192 "Get the entry text, after heading, entire subtree."
6193 (save-excursion
6194 (org-back-to-heading t)
6195 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6197 (defun org-insert-heading-after-current ()
6198 "Insert a new heading with same level as current, after current subtree."
6199 (interactive)
6200 (org-back-to-heading)
6201 (org-insert-heading)
6202 (org-move-subtree-down)
6203 (end-of-line 1))
6205 (defun org-insert-heading-respect-content ()
6206 (interactive)
6207 (let ((org-insert-heading-respect-content t))
6208 (org-insert-heading t)))
6210 (defun org-insert-todo-heading-respect-content (&optional force-state)
6211 (interactive "P")
6212 (let ((org-insert-heading-respect-content t))
6213 (org-insert-todo-heading force-state t)))
6215 (defun org-insert-todo-heading (arg &optional force-heading)
6216 "Insert a new heading with the same level and TODO state as current heading.
6217 If the heading has no TODO state, or if the state is DONE, use the first
6218 state (TODO by default). Also with prefix arg, force first state."
6219 (interactive "P")
6220 (when (or force-heading (not (org-insert-item 'checkbox)))
6221 (org-insert-heading force-heading)
6222 (save-excursion
6223 (org-back-to-heading)
6224 (outline-previous-heading)
6225 (looking-at org-todo-line-regexp))
6226 (let*
6227 ((new-mark-x
6228 (if (or arg
6229 (not (match-beginning 2))
6230 (member (match-string 2) org-done-keywords))
6231 (car org-todo-keywords-1)
6232 (match-string 2)))
6233 (new-mark
6235 (run-hook-with-args-until-success
6236 'org-todo-get-default-hook new-mark-x nil)
6237 new-mark-x)))
6238 (beginning-of-line 1)
6239 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6240 (if org-treat-insert-todo-heading-as-state-change
6241 (org-todo new-mark)
6242 (insert new-mark " "))))
6243 (when org-provide-todo-statistics
6244 (org-update-parent-todo-statistics))))
6246 (defun org-insert-subheading (arg)
6247 "Insert a new subheading and demote it.
6248 Works for outline headings and for plain lists alike."
6249 (interactive "P")
6250 (org-insert-heading arg)
6251 (cond
6252 ((org-on-heading-p) (org-do-demote))
6253 ((org-at-item-p) (org-indent-item 1))))
6255 (defun org-insert-todo-subheading (arg)
6256 "Insert a new subheading with TODO keyword or checkbox and demote it.
6257 Works for outline headings and for plain lists alike."
6258 (interactive "P")
6259 (org-insert-todo-heading arg)
6260 (cond
6261 ((org-on-heading-p) (org-do-demote))
6262 ((org-at-item-p) (org-indent-item 1))))
6264 ;;; Promotion and Demotion
6266 (defvar org-after-demote-entry-hook nil
6267 "Hook run after an entry has been demoted.
6268 The cursor will be at the beginning of the entry.
6269 When a subtree is being demoted, the hook will be called for each node.")
6271 (defvar org-after-promote-entry-hook nil
6272 "Hook run after an entry has been promoted.
6273 The cursor will be at the beginning of the entry.
6274 When a subtree is being promoted, the hook will be called for each node.")
6276 (defun org-promote-subtree ()
6277 "Promote the entire subtree.
6278 See also `org-promote'."
6279 (interactive)
6280 (save-excursion
6281 (org-map-tree 'org-promote))
6282 (org-fix-position-after-promote))
6284 (defun org-demote-subtree ()
6285 "Demote the entire subtree. See `org-demote'.
6286 See also `org-promote'."
6287 (interactive)
6288 (save-excursion
6289 (org-map-tree 'org-demote))
6290 (org-fix-position-after-promote))
6293 (defun org-do-promote ()
6294 "Promote the current heading higher up the tree.
6295 If the region is active in `transient-mark-mode', promote all headings
6296 in the region."
6297 (interactive)
6298 (save-excursion
6299 (if (org-region-active-p)
6300 (org-map-region 'org-promote (region-beginning) (region-end))
6301 (org-promote)))
6302 (org-fix-position-after-promote))
6304 (defun org-do-demote ()
6305 "Demote the current heading lower down the tree.
6306 If the region is active in `transient-mark-mode', demote all headings
6307 in the region."
6308 (interactive)
6309 (save-excursion
6310 (if (org-region-active-p)
6311 (org-map-region 'org-demote (region-beginning) (region-end))
6312 (org-demote)))
6313 (org-fix-position-after-promote))
6315 (defun org-fix-position-after-promote ()
6316 "Make sure that after pro/demotion cursor position is right."
6317 (let ((pos (point)))
6318 (when (save-excursion
6319 (beginning-of-line 1)
6320 (looking-at org-todo-line-regexp)
6321 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6322 (cond ((eobp) (insert " "))
6323 ((eolp) (insert " "))
6324 ((equal (char-after) ?\ ) (forward-char 1))))))
6326 (defun org-current-level ()
6327 "Return the level of the current entry, or nil if before the first headline.
6328 The level is the number of stars at the beginning of the headline."
6329 (save-excursion
6330 (condition-case nil
6331 (progn
6332 (org-back-to-heading t)
6333 (funcall outline-level))
6334 (error nil))))
6336 (defun org-reduced-level (l)
6337 "Compute the effective level of a heading.
6338 This takes into account the setting of `org-odd-levels-only'."
6339 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6341 (defun org-get-valid-level (level &optional change)
6342 "Rectify a level change under the influence of `org-odd-levels-only'
6343 LEVEL is a current level, CHANGE is by how much the level should be
6344 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6345 even level numbers will become the next higher odd number."
6346 (if org-odd-levels-only
6347 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6348 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6349 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6350 (max 1 (+ level (or change 0)))))
6352 (if (boundp 'define-obsolete-function-alias)
6353 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6354 (define-obsolete-function-alias 'org-get-legal-level
6355 'org-get-valid-level)
6356 (define-obsolete-function-alias 'org-get-legal-level
6357 'org-get-valid-level "23.1")))
6359 (defun org-promote ()
6360 "Promote the current heading higher up the tree.
6361 If the region is active in `transient-mark-mode', promote all headings
6362 in the region."
6363 (org-back-to-heading t)
6364 (let* ((level (save-match-data (funcall outline-level)))
6365 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6366 (diff (abs (- level (length up-head) -1))))
6367 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6368 (replace-match up-head nil t)
6369 ;; Fixup tag positioning
6370 (and org-auto-align-tags (org-set-tags nil t))
6371 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6372 (run-hooks 'org-after-promote-entry-hook)))
6374 (defun org-demote ()
6375 "Demote the current heading lower down the tree.
6376 If the region is active in `transient-mark-mode', demote all headings
6377 in the region."
6378 (org-back-to-heading t)
6379 (let* ((level (save-match-data (funcall outline-level)))
6380 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6381 (diff (abs (- level (length down-head) -1))))
6382 (replace-match down-head nil t)
6383 ;; Fixup tag positioning
6384 (and org-auto-align-tags (org-set-tags nil t))
6385 (if org-adapt-indentation (org-fixup-indentation diff))
6386 (run-hooks 'org-after-demote-entry-hook)))
6388 (defvar org-tab-ind-state nil)
6390 (defun org-cycle-level ()
6391 (let ((org-adapt-indentation nil))
6392 (when (and (looking-at "[ \t]*$")
6393 (org-looking-back
6394 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6395 (setq this-command 'org-cycle-level)
6396 (if (eq last-command 'org-cycle-level)
6397 (condition-case nil
6398 (progn (org-do-promote)
6399 (if (equal org-tab-ind-state (org-current-level))
6400 (org-do-promote)))
6401 (error
6402 (progn
6403 (save-excursion
6404 (beginning-of-line 1)
6405 (and (looking-at "\\*+")
6406 (replace-match
6407 (make-string org-tab-ind-state ?*))))
6408 (setq this-command 'org-cycle))))
6409 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6410 (org-do-demote))
6411 t)))
6413 (defun org-map-tree (fun)
6414 "Call FUN for every heading underneath the current one."
6415 (org-back-to-heading)
6416 (let ((level (funcall outline-level)))
6417 (save-excursion
6418 (funcall fun)
6419 (while (and (progn
6420 (outline-next-heading)
6421 (> (funcall outline-level) level))
6422 (not (eobp)))
6423 (funcall fun)))))
6425 (defun org-map-region (fun beg end)
6426 "Call FUN for every heading between BEG and END."
6427 (let ((org-ignore-region t))
6428 (save-excursion
6429 (setq end (copy-marker end))
6430 (goto-char beg)
6431 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6432 (< (point) end))
6433 (funcall fun))
6434 (while (and (progn
6435 (outline-next-heading)
6436 (< (point) end))
6437 (not (eobp)))
6438 (funcall fun)))))
6440 (defun org-fixup-indentation (diff)
6441 "Change the indentation in the current entry by DIFF
6442 However, if any line in the current entry has no indentation, or if it
6443 would end up with no indentation after the change, nothing at all is done."
6444 (save-excursion
6445 (let ((end (save-excursion (outline-next-heading)
6446 (point-marker)))
6447 (prohibit (if (> diff 0)
6448 "^\\S-"
6449 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6450 col)
6451 (unless (save-excursion (end-of-line 1)
6452 (re-search-forward prohibit end t))
6453 (while (and (< (point) end)
6454 (re-search-forward "^[ \t]+" end t))
6455 (goto-char (match-end 0))
6456 (setq col (current-column))
6457 (if (< diff 0) (replace-match ""))
6458 (org-indent-to-column (+ diff col))))
6459 (move-marker end nil))))
6461 (defun org-convert-to-odd-levels ()
6462 "Convert an org-mode file with all levels allowed to one with odd levels.
6463 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6464 level 5 etc."
6465 (interactive)
6466 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6467 (let ((outline-regexp org-outline-regexp)
6468 (outline-level 'org-outline-level)
6469 (org-odd-levels-only nil) n)
6470 (save-excursion
6471 (goto-char (point-min))
6472 (while (re-search-forward "^\\*\\*+ " nil t)
6473 (setq n (- (length (match-string 0)) 2))
6474 (while (>= (setq n (1- n)) 0)
6475 (org-demote))
6476 (end-of-line 1))))))
6478 (defun org-convert-to-oddeven-levels ()
6479 "Convert an org-mode file with only odd levels to one with odd and even levels.
6480 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6481 section with an even level, conversion would destroy the structure of the file. An error
6482 is signaled in this case."
6483 (interactive)
6484 (goto-char (point-min))
6485 ;; First check if there are no even levels
6486 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6487 (org-show-context t)
6488 (error "Not all levels are odd in this file. Conversion not possible"))
6489 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6490 (let ((outline-regexp org-outline-regexp)
6491 (outline-level 'org-outline-level)
6492 (org-odd-levels-only nil) n)
6493 (save-excursion
6494 (goto-char (point-min))
6495 (while (re-search-forward "^\\*\\*+ " nil t)
6496 (setq n (/ (1- (length (match-string 0))) 2))
6497 (while (>= (setq n (1- n)) 0)
6498 (org-promote))
6499 (end-of-line 1))))))
6501 (defun org-tr-level (n)
6502 "Make N odd if required."
6503 (if org-odd-levels-only (1+ (/ n 2)) n))
6505 ;;; Vertical tree motion, cutting and pasting of subtrees
6507 (defun org-move-subtree-up (&optional arg)
6508 "Move the current subtree up past ARG headlines of the same level."
6509 (interactive "p")
6510 (org-move-subtree-down (- (prefix-numeric-value arg))))
6512 (defun org-move-subtree-down (&optional arg)
6513 "Move the current subtree down past ARG headlines of the same level."
6514 (interactive "p")
6515 (setq arg (prefix-numeric-value arg))
6516 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6517 'org-get-last-sibling))
6518 (ins-point (make-marker))
6519 (cnt (abs arg))
6520 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6521 ;; Select the tree
6522 (org-back-to-heading)
6523 (setq beg0 (point))
6524 (save-excursion
6525 (setq ne-beg (org-back-over-empty-lines))
6526 (setq beg (point)))
6527 (save-match-data
6528 (save-excursion (outline-end-of-heading)
6529 (setq folded (org-invisible-p)))
6530 (outline-end-of-subtree))
6531 (outline-next-heading)
6532 (setq ne-end (org-back-over-empty-lines))
6533 (setq end (point))
6534 (goto-char beg0)
6535 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6536 ;; include less whitespace
6537 (save-excursion
6538 (goto-char beg)
6539 (forward-line (- ne-beg ne-end))
6540 (setq beg (point))))
6541 ;; Find insertion point, with error handling
6542 (while (> cnt 0)
6543 (or (and (funcall movfunc) (looking-at outline-regexp))
6544 (progn (goto-char beg0)
6545 (error "Cannot move past superior level or buffer limit")))
6546 (setq cnt (1- cnt)))
6547 (if (> arg 0)
6548 ;; Moving forward - still need to move over subtree
6549 (progn (org-end-of-subtree t t)
6550 (save-excursion
6551 (org-back-over-empty-lines)
6552 (or (bolp) (newline)))))
6553 (setq ne-ins (org-back-over-empty-lines))
6554 (move-marker ins-point (point))
6555 (setq txt (buffer-substring beg end))
6556 (org-save-markers-in-region beg end)
6557 (delete-region beg end)
6558 (org-remove-empty-overlays-at beg)
6559 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6560 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6561 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6562 (let ((bbb (point)))
6563 (insert-before-markers txt)
6564 (org-reinstall-markers-in-region bbb)
6565 (move-marker ins-point bbb))
6566 (or (bolp) (insert "\n"))
6567 (setq ins-end (point))
6568 (goto-char ins-point)
6569 (org-skip-whitespace)
6570 (when (and (< arg 0)
6571 (org-first-sibling-p)
6572 (> ne-ins ne-beg))
6573 ;; Move whitespace back to beginning
6574 (save-excursion
6575 (goto-char ins-end)
6576 (let ((kill-whole-line t))
6577 (kill-line (- ne-ins ne-beg)) (point)))
6578 (insert (make-string (- ne-ins ne-beg) ?\n)))
6579 (move-marker ins-point nil)
6580 (if folded
6581 (hide-subtree)
6582 (org-show-entry)
6583 (show-children)
6584 (org-cycle-hide-drawers 'children))
6585 (org-clean-visibility-after-subtree-move)))
6587 (defvar org-subtree-clip ""
6588 "Clipboard for cut and paste of subtrees.
6589 This is actually only a copy of the kill, because we use the normal kill
6590 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6592 (defvar org-subtree-clip-folded nil
6593 "Was the last copied subtree folded?
6594 This is used to fold the tree back after pasting.")
6596 (defun org-cut-subtree (&optional n)
6597 "Cut the current subtree into the clipboard.
6598 With prefix arg N, cut this many sequential subtrees.
6599 This is a short-hand for marking the subtree and then cutting it."
6600 (interactive "p")
6601 (org-copy-subtree n 'cut))
6603 (defun org-copy-subtree (&optional n cut force-store-markers)
6604 "Cut the current subtree into the clipboard.
6605 With prefix arg N, cut this many sequential subtrees.
6606 This is a short-hand for marking the subtree and then copying it.
6607 If CUT is non-nil, actually cut the subtree.
6608 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6609 of some markers in the region, even if CUT is non-nil. This is
6610 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6611 (interactive "p")
6612 (let (beg end folded (beg0 (point)))
6613 (if (interactive-p)
6614 (org-back-to-heading nil) ; take what looks like a subtree
6615 (org-back-to-heading t)) ; take what is really there
6616 (org-back-over-empty-lines)
6617 (setq beg (point))
6618 (skip-chars-forward " \t\r\n")
6619 (save-match-data
6620 (save-excursion (outline-end-of-heading)
6621 (setq folded (org-invisible-p)))
6622 (condition-case nil
6623 (org-forward-same-level (1- n) t)
6624 (error nil))
6625 (org-end-of-subtree t t))
6626 (org-back-over-empty-lines)
6627 (setq end (point))
6628 (goto-char beg0)
6629 (when (> end beg)
6630 (setq org-subtree-clip-folded folded)
6631 (when (or cut force-store-markers)
6632 (org-save-markers-in-region beg end))
6633 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6634 (setq org-subtree-clip (current-kill 0))
6635 (message "%s: Subtree(s) with %d characters"
6636 (if cut "Cut" "Copied")
6637 (length org-subtree-clip)))))
6639 (defun org-paste-subtree (&optional level tree for-yank)
6640 "Paste the clipboard as a subtree, with modification of headline level.
6641 The entire subtree is promoted or demoted in order to match a new headline
6642 level.
6644 If the cursor is at the beginning of a headline, the same level as
6645 that headline is used to paste the tree
6647 If not, the new level is derived from the *visible* headings
6648 before and after the insertion point, and taken to be the inferior headline
6649 level of the two. So if the previous visible heading is level 3 and the
6650 next is level 4 (or vice versa), level 4 will be used for insertion.
6651 This makes sure that the subtree remains an independent subtree and does
6652 not swallow low level entries.
6654 You can also force a different level, either by using a numeric prefix
6655 argument, or by inserting the heading marker by hand. For example, if the
6656 cursor is after \"*****\", then the tree will be shifted to level 5.
6658 If optional TREE is given, use this text instead of the kill ring.
6660 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6661 move back over whitespace before inserting, and move point to the end of
6662 the inserted text when done."
6663 (interactive "P")
6664 (setq tree (or tree (and kill-ring (current-kill 0))))
6665 (unless (org-kill-is-subtree-p tree)
6666 (error "%s"
6667 (substitute-command-keys
6668 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6669 (let* ((visp (not (org-invisible-p)))
6670 (txt tree)
6671 (^re (concat "^\\(" outline-regexp "\\)"))
6672 (re (concat "\\(" outline-regexp "\\)"))
6673 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6675 (old-level (if (string-match ^re txt)
6676 (- (match-end 0) (match-beginning 0) 1)
6677 -1))
6678 (force-level (cond (level (prefix-numeric-value level))
6679 ((and (looking-at "[ \t]*$")
6680 (string-match
6681 ^re_ (buffer-substring
6682 (point-at-bol) (point))))
6683 (- (match-end 1) (match-beginning 1)))
6684 ((and (bolp)
6685 (looking-at org-outline-regexp))
6686 (- (match-end 0) (point) 1))
6687 (t nil)))
6688 (previous-level (save-excursion
6689 (condition-case nil
6690 (progn
6691 (outline-previous-visible-heading 1)
6692 (if (looking-at re)
6693 (- (match-end 0) (match-beginning 0) 1)
6695 (error 1))))
6696 (next-level (save-excursion
6697 (condition-case nil
6698 (progn
6699 (or (looking-at outline-regexp)
6700 (outline-next-visible-heading 1))
6701 (if (looking-at re)
6702 (- (match-end 0) (match-beginning 0) 1)
6704 (error 1))))
6705 (new-level (or force-level (max previous-level next-level)))
6706 (shift (if (or (= old-level -1)
6707 (= new-level -1)
6708 (= old-level new-level))
6710 (- new-level old-level)))
6711 (delta (if (> shift 0) -1 1))
6712 (func (if (> shift 0) 'org-demote 'org-promote))
6713 (org-odd-levels-only nil)
6714 beg end newend)
6715 ;; Remove the forced level indicator
6716 (if force-level
6717 (delete-region (point-at-bol) (point)))
6718 ;; Paste
6719 (beginning-of-line 1)
6720 (unless for-yank (org-back-over-empty-lines))
6721 (setq beg (point))
6722 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6723 (insert-before-markers txt)
6724 (unless (string-match "\n\\'" txt) (insert "\n"))
6725 (setq newend (point))
6726 (org-reinstall-markers-in-region beg)
6727 (setq end (point))
6728 (goto-char beg)
6729 (skip-chars-forward " \t\n\r")
6730 (setq beg (point))
6731 (if (and (org-invisible-p) visp)
6732 (save-excursion (outline-show-heading)))
6733 ;; Shift if necessary
6734 (unless (= shift 0)
6735 (save-restriction
6736 (narrow-to-region beg end)
6737 (while (not (= shift 0))
6738 (org-map-region func (point-min) (point-max))
6739 (setq shift (+ delta shift)))
6740 (goto-char (point-min))
6741 (setq newend (point-max))))
6742 (when (or (interactive-p) for-yank)
6743 (message "Clipboard pasted as level %d subtree" new-level))
6744 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6745 kill-ring
6746 (eq org-subtree-clip (current-kill 0))
6747 org-subtree-clip-folded)
6748 ;; The tree was folded before it was killed/copied
6749 (hide-subtree))
6750 (and for-yank (goto-char newend))))
6752 (defun org-kill-is-subtree-p (&optional txt)
6753 "Check if the current kill is an outline subtree, or a set of trees.
6754 Returns nil if kill does not start with a headline, or if the first
6755 headline level is not the largest headline level in the tree.
6756 So this will actually accept several entries of equal levels as well,
6757 which is OK for `org-paste-subtree'.
6758 If optional TXT is given, check this string instead of the current kill."
6759 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6760 (start-level (and kill
6761 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6762 org-outline-regexp "\\)")
6763 kill)
6764 (- (match-end 2) (match-beginning 2) 1)))
6765 (re (concat "^" org-outline-regexp))
6766 (start (1+ (or (match-beginning 2) -1))))
6767 (if (not start-level)
6768 (progn
6769 nil) ;; does not even start with a heading
6770 (catch 'exit
6771 (while (setq start (string-match re kill (1+ start)))
6772 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6773 (throw 'exit nil)))
6774 t))))
6776 (defvar org-markers-to-move nil
6777 "Markers that should be moved with a cut-and-paste operation.
6778 Those markers are stored together with their positions relative to
6779 the start of the region.")
6781 (defun org-save-markers-in-region (beg end)
6782 "Check markers in region.
6783 If these markers are between BEG and END, record their position relative
6784 to BEG, so that after moving the block of text, we can put the markers back
6785 into place.
6786 This function gets called just before an entry or tree gets cut from the
6787 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6788 called immediately, to move the markers with the entries."
6789 (setq org-markers-to-move nil)
6790 (when (featurep 'org-clock)
6791 (org-clock-save-markers-for-cut-and-paste beg end))
6792 (when (featurep 'org-agenda)
6793 (org-agenda-save-markers-for-cut-and-paste beg end)))
6795 (defun org-check-and-save-marker (marker beg end)
6796 "Check if MARKER is between BEG and END.
6797 If yes, remember the marker and the distance to BEG."
6798 (when (and (marker-buffer marker)
6799 (equal (marker-buffer marker) (current-buffer)))
6800 (if (and (>= marker beg) (< marker end))
6801 (push (cons marker (- marker beg)) org-markers-to-move))))
6803 (defun org-reinstall-markers-in-region (beg)
6804 "Move all remembered markers to their position relative to BEG."
6805 (mapc (lambda (x)
6806 (move-marker (car x) (+ beg (cdr x))))
6807 org-markers-to-move)
6808 (setq org-markers-to-move nil))
6810 (defun org-narrow-to-subtree ()
6811 "Narrow buffer to the current subtree."
6812 (interactive)
6813 (save-excursion
6814 (save-match-data
6815 (narrow-to-region
6816 (progn (org-back-to-heading t) (point))
6817 (progn (org-end-of-subtree t t) (point))))))
6819 (defun org-clone-subtree-with-time-shift (n &optional shift)
6820 "Clone the task (subtree) at point N times.
6821 The clones will be inserted as siblings.
6823 In interactive use, the user will be prompted for the number of clones
6824 to be produced, and for a time SHIFT, which may be a repeater as used
6825 in time stamps, for example `+3d'.
6827 When a valid repeater is given and the entry contains any time stamps,
6828 the clones will become a sequence in time, with time stamps in the
6829 subtree shifted for each clone produced. If SHIFT is nil or the
6830 empty string, time stamps will be left alone.
6832 If the original subtree did contain time stamps with a repeater,
6833 the following will happen:
6834 - the repeater will be removed in each clone
6835 - an additional clone will be produced, with the current, unshifted
6836 date(s) in the entry.
6837 - the original entry will be placed *after* all the clones, with
6838 repeater intact.
6839 - the start days in the repeater in the original entry will be shifted
6840 to past the last clone.
6841 I this way you can spell out a number of instances of a repeating task,
6842 and still retain the repeater to cover future instances of the task."
6843 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6844 (let (beg end template task
6845 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6846 (if (not (and (integerp n) (> n 0)))
6847 (error "Invalid number of replications %s" n))
6848 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6849 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6850 shift)))
6851 (error "Invalid shift specification %s" shift))
6852 (when doshift
6853 (setq shift-n (string-to-number (match-string 1 shift))
6854 shift-what (cdr (assoc (match-string 2 shift)
6855 '(("d" . day) ("w" . week)
6856 ("m" . month) ("y" . year))))))
6857 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6858 (setq nmin 1 nmax n)
6859 (org-back-to-heading t)
6860 (setq beg (point))
6861 (org-end-of-subtree t t)
6862 (or (bolp) (insert "\n"))
6863 (setq end (point))
6864 (setq template (buffer-substring beg end))
6865 (when (and doshift
6866 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6867 (delete-region beg end)
6868 (setq end beg)
6869 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6870 (goto-char end)
6871 (loop for n from nmin to nmax do
6872 (if (not doshift)
6873 (setq task template)
6874 (with-temp-buffer
6875 (insert template)
6876 (org-mode)
6877 (goto-char (point-min))
6878 (while (re-search-forward org-ts-regexp-both nil t)
6879 (org-timestamp-change (* n shift-n) shift-what))
6880 (unless (= n n-no-remove)
6881 (goto-char (point-min))
6882 (while (re-search-forward org-ts-regexp nil t)
6883 (save-excursion
6884 (goto-char (match-beginning 0))
6885 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6886 (delete-region (match-beginning 1) (match-end 1))))))
6887 (setq task (buffer-string))))
6888 (insert task))
6889 (goto-char beg)))
6891 ;;; Outline Sorting
6893 (defun org-sort (with-case)
6894 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6895 Optional argument WITH-CASE means sort case-sensitively.
6896 With a double prefix argument, also remove duplicate entries."
6897 (interactive "P")
6898 (if (org-at-table-p)
6899 (org-call-with-arg 'org-table-sort-lines with-case)
6900 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6902 (defun org-sort-remove-invisible (s)
6903 (remove-text-properties 0 (length s) org-rm-props s)
6904 (while (string-match org-bracket-link-regexp s)
6905 (setq s (replace-match (if (match-end 2)
6906 (match-string 3 s)
6907 (match-string 1 s)) t t s)))
6910 (defvar org-priority-regexp) ; defined later in the file
6912 (defvar org-after-sorting-entries-or-items-hook nil
6913 "Hook that is run after a bunch of entries or items have been sorted.
6914 When children are sorted, the cursor is in the parent line when this
6915 hook gets called. When a region or a plain list is sorted, the cursor
6916 will be in the first entry of the sorted region/list.")
6918 (defun org-sort-entries-or-items
6919 (&optional with-case sorting-type getkey-func compare-func property)
6920 "Sort entries on a certain level of an outline tree, or plain list items.
6921 If there is an active region, the entries in the region are sorted.
6922 Else, if the cursor is before the first entry, sort the top-level items.
6923 Else, the children of the entry at point are sorted.
6924 If the cursor is at the first item in a plain list, the list items will be
6925 sorted.
6927 Sorting can be alphabetically, numerically, by date/time as given by
6928 a time stamp, by a property or by priority.
6930 The command prompts for the sorting type unless it has been given to the
6931 function through the SORTING-TYPE argument, which needs to a character,
6932 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6933 precise meaning of each character:
6935 n Numerically, by converting the beginning of the entry/item to a number.
6936 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6937 t By date/time, either the first active time stamp in the entry, or, if
6938 none exist, by the first inactive one.
6939 In items, only the first line will be checked.
6940 s By the scheduled date/time.
6941 d By deadline date/time.
6942 c By creation time, which is assumed to be the first inactive time stamp
6943 at the beginning of a line.
6944 p By priority according to the cookie.
6945 r By the value of a property.
6947 Capital letters will reverse the sort order.
6949 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6950 called with point at the beginning of the record. It must return either
6951 a string or a number that should serve as the sorting key for that record.
6953 Comparing entries ignores case by default. However, with an optional argument
6954 WITH-CASE, the sorting considers case as well."
6955 (interactive "P")
6956 (let ((case-func (if with-case 'identity 'downcase))
6957 start beg end stars re re2
6958 txt what tmp plain-list-p)
6959 ;; Find beginning and end of region to sort
6960 (cond
6961 ((org-region-active-p)
6962 ;; we will sort the region
6963 (setq end (region-end)
6964 what "region")
6965 (goto-char (region-beginning))
6966 (if (not (org-on-heading-p)) (outline-next-heading))
6967 (setq start (point)))
6968 ((org-at-item-p)
6969 ;; we will sort this plain list
6970 (org-beginning-of-item-list) (setq start (point))
6971 (org-end-of-item-list)
6972 (or (bolp) (insert "\n"))
6973 (setq end (point))
6974 (goto-char start)
6975 (setq plain-list-p t
6976 what "plain list"))
6977 ((or (org-on-heading-p)
6978 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6979 ;; we will sort the children of the current headline
6980 (org-back-to-heading)
6981 (setq start (point)
6982 end (progn (org-end-of-subtree t t)
6983 (or (bolp) (insert "\n"))
6984 (org-back-over-empty-lines)
6985 (point))
6986 what "children")
6987 (goto-char start)
6988 (show-subtree)
6989 (outline-next-heading))
6991 ;; we will sort the top-level entries in this file
6992 (goto-char (point-min))
6993 (or (org-on-heading-p) (outline-next-heading))
6994 (setq start (point))
6995 (goto-char (point-max))
6996 (beginning-of-line 1)
6997 (when (looking-at ".*?\\S-")
6998 ;; File ends in a non-white line
6999 (end-of-line 1)
7000 (insert "\n"))
7001 (setq end (point-max))
7002 (setq what "top-level")
7003 (goto-char start)
7004 (show-all)))
7006 (setq beg (point))
7007 (if (>= beg end) (error "Nothing to sort"))
7009 (unless plain-list-p
7010 (looking-at "\\(\\*+\\)")
7011 (setq stars (match-string 1)
7012 re (concat "^" (regexp-quote stars) " +")
7013 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7014 txt (buffer-substring beg end))
7015 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7016 (if (and (not (equal stars "*")) (string-match re2 txt))
7017 (error "Region to sort contains a level above the first entry")))
7019 (unless sorting-type
7020 (message
7021 (if plain-list-p
7022 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7023 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7024 [t]ime [s]cheduled [d]eadline [c]reated
7025 A/N/T/S/D/C/P/O/F means reversed:")
7026 what)
7027 (setq sorting-type (read-char-exclusive))
7029 (and (= (downcase sorting-type) ?f)
7030 (setq getkey-func
7031 (org-icompleting-read "Sort using function: "
7032 obarray 'fboundp t nil nil))
7033 (setq getkey-func (intern getkey-func)))
7035 (and (= (downcase sorting-type) ?r)
7036 (setq property
7037 (org-icompleting-read "Property: "
7038 (mapcar 'list (org-buffer-property-keys t))
7039 nil t))))
7041 (message "Sorting entries...")
7043 (save-restriction
7044 (narrow-to-region start end)
7046 (let ((dcst (downcase sorting-type))
7047 (case-fold-search nil)
7048 (now (current-time)))
7049 (sort-subr
7050 (/= dcst sorting-type)
7051 ;; This function moves to the beginning character of the "record" to
7052 ;; be sorted.
7053 (if plain-list-p
7054 (lambda nil
7055 (if (org-at-item-p) t (goto-char (point-max))))
7056 (lambda nil
7057 (if (re-search-forward re nil t)
7058 (goto-char (match-beginning 0))
7059 (goto-char (point-max)))))
7060 ;; This function moves to the last character of the "record" being
7061 ;; sorted.
7062 (if plain-list-p
7063 'org-end-of-item
7064 (lambda nil
7065 (save-match-data
7066 (condition-case nil
7067 (outline-forward-same-level 1)
7068 (error
7069 (goto-char (point-max)))))))
7071 ;; This function returns the value that gets sorted against.
7072 (if plain-list-p
7073 (lambda nil
7074 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7075 (cond
7076 ((= dcst ?n)
7077 (string-to-number (buffer-substring (match-end 0)
7078 (point-at-eol))))
7079 ((= dcst ?a)
7080 (buffer-substring (match-end 0) (point-at-eol)))
7081 ((= dcst ?t)
7082 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7083 (re-search-forward org-ts-regexp-both
7084 (point-at-eol) t))
7085 (org-time-string-to-seconds (match-string 0))
7086 (org-float-time now)))
7087 ((= dcst ?f)
7088 (if getkey-func
7089 (progn
7090 (setq tmp (funcall getkey-func))
7091 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7092 tmp)
7093 (error "Invalid key function `%s'" getkey-func)))
7094 (t (error "Invalid sorting type `%c'" sorting-type)))))
7095 (lambda nil
7096 (cond
7097 ((= dcst ?n)
7098 (if (looking-at org-complex-heading-regexp)
7099 (string-to-number (match-string 4))
7100 nil))
7101 ((= dcst ?a)
7102 (if (looking-at org-complex-heading-regexp)
7103 (funcall case-func (match-string 4))
7104 nil))
7105 ((= dcst ?t)
7106 (let ((end (save-excursion (outline-next-heading) (point))))
7107 (if (or (re-search-forward org-ts-regexp end t)
7108 (re-search-forward org-ts-regexp-both end t))
7109 (org-time-string-to-seconds (match-string 0))
7110 (org-float-time now))))
7111 ((= dcst ?c)
7112 (let ((end (save-excursion (outline-next-heading) (point))))
7113 (if (re-search-forward
7114 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7115 end t)
7116 (org-time-string-to-seconds (match-string 0))
7117 (org-float-time now))))
7118 ((= dcst ?s)
7119 (let ((end (save-excursion (outline-next-heading) (point))))
7120 (if (re-search-forward org-scheduled-time-regexp end t)
7121 (org-time-string-to-seconds (match-string 1))
7122 (org-float-time now))))
7123 ((= dcst ?d)
7124 (let ((end (save-excursion (outline-next-heading) (point))))
7125 (if (re-search-forward org-deadline-time-regexp end t)
7126 (org-time-string-to-seconds (match-string 1))
7127 (org-float-time now))))
7128 ((= dcst ?p)
7129 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7130 (string-to-char (match-string 2))
7131 org-default-priority))
7132 ((= dcst ?r)
7133 (or (org-entry-get nil property) ""))
7134 ((= dcst ?o)
7135 (if (looking-at org-complex-heading-regexp)
7136 (- 9999 (length (member (match-string 2)
7137 org-todo-keywords-1)))))
7138 ((= dcst ?f)
7139 (if getkey-func
7140 (progn
7141 (setq tmp (funcall getkey-func))
7142 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7143 tmp)
7144 (error "Invalid key function `%s'" getkey-func)))
7145 (t (error "Invalid sorting type `%c'" sorting-type)))))
7147 (cond
7148 ((= dcst ?a) 'string<)
7149 ((= dcst ?f) compare-func)
7150 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7151 (t nil)))))
7152 (run-hooks 'org-after-sorting-entries-or-items-hook)
7153 (message "Sorting entries...done")))
7155 (defun org-do-sort (table what &optional with-case sorting-type)
7156 "Sort TABLE of WHAT according to SORTING-TYPE.
7157 The user will be prompted for the SORTING-TYPE if the call to this
7158 function does not specify it. WHAT is only for the prompt, to indicate
7159 what is being sorted. The sorting key will be extracted from
7160 the car of the elements of the table.
7161 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7162 (unless sorting-type
7163 (message
7164 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7165 what)
7166 (setq sorting-type (read-char-exclusive)))
7167 (let ((dcst (downcase sorting-type))
7168 extractfun comparefun)
7169 ;; Define the appropriate functions
7170 (cond
7171 ((= dcst ?n)
7172 (setq extractfun 'string-to-number
7173 comparefun (if (= dcst sorting-type) '< '>)))
7174 ((= dcst ?a)
7175 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7176 (lambda(x) (downcase (org-sort-remove-invisible x))))
7177 comparefun (if (= dcst sorting-type)
7178 'string<
7179 (lambda (a b) (and (not (string< a b))
7180 (not (string= a b)))))))
7181 ((= dcst ?t)
7182 (setq extractfun
7183 (lambda (x)
7184 (if (or (string-match org-ts-regexp x)
7185 (string-match org-ts-regexp-both x))
7186 (org-float-time
7187 (org-time-string-to-time (match-string 0 x)))
7189 comparefun (if (= dcst sorting-type) '< '>)))
7190 (t (error "Invalid sorting type `%c'" sorting-type)))
7192 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7193 table)
7194 (lambda (a b) (funcall comparefun (car a) (car b))))))
7197 ;;; The orgstruct minor mode
7199 ;; Define a minor mode which can be used in other modes in order to
7200 ;; integrate the org-mode structure editing commands.
7202 ;; This is really a hack, because the org-mode structure commands use
7203 ;; keys which normally belong to the major mode. Here is how it
7204 ;; works: The minor mode defines all the keys necessary to operate the
7205 ;; structure commands, but wraps the commands into a function which
7206 ;; tests if the cursor is currently at a headline or a plain list
7207 ;; item. If that is the case, the structure command is used,
7208 ;; temporarily setting many Org-mode variables like regular
7209 ;; expressions for filling etc. However, when any of those keys is
7210 ;; used at a different location, function uses `key-binding' to look
7211 ;; up if the key has an associated command in another currently active
7212 ;; keymap (minor modes, major mode, global), and executes that
7213 ;; command. There might be problems if any of the keys is otherwise
7214 ;; used as a prefix key.
7216 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7217 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7218 ;; addresses this by checking explicitly for both bindings.
7220 (defvar orgstruct-mode-map (make-sparse-keymap)
7221 "Keymap for the minor `orgstruct-mode'.")
7223 (defvar org-local-vars nil
7224 "List of local variables, for use by `orgstruct-mode'")
7226 ;;;###autoload
7227 (define-minor-mode orgstruct-mode
7228 "Toggle the minor more `orgstruct-mode'.
7229 This mode is for using Org-mode structure commands in other modes.
7230 The following key behave as if Org-mode was active, if the cursor
7231 is on a headline, or on a plain list item (both in the definition
7232 of Org-mode).
7234 M-up Move entry/item up
7235 M-down Move entry/item down
7236 M-left Promote
7237 M-right Demote
7238 M-S-up Move entry/item up
7239 M-S-down Move entry/item down
7240 M-S-left Promote subtree
7241 M-S-right Demote subtree
7242 M-q Fill paragraph and items like in Org-mode
7243 C-c ^ Sort entries
7244 C-c - Cycle list bullet
7245 TAB Cycle item visibility
7246 M-RET Insert new heading/item
7247 S-M-RET Insert new TODO heading / Checkbox item
7248 C-c C-c Set tags / toggle checkbox"
7249 nil " OrgStruct" nil
7250 (org-load-modules-maybe)
7251 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7253 ;;;###autoload
7254 (defun turn-on-orgstruct ()
7255 "Unconditionally turn on `orgstruct-mode'."
7256 (orgstruct-mode 1))
7258 (defun orgstruct++-mode (&optional arg)
7259 "Toggle `orgstruct-mode', the enhanced version of it.
7260 In addition to setting orgstruct-mode, this also exports all indentation
7261 and autofilling variables from org-mode into the buffer. It will also
7262 recognize item context in multiline items.
7263 Note that turning off orgstruct-mode will *not* remove the
7264 indentation/paragraph settings. This can only be done by refreshing the
7265 major mode, for example with \\[normal-mode]."
7266 (interactive "P")
7267 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7268 (if (< arg 1)
7269 (orgstruct-mode -1)
7270 (orgstruct-mode 1)
7271 (let (var val)
7272 (mapc
7273 (lambda (x)
7274 (when (string-match
7275 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7276 (symbol-name (car x)))
7277 (setq var (car x) val (nth 1 x))
7278 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7279 org-local-vars)
7280 (org-set-local 'orgstruct-is-++ t))))
7282 (defvar orgstruct-is-++ nil
7283 "Is orgstruct-mode in ++ version in the current-buffer?")
7284 (make-variable-buffer-local 'orgstruct-is-++)
7286 ;;;###autoload
7287 (defun turn-on-orgstruct++ ()
7288 "Unconditionally turn on `orgstruct++-mode'."
7289 (orgstruct++-mode 1))
7291 (defun orgstruct-error ()
7292 "Error when there is no default binding for a structure key."
7293 (interactive)
7294 (error "This key has no function outside structure elements"))
7296 (defun orgstruct-setup ()
7297 "Setup orgstruct keymaps."
7298 (let ((nfunc 0)
7299 (bindings
7300 (list
7301 '([(meta up)] org-metaup)
7302 '([(meta down)] org-metadown)
7303 '([(meta left)] org-metaleft)
7304 '([(meta right)] org-metaright)
7305 '([(meta shift up)] org-shiftmetaup)
7306 '([(meta shift down)] org-shiftmetadown)
7307 '([(meta shift left)] org-shiftmetaleft)
7308 '([(meta shift right)] org-shiftmetaright)
7309 '([?\e (up)] org-metaup)
7310 '([?\e (down)] org-metadown)
7311 '([?\e (left)] org-metaleft)
7312 '([?\e (right)] org-metaright)
7313 '([?\e (shift up)] org-shiftmetaup)
7314 '([?\e (shift down)] org-shiftmetadown)
7315 '([?\e (shift left)] org-shiftmetaleft)
7316 '([?\e (shift right)] org-shiftmetaright)
7317 '([(shift up)] org-shiftup)
7318 '([(shift down)] org-shiftdown)
7319 '([(shift left)] org-shiftleft)
7320 '([(shift right)] org-shiftright)
7321 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7322 '("\M-q" fill-paragraph)
7323 '("\C-c^" org-sort)
7324 '("\C-c-" org-cycle-list-bullet)))
7325 elt key fun cmd)
7326 (while (setq elt (pop bindings))
7327 (setq nfunc (1+ nfunc))
7328 (setq key (org-key (car elt))
7329 fun (nth 1 elt)
7330 cmd (orgstruct-make-binding fun nfunc key))
7331 (org-defkey orgstruct-mode-map key cmd))
7333 ;; Special treatment needed for TAB and RET
7334 (org-defkey orgstruct-mode-map [(tab)]
7335 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7336 (org-defkey orgstruct-mode-map "\C-i"
7337 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7339 (org-defkey orgstruct-mode-map "\M-\C-m"
7340 (orgstruct-make-binding 'org-insert-heading 105
7341 "\M-\C-m" [(meta return)]))
7342 (org-defkey orgstruct-mode-map [(meta return)]
7343 (orgstruct-make-binding 'org-insert-heading 106
7344 [(meta return)] "\M-\C-m"))
7346 (org-defkey orgstruct-mode-map [(shift meta return)]
7347 (orgstruct-make-binding 'org-insert-todo-heading 107
7348 [(meta return)] "\M-\C-m"))
7350 (org-defkey orgstruct-mode-map "\e\C-m"
7351 (orgstruct-make-binding 'org-insert-heading 108
7352 "\e\C-m" [?\e (return)]))
7353 (org-defkey orgstruct-mode-map [?\e (return)]
7354 (orgstruct-make-binding 'org-insert-heading 109
7355 [?\e (return)] "\e\C-m"))
7356 (org-defkey orgstruct-mode-map [?\e (shift return)]
7357 (orgstruct-make-binding 'org-insert-todo-heading 110
7358 [?\e (return)] "\e\C-m"))
7360 (unless org-local-vars
7361 (setq org-local-vars (org-get-local-variables)))
7365 (defun orgstruct-make-binding (fun n &rest keys)
7366 "Create a function for binding in the structure minor mode.
7367 FUN is the command to call inside a table. N is used to create a unique
7368 command name. KEYS are keys that should be checked in for a command
7369 to execute outside of tables."
7370 (eval
7371 (list 'defun
7372 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7373 '(arg)
7374 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7375 "Outside of structure, run the binding of `"
7376 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7377 "'.")
7378 '(interactive "p")
7379 (list 'if
7380 `(org-context-p 'headline 'item
7381 (and orgstruct-is-++
7382 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7383 'item-body))
7384 (list 'org-run-like-in-org-mode (list 'quote fun))
7385 (list 'let '(orgstruct-mode)
7386 (list 'call-interactively
7387 (append '(or)
7388 (mapcar (lambda (k)
7389 (list 'key-binding k))
7390 keys)
7391 '('orgstruct-error))))))))
7393 (defun org-context-p (&rest contexts)
7394 "Check if local context is any of CONTEXTS.
7395 Possible values in the list of contexts are `table', `headline', and `item'."
7396 (let ((pos (point)))
7397 (goto-char (point-at-bol))
7398 (prog1 (or (and (memq 'table contexts)
7399 (looking-at "[ \t]*|"))
7400 (and (memq 'headline contexts)
7401 ;;????????? (looking-at "\\*+"))
7402 (looking-at outline-regexp))
7403 (and (memq 'item contexts)
7404 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7405 (and (memq 'item-body contexts)
7406 (org-in-item-p)))
7407 (goto-char pos))))
7409 (defun org-get-local-variables ()
7410 "Return a list of all local variables in an org-mode buffer."
7411 (let (varlist)
7412 (with-current-buffer (get-buffer-create "*Org tmp*")
7413 (erase-buffer)
7414 (org-mode)
7415 (setq varlist (buffer-local-variables)))
7416 (kill-buffer "*Org tmp*")
7417 (delq nil
7418 (mapcar
7419 (lambda (x)
7420 (setq x
7421 (if (symbolp x)
7422 (list x)
7423 (list (car x) (list 'quote (cdr x)))))
7424 (if (string-match
7425 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7426 (symbol-name (car x)))
7427 x nil))
7428 varlist))))
7430 ;;;###autoload
7431 (defun org-run-like-in-org-mode (cmd)
7432 "Run a command, pretending that the current buffer is in Org-mode.
7433 This will temporarily bind local variables that are typically bound in
7434 Org-mode to the values they have in Org-mode, and then interactively
7435 call CMD."
7436 (org-load-modules-maybe)
7437 (unless org-local-vars
7438 (setq org-local-vars (org-get-local-variables)))
7439 (eval (list 'let org-local-vars
7440 (list 'call-interactively (list 'quote cmd)))))
7442 ;;;; Archiving
7444 (defun org-get-category (&optional pos)
7445 "Get the category applying to position POS."
7446 (get-text-property (or pos (point)) 'org-category))
7448 (defun org-refresh-category-properties ()
7449 "Refresh category text properties in the buffer."
7450 (let ((def-cat (cond
7451 ((null org-category)
7452 (if buffer-file-name
7453 (file-name-sans-extension
7454 (file-name-nondirectory buffer-file-name))
7455 "???"))
7456 ((symbolp org-category) (symbol-name org-category))
7457 (t org-category)))
7458 beg end cat pos optionp)
7459 (org-unmodified
7460 (save-excursion
7461 (save-restriction
7462 (widen)
7463 (goto-char (point-min))
7464 (put-text-property (point) (point-max) 'org-category def-cat)
7465 (while (re-search-forward
7466 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7467 (setq pos (match-end 0)
7468 optionp (equal (char-after (match-beginning 0)) ?#)
7469 cat (org-trim (match-string 2)))
7470 (if optionp
7471 (setq beg (point-at-bol) end (point-max))
7472 (org-back-to-heading t)
7473 (setq beg (point) end (org-end-of-subtree t t)))
7474 (put-text-property beg end 'org-category cat)
7475 (goto-char pos)))))))
7478 ;;;; Link Stuff
7480 ;;; Link abbreviations
7482 (defun org-link-expand-abbrev (link)
7483 "Apply replacements as defined in `org-link-abbrev-alist."
7484 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7485 (let* ((key (match-string 1 link))
7486 (as (or (assoc key org-link-abbrev-alist-local)
7487 (assoc key org-link-abbrev-alist)))
7488 (tag (and (match-end 2) (match-string 3 link)))
7489 rpl)
7490 (if (not as)
7491 link
7492 (setq rpl (cdr as))
7493 (cond
7494 ((symbolp rpl) (funcall rpl tag))
7495 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7496 ((string-match "%h" rpl)
7497 (replace-match (url-hexify-string (or tag "")) t t rpl))
7498 (t (concat rpl tag)))))
7499 link))
7501 ;;; Storing and inserting links
7503 (defvar org-insert-link-history nil
7504 "Minibuffer history for links inserted with `org-insert-link'.")
7506 (defvar org-stored-links nil
7507 "Contains the links stored with `org-store-link'.")
7509 (defvar org-store-link-plist nil
7510 "Plist with info about the most recently link created with `org-store-link'.")
7512 (defvar org-link-protocols nil
7513 "Link protocols added to Org-mode using `org-add-link-type'.")
7515 (defvar org-store-link-functions nil
7516 "List of functions that are called to create and store a link.
7517 Each function will be called in turn until one returns a non-nil
7518 value. Each function should check if it is responsible for creating
7519 this link (for example by looking at the major mode).
7520 If not, it must exit and return nil.
7521 If yes, it should return a non-nil value after a calling
7522 `org-store-link-props' with a list of properties and values.
7523 Special properties are:
7525 :type The link prefix. like \"http\". This must be given.
7526 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7527 This is obligatory as well.
7528 :description Optional default description for the second pair
7529 of brackets in an Org-mode link. The user can still change
7530 this when inserting this link into an Org-mode buffer.
7532 In addition to these, any additional properties can be specified
7533 and then used in remember templates.")
7535 (defun org-add-link-type (type &optional follow export)
7536 "Add TYPE to the list of `org-link-types'.
7537 Re-compute all regular expressions depending on `org-link-types'
7539 FOLLOW and EXPORT are two functions.
7541 FOLLOW should take the link path as the single argument and do whatever
7542 is necessary to follow the link, for example find a file or display
7543 a mail message.
7545 EXPORT should format the link path for export to one of the export formats.
7546 It should be a function accepting three arguments:
7548 path the path of the link, the text after the prefix (like \"http:\")
7549 desc the description of the link, if any, nil if there was no description
7550 format the export format, a symbol like `html' or `latex'.
7552 The function may use the FORMAT information to return different values
7553 depending on the format. The return value will be put literally into
7554 the exported file.
7555 Org-mode has a built-in default for exporting links. If you are happy with
7556 this default, there is no need to define an export function for the link
7557 type. For a simple example of an export function, see `org-bbdb.el'."
7558 (add-to-list 'org-link-types type t)
7559 (org-make-link-regexps)
7560 (if (assoc type org-link-protocols)
7561 (setcdr (assoc type org-link-protocols) (list follow export))
7562 (push (list type follow export) org-link-protocols)))
7564 (defvar org-agenda-buffer-name)
7566 ;;;###autoload
7567 (defun org-store-link (arg)
7568 "\\<org-mode-map>Store an org-link to the current location.
7569 This link is added to `org-stored-links' and can later be inserted
7570 into an org-buffer with \\[org-insert-link].
7572 For some link types, a prefix arg is interpreted:
7573 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7574 For file links, arg negates `org-context-in-file-links'."
7575 (interactive "P")
7576 (org-load-modules-maybe)
7577 (setq org-store-link-plist nil) ; reset
7578 (let ((outline-regexp (org-get-limited-outline-regexp))
7579 link cpltxt desc description search txt custom-id)
7580 (cond
7582 ((run-hook-with-args-until-success 'org-store-link-functions)
7583 (setq link (plist-get org-store-link-plist :link)
7584 desc (or (plist-get org-store-link-plist :description) link)))
7586 ((equal (buffer-name) "*Org Edit Src Example*")
7587 (let (label gc)
7588 (while (or (not label)
7589 (save-excursion
7590 (save-restriction
7591 (widen)
7592 (goto-char (point-min))
7593 (re-search-forward
7594 (regexp-quote (format org-coderef-label-format label))
7595 nil t))))
7596 (when label (message "Label exists already") (sit-for 2))
7597 (setq label (read-string "Code line label: " label)))
7598 (end-of-line 1)
7599 (setq link (format org-coderef-label-format label))
7600 (setq gc (- 79 (length link)))
7601 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7602 (insert link)
7603 (setq link (concat "(" label ")") desc nil)))
7605 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7606 ;; We are in the agenda, link to referenced location
7607 (let ((m (or (get-text-property (point) 'org-hd-marker)
7608 (get-text-property (point) 'org-marker))))
7609 (when m
7610 (org-with-point-at m
7611 (call-interactively 'org-store-link)))))
7613 ((eq major-mode 'calendar-mode)
7614 (let ((cd (calendar-cursor-to-date)))
7615 (setq link
7616 (format-time-string
7617 (car org-time-stamp-formats)
7618 (apply 'encode-time
7619 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7620 nil nil nil))))
7621 (org-store-link-props :type "calendar" :date cd)))
7623 ((eq major-mode 'w3-mode)
7624 (setq cpltxt (if (and (buffer-name)
7625 (not (string-match "Untitled" (buffer-name))))
7626 (buffer-name)
7627 (url-view-url t))
7628 link (org-make-link (url-view-url t)))
7629 (org-store-link-props :type "w3" :url (url-view-url t)))
7631 ((eq major-mode 'w3m-mode)
7632 (setq cpltxt (or w3m-current-title w3m-current-url)
7633 link (org-make-link w3m-current-url))
7634 (org-store-link-props :type "w3m" :url (url-view-url t)))
7636 ((setq search (run-hook-with-args-until-success
7637 'org-create-file-search-functions))
7638 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7639 "::" search))
7640 (setq cpltxt (or description link)))
7642 ((eq major-mode 'image-mode)
7643 (setq cpltxt (concat "file:"
7644 (abbreviate-file-name buffer-file-name))
7645 link (org-make-link cpltxt))
7646 (org-store-link-props :type "image" :file buffer-file-name))
7648 ((eq major-mode 'dired-mode)
7649 ;; link to the file in the current line
7650 (setq cpltxt (concat "file:"
7651 (abbreviate-file-name
7652 (expand-file-name
7653 (dired-get-filename nil t))))
7654 link (org-make-link cpltxt)))
7656 ((and buffer-file-name (org-mode-p))
7657 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7658 (cond
7659 ((org-in-regexp "<<\\(.*?\\)>>")
7660 (setq cpltxt
7661 (concat "file:"
7662 (abbreviate-file-name buffer-file-name)
7663 "::" (match-string 1))
7664 link (org-make-link cpltxt)))
7665 ((and (featurep 'org-id)
7666 (or (eq org-link-to-org-use-id t)
7667 (and (eq org-link-to-org-use-id 'create-if-interactive)
7668 (interactive-p))
7669 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7670 (interactive-p)
7671 (not custom-id))
7672 (and org-link-to-org-use-id
7673 (condition-case nil
7674 (org-entry-get nil "ID")
7675 (error nil)))))
7676 ;; We can make a link using the ID.
7677 (setq link (condition-case nil
7678 (prog1 (org-id-store-link)
7679 (setq desc (plist-get org-store-link-plist
7680 :description)))
7681 (error
7682 ;; probably before first headline, link to file only
7683 (concat "file:"
7684 (abbreviate-file-name buffer-file-name))))))
7686 ;; Just link to current headline
7687 (setq cpltxt (concat "file:"
7688 (abbreviate-file-name buffer-file-name)))
7689 ;; Add a context search string
7690 (when (org-xor org-context-in-file-links arg)
7691 (setq txt (cond
7692 ((org-on-heading-p) nil)
7693 ((org-region-active-p)
7694 (buffer-substring (region-beginning) (region-end)))
7695 (t nil)))
7696 (when (or (null txt) (string-match "\\S-" txt))
7697 (setq cpltxt
7698 (concat cpltxt "::"
7699 (condition-case nil
7700 (org-make-org-heading-search-string txt)
7701 (error "")))
7702 desc (or (nth 4 (ignore-errors
7703 (org-heading-components))) "NONE"))))
7704 (if (string-match "::\\'" cpltxt)
7705 (setq cpltxt (substring cpltxt 0 -2)))
7706 (setq link (org-make-link cpltxt)))))
7708 ((buffer-file-name (buffer-base-buffer))
7709 ;; Just link to this file here.
7710 (setq cpltxt (concat "file:"
7711 (abbreviate-file-name
7712 (buffer-file-name (buffer-base-buffer)))))
7713 ;; Add a context string
7714 (when (org-xor org-context-in-file-links arg)
7715 (setq txt (if (org-region-active-p)
7716 (buffer-substring (region-beginning) (region-end))
7717 (buffer-substring (point-at-bol) (point-at-eol))))
7718 ;; Only use search option if there is some text.
7719 (when (string-match "\\S-" txt)
7720 (setq cpltxt
7721 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7722 desc "NONE")))
7723 (setq link (org-make-link cpltxt)))
7725 ((interactive-p)
7726 (error "Cannot link to a buffer which is not visiting a file"))
7728 (t (setq link nil)))
7730 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7731 (setq link (or link cpltxt)
7732 desc (or desc cpltxt))
7733 (if (equal desc "NONE") (setq desc nil))
7735 (if (and (or (interactive-p) executing-kbd-macro) link)
7736 (progn
7737 (setq org-stored-links
7738 (cons (list link desc) org-stored-links))
7739 (message "Stored: %s" (or desc link))
7740 (when custom-id
7741 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7742 "::#" custom-id))
7743 (setq org-stored-links
7744 (cons (list link desc) org-stored-links))))
7745 (and link (org-make-link-string link desc)))))
7747 (defun org-store-link-props (&rest plist)
7748 "Store link properties, extract names and addresses."
7749 (let (x adr)
7750 (when (setq x (plist-get plist :from))
7751 (setq adr (mail-extract-address-components x))
7752 (setq plist (plist-put plist :fromname (car adr)))
7753 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7754 (when (setq x (plist-get plist :to))
7755 (setq adr (mail-extract-address-components x))
7756 (setq plist (plist-put plist :toname (car adr)))
7757 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7758 (let ((from (plist-get plist :from))
7759 (to (plist-get plist :to)))
7760 (when (and from to org-from-is-user-regexp)
7761 (setq plist
7762 (plist-put plist :fromto
7763 (if (string-match org-from-is-user-regexp from)
7764 (concat "to %t")
7765 (concat "from %f"))))))
7766 (setq org-store-link-plist plist))
7768 (defun org-add-link-props (&rest plist)
7769 "Add these properties to the link property list."
7770 (let (key value)
7771 (while plist
7772 (setq key (pop plist) value (pop plist))
7773 (setq org-store-link-plist
7774 (plist-put org-store-link-plist key value)))))
7776 (defun org-email-link-description (&optional fmt)
7777 "Return the description part of an email link.
7778 This takes information from `org-store-link-plist' and formats it
7779 according to FMT (default from `org-email-link-description-format')."
7780 (setq fmt (or fmt org-email-link-description-format))
7781 (let* ((p org-store-link-plist)
7782 (to (plist-get p :toaddress))
7783 (from (plist-get p :fromaddress))
7784 (table
7785 (list
7786 (cons "%c" (plist-get p :fromto))
7787 (cons "%F" (plist-get p :from))
7788 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7789 (cons "%T" (plist-get p :to))
7790 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7791 (cons "%s" (plist-get p :subject))
7792 (cons "%m" (plist-get p :message-id)))))
7793 (when (string-match "%c" fmt)
7794 ;; Check if the user wrote this message
7795 (if (and org-from-is-user-regexp from to
7796 (save-match-data (string-match org-from-is-user-regexp from)))
7797 (setq fmt (replace-match "to %t" t t fmt))
7798 (setq fmt (replace-match "from %f" t t fmt))))
7799 (org-replace-escapes fmt table)))
7801 (defun org-make-org-heading-search-string (&optional string heading)
7802 "Make search string for STRING or current headline."
7803 (interactive)
7804 (let ((s (or string (org-get-heading))))
7805 (unless (and string (not heading))
7806 ;; We are using a headline, clean up garbage in there.
7807 (if (string-match org-todo-regexp s)
7808 (setq s (replace-match "" t t s)))
7809 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7810 (setq s (replace-match "" t t s)))
7811 (setq s (org-trim s))
7812 (if (string-match (concat "^\\(" org-quote-string "\\|"
7813 org-comment-string "\\)") s)
7814 (setq s (replace-match "" t t s)))
7815 (while (string-match org-ts-regexp s)
7816 (setq s (replace-match "" t t s))))
7817 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7818 (setq s (replace-match " " t t s)))
7819 (or string (setq s (concat "*" s))) ; Add * for headlines
7820 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7822 (defun org-make-link (&rest strings)
7823 "Concatenate STRINGS."
7824 (apply 'concat strings))
7826 (defun org-make-link-string (link &optional description)
7827 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7828 (unless (string-match "\\S-" link)
7829 (error "Empty link"))
7830 (when (and description
7831 (stringp description)
7832 (not (string-match "\\S-" description)))
7833 (setq description nil))
7834 (when (stringp description)
7835 ;; Remove brackets from the description, they are fatal.
7836 (while (string-match "\\[" description)
7837 (setq description (replace-match "{" t t description)))
7838 (while (string-match "\\]" description)
7839 (setq description (replace-match "}" t t description))))
7840 (when (equal (org-link-escape link) description)
7841 ;; No description needed, it is identical
7842 (setq description nil))
7843 (when (and (not description)
7844 (not (equal link (org-link-escape link))))
7845 (setq description (org-extract-attributes link)))
7846 (concat "[[" (org-link-escape link) "]"
7847 (if description (concat "[" description "]") "")
7848 "]"))
7850 (defconst org-link-escape-chars
7851 '((?\ . "%20")
7852 (?\[ . "%5B")
7853 (?\] . "%5D")
7854 (?\340 . "%E0") ; `a
7855 (?\342 . "%E2") ; ^a
7856 (?\347 . "%E7") ; ,c
7857 (?\350 . "%E8") ; `e
7858 (?\351 . "%E9") ; 'e
7859 (?\352 . "%EA") ; ^e
7860 (?\356 . "%EE") ; ^i
7861 (?\364 . "%F4") ; ^o
7862 (?\371 . "%F9") ; `u
7863 (?\373 . "%FB") ; ^u
7864 (?\; . "%3B")
7865 (?? . "%3F")
7866 (?= . "%3D")
7867 (?+ . "%2B")
7869 "Association list of escapes for some characters problematic in links.
7870 This is the list that is used for internal purposes.")
7872 (defvar org-url-encoding-use-url-hexify nil)
7874 (defconst org-link-escape-chars-browser
7875 '((?\ . "%20")) ; 32 for the SPC char
7876 "Association list of escapes for some characters problematic in links.
7877 This is the list that is used before handing over to the browser.")
7879 (defun org-link-escape (text &optional table)
7880 "Escape characters in TEXT that are problematic for links."
7881 (if org-url-encoding-use-url-hexify
7882 (url-hexify-string text)
7883 (setq table (or table org-link-escape-chars))
7884 (when text
7885 (let ((re (mapconcat (lambda (x) (regexp-quote
7886 (char-to-string (car x))))
7887 table "\\|")))
7888 (while (string-match re text)
7889 (setq text
7890 (replace-match
7891 (cdr (assoc (string-to-char (match-string 0 text))
7892 table))
7893 t t text)))
7894 text))))
7896 (defun org-link-unescape (text &optional table)
7897 "Reverse the action of `org-link-escape'."
7898 (if org-url-encoding-use-url-hexify
7899 (url-unhex-string text)
7900 (setq table (or table org-link-escape-chars))
7901 (when text
7902 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7903 table "\\|")))
7904 (while (string-match re text)
7905 (setq text
7906 (replace-match
7907 (char-to-string (car (rassoc (match-string 0 text) table)))
7908 t t text)))
7909 text))))
7911 (defun org-xor (a b)
7912 "Exclusive or."
7913 (if a (not b) b))
7915 (defun org-fixup-message-id-for-http (s)
7916 "Replace special characters in a message id, so it can be used in an http query."
7917 (while (string-match "<" s)
7918 (setq s (replace-match "%3C" t t s)))
7919 (while (string-match ">" s)
7920 (setq s (replace-match "%3E" t t s)))
7921 (while (string-match "@" s)
7922 (setq s (replace-match "%40" t t s)))
7925 ;;;###autoload
7926 (defun org-insert-link-global ()
7927 "Insert a link like Org-mode does.
7928 This command can be called in any mode to insert a link in Org-mode syntax."
7929 (interactive)
7930 (org-load-modules-maybe)
7931 (org-run-like-in-org-mode 'org-insert-link))
7933 (defun org-insert-link (&optional complete-file link-location)
7934 "Insert a link. At the prompt, enter the link.
7936 Completion can be used to insert any of the link protocol prefixes like
7937 http or ftp in use.
7939 The history can be used to select a link previously stored with
7940 `org-store-link'. When the empty string is entered (i.e. if you just
7941 press RET at the prompt), the link defaults to the most recently
7942 stored link. As SPC triggers completion in the minibuffer, you need to
7943 use M-SPC or C-q SPC to force the insertion of a space character.
7945 You will also be prompted for a description, and if one is given, it will
7946 be displayed in the buffer instead of the link.
7948 If there is already a link at point, this command will allow you to edit link
7949 and description parts.
7951 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7952 be selected using completion. The path to the file will be relative to the
7953 current directory if the file is in the current directory or a subdirectory.
7954 Otherwise, the link will be the absolute path as completed in the minibuffer
7955 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7956 option `org-link-file-path-type'.
7958 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7959 the current directory or below.
7961 With three \\[universal-argument] prefixes, negate the meaning of
7962 `org-keep-stored-link-after-insertion'.
7964 If `org-make-link-description-function' is non-nil, this function will be
7965 called with the link target, and the result will be the default
7966 link description.
7968 If the LINK-LOCATION parameter is non-nil, this value will be
7969 used as the link location instead of reading one interactively."
7970 (interactive "P")
7971 (let* ((wcf (current-window-configuration))
7972 (region (if (org-region-active-p)
7973 (buffer-substring (region-beginning) (region-end))))
7974 (remove (and region (list (region-beginning) (region-end))))
7975 (desc region)
7976 tmphist ; byte-compile incorrectly complains about this
7977 (link link-location)
7978 entry file all-prefixes)
7979 (cond
7980 (link-location) ; specified by arg, just use it.
7981 ((org-in-regexp org-bracket-link-regexp 1)
7982 ;; We do have a link at point, and we are going to edit it.
7983 (setq remove (list (match-beginning 0) (match-end 0)))
7984 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7985 (setq link (read-string "Link: "
7986 (org-link-unescape
7987 (org-match-string-no-properties 1)))))
7988 ((or (org-in-regexp org-angle-link-re)
7989 (org-in-regexp org-plain-link-re))
7990 ;; Convert to bracket link
7991 (setq remove (list (match-beginning 0) (match-end 0))
7992 link (read-string "Link: "
7993 (org-remove-angle-brackets (match-string 0)))))
7994 ((member complete-file '((4) (16)))
7995 ;; Completing read for file names.
7996 (setq link (org-file-complete-link complete-file)))
7998 ;; Read link, with completion for stored links.
7999 (with-output-to-temp-buffer "*Org Links*"
8000 (princ "Insert a link.
8001 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8002 (when org-stored-links
8003 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8004 (princ (mapconcat
8005 (lambda (x)
8006 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8007 (reverse org-stored-links) "\n"))))
8008 (let ((cw (selected-window)))
8009 (select-window (get-buffer-window "*Org Links*"))
8010 (setq truncate-lines t)
8011 (unless (pos-visible-in-window-p (point-max))
8012 (org-fit-window-to-buffer))
8013 (and (window-live-p cw) (select-window cw)))
8014 ;; Fake a link history, containing the stored links.
8015 (setq tmphist (append (mapcar 'car org-stored-links)
8016 org-insert-link-history))
8017 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8018 (mapcar 'car org-link-abbrev-alist)
8019 org-link-types))
8020 (unwind-protect
8021 (progn
8022 (setq link
8023 (let ((org-completion-use-ido nil)
8024 (org-completion-use-iswitchb nil))
8025 (org-completing-read
8026 "Link: "
8027 (append
8028 (mapcar (lambda (x) (list (concat x ":")))
8029 all-prefixes)
8030 (mapcar 'car org-stored-links))
8031 nil nil nil
8032 'tmphist
8033 (car (car org-stored-links)))))
8034 (if (not (string-match "\\S-" link))
8035 (error "No link selected"))
8036 (if (or (member link all-prefixes)
8037 (and (equal ":" (substring link -1))
8038 (member (substring link 0 -1) all-prefixes)
8039 (setq link (substring link 0 -1))))
8040 (setq link (org-link-try-special-completion link))))
8041 (set-window-configuration wcf)
8042 (kill-buffer "*Org Links*"))
8043 (setq entry (assoc link org-stored-links))
8044 (or entry (push link org-insert-link-history))
8045 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8046 (not org-keep-stored-link-after-insertion))
8047 (setq org-stored-links (delq (assoc link org-stored-links)
8048 org-stored-links)))
8049 (setq desc (or desc (nth 1 entry)))))
8051 (if (string-match org-plain-link-re link)
8052 ;; URL-like link, normalize the use of angular brackets.
8053 (setq link (org-make-link (org-remove-angle-brackets link))))
8055 ;; Check if we are linking to the current file with a search option
8056 ;; If yes, simplify the link by using only the search option.
8057 (when (and buffer-file-name
8058 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8059 (let* ((path (match-string 1 link))
8060 (case-fold-search nil)
8061 (search (match-string 2 link)))
8062 (save-match-data
8063 (if (equal (file-truename buffer-file-name) (file-truename path))
8064 ;; We are linking to this same file, with a search option
8065 (setq link search)))))
8067 ;; Check if we can/should use a relative path. If yes, simplify the link
8068 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8069 (let* ((type (match-string 1 link))
8070 (path (match-string 2 link))
8071 (origpath path)
8072 (case-fold-search nil))
8073 (cond
8074 ((or (eq org-link-file-path-type 'absolute)
8075 (equal complete-file '(16)))
8076 (setq path (abbreviate-file-name (expand-file-name path))))
8077 ((eq org-link-file-path-type 'noabbrev)
8078 (setq path (expand-file-name path)))
8079 ((eq org-link-file-path-type 'relative)
8080 (setq path (file-relative-name path)))
8082 (save-match-data
8083 (if (string-match (concat "^" (regexp-quote
8084 (file-name-as-directory
8085 (expand-file-name "."))))
8086 (expand-file-name path))
8087 ;; We are linking a file with relative path name.
8088 (setq path (substring (expand-file-name path)
8089 (match-end 0)))
8090 (setq path (abbreviate-file-name (expand-file-name path)))))))
8091 (setq link (concat type path))
8092 (if (equal desc origpath)
8093 (setq desc path))))
8095 (if org-make-link-description-function
8096 (setq desc (funcall org-make-link-description-function link desc)))
8098 (setq desc (read-string "Description: " desc))
8099 (unless (string-match "\\S-" desc) (setq desc nil))
8100 (if remove (apply 'delete-region remove))
8101 (insert (org-make-link-string link desc))))
8103 (defun org-link-try-special-completion (type)
8104 "If there is completion support for link type TYPE, offer it."
8105 (let ((fun (intern (concat "org-" type "-complete-link"))))
8106 (if (functionp fun)
8107 (funcall fun)
8108 (read-string "Link (no completion support): " (concat type ":")))))
8110 (defun org-file-complete-link (&optional arg)
8111 "Create a file link using completion."
8112 (let (file link)
8113 (setq file (read-file-name "File: "))
8114 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8115 (pwd1 (file-name-as-directory (abbreviate-file-name
8116 (expand-file-name ".")))))
8117 (cond
8118 ((equal arg '(16))
8119 (setq link (org-make-link
8120 "file:"
8121 (abbreviate-file-name (expand-file-name file)))))
8122 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8123 (setq link (org-make-link "file:" (match-string 1 file))))
8124 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8125 (expand-file-name file))
8126 (setq link (org-make-link
8127 "file:" (match-string 1 (expand-file-name file)))))
8128 (t (setq link (org-make-link "file:" file)))))
8129 link))
8131 (defun org-completing-read (&rest args)
8132 "Completing-read with SPACE being a normal character."
8133 (let ((minibuffer-local-completion-map
8134 (copy-keymap minibuffer-local-completion-map)))
8135 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8136 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8137 (apply 'org-icompleting-read args)))
8139 (defun org-completing-read-no-i (&rest args)
8140 (let (org-completion-use-ido org-completion-use-iswitchb)
8141 (apply 'org-completing-read args)))
8143 (defun org-iswitchb-completing-read (prompt choices &rest args)
8144 "Use iswitch as a completing-read replacement to choose from choices.
8145 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8146 from."
8147 (let* ((iswitchb-use-virtual-buffers nil)
8148 (iswitchb-make-buflist-hook
8149 (lambda ()
8150 (setq iswitchb-temp-buflist choices))))
8151 (iswitchb-read-buffer prompt)))
8153 (defun org-icompleting-read (&rest args)
8154 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8155 (org-without-partial-completion
8156 (if (and org-completion-use-ido
8157 (fboundp 'ido-completing-read)
8158 (boundp 'ido-mode) ido-mode
8159 (listp (second args)))
8160 (let ((ido-enter-matching-directory nil))
8161 (apply 'ido-completing-read (concat (car args))
8162 (if (consp (car (nth 1 args)))
8163 (mapcar (lambda (x) (car x)) (nth 1 args))
8164 (nth 1 args))
8165 (cddr args)))
8166 (if (and org-completion-use-iswitchb
8167 (boundp 'iswitchb-mode) iswitchb-mode
8168 (listp (second args)))
8169 (apply 'org-iswitchb-completing-read (concat (car args))
8170 (if (consp (car (nth 1 args)))
8171 (mapcar (lambda (x) (car x)) (nth 1 args))
8172 (nth 1 args))
8173 (cddr args))
8174 (apply 'completing-read args)))))
8176 (defun org-extract-attributes (s)
8177 "Extract the attributes cookie from a string and set as text property."
8178 (let (a attr (start 0) key value)
8179 (save-match-data
8180 (when (string-match "{{\\([^}]+\\)}}$" s)
8181 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8182 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8183 (setq key (match-string 1 a) value (match-string 2 a)
8184 start (match-end 0)
8185 attr (plist-put attr (intern key) value))))
8186 (org-add-props s nil 'org-attr attr))
8189 (defun org-extract-attributes-from-string (tag)
8190 (let (key value attr)
8191 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8192 (setq key (match-string 1 tag) value (match-string 2 tag)
8193 tag (replace-match "" t t tag)
8194 attr (plist-put attr (intern key) value)))
8195 (cons tag attr)))
8197 (defun org-attributes-to-string (plist)
8198 "Format a property list into an HTML attribute list."
8199 (let ((s "") key value)
8200 (while plist
8201 (setq key (pop plist) value (pop plist))
8202 (and value
8203 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8206 ;;; Opening/following a link
8208 (defvar org-link-search-failed nil)
8210 (defvar org-open-link-functions nil
8211 "Hook for functions finding a plain text link.
8212 These functions must take a single argument, the link content.
8213 They will be called for links that look like [[link text][description]]
8214 when LINK TEXT does not have a protocol like \"http:\" and does not look
8215 like a filename (e.g. \"./blue.png\").
8217 These functions will be called *before* Org attempts to resolve the
8218 link by doing text searches in the current buffer - so if you want a
8219 link \"[[target]]\" to still find \"<<target>>\", your function should
8220 handle this as a special case.
8222 When the function does handle the link, it must return a non-nil value.
8223 If it decides that it is not responsible for this link, it must return
8224 nil to indicate that that Org-mode can continue with other options
8225 like exact and fuzzy text search.")
8227 (defun org-next-link ()
8228 "Move forward to the next link.
8229 If the link is in hidden text, expose it."
8230 (interactive)
8231 (when (and org-link-search-failed (eq this-command last-command))
8232 (goto-char (point-min))
8233 (message "Link search wrapped back to beginning of buffer"))
8234 (setq org-link-search-failed nil)
8235 (let* ((pos (point))
8236 (ct (org-context))
8237 (a (assoc :link ct)))
8238 (if a (goto-char (nth 2 a)))
8239 (if (re-search-forward org-any-link-re nil t)
8240 (progn
8241 (goto-char (match-beginning 0))
8242 (if (org-invisible-p) (org-show-context)))
8243 (goto-char pos)
8244 (setq org-link-search-failed t)
8245 (error "No further link found"))))
8247 (defun org-previous-link ()
8248 "Move backward to the previous link.
8249 If the link is in hidden text, expose it."
8250 (interactive)
8251 (when (and org-link-search-failed (eq this-command last-command))
8252 (goto-char (point-max))
8253 (message "Link search wrapped back to end of buffer"))
8254 (setq org-link-search-failed nil)
8255 (let* ((pos (point))
8256 (ct (org-context))
8257 (a (assoc :link ct)))
8258 (if a (goto-char (nth 1 a)))
8259 (if (re-search-backward org-any-link-re nil t)
8260 (progn
8261 (goto-char (match-beginning 0))
8262 (if (org-invisible-p) (org-show-context)))
8263 (goto-char pos)
8264 (setq org-link-search-failed t)
8265 (error "No further link found"))))
8267 (defun org-translate-link (s)
8268 "Translate a link string if a translation function has been defined."
8269 (if (and org-link-translation-function
8270 (fboundp org-link-translation-function)
8271 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8272 (progn
8273 (setq s (funcall org-link-translation-function
8274 (match-string 1) (match-string 2)))
8275 (concat (car s) ":" (cdr s)))
8278 (defun org-translate-link-from-planner (type path)
8279 "Translate a link from Emacs Planner syntax so that Org can follow it.
8280 This is still an experimental function, your mileage may vary."
8281 (cond
8282 ((member type '("http" "https" "news" "ftp"))
8283 ;; standard Internet links are the same.
8284 nil)
8285 ((and (equal type "irc") (string-match "^//" path))
8286 ;; Planner has two / at the beginning of an irc link, we have 1.
8287 ;; We should have zero, actually....
8288 (setq path (substring path 1)))
8289 ((and (equal type "lisp") (string-match "^/" path))
8290 ;; Planner has a slash, we do not.
8291 (setq type "elisp" path (substring path 1)))
8292 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8293 ;; A typical message link. Planner has the id after the final slash,
8294 ;; we separate it with a hash mark
8295 (setq path (concat (match-string 1 path) "#"
8296 (org-remove-angle-brackets (match-string 2 path)))))
8298 (cons type path))
8300 (defun org-find-file-at-mouse (ev)
8301 "Open file link or URL at mouse."
8302 (interactive "e")
8303 (mouse-set-point ev)
8304 (org-open-at-point 'in-emacs))
8306 (defun org-open-at-mouse (ev)
8307 "Open file link or URL at mouse."
8308 (interactive "e")
8309 (mouse-set-point ev)
8310 (if (eq major-mode 'org-agenda-mode)
8311 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8312 (org-open-at-point))
8314 (defvar org-window-config-before-follow-link nil
8315 "The window configuration before following a link.
8316 This is saved in case the need arises to restore it.")
8318 (defvar org-open-link-marker (make-marker)
8319 "Marker pointing to the location where `org-open-at-point; was called.")
8321 ;;;###autoload
8322 (defun org-open-at-point-global ()
8323 "Follow a link like Org-mode does.
8324 This command can be called in any mode to follow a link that has
8325 Org-mode syntax."
8326 (interactive)
8327 (org-run-like-in-org-mode 'org-open-at-point))
8329 ;;;###autoload
8330 (defun org-open-link-from-string (s &optional arg reference-buffer)
8331 "Open a link in the string S, as if it was in Org-mode."
8332 (interactive "sLink: \nP")
8333 (let ((reference-buffer (or reference-buffer (current-buffer))))
8334 (with-temp-buffer
8335 (let ((org-inhibit-startup t))
8336 (org-mode)
8337 (insert s)
8338 (goto-char (point-min))
8339 (org-open-at-point arg reference-buffer)))))
8341 (defun org-open-at-point (&optional in-emacs reference-buffer)
8342 "Open link at or after point.
8343 If there is no link at point, this function will search forward up to
8344 the end of the current line.
8345 Normally, files will be opened by an appropriate application. If the
8346 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8347 With a double prefix argument, try to open outside of Emacs, in the
8348 application the system uses for this file type."
8349 (interactive "P")
8350 (org-load-modules-maybe)
8351 (move-marker org-open-link-marker (point))
8352 (setq org-window-config-before-follow-link (current-window-configuration))
8353 (org-remove-occur-highlights nil nil t)
8354 (cond
8355 ((and (org-on-heading-p)
8356 (not (org-in-regexp
8357 (concat org-plain-link-re "\\|"
8358 org-bracket-link-regexp "\\|"
8359 org-angle-link-re "\\|"
8360 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8361 (or (org-offer-links-in-entry in-emacs)
8362 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8363 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8364 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8365 (org-footnote-action))
8367 (let (type path link line search (pos (point)))
8368 (catch 'match
8369 (save-excursion
8370 (skip-chars-forward "^]\n\r")
8371 (when (org-in-regexp org-bracket-link-regexp 1)
8372 (setq link (org-extract-attributes
8373 (org-link-unescape (org-match-string-no-properties 1))))
8374 (while (string-match " *\n *" link)
8375 (setq link (replace-match " " t t link)))
8376 (setq link (org-link-expand-abbrev link))
8377 (cond
8378 ((or (file-name-absolute-p link)
8379 (string-match "^\\.\\.?/" link))
8380 (setq type "file" path link))
8381 ((string-match org-link-re-with-space3 link)
8382 (setq type (match-string 1 link) path (match-string 2 link)))
8383 (t (setq type "thisfile" path link)))
8384 (throw 'match t)))
8386 (when (get-text-property (point) 'org-linked-text)
8387 (setq type "thisfile"
8388 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8389 (1+ (point)) (point))
8390 path (buffer-substring
8391 (previous-single-property-change pos 'org-linked-text)
8392 (next-single-property-change pos 'org-linked-text)))
8393 (throw 'match t))
8395 (save-excursion
8396 (when (or (org-in-regexp org-angle-link-re)
8397 (org-in-regexp org-plain-link-re))
8398 (setq type (match-string 1) path (match-string 2))
8399 (throw 'match t)))
8400 (save-excursion
8401 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8402 (setq type "tags"
8403 path (match-string 1))
8404 (while (string-match ":" path)
8405 (setq path (replace-match "+" t t path)))
8406 (throw 'match t)))
8407 (when (org-in-regexp "<\\([^><\n]+\\)>")
8408 (setq type "tree-match"
8409 path (match-string 1))
8410 (throw 'match t)))
8411 (unless path
8412 (error "No link found"))
8414 ;; switch back to reference buffer
8415 ;; needed when if called in a temporary buffer through
8416 ;; org-open-link-from-string
8417 (with-current-buffer (or reference-buffer (current-buffer))
8419 ;; Remove any trailing spaces in path
8420 (if (string-match " +\\'" path)
8421 (setq path (replace-match "" t t path)))
8422 (if (and org-link-translation-function
8423 (fboundp org-link-translation-function))
8424 ;; Check if we need to translate the link
8425 (let ((tmp (funcall org-link-translation-function type path)))
8426 (setq type (car tmp) path (cdr tmp))))
8428 (cond
8430 ((assoc type org-link-protocols)
8431 (funcall (nth 1 (assoc type org-link-protocols)) path))
8433 ((equal type "mailto")
8434 (let ((cmd (car org-link-mailto-program))
8435 (args (cdr org-link-mailto-program)) args1
8436 (address path) (subject "") a)
8437 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8438 (setq address (match-string 1 path)
8439 subject (org-link-escape (match-string 2 path))))
8440 (while args
8441 (cond
8442 ((not (stringp (car args))) (push (pop args) args1))
8443 (t (setq a (pop args))
8444 (if (string-match "%a" a)
8445 (setq a (replace-match address t t a)))
8446 (if (string-match "%s" a)
8447 (setq a (replace-match subject t t a)))
8448 (push a args1))))
8449 (apply cmd (nreverse args1))))
8451 ((member type '("http" "https" "ftp" "news"))
8452 (browse-url (concat type ":" (org-link-escape
8453 path org-link-escape-chars-browser))))
8455 ((member type '("message"))
8456 (browse-url (concat type ":" path)))
8458 ((string= type "tags")
8459 (org-tags-view in-emacs path))
8461 ((string= type "tree-match")
8462 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8464 ((string= type "file")
8465 (if (string-match "::\\([0-9]+\\)\\'" path)
8466 (setq line (string-to-number (match-string 1 path))
8467 path (substring path 0 (match-beginning 0)))
8468 (if (string-match "::\\(.+\\)\\'" path)
8469 (setq search (match-string 1 path)
8470 path (substring path 0 (match-beginning 0)))))
8471 (if (string-match "[*?{]" (file-name-nondirectory path))
8472 (dired path)
8473 (org-open-file path in-emacs line search)))
8475 ((string= type "news")
8476 (require 'org-gnus)
8477 (org-gnus-follow-link path))
8479 ((string= type "shell")
8480 (let ((cmd path))
8481 (if (or (not org-confirm-shell-link-function)
8482 (funcall org-confirm-shell-link-function
8483 (format "Execute \"%s\" in shell? "
8484 (org-add-props cmd nil
8485 'face 'org-warning))))
8486 (progn
8487 (message "Executing %s" cmd)
8488 (shell-command cmd))
8489 (error "Abort"))))
8491 ((string= type "elisp")
8492 (let ((cmd path))
8493 (if (or (not org-confirm-elisp-link-function)
8494 (funcall org-confirm-elisp-link-function
8495 (format "Execute \"%s\" as elisp? "
8496 (org-add-props cmd nil
8497 'face 'org-warning))))
8498 (message "%s => %s" cmd
8499 (if (equal (string-to-char cmd) ?\()
8500 (eval (read cmd))
8501 (call-interactively (read cmd))))
8502 (error "Abort"))))
8504 ((and (string= type "thisfile")
8505 (run-hook-with-args-until-success
8506 'org-open-link-functions path)))
8508 ((string= type "thisfile")
8509 (if in-emacs
8510 (switch-to-buffer-other-window
8511 (org-get-buffer-for-internal-link (current-buffer)))
8512 (org-mark-ring-push))
8513 (let ((cmd `(org-link-search
8514 ,path
8515 ,(cond ((equal in-emacs '(4)) 'occur)
8516 ((equal in-emacs '(16)) 'org-occur)
8517 (t nil))
8518 ,pos)))
8519 (condition-case nil (eval cmd)
8520 (error (progn (widen) (eval cmd))))))
8523 (browse-url-at-point)))))))
8524 (move-marker org-open-link-marker nil)
8525 (run-hook-with-args 'org-follow-link-hook))
8527 (defun org-offer-links-in-entry (&optional nth zero)
8528 "Offer links in the current entry and follow the selected link.
8529 If there is only one link, follow it immediately as well.
8530 If NTH is an integer, immediately pick the NTH link found.
8531 If ZERO is a string, check also this string for a link, and if
8532 there is one, offer it as link number zero."
8533 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8534 "\\(" org-angle-link-re "\\)\\|"
8535 "\\(" org-plain-link-re "\\)"))
8536 (cnt ?0)
8537 (in-emacs (if (integerp nth) nil nth))
8538 have-zero end links link c)
8539 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8540 (push (match-string 0 zero) links)
8541 (setq cnt (1- cnt) have-zero t))
8542 (save-excursion
8543 (org-back-to-heading t)
8544 (setq end (save-excursion (outline-next-heading) (point)))
8545 (while (re-search-forward re end t)
8546 (push (match-string 0) links))
8547 (setq links (org-uniquify (reverse links))))
8549 (cond
8550 ((null links)
8551 (message "No links"))
8552 ((equal (length links) 1)
8553 (setq link (car links)))
8554 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8555 (setq link (nth (if have-zero nth (1- nth)) links)))
8556 (t ; we have to select a link
8557 (save-excursion
8558 (save-window-excursion
8559 (delete-other-windows)
8560 (with-output-to-temp-buffer "*Select Link*"
8561 (mapc (lambda (l)
8562 (if (not (string-match org-bracket-link-regexp l))
8563 (princ (format "[%c] %s\n" (incf cnt)
8564 (org-remove-angle-brackets l)))
8565 (if (match-end 3)
8566 (princ (format "[%c] %s (%s)\n" (incf cnt)
8567 (match-string 3 l) (match-string 1 l)))
8568 (princ (format "[%c] %s\n" (incf cnt)
8569 (match-string 1 l))))))
8570 links))
8571 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8572 (message "Select link to open:")
8573 (setq c (read-char-exclusive))
8574 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8575 (when (equal c ?q) (error "Abort"))
8576 (setq nth (- c ?0))
8577 (if have-zero (setq nth (1+ nth)))
8578 (unless (and (integerp nth) (>= (length links) nth))
8579 (error "Invalid link selection"))
8580 (setq link (nth (1- nth) links))))
8581 (if link
8582 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8583 nil)))
8585 ;;;; Time estimates
8587 (defun org-get-effort (&optional pom)
8588 "Get the effort estimate for the current entry."
8589 (org-entry-get pom org-effort-property))
8591 ;;; File search
8593 (defvar org-create-file-search-functions nil
8594 "List of functions to construct the right search string for a file link.
8595 These functions are called in turn with point at the location to
8596 which the link should point.
8598 A function in the hook should first test if it would like to
8599 handle this file type, for example by checking the major-mode or
8600 the file extension. If it decides not to handle this file, it
8601 should just return nil to give other functions a chance. If it
8602 does handle the file, it must return the search string to be used
8603 when following the link. The search string will be part of the
8604 file link, given after a double colon, and `org-open-at-point'
8605 will automatically search for it. If special measures must be
8606 taken to make the search successful, another function should be
8607 added to the companion hook `org-execute-file-search-functions',
8608 which see.
8610 A function in this hook may also use `setq' to set the variable
8611 `description' to provide a suggestion for the descriptive text to
8612 be used for this link when it gets inserted into an Org-mode
8613 buffer with \\[org-insert-link].")
8615 (defvar org-execute-file-search-functions nil
8616 "List of functions to execute a file search triggered by a link.
8618 Functions added to this hook must accept a single argument, the
8619 search string that was part of the file link, the part after the
8620 double colon. The function must first check if it would like to
8621 handle this search, for example by checking the major-mode or the
8622 file extension. If it decides not to handle this search, it
8623 should just return nil to give other functions a chance. If it
8624 does handle the search, it must return a non-nil value to keep
8625 other functions from trying.
8627 Each function can access the current prefix argument through the
8628 variable `current-prefix-argument'. Note that a single prefix is
8629 used to force opening a link in Emacs, so it may be good to only
8630 use a numeric or double prefix to guide the search function.
8632 In case this is needed, a function in this hook can also restore
8633 the window configuration before `org-open-at-point' was called using:
8635 (set-window-configuration org-window-config-before-follow-link)")
8637 (defun org-link-search (s &optional type avoid-pos)
8638 "Search for a link search option.
8639 If S is surrounded by forward slashes, it is interpreted as a
8640 regular expression. In org-mode files, this will create an `org-occur'
8641 sparse tree. In ordinary files, `occur' will be used to list matches.
8642 If the current buffer is in `dired-mode', grep will be used to search
8643 in all files. If AVOID-POS is given, ignore matches near that position."
8644 (let ((case-fold-search t)
8645 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8646 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8647 (append '(("") (" ") ("\t") ("\n"))
8648 org-emphasis-alist)
8649 "\\|") "\\)"))
8650 (pos (point))
8651 (pre nil) (post nil)
8652 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8653 (cond
8654 ;; First check if there are any special
8655 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8656 ;; Now try the builtin stuff
8657 ((and (equal (string-to-char s0) ?#)
8658 (> (length s0) 1)
8659 (save-excursion
8660 (goto-char (point-min))
8661 (and
8662 (re-search-forward
8663 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8664 (setq type 'dedicated
8665 pos (match-beginning 0))))
8666 ;; There is an exact target for this
8667 (goto-char pos)
8668 (org-back-to-heading t)))
8669 ((save-excursion
8670 (goto-char (point-min))
8671 (and
8672 (re-search-forward
8673 (concat "<<" (regexp-quote s0) ">>") nil t)
8674 (setq type 'dedicated
8675 pos (match-beginning 0))))
8676 ;; There is an exact target for this
8677 (goto-char pos))
8678 ((and (string-match "^(\\(.*\\))$" s0)
8679 (save-excursion
8680 (goto-char (point-min))
8681 (and
8682 (re-search-forward
8683 (concat "[^[]" (regexp-quote
8684 (format org-coderef-label-format
8685 (match-string 1 s0))))
8686 nil t)
8687 (setq type 'dedicated
8688 pos (1+ (match-beginning 0))))))
8689 ;; There is a coderef target for this
8690 (goto-char pos))
8691 ((string-match "^/\\(.*\\)/$" s)
8692 ;; A regular expression
8693 (cond
8694 ((org-mode-p)
8695 (org-occur (match-string 1 s)))
8696 ;;((eq major-mode 'dired-mode)
8697 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8698 (t (org-do-occur (match-string 1 s)))))
8700 ;; A normal search strings
8701 (when (equal (string-to-char s) ?*)
8702 ;; Anchor on headlines, post may include tags.
8703 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8704 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8705 s (substring s 1)))
8706 (remove-text-properties
8707 0 (length s)
8708 '(face nil mouse-face nil keymap nil fontified nil) s)
8709 ;; Make a series of regular expressions to find a match
8710 (setq words (org-split-string s "[ \n\r\t]+")
8712 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8713 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8714 "\\)" markers)
8715 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8716 re2a (concat "[ \t\r\n]" re2a_)
8717 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8718 re4 (concat "[^a-zA-Z_]" re4_)
8720 re1 (concat pre re2 post)
8721 re3 (concat pre (if pre re4_ re4) post)
8722 re5 (concat pre ".*" re4)
8723 re2 (concat pre re2)
8724 re2a (concat pre (if pre re2a_ re2a))
8725 re4 (concat pre (if pre re4_ re4))
8726 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8727 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8728 re5 "\\)"
8730 (cond
8731 ((eq type 'org-occur) (org-occur reall))
8732 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8733 (t (goto-char (point-min))
8734 (setq type 'fuzzy)
8735 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8736 (org-search-not-self 1 re1 nil t)
8737 (org-search-not-self 1 re2 nil t)
8738 (org-search-not-self 1 re2a nil t)
8739 (org-search-not-self 1 re3 nil t)
8740 (org-search-not-self 1 re4 nil t)
8741 (org-search-not-self 1 re5 nil t)
8743 (goto-char (match-beginning 1))
8744 (goto-char pos)
8745 (error "No match")))))
8747 ;; Normal string-search
8748 (goto-char (point-min))
8749 (if (search-forward s nil t)
8750 (goto-char (match-beginning 0))
8751 (error "No match"))))
8752 (and (org-mode-p) (org-show-context 'link-search))
8753 type))
8755 (defun org-search-not-self (group &rest args)
8756 "Execute `re-search-forward', but only accept matches that do not
8757 enclose the position of `org-open-link-marker'."
8758 (let ((m org-open-link-marker))
8759 (catch 'exit
8760 (while (apply 're-search-forward args)
8761 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8762 (goto-char (match-end group))
8763 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8764 (> (match-beginning 0) (marker-position m))
8765 (< (match-end 0) (marker-position m)))
8766 (save-match-data
8767 (or (not (org-in-regexp
8768 org-bracket-link-analytic-regexp 1))
8769 (not (match-end 4)) ; no description
8770 (and (<= (match-beginning 4) (point))
8771 (>= (match-end 4) (point))))))
8772 (throw 'exit (point))))))))
8774 (defun org-get-buffer-for-internal-link (buffer)
8775 "Return a buffer to be used for displaying the link target of internal links."
8776 (cond
8777 ((not org-display-internal-link-with-indirect-buffer)
8778 buffer)
8779 ((string-match "(Clone)$" (buffer-name buffer))
8780 (message "Buffer is already a clone, not making another one")
8781 ;; we also do not modify visibility in this case
8782 buffer)
8783 (t ; make a new indirect buffer for displaying the link
8784 (let* ((bn (buffer-name buffer))
8785 (ibn (concat bn "(Clone)"))
8786 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8787 (with-current-buffer ib (org-overview))
8788 ib))))
8790 (defun org-do-occur (regexp &optional cleanup)
8791 "Call the Emacs command `occur'.
8792 If CLEANUP is non-nil, remove the printout of the regular expression
8793 in the *Occur* buffer. This is useful if the regex is long and not useful
8794 to read."
8795 (occur regexp)
8796 (when cleanup
8797 (let ((cwin (selected-window)) win beg end)
8798 (when (setq win (get-buffer-window "*Occur*"))
8799 (select-window win))
8800 (goto-char (point-min))
8801 (when (re-search-forward "match[a-z]+" nil t)
8802 (setq beg (match-end 0))
8803 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8804 (setq end (1- (match-beginning 0)))))
8805 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8806 (goto-char (point-min))
8807 (select-window cwin))))
8809 ;;; The mark ring for links jumps
8811 (defvar org-mark-ring nil
8812 "Mark ring for positions before jumps in Org-mode.")
8813 (defvar org-mark-ring-last-goto nil
8814 "Last position in the mark ring used to go back.")
8815 ;; Fill and close the ring
8816 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8817 (loop for i from 1 to org-mark-ring-length do
8818 (push (make-marker) org-mark-ring))
8819 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8820 org-mark-ring)
8822 (defun org-mark-ring-push (&optional pos buffer)
8823 "Put the current position or POS into the mark ring and rotate it."
8824 (interactive)
8825 (setq pos (or pos (point)))
8826 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8827 (move-marker (car org-mark-ring)
8828 (or pos (point))
8829 (or buffer (current-buffer)))
8830 (message "%s"
8831 (substitute-command-keys
8832 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8834 (defun org-mark-ring-goto (&optional n)
8835 "Jump to the previous position in the mark ring.
8836 With prefix arg N, jump back that many stored positions. When
8837 called several times in succession, walk through the entire ring.
8838 Org-mode commands jumping to a different position in the current file,
8839 or to another Org-mode file, automatically push the old position
8840 onto the ring."
8841 (interactive "p")
8842 (let (p m)
8843 (if (eq last-command this-command)
8844 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8845 (setq p org-mark-ring))
8846 (setq org-mark-ring-last-goto p)
8847 (setq m (car p))
8848 (switch-to-buffer (marker-buffer m))
8849 (goto-char m)
8850 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8852 (defun org-remove-angle-brackets (s)
8853 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8854 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8856 (defun org-add-angle-brackets (s)
8857 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8858 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8860 (defun org-remove-double-quotes (s)
8861 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8862 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8865 ;;; Following specific links
8867 (defun org-follow-timestamp-link ()
8868 (cond
8869 ((org-at-date-range-p t)
8870 (let ((org-agenda-start-on-weekday)
8871 (t1 (match-string 1))
8872 (t2 (match-string 2)))
8873 (setq t1 (time-to-days (org-time-string-to-time t1))
8874 t2 (time-to-days (org-time-string-to-time t2)))
8875 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8876 ((org-at-timestamp-p t)
8877 (org-agenda-list nil (time-to-days (org-time-string-to-time
8878 (substring (match-string 1) 0 10)))
8880 (t (error "This should not happen"))))
8883 ;;; Following file links
8884 (defvar org-wait nil)
8885 (defun org-open-file (path &optional in-emacs line search)
8886 "Open the file at PATH.
8887 First, this expands any special file name abbreviations. Then the
8888 configuration variable `org-file-apps' is checked if it contains an
8889 entry for this file type, and if yes, the corresponding command is launched.
8891 If no application is found, Emacs simply visits the file.
8893 With optional prefix argument IN-EMACS, Emacs will visit the file.
8894 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8895 and o use an external application to visit the file.
8897 Optional LINE specifies a line to go to, optional SEARCH a string to
8898 search for. If LINE or SEARCH is given, the file will always be
8899 opened in Emacs.
8900 If the file does not exist, an error is thrown."
8901 (setq in-emacs (or in-emacs line search))
8902 (let* ((file (if (equal path "")
8903 buffer-file-name
8904 (substitute-in-file-name (expand-file-name path))))
8905 (apps (append org-file-apps (org-default-apps)))
8906 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8907 (dirp (if remp nil (file-directory-p file)))
8908 (file (if (and dirp org-open-directory-means-index-dot-org)
8909 (concat (file-name-as-directory file) "index.org")
8910 file))
8911 (a-m-a-p (assq 'auto-mode apps))
8912 (dfile (downcase file))
8913 (old-buffer (current-buffer))
8914 (old-pos (point))
8915 (old-mode major-mode)
8916 ext cmd)
8917 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8918 (setq ext (match-string 1 dfile))
8919 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8920 (setq ext (match-string 1 dfile))))
8921 (cond
8922 ((equal in-emacs '(16))
8923 (setq cmd (cdr (assoc 'system apps))))
8924 (in-emacs (setq cmd 'emacs))
8926 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8927 (and dirp (cdr (assoc 'directory apps)))
8928 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8929 'string-match)
8930 (cdr (assoc ext apps))
8931 (cdr (assoc t apps))))))
8932 (when (eq cmd 'system)
8933 (setq cmd (cdr (assoc 'system apps))))
8934 (when (eq cmd 'default)
8935 (setq cmd (cdr (assoc t apps))))
8936 (when (eq cmd 'mailcap)
8937 (require 'mailcap)
8938 (mailcap-parse-mailcaps)
8939 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8940 (command (mailcap-mime-info mime-type)))
8941 (if (stringp command)
8942 (setq cmd command)
8943 (setq cmd 'emacs))))
8944 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8945 (not (file-exists-p file))
8946 (not org-open-non-existing-files))
8947 (error "No such file: %s" file))
8948 (cond
8949 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8950 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8951 (while (string-match "['\"]%s['\"]" cmd)
8952 (setq cmd (replace-match "%s" t t cmd)))
8953 (while (string-match "%s" cmd)
8954 (setq cmd (replace-match
8955 (save-match-data
8956 (shell-quote-argument
8957 (convert-standard-filename file)))
8958 t t cmd)))
8959 (save-window-excursion
8960 (start-process-shell-command cmd nil cmd)
8961 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8963 ((or (stringp cmd)
8964 (eq cmd 'emacs))
8965 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8966 (widen)
8967 (if line (org-goto-line line)
8968 (if search (org-link-search search))))
8969 ((consp cmd)
8970 (let ((file (convert-standard-filename file)))
8971 (eval cmd)))
8972 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8973 (and (org-mode-p) (eq old-mode 'org-mode)
8974 (or (not (equal old-buffer (current-buffer)))
8975 (not (equal old-pos (point))))
8976 (org-mark-ring-push old-pos old-buffer))))
8978 (defun org-default-apps ()
8979 "Return the default applications for this operating system."
8980 (cond
8981 ((eq system-type 'darwin)
8982 org-file-apps-defaults-macosx)
8983 ((eq system-type 'windows-nt)
8984 org-file-apps-defaults-windowsnt)
8985 (t org-file-apps-defaults-gnu)))
8987 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8988 "Convert extensions to regular expressions in the cars of LIST.
8989 Also, weed out any non-string entries, because the return value is used
8990 only for regexp matching.
8991 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8992 point to the symbol `emacs', indicating that the file should
8993 be opened in Emacs."
8994 (append
8995 (delq nil
8996 (mapcar (lambda (x)
8997 (if (not (stringp (car x)))
8999 (if (string-match "\\W" (car x))
9001 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9002 list))
9003 (if add-auto-mode
9004 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9006 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9007 (defun org-file-remote-p (file)
9008 "Test whether FILE specifies a location on a remote system.
9009 Return non-nil if the location is indeed remote.
9011 For example, the filename \"/user@host:/foo\" specifies a location
9012 on the system \"/user@host:\"."
9013 (cond ((fboundp 'file-remote-p)
9014 (file-remote-p file))
9015 ((fboundp 'tramp-handle-file-remote-p)
9016 (tramp-handle-file-remote-p file))
9017 ((and (boundp 'ange-ftp-name-format)
9018 (string-match (car ange-ftp-name-format) file))
9020 (t nil)))
9023 ;;;; Refiling
9025 (defun org-get-org-file ()
9026 "Read a filename, with default directory `org-directory'."
9027 (let ((default (or org-default-notes-file remember-data-file)))
9028 (read-file-name (format "File name [%s]: " default)
9029 (file-name-as-directory org-directory)
9030 default)))
9032 (defun org-notes-order-reversed-p ()
9033 "Check if the current file should receive notes in reversed order."
9034 (cond
9035 ((not org-reverse-note-order) nil)
9036 ((eq t org-reverse-note-order) t)
9037 ((not (listp org-reverse-note-order)) nil)
9038 (t (catch 'exit
9039 (let ((all org-reverse-note-order)
9040 entry)
9041 (while (setq entry (pop all))
9042 (if (string-match (car entry) buffer-file-name)
9043 (throw 'exit (cdr entry))))
9044 nil)))))
9046 (defvar org-refile-target-table nil
9047 "The list of refile targets, created by `org-refile'.")
9049 (defvar org-agenda-new-buffers nil
9050 "Buffers created to visit agenda files.")
9052 (defun org-get-refile-targets (&optional default-buffer)
9053 "Produce a table with refile targets."
9054 (let ((case-fold-search nil)
9055 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9056 (entries (or org-refile-targets '((nil . (:level . 1)))))
9057 targets txt re files f desc descre fast-path-p level pos0)
9058 (message "Getting targets...")
9059 (with-current-buffer (or default-buffer (current-buffer))
9060 (while (setq entry (pop entries))
9061 (setq files (car entry) desc (cdr entry))
9062 (setq fast-path-p nil)
9063 (cond
9064 ((null files) (setq files (list (current-buffer))))
9065 ((eq files 'org-agenda-files)
9066 (setq files (org-agenda-files 'unrestricted)))
9067 ((and (symbolp files) (fboundp files))
9068 (setq files (funcall files)))
9069 ((and (symbolp files) (boundp files))
9070 (setq files (symbol-value files))))
9071 (if (stringp files) (setq files (list files)))
9072 (cond
9073 ((eq (car desc) :tag)
9074 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9075 ((eq (car desc) :todo)
9076 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9077 ((eq (car desc) :regexp)
9078 (setq descre (cdr desc)))
9079 ((eq (car desc) :level)
9080 (setq descre (concat "^\\*\\{" (number-to-string
9081 (if org-odd-levels-only
9082 (1- (* 2 (cdr desc)))
9083 (cdr desc)))
9084 "\\}[ \t]")))
9085 ((eq (car desc) :maxlevel)
9086 (setq fast-path-p t)
9087 (setq descre (concat "^\\*\\{1," (number-to-string
9088 (if org-odd-levels-only
9089 (1- (* 2 (cdr desc)))
9090 (cdr desc)))
9091 "\\}[ \t]")))
9092 (t (error "Bad refiling target description %s" desc)))
9093 (while (setq f (pop files))
9094 (with-current-buffer
9095 (if (bufferp f) f (org-get-agenda-file-buffer f))
9096 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9097 (setq f (and f (expand-file-name f)))
9098 (if (eq org-refile-use-outline-path 'file)
9099 (push (list (file-name-nondirectory f) f nil nil) targets))
9100 (save-excursion
9101 (save-restriction
9102 (widen)
9103 (goto-char (point-min))
9104 (while (re-search-forward descre nil t)
9105 (goto-char (setq pos0 (point-at-bol)))
9106 (catch 'next
9107 (when org-refile-target-verify-function
9108 (save-match-data
9109 (or (funcall org-refile-target-verify-function)
9110 (throw 'next t))))
9111 (when (looking-at org-complex-heading-regexp)
9112 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9113 txt (org-link-display-format (match-string 4))
9114 re (concat "^" (regexp-quote
9115 (buffer-substring (match-beginning 1)
9116 (match-end 4)))))
9117 (if (match-end 5) (setq re (concat re "[ \t]+"
9118 (regexp-quote
9119 (match-string 5)))))
9120 (setq re (concat re "[ \t]*$"))
9121 (when org-refile-use-outline-path
9122 (setq txt (mapconcat 'org-protect-slash
9123 (append
9124 (if (eq org-refile-use-outline-path 'file)
9125 (list (file-name-nondirectory
9126 (buffer-file-name (buffer-base-buffer))))
9127 (if (eq org-refile-use-outline-path 'full-file-path)
9128 (list (buffer-file-name (buffer-base-buffer)))))
9129 (org-get-outline-path fast-path-p level txt)
9130 (list txt))
9131 "/")))
9132 (push (list txt f re (point)) targets)))
9133 (when (= (point) pos0)
9134 ;; verification function has not moved point
9135 (goto-char (point-at-eol))))))))))
9136 (message "Getting targets...done")
9137 (nreverse targets)))
9139 (defun org-protect-slash (s)
9140 (while (string-match "/" s)
9141 (setq s (replace-match "\\" t t s)))
9144 (defvar org-olpa (make-vector 20 nil))
9146 (defun org-get-outline-path (&optional fastp level heading)
9147 "Return the outline path to the current entry, as a list.
9148 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9149 routine which makes outline path derivations for an entire file,
9150 avoiding backtracing."
9151 (if fastp
9152 (progn
9153 (if (> level 19)
9154 (error "Outline path failure, more than 19 levels."))
9155 (loop for i from level upto 19 do
9156 (aset org-olpa i nil))
9157 (prog1
9158 (delq nil (append org-olpa nil))
9159 (aset org-olpa level heading)))
9160 (let (rtn case-fold-search)
9161 (save-excursion
9162 (save-restriction
9163 (widen)
9164 (while (org-up-heading-safe)
9165 (when (looking-at org-complex-heading-regexp)
9166 (push (org-match-string-no-properties 4) rtn)))
9167 rtn)))))
9169 (defun org-format-outline-path (path &optional width prefix)
9170 "Format the outlie path PATH for display.
9171 Width is the maximum number of characters that is available.
9172 Prefix is a prefix to be included in the returned string,
9173 such as the file name."
9174 (setq width (or width 79))
9175 (if prefix (setq width (- width (length prefix))))
9176 (if (not path)
9177 (or prefix "")
9178 (let* ((nsteps (length path))
9179 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9180 (maxwidth (if (<= total-width width)
9181 10000 ;; everything fits
9182 ;; we need to shorten the level headings
9183 (/ (- width nsteps) nsteps)))
9184 (org-odd-levels-only nil)
9185 (n 0)
9186 (total (1+ (length prefix))))
9187 (setq maxwidth (max maxwidth 10))
9188 (concat prefix
9189 (mapconcat
9190 (lambda (h)
9191 (setq n (1+ n))
9192 (if (and (= n nsteps) (< maxwidth 10000))
9193 (setq maxwidth (- total-width total)))
9194 (if (< (length h) maxwidth)
9195 (progn (setq total (+ total (length h) 1)) h)
9196 (setq h (substring h 0 (- maxwidth 2))
9197 total (+ total maxwidth 1))
9198 (if (string-match "[ \t]+\\'" h)
9199 (setq h (substring h 0 (match-beginning 0))))
9200 (setq h (concat h "..")))
9201 (org-add-props h nil 'face
9202 (nth (% (1- n) org-n-level-faces)
9203 org-level-faces))
9205 path "/")))))
9207 (defun org-display-outline-path (&optional file current)
9208 "Display the current outline path in the echo area."
9209 (interactive "P")
9210 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9211 (case-fold-search nil)
9212 (path (and (org-mode-p) (org-get-outline-path))))
9213 (if current (setq path (append path
9214 (save-excursion
9215 (org-back-to-heading t)
9216 (if (looking-at org-complex-heading-regexp)
9217 (list (match-string 4)))))))
9218 (message "%s"
9219 (org-format-outline-path
9220 path
9221 (1- (frame-width))
9222 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9224 (defvar org-refile-history nil
9225 "History for refiling operations.")
9227 (defvar org-after-refile-insert-hook nil
9228 "Hook run after `org-refile' has inserted its stuff at the new location.
9229 Note that this is still *before* the stuff will be removed from
9230 the *old* location.")
9232 (defun org-refile (&optional goto default-buffer rfloc)
9233 "Move the entry at point to another heading.
9234 The list of target headings is compiled using the information in
9235 `org-refile-targets', which see. This list is created before each use
9236 and will therefore always be up-to-date.
9238 At the target location, the entry is filed as a subitem of the target heading.
9239 Depending on `org-reverse-note-order', the new subitem will either be the
9240 first or the last subitem.
9242 If there is an active region, all entries in that region will be moved.
9243 However, the region must fulfil the requirement that the first heading
9244 is the first one sets the top-level of the moved text - at most siblings
9245 below it are allowed.
9247 With prefix arg GOTO, the command will only visit the target location,
9248 not actually move anything.
9249 With a double prefix `C-u C-u', go to the location where the last refiling
9250 operation has put the subtree.
9251 With a prefix argument of `2', refile to the running clock.
9253 RFLOC can be a refile location obtained in a different way.
9255 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9256 (interactive "P")
9257 (let* ((cbuf (current-buffer))
9258 (regionp (org-region-active-p))
9259 (region-start (and regionp (region-beginning)))
9260 (region-end (and regionp (region-end)))
9261 (region-length (and regionp (- region-end region-start)))
9262 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9263 pos it nbuf file re level reversed)
9264 (setq last-command nil)
9265 (when regionp
9266 (goto-char region-start)
9267 (or (bolp) (goto-char (point-at-bol)))
9268 (setq region-start (point))
9269 (unless (org-kill-is-subtree-p
9270 (buffer-substring region-start region-end))
9271 (error "The region is not a (sequence of) subtree(s)")))
9272 (if (equal goto '(16))
9273 (org-refile-goto-last-stored)
9274 (when (or
9275 (and (equal goto 2)
9276 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9277 (prog1
9278 (setq it (list (or org-clock-heading "running clock")
9279 (buffer-file-name
9280 (marker-buffer org-clock-hd-marker))
9282 (marker-position org-clock-hd-marker)))
9283 (setq goto nil)))
9284 (setq it (or rfloc
9285 (save-excursion
9286 (org-refile-get-location
9287 (if goto "Goto: " "Refile to: ") default-buffer
9288 org-refile-allow-creating-parent-nodes)))))
9289 (setq file (nth 1 it)
9290 re (nth 2 it)
9291 pos (nth 3 it))
9292 (if (and (not goto)
9294 (equal (buffer-file-name) file)
9295 (if regionp
9296 (and (>= pos region-start)
9297 (<= pos region-end))
9298 (and (>= pos (point))
9299 (< pos (save-excursion
9300 (org-end-of-subtree t t))))))
9301 (error "Cannot refile to position inside the tree or region"))
9303 (setq nbuf (or (find-buffer-visiting file)
9304 (find-file-noselect file)))
9305 (if goto
9306 (progn
9307 (switch-to-buffer nbuf)
9308 (goto-char pos)
9309 (org-show-context 'org-goto))
9310 (if regionp
9311 (progn
9312 (org-kill-new (buffer-substring region-start region-end))
9313 (org-save-markers-in-region region-start region-end))
9314 (org-copy-subtree 1 nil t))
9315 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9316 (find-file-noselect file)))
9317 (setq reversed (org-notes-order-reversed-p))
9318 (save-excursion
9319 (save-restriction
9320 (widen)
9321 (if pos
9322 (progn
9323 (goto-char pos)
9324 (looking-at outline-regexp)
9325 (setq level (org-get-valid-level (funcall outline-level) 1))
9326 (goto-char
9327 (if reversed
9328 (or (outline-next-heading) (point-max))
9329 (or (save-excursion (org-get-next-sibling))
9330 (org-end-of-subtree t t)
9331 (point-max)))))
9332 (setq level 1)
9333 (if (not reversed)
9334 (goto-char (point-max))
9335 (goto-char (point-min))
9336 (or (outline-next-heading) (goto-char (point-max)))))
9337 (if (not (bolp)) (newline))
9338 (bookmark-set "org-refile-last-stored")
9339 (org-paste-subtree level)
9340 (if (fboundp 'deactivate-mark) (deactivate-mark))
9341 (run-hooks 'org-after-refile-insert-hook))))
9342 (if regionp
9343 (delete-region (point) (+ (point) region-length))
9344 (org-cut-subtree))
9345 (when (featurep 'org-inlinetask)
9346 (org-inlinetask-remove-END-maybe))
9347 (setq org-markers-to-move nil)
9348 (message "Refiled to \"%s\"" (car it))))))
9349 (org-reveal))
9351 (defun org-refile-goto-last-stored ()
9352 "Go to the location where the last refile was stored."
9353 (interactive)
9354 (bookmark-jump "org-refile-last-stored")
9355 (message "This is the location of the last refile"))
9357 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9358 "Prompt the user for a refile location, using PROMPT."
9359 (let ((org-refile-targets org-refile-targets)
9360 (org-refile-use-outline-path org-refile-use-outline-path))
9361 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9362 (unless org-refile-target-table
9363 (error "No refile targets"))
9364 (let* ((cbuf (current-buffer))
9365 (partial-completion-mode nil)
9366 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9367 (cfunc (if (and org-refile-use-outline-path
9368 org-outline-path-complete-in-steps)
9369 'org-olpath-completing-read
9370 'org-icompleting-read))
9371 (extra (if org-refile-use-outline-path "/" ""))
9372 (filename (and cfn (expand-file-name cfn)))
9373 (tbl (mapcar
9374 (lambda (x)
9375 (if (and (not (member org-refile-use-outline-path
9376 '(file full-file-path)))
9377 (not (equal filename (nth 1 x))))
9378 (cons (concat (car x) extra " ("
9379 (file-name-nondirectory (nth 1 x)) ")")
9380 (cdr x))
9381 (cons (concat (car x) extra) (cdr x))))
9382 org-refile-target-table))
9383 (completion-ignore-case t)
9384 pa answ parent-target child parent old-hist)
9385 (setq old-hist org-refile-history)
9386 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9387 nil 'org-refile-history))
9388 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9389 (if pa
9390 (progn
9391 (when (or (not org-refile-history)
9392 (not (eq old-hist org-refile-history))
9393 (not (equal (car pa) (car org-refile-history))))
9394 (setq org-refile-history
9395 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9396 org-refile-history
9397 (cdr org-refile-history))))
9398 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9399 (pop org-refile-history)))
9401 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9402 (setq parent (match-string 1 answ)
9403 child (match-string 2 answ))
9404 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9405 (when (and parent-target
9406 (or (eq new-nodes t)
9407 (and (eq new-nodes 'confirm)
9408 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9409 (org-refile-new-child parent-target child))))))
9411 (defun org-refile-new-child (parent-target child)
9412 "Use refile target PARENT-TARGET to add new CHILD below it."
9413 (unless parent-target
9414 (error "Cannot find parent for new node"))
9415 (let ((file (nth 1 parent-target))
9416 (pos (nth 3 parent-target))
9417 level)
9418 (with-current-buffer (or (find-buffer-visiting file)
9419 (find-file-noselect file))
9420 (save-excursion
9421 (save-restriction
9422 (widen)
9423 (if pos
9424 (goto-char pos)
9425 (goto-char (point-max))
9426 (if (not (bolp)) (newline)))
9427 (when (looking-at outline-regexp)
9428 (setq level (funcall outline-level))
9429 (org-end-of-subtree t t))
9430 (org-back-over-empty-lines)
9431 (insert "\n" (make-string
9432 (if pos (org-get-valid-level level 1) 1) ?*)
9433 " " child "\n")
9434 (beginning-of-line 0)
9435 (list (concat (car parent-target) "/" child) file "" (point)))))))
9437 (defun org-olpath-completing-read (prompt collection &rest args)
9438 "Read an outline path like a file name."
9439 (let ((thetable collection)
9440 (org-completion-use-ido nil) ; does not work with ido.
9441 (org-completion-use-iswitchb nil)) ; or iswitchb
9442 (apply
9443 'org-icompleting-read prompt
9444 (lambda (string predicate &optional flag)
9445 (let (rtn r f (l (length string)))
9446 (cond
9447 ((eq flag nil)
9448 ;; try completion
9449 (try-completion string thetable))
9450 ((eq flag t)
9451 ;; all-completions
9452 (setq rtn (all-completions string thetable predicate))
9453 (mapcar
9454 (lambda (x)
9455 (setq r (substring x l))
9456 (if (string-match " ([^)]*)$" x)
9457 (setq f (match-string 0 x))
9458 (setq f ""))
9459 (if (string-match "/" r)
9460 (concat string (substring r 0 (match-end 0)) f)
9462 rtn))
9463 ((eq flag 'lambda)
9464 ;; exact match?
9465 (assoc string thetable)))
9467 args)))
9469 ;;;; Dynamic blocks
9471 (defun org-find-dblock (name)
9472 "Find the first dynamic block with name NAME in the buffer.
9473 If not found, stay at current position and return nil."
9474 (let (pos)
9475 (save-excursion
9476 (goto-char (point-min))
9477 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9478 nil t)
9479 (match-beginning 0))))
9480 (if pos (goto-char pos))
9481 pos))
9483 (defconst org-dblock-start-re
9484 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9485 "Matches the start line of a dynamic block, with parameters.")
9487 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9488 "Matches the end of a dynamic block.")
9490 (defun org-create-dblock (plist)
9491 "Create a dynamic block section, with parameters taken from PLIST.
9492 PLIST must contain a :name entry which is used as name of the block."
9493 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9494 (end-of-line 1)
9495 (newline))
9496 (let ((col (current-column))
9497 (name (plist-get plist :name)))
9498 (insert "#+BEGIN: " name)
9499 (while plist
9500 (if (eq (car plist) :name)
9501 (setq plist (cddr plist))
9502 (insert " " (prin1-to-string (pop plist)))))
9503 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9504 (beginning-of-line -2)))
9506 (defun org-prepare-dblock ()
9507 "Prepare dynamic block for refresh.
9508 This empties the block, puts the cursor at the insert position and returns
9509 the property list including an extra property :name with the block name."
9510 (unless (looking-at org-dblock-start-re)
9511 (error "Not at a dynamic block"))
9512 (let* ((begdel (1+ (match-end 0)))
9513 (name (org-no-properties (match-string 1)))
9514 (params (append (list :name name)
9515 (read (concat "(" (match-string 3) ")")))))
9516 (save-excursion
9517 (beginning-of-line 1)
9518 (skip-chars-forward " \t")
9519 (setq params (plist-put params :indentation-column (current-column))))
9520 (unless (re-search-forward org-dblock-end-re nil t)
9521 (error "Dynamic block not terminated"))
9522 (setq params
9523 (append params
9524 (list :content (buffer-substring
9525 begdel (match-beginning 0)))))
9526 (delete-region begdel (match-beginning 0))
9527 (goto-char begdel)
9528 (open-line 1)
9529 params))
9531 (defun org-map-dblocks (&optional command)
9532 "Apply COMMAND to all dynamic blocks in the current buffer.
9533 If COMMAND is not given, use `org-update-dblock'."
9534 (let ((cmd (or command 'org-update-dblock))
9535 pos)
9536 (save-excursion
9537 (goto-char (point-min))
9538 (while (re-search-forward org-dblock-start-re nil t)
9539 (goto-char (setq pos (match-beginning 0)))
9540 (condition-case nil
9541 (funcall cmd)
9542 (error (message "Error during update of dynamic block")))
9543 (goto-char pos)
9544 (unless (re-search-forward org-dblock-end-re nil t)
9545 (error "Dynamic block not terminated"))))))
9547 (defun org-dblock-update (&optional arg)
9548 "User command for updating dynamic blocks.
9549 Update the dynamic block at point. With prefix ARG, update all dynamic
9550 blocks in the buffer."
9551 (interactive "P")
9552 (if arg
9553 (org-update-all-dblocks)
9554 (or (looking-at org-dblock-start-re)
9555 (org-beginning-of-dblock))
9556 (org-update-dblock)))
9558 (defun org-update-dblock ()
9559 "Update the dynamic block at point
9560 This means to empty the block, parse for parameters and then call
9561 the correct writing function."
9562 (save-window-excursion
9563 (let* ((pos (point))
9564 (line (org-current-line))
9565 (params (org-prepare-dblock))
9566 (name (plist-get params :name))
9567 (indent (plist-get params :indentation-column))
9568 (cmd (intern (concat "org-dblock-write:" name))))
9569 (message "Updating dynamic block `%s' at line %d..." name line)
9570 (funcall cmd params)
9571 (message "Updating dynamic block `%s' at line %d...done" name line)
9572 (goto-char pos)
9573 (when (and indent (> indent 0))
9574 (setq indent (make-string indent ?\ ))
9575 (save-excursion
9576 (org-beginning-of-dblock)
9577 (forward-line 1)
9578 (while (not (looking-at org-dblock-end-re))
9579 (insert indent)
9580 (beginning-of-line 2))
9581 (when (looking-at org-dblock-end-re)
9582 (and (looking-at "[ \t]+")
9583 (replace-match ""))
9584 (insert indent)))))))
9586 (defun org-beginning-of-dblock ()
9587 "Find the beginning of the dynamic block at point.
9588 Error if there is no such block at point."
9589 (let ((pos (point))
9590 beg)
9591 (end-of-line 1)
9592 (if (and (re-search-backward org-dblock-start-re nil t)
9593 (setq beg (match-beginning 0))
9594 (re-search-forward org-dblock-end-re nil t)
9595 (> (match-end 0) pos))
9596 (goto-char beg)
9597 (goto-char pos)
9598 (error "Not in a dynamic block"))))
9600 (defun org-update-all-dblocks ()
9601 "Update all dynamic blocks in the buffer.
9602 This function can be used in a hook."
9603 (when (org-mode-p)
9604 (org-map-dblocks 'org-update-dblock)))
9607 ;;;; Completion
9609 (defconst org-additional-option-like-keywords
9610 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9611 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9612 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9613 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9614 "BEGIN:" "END:"
9615 "ORGTBL" "TBLFM:" "TBLNAME:"
9616 "BEGIN_EXAMPLE" "END_EXAMPLE"
9617 "BEGIN_QUOTE" "END_QUOTE"
9618 "BEGIN_VERSE" "END_VERSE"
9619 "BEGIN_CENTER" "END_CENTER"
9620 "BEGIN_SRC" "END_SRC"
9621 "CATEGORY" "COLUMNS"
9622 "CAPTION" "LABEL"
9623 "SETUPFILE"
9624 "BIND"
9625 "MACRO"))
9627 (defcustom org-structure-template-alist
9629 ("s" "#+begin_src ?\n\n#+end_src"
9630 "<src lang=\"?\">\n\n</src>")
9631 ("e" "#+begin_example\n?\n#+end_example"
9632 "<example>\n?\n</example>")
9633 ("q" "#+begin_quote\n?\n#+end_quote"
9634 "<quote>\n?\n</quote>")
9635 ("v" "#+begin_verse\n?\n#+end_verse"
9636 "<verse>\n?\n/verse>")
9637 ("c" "#+begin_center\n?\n#+end_center"
9638 "<center>\n?\n/center>")
9639 ("l" "#+begin_latex\n?\n#+end_latex"
9640 "<literal style=\"latex\">\n?\n</literal>")
9641 ("L" "#+latex: "
9642 "<literal style=\"latex\">?</literal>")
9643 ("h" "#+begin_html\n?\n#+end_html"
9644 "<literal style=\"html\">\n?\n</literal>")
9645 ("H" "#+html: "
9646 "<literal style=\"html\">?</literal>")
9647 ("a" "#+begin_ascii\n?\n#+end_ascii")
9648 ("A" "#+ascii: ")
9649 ("i" "#+include %file ?"
9650 "<include file=%file markup=\"?\">")
9652 "Structure completion elements.
9653 This is a list of abbreviation keys and values. The value gets inserted
9654 it you type @samp{.} followed by the key and then the completion key,
9655 usually `M-TAB'. %file will be replaced by a file name after prompting
9656 for the file using completion.
9657 There are two templates for each key, the first uses the original Org syntax,
9658 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9659 the default when the /org-mtags.el/ module has been loaded. See also the
9660 variable `org-mtags-prefer-muse-templates'.
9661 This is an experimental feature, it is undecided if it is going to stay in."
9662 :group 'org-completion
9663 :type '(repeat
9664 (string :tag "Key")
9665 (string :tag "Template")
9666 (string :tag "Muse Template")))
9668 (defun org-try-structure-completion ()
9669 "Try to complete a structure template before point.
9670 This looks for strings like \"<e\" on an otherwise empty line and
9671 expands them."
9672 (let ((l (buffer-substring (point-at-bol) (point)))
9674 (when (and (looking-at "[ \t]*$")
9675 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9676 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9677 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9678 (match-beginning 1)) a)
9679 t)))
9681 (defun org-complete-expand-structure-template (start cell)
9682 "Expand a structure template."
9683 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9684 (rpl (nth (if musep 2 1) cell))
9685 (ind ""))
9686 (delete-region start (point))
9687 (when (string-match "\\`#\\+" rpl)
9688 (cond
9689 ((bolp))
9690 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9691 (setq ind (buffer-substring (point-at-bol) (point))))
9692 (t (newline))))
9693 (setq start (point))
9694 (if (string-match "%file" rpl)
9695 (setq rpl (replace-match
9696 (concat
9697 "\""
9698 (save-match-data
9699 (abbreviate-file-name (read-file-name "Include file: ")))
9700 "\"")
9701 t t rpl)))
9702 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9703 (concat "\n" ind)))
9704 (insert rpl)
9705 (if (re-search-backward "\\?" start t) (delete-char 1))))
9708 (defun org-complete (&optional arg)
9709 "Perform completion on word at point.
9710 At the beginning of a headline, this completes TODO keywords as given in
9711 `org-todo-keywords'.
9712 If the current word is preceded by a backslash, completes the TeX symbols
9713 that are supported for HTML support.
9714 If the current word is preceded by \"#+\", completes special words for
9715 setting file options.
9716 In the line after \"#+STARTUP:, complete valid keywords.\"
9717 At all other locations, this simply calls the value of
9718 `org-completion-fallback-command'."
9719 (interactive "P")
9720 (org-without-partial-completion
9721 (catch 'exit
9722 (let* ((a nil)
9723 (end (point))
9724 (beg1 (save-excursion
9725 (skip-chars-backward (org-re "[:alnum:]_@"))
9726 (point)))
9727 (beg (save-excursion
9728 (skip-chars-backward "a-zA-Z0-9_:$")
9729 (point)))
9730 (confirm (lambda (x) (stringp (car x))))
9731 (searchhead (equal (char-before beg) ?*))
9732 (struct
9733 (when (and (member (char-before beg1) '(?. ?<))
9734 (setq a (assoc (buffer-substring beg1 (point))
9735 org-structure-template-alist)))
9736 (org-complete-expand-structure-template (1- beg1) a)
9737 (throw 'exit t)))
9738 (tag (and (equal (char-before beg1) ?:)
9739 (equal (char-after (point-at-bol)) ?*)))
9740 (prop (and (equal (char-before beg1) ?:)
9741 (not (equal (char-after (point-at-bol)) ?*))))
9742 (texp (equal (char-before beg) ?\\))
9743 (link (equal (char-before beg) ?\[))
9744 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9745 beg)
9746 "#+"))
9747 (startup (string-match "^#\\+STARTUP:.*"
9748 (buffer-substring (point-at-bol) (point))))
9749 (completion-ignore-case opt)
9750 (type nil)
9751 (tbl nil)
9752 (table (cond
9753 (opt
9754 (setq type :opt)
9755 (require 'org-exp)
9756 (append
9757 (delq nil
9758 (mapcar
9759 (lambda (x)
9760 (if (string-match
9761 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9762 (cons (match-string 2 x)
9763 (match-string 1 x))))
9764 (org-split-string (org-get-current-options) "\n")))
9765 (mapcar 'list org-additional-option-like-keywords)))
9766 (startup
9767 (setq type :startup)
9768 org-startup-options)
9769 (link (append org-link-abbrev-alist-local
9770 org-link-abbrev-alist))
9771 (texp
9772 (setq type :tex)
9773 org-html-entities)
9774 ((string-match "\\`\\*+[ \t]+\\'"
9775 (buffer-substring (point-at-bol) beg))
9776 (setq type :todo)
9777 (mapcar 'list org-todo-keywords-1))
9778 (searchhead
9779 (setq type :searchhead)
9780 (save-excursion
9781 (goto-char (point-min))
9782 (while (re-search-forward org-todo-line-regexp nil t)
9783 (push (list
9784 (org-make-org-heading-search-string
9785 (match-string 3) t))
9786 tbl)))
9787 tbl)
9788 (tag (setq type :tag beg beg1)
9789 (or org-tag-alist (org-get-buffer-tags)))
9790 (prop (setq type :prop beg beg1)
9791 (mapcar 'list (org-buffer-property-keys nil t t)))
9792 (t (progn
9793 (call-interactively org-completion-fallback-command)
9794 (throw 'exit nil)))))
9795 (pattern (buffer-substring-no-properties beg end))
9796 (completion (try-completion pattern table confirm)))
9797 (cond ((eq completion t)
9798 (if (not (assoc (upcase pattern) table))
9799 (message "Already complete")
9800 (if (and (equal type :opt)
9801 (not (member (car (assoc (upcase pattern) table))
9802 org-additional-option-like-keywords)))
9803 (insert (substring (cdr (assoc (upcase pattern) table))
9804 (length pattern)))
9805 (if (memq type '(:tag :prop)) (insert ":")))))
9806 ((null completion)
9807 (message "Can't find completion for \"%s\"" pattern)
9808 (ding))
9809 ((not (string= pattern completion))
9810 (delete-region beg end)
9811 (if (string-match " +$" completion)
9812 (setq completion (replace-match "" t t completion)))
9813 (insert completion)
9814 (if (get-buffer-window "*Completions*")
9815 (delete-window (get-buffer-window "*Completions*")))
9816 (if (assoc completion table)
9817 (if (eq type :todo) (insert " ")
9818 (if (memq type '(:tag :prop)) (insert ":"))))
9819 (if (and (equal type :opt) (assoc completion table))
9820 (message "%s" (substitute-command-keys
9821 "Press \\[org-complete] again to insert example settings"))))
9823 (message "Making completion list...")
9824 (let ((list (sort (all-completions pattern table confirm)
9825 'string<)))
9826 (with-output-to-temp-buffer "*Completions*"
9827 (condition-case nil
9828 ;; Protection needed for XEmacs and emacs 21
9829 (display-completion-list list pattern)
9830 (error (display-completion-list list)))))
9831 (message "Making completion list...%s" "done")))))))
9833 ;;;; TODO, DEADLINE, Comments
9835 (defun org-toggle-comment ()
9836 "Change the COMMENT state of an entry."
9837 (interactive)
9838 (save-excursion
9839 (org-back-to-heading)
9840 (let (case-fold-search)
9841 (if (looking-at (concat outline-regexp
9842 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9843 (replace-match "" t t nil 1)
9844 (if (looking-at outline-regexp)
9845 (progn
9846 (goto-char (match-end 0))
9847 (insert org-comment-string " ")))))))
9849 (defvar org-last-todo-state-is-todo nil
9850 "This is non-nil when the last TODO state change led to a TODO state.
9851 If the last change removed the TODO tag or switched to DONE, then
9852 this is nil.")
9854 (defvar org-setting-tags nil) ; dynamically skipped
9856 (defun org-parse-local-options (string var)
9857 "Parse STRING for startup setting relevant for variable VAR."
9858 (let ((rtn (symbol-value var))
9859 e opts)
9860 (save-match-data
9861 (if (or (not string) (not (string-match "\\S-" string)))
9863 (setq opts (delq nil (mapcar (lambda (x)
9864 (setq e (assoc x org-startup-options))
9865 (if (eq (nth 1 e) var) e nil))
9866 (org-split-string string "[ \t]+"))))
9867 (if (not opts)
9869 (setq rtn nil)
9870 (while (setq e (pop opts))
9871 (if (not (nth 3 e))
9872 (setq rtn (nth 2 e))
9873 (if (not (listp rtn)) (setq rtn nil))
9874 (push (nth 2 e) rtn)))
9875 rtn)))))
9877 (defvar org-todo-setup-filter-hook nil
9878 "Hook for functions that pre-filter todo specs.
9880 Each function takes a todo spec and returns either `nil' or the spec
9881 transformed into canonical form." )
9883 (defvar org-todo-get-default-hook nil
9884 "Hook for functions that get a default item for todo.
9886 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9887 `nil' or a string to be used for the todo mark." )
9889 (defvar org-agenda-headline-snapshot-before-repeat)
9891 (defun org-todo (&optional arg)
9892 "Change the TODO state of an item.
9893 The state of an item is given by a keyword at the start of the heading,
9894 like
9895 *** TODO Write paper
9896 *** DONE Call mom
9898 The different keywords are specified in the variable `org-todo-keywords'.
9899 By default the available states are \"TODO\" and \"DONE\".
9900 So for this example: when the item starts with TODO, it is changed to DONE.
9901 When it starts with DONE, the DONE is removed. And when neither TODO nor
9902 DONE are present, add TODO at the beginning of the heading.
9904 With C-u prefix arg, use completion to determine the new state.
9905 With numeric prefix arg, switch to that state.
9906 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9907 With a triple C-u prefix, circumvent any state blocking.
9909 For calling through lisp, arg is also interpreted in the following way:
9910 'none -> empty state
9911 \"\"(empty string) -> switch to empty state
9912 'done -> switch to DONE
9913 'nextset -> switch to the next set of keywords
9914 'previousset -> switch to the previous set of keywords
9915 \"WAITING\" -> switch to the specified keyword, but only if it
9916 really is a member of `org-todo-keywords'."
9917 (interactive "P")
9918 (if (equal arg '(16)) (setq arg 'nextset))
9919 (let ((org-blocker-hook org-blocker-hook)
9920 (case-fold-search nil))
9921 (when (equal arg '(64))
9922 (setq arg nil org-blocker-hook nil))
9923 (when (and org-blocker-hook
9924 (or org-inhibit-blocking
9925 (org-entry-get nil "NOBLOCKING")))
9926 (setq org-blocker-hook nil))
9927 (save-excursion
9928 (catch 'exit
9929 (org-back-to-heading t)
9930 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9931 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9932 (looking-at " *"))
9933 (let* ((match-data (match-data))
9934 (startpos (point-at-bol))
9935 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9936 (org-log-done org-log-done)
9937 (org-log-repeat org-log-repeat)
9938 (org-todo-log-states org-todo-log-states)
9939 (this (match-string 1))
9940 (hl-pos (match-beginning 0))
9941 (head (org-get-todo-sequence-head this))
9942 (ass (assoc head org-todo-kwd-alist))
9943 (interpret (nth 1 ass))
9944 (done-word (nth 3 ass))
9945 (final-done-word (nth 4 ass))
9946 (last-state (or this ""))
9947 (completion-ignore-case t)
9948 (member (member this org-todo-keywords-1))
9949 (tail (cdr member))
9950 (state (cond
9951 ((and org-todo-key-trigger
9952 (or (and (equal arg '(4))
9953 (eq org-use-fast-todo-selection 'prefix))
9954 (and (not arg) org-use-fast-todo-selection
9955 (not (eq org-use-fast-todo-selection
9956 'prefix)))))
9957 ;; Use fast selection
9958 (org-fast-todo-selection))
9959 ((and (equal arg '(4))
9960 (or (not org-use-fast-todo-selection)
9961 (not org-todo-key-trigger)))
9962 ;; Read a state with completion
9963 (org-icompleting-read
9964 "State: " (mapcar (lambda(x) (list x))
9965 org-todo-keywords-1)
9966 nil t))
9967 ((eq arg 'right)
9968 (if this
9969 (if tail (car tail) nil)
9970 (car org-todo-keywords-1)))
9971 ((eq arg 'left)
9972 (if (equal member org-todo-keywords-1)
9974 (if this
9975 (nth (- (length org-todo-keywords-1)
9976 (length tail) 2)
9977 org-todo-keywords-1)
9978 (org-last org-todo-keywords-1))))
9979 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9980 (setq arg nil))) ; hack to fall back to cycling
9981 (arg
9982 ;; user or caller requests a specific state
9983 (cond
9984 ((equal arg "") nil)
9985 ((eq arg 'none) nil)
9986 ((eq arg 'done) (or done-word (car org-done-keywords)))
9987 ((eq arg 'nextset)
9988 (or (car (cdr (member head org-todo-heads)))
9989 (car org-todo-heads)))
9990 ((eq arg 'previousset)
9991 (let ((org-todo-heads (reverse org-todo-heads)))
9992 (or (car (cdr (member head org-todo-heads)))
9993 (car org-todo-heads))))
9994 ((car (member arg org-todo-keywords-1)))
9995 ((stringp arg)
9996 (error "State `%s' not valid in this file" arg))
9997 ((nth (1- (prefix-numeric-value arg))
9998 org-todo-keywords-1))))
9999 ((null member) (or head (car org-todo-keywords-1)))
10000 ((equal this final-done-word) nil) ;; -> make empty
10001 ((null tail) nil) ;; -> first entry
10002 ((memq interpret '(type priority))
10003 (if (eq this-command last-command)
10004 (car tail)
10005 (if (> (length tail) 0)
10006 (or done-word (car org-done-keywords))
10007 nil)))
10009 (car tail))))
10010 (state (or
10011 (run-hook-with-args-until-success
10012 'org-todo-get-default-hook state last-state)
10013 state))
10014 (next (if state (concat " " state " ") " "))
10015 (change-plist (list :type 'todo-state-change :from this :to state
10016 :position startpos))
10017 dolog now-done-p)
10018 (when org-blocker-hook
10019 (setq org-last-todo-state-is-todo
10020 (not (member this org-done-keywords)))
10021 (unless (save-excursion
10022 (save-match-data
10023 (run-hook-with-args-until-failure
10024 'org-blocker-hook change-plist)))
10025 (if (interactive-p)
10026 (error "TODO state change from %s to %s blocked" this state)
10027 ;; fail silently
10028 (message "TODO state change from %s to %s blocked" this state)
10029 (throw 'exit nil))))
10030 (store-match-data match-data)
10031 (replace-match next t t)
10032 (unless (pos-visible-in-window-p hl-pos)
10033 (message "TODO state changed to %s" (org-trim next)))
10034 (unless head
10035 (setq head (org-get-todo-sequence-head state)
10036 ass (assoc head org-todo-kwd-alist)
10037 interpret (nth 1 ass)
10038 done-word (nth 3 ass)
10039 final-done-word (nth 4 ass)))
10040 (when (memq arg '(nextset previousset))
10041 (message "Keyword-Set %d/%d: %s"
10042 (- (length org-todo-sets) -1
10043 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10044 (length org-todo-sets)
10045 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10046 (setq org-last-todo-state-is-todo
10047 (not (member state org-done-keywords)))
10048 (setq now-done-p (and (member state org-done-keywords)
10049 (not (member this org-done-keywords))))
10050 (and logging (org-local-logging logging))
10051 (when (and (or org-todo-log-states org-log-done)
10052 (not (eq org-inhibit-logging t))
10053 (not (memq arg '(nextset previousset))))
10054 ;; we need to look at recording a time and note
10055 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10056 (nth 2 (assoc this org-todo-log-states))))
10057 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10058 (setq dolog 'time))
10059 (when (and state
10060 (member state org-not-done-keywords)
10061 (not (member this org-not-done-keywords)))
10062 ;; This is now a todo state and was not one before
10063 ;; If there was a CLOSED time stamp, get rid of it.
10064 (org-add-planning-info nil nil 'closed))
10065 (when (and now-done-p org-log-done)
10066 ;; It is now done, and it was not done before
10067 (org-add-planning-info 'closed (org-current-time))
10068 (if (and (not dolog) (eq 'note org-log-done))
10069 (org-add-log-setup 'done state this 'findpos 'note)))
10070 (when (and state dolog)
10071 ;; This is a non-nil state, and we need to log it
10072 (org-add-log-setup 'state state this 'findpos dolog)))
10073 ;; Fixup tag positioning
10074 (org-todo-trigger-tag-changes state)
10075 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10076 (when org-provide-todo-statistics
10077 (org-update-parent-todo-statistics))
10078 (run-hooks 'org-after-todo-state-change-hook)
10079 (if (and arg (not (member state org-done-keywords)))
10080 (setq head (org-get-todo-sequence-head state)))
10081 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10082 ;; Do we need to trigger a repeat?
10083 (when now-done-p
10084 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10085 ;; This is for the agenda, take a snapshot of the headline.
10086 (save-match-data
10087 (setq org-agenda-headline-snapshot-before-repeat
10088 (org-get-heading))))
10089 (org-auto-repeat-maybe state))
10090 ;; Fixup cursor location if close to the keyword
10091 (if (and (outline-on-heading-p)
10092 (not (bolp))
10093 (save-excursion (beginning-of-line 1)
10094 (looking-at org-todo-line-regexp))
10095 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10096 (progn
10097 (goto-char (or (match-end 2) (match-end 1)))
10098 (and (looking-at " ") (just-one-space))))
10099 (when org-trigger-hook
10100 (save-excursion
10101 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10103 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10104 "Block turning an entry into a TODO, using the hierarchy.
10105 This checks whether the current task should be blocked from state
10106 changes. Such blocking occurs when:
10108 1. The task has children which are not all in a completed state.
10110 2. A task has a parent with the property :ORDERED:, and there
10111 are siblings prior to the current task with incomplete
10112 status.
10114 3. The parent of the task is blocked because it has siblings that should
10115 be done first, or is child of a block grandparent TODO entry."
10117 (catch 'dont-block
10118 ;; If this is not a todo state change, or if this entry is already DONE,
10119 ;; do not block
10120 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10121 (member (plist-get change-plist :from)
10122 (cons 'done org-done-keywords))
10123 (member (plist-get change-plist :to)
10124 (cons 'todo org-not-done-keywords))
10125 (not (plist-get change-plist :to)))
10126 (throw 'dont-block t))
10127 ;; If this task has children, and any are undone, it's blocked
10128 (save-excursion
10129 (org-back-to-heading t)
10130 (let ((this-level (funcall outline-level)))
10131 (outline-next-heading)
10132 (let ((child-level (funcall outline-level)))
10133 (while (and (not (eobp))
10134 (> child-level this-level))
10135 ;; this todo has children, check whether they are all
10136 ;; completed
10137 (if (and (not (org-entry-is-done-p))
10138 (org-entry-is-todo-p))
10139 (throw 'dont-block nil))
10140 (outline-next-heading)
10141 (setq child-level (funcall outline-level))))))
10142 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10143 ;; any previous siblings are undone, it's blocked
10144 (save-excursion
10145 (org-back-to-heading t)
10146 (let* ((pos (point))
10147 (parent-pos (and (org-up-heading-safe) (point))))
10148 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10149 (when (and (org-entry-get (point) "ORDERED")
10150 (forward-line 1)
10151 (re-search-forward org-not-done-heading-regexp pos t))
10152 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10153 ;; Search further up the hierarchy, to see if an anchestor is blocked
10154 (while t
10155 (goto-char parent-pos)
10156 (if (not (looking-at org-not-done-heading-regexp))
10157 (throw 'dont-block t)) ; do not block, parent is not a TODO
10158 (setq pos (point))
10159 (setq parent-pos (and (org-up-heading-safe) (point)))
10160 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10161 (when (and (org-entry-get (point) "ORDERED")
10162 (forward-line 1)
10163 (re-search-forward org-not-done-heading-regexp pos t))
10164 (throw 'dont-block nil))))))) ; block, older sibling not done.
10166 (defcustom org-track-ordered-property-with-tag nil
10167 "Should the ORDERED property also be shown as a tag?
10168 The ORDERED property decides if an entry should require subtasks to be
10169 completed in sequence. Since a property is not very visible, setting
10170 this option means that toggling the ORDERED property with the command
10171 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10172 not relevant for the behavior, but it makes things more visible.
10174 Note that toggling the tag with tags commands will not change the property
10175 and therefore not influence behavior!
10177 This can be t, meaning the tag ORDERED should be used, It can also be a
10178 string to select a different tag for this task."
10179 :group 'org-todo
10180 :type '(choice
10181 (const :tag "No tracking" nil)
10182 (const :tag "Track with ORDERED tag" t)
10183 (string :tag "Use other tag")))
10185 (defun org-toggle-ordered-property ()
10186 "Toggle the ORDERED property of the current entry.
10187 For better visibility, you can track the value of this property with a tag.
10188 See variable `org-track-ordered-property-with-tag'."
10189 (interactive)
10190 (let* ((t1 org-track-ordered-property-with-tag)
10191 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10192 (save-excursion
10193 (org-back-to-heading)
10194 (if (org-entry-get nil "ORDERED")
10195 (progn
10196 (org-delete-property "ORDERED")
10197 (and tag (org-toggle-tag tag 'off))
10198 (message "Subtasks can be completed in arbitrary order"))
10199 (org-entry-put nil "ORDERED" "t")
10200 (and tag (org-toggle-tag tag 'on))
10201 (message "Subtasks must be completed in sequence")))))
10203 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10204 (defun org-block-todo-from-checkboxes (change-plist)
10205 "Block turning an entry into a TODO, using checkboxes.
10206 This checks whether the current task should be blocked from state
10207 changes because there are unchecked boxes in this entry."
10208 (catch 'dont-block
10209 ;; If this is not a todo state change, or if this entry is already DONE,
10210 ;; do not block
10211 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10212 (member (plist-get change-plist :from)
10213 (cons 'done org-done-keywords))
10214 (member (plist-get change-plist :to)
10215 (cons 'todo org-not-done-keywords))
10216 (not (plist-get change-plist :to)))
10217 (throw 'dont-block t))
10218 ;; If this task has checkboxes that are not checked, it's blocked
10219 (save-excursion
10220 (org-back-to-heading t)
10221 (let ((beg (point)) end)
10222 (outline-next-heading)
10223 (setq end (point))
10224 (goto-char beg)
10225 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10226 end t)
10227 (progn
10228 (if (boundp 'org-blocked-by-checkboxes)
10229 (setq org-blocked-by-checkboxes t))
10230 (throw 'dont-block nil)))))
10231 t)) ; do not block
10233 (defun org-update-statistics-cookies (all)
10234 "Update the statistics cookie, either from TODO or from checkboxes.
10235 This should be called with the cursor in a line with a statistics cookie."
10236 (interactive "P")
10237 (if all
10238 (progn
10239 (org-update-checkbox-count 'all)
10240 (org-map-entries 'org-update-parent-todo-statistics))
10241 (if (not (org-on-heading-p))
10242 (org-update-checkbox-count)
10243 (let ((pos (move-marker (make-marker) (point)))
10244 end l1 l2)
10245 (ignore-errors (org-back-to-heading t))
10246 (if (not (org-on-heading-p))
10247 (org-update-checkbox-count)
10248 (setq l1 (org-outline-level))
10249 (setq end (save-excursion
10250 (outline-next-heading)
10251 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10252 (point)))
10253 (if (and (save-excursion (re-search-forward
10254 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10255 (not (save-excursion (re-search-forward
10256 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10257 (org-update-checkbox-count)
10258 (if (and l2 (> l2 l1))
10259 (progn
10260 (goto-char end)
10261 (org-update-parent-todo-statistics))
10262 (error "No data for statistics cookie"))))
10263 (goto-char pos)
10264 (move-marker pos nil)))))
10266 (defvar org-entry-property-inherited-from) ;; defined below
10267 (defun org-update-parent-todo-statistics ()
10268 "Update any statistics cookie in the parent of the current headline.
10269 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10270 the entire subtree and this will travel up the hierarchy and update
10271 statistics everywhere."
10272 (interactive)
10273 (let* ((lim 0) prop
10274 (recursive (or (not org-hierarchical-todo-statistics)
10275 (string-match
10276 "\\<recursive\\>"
10277 (or (setq prop (org-entry-get
10278 nil "COOKIE_DATA" 'inherit)) ""))))
10279 (lim (or (and prop (marker-position
10280 org-entry-property-inherited-from))
10281 lim))
10282 (first t)
10283 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10284 level ltoggle l1 new ndel
10285 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10286 (catch 'exit
10287 (save-excursion
10288 (beginning-of-line 1)
10289 (if (org-at-heading-p)
10290 (setq ltoggle (funcall outline-level))
10291 (error "This should not happen"))
10292 (while (and (setq level (org-up-heading-safe))
10293 (or recursive first)
10294 (>= (point) lim))
10295 (setq first nil cookie-present nil)
10296 (unless (and level
10297 (not (string-match
10298 "\\<checkbox\\>"
10299 (downcase
10300 (or (org-entry-get
10301 nil "COOKIE_DATA")
10302 "")))))
10303 (throw 'exit nil))
10304 (while (re-search-forward box-re (point-at-eol) t)
10305 (setq cnt-all 0 cnt-done 0 cookie-present t)
10306 (setq is-percent (match-end 2))
10307 (save-match-data
10308 (unless (outline-next-heading) (throw 'exit nil))
10309 (while (and (looking-at org-complex-heading-regexp)
10310 (> (setq l1 (length (match-string 1))) level))
10311 (setq kwd (and (or recursive (= l1 ltoggle))
10312 (match-string 2)))
10313 (if (or (eq org-provide-todo-statistics 'all-headlines)
10314 (and (listp org-provide-todo-statistics)
10315 (or (member kwd org-provide-todo-statistics)
10316 (member kwd org-done-keywords))))
10317 (setq cnt-all (1+ cnt-all))
10318 (if (eq org-provide-todo-statistics t)
10319 (and kwd (setq cnt-all (1+ cnt-all)))))
10320 (and (member kwd org-done-keywords)
10321 (setq cnt-done (1+ cnt-done)))
10322 (outline-next-heading)))
10323 (setq new
10324 (if is-percent
10325 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10326 (format "[%d/%d]" cnt-done cnt-all))
10327 ndel (- (match-end 0) (match-beginning 0)))
10328 (goto-char (match-beginning 0))
10329 (insert new)
10330 (delete-region (point) (+ (point) ndel)))
10331 (when cookie-present
10332 (run-hook-with-args 'org-after-todo-statistics-hook
10333 cnt-done (- cnt-all cnt-done))))))
10334 (run-hooks 'org-todo-statistics-hook)))
10336 (defvar org-after-todo-statistics-hook nil
10337 "Hook that is called after a TODO statistics cookie has been updated.
10338 Each function is called with two arguments: the number of not-done entries
10339 and the number of done entries.
10341 For example, the following function, when added to this hook, will switch
10342 an entry to DONE when all children are done, and back to TODO when new
10343 entries are set to a TODO status. Note that this hook is only called
10344 when there is a statistics cookie in the headline!
10346 (defun org-summary-todo (n-done n-not-done)
10347 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10348 (let (org-log-done org-log-states) ; turn off logging
10349 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10352 (defvar org-todo-statistics-hook nil
10353 "Hook that is run whenever Org thinks TODO statistics should be updated.
10354 This hook runs even if there is no statistics cookie present, in which case
10355 `org-after-todo-statistics-hook' would not run.")
10357 (defun org-todo-trigger-tag-changes (state)
10358 "Apply the changes defined in `org-todo-state-tags-triggers'."
10359 (let ((l org-todo-state-tags-triggers)
10360 changes)
10361 (when (or (not state) (equal state ""))
10362 (setq changes (append changes (cdr (assoc "" l)))))
10363 (when (and (stringp state) (> (length state) 0))
10364 (setq changes (append changes (cdr (assoc state l)))))
10365 (when (member state org-not-done-keywords)
10366 (setq changes (append changes (cdr (assoc 'todo l)))))
10367 (when (member state org-done-keywords)
10368 (setq changes (append changes (cdr (assoc 'done l)))))
10369 (dolist (c changes)
10370 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10372 (defun org-local-logging (value)
10373 "Get logging settings from a property VALUE."
10374 (let* (words w a)
10375 ;; directly set the variables, they are already local.
10376 (setq org-log-done nil
10377 org-log-repeat nil
10378 org-todo-log-states nil)
10379 (setq words (org-split-string value))
10380 (while (setq w (pop words))
10381 (cond
10382 ((setq a (assoc w org-startup-options))
10383 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10384 (set (nth 1 a) (nth 2 a))))
10385 ((setq a (org-extract-log-state-settings w))
10386 (and (member (car a) org-todo-keywords-1)
10387 (push a org-todo-log-states)))))))
10389 (defun org-get-todo-sequence-head (kwd)
10390 "Return the head of the TODO sequence to which KWD belongs.
10391 If KWD is not set, check if there is a text property remembering the
10392 right sequence."
10393 (let (p)
10394 (cond
10395 ((not kwd)
10396 (or (get-text-property (point-at-bol) 'org-todo-head)
10397 (progn
10398 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10399 nil (point-at-eol)))
10400 (get-text-property p 'org-todo-head))))
10401 ((not (member kwd org-todo-keywords-1))
10402 (car org-todo-keywords-1))
10403 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10405 (defun org-fast-todo-selection ()
10406 "Fast TODO keyword selection with single keys.
10407 Returns the new TODO keyword, or nil if no state change should occur."
10408 (let* ((fulltable org-todo-key-alist)
10409 (done-keywords org-done-keywords) ;; needed for the faces.
10410 (maxlen (apply 'max (mapcar
10411 (lambda (x)
10412 (if (stringp (car x)) (string-width (car x)) 0))
10413 fulltable)))
10414 (expert nil)
10415 (fwidth (+ maxlen 3 1 3))
10416 (ncol (/ (- (window-width) 4) fwidth))
10417 tg cnt e c tbl
10418 groups ingroup)
10419 (save-excursion
10420 (save-window-excursion
10421 (if expert
10422 (set-buffer (get-buffer-create " *Org todo*"))
10423 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10424 (erase-buffer)
10425 (org-set-local 'org-done-keywords done-keywords)
10426 (setq tbl fulltable cnt 0)
10427 (while (setq e (pop tbl))
10428 (cond
10429 ((equal e '(:startgroup))
10430 (push '() groups) (setq ingroup t)
10431 (when (not (= cnt 0))
10432 (setq cnt 0)
10433 (insert "\n"))
10434 (insert "{ "))
10435 ((equal e '(:endgroup))
10436 (setq ingroup nil cnt 0)
10437 (insert "}\n"))
10438 ((equal e '(:newline))
10439 (when (not (= cnt 0))
10440 (setq cnt 0)
10441 (insert "\n")
10442 (setq e (car tbl))
10443 (while (equal (car tbl) '(:newline))
10444 (insert "\n")
10445 (setq tbl (cdr tbl)))))
10447 (setq tg (car e) c (cdr e))
10448 (if ingroup (push tg (car groups)))
10449 (setq tg (org-add-props tg nil 'face
10450 (org-get-todo-face tg)))
10451 (if (and (= cnt 0) (not ingroup)) (insert " "))
10452 (insert "[" c "] " tg (make-string
10453 (- fwidth 4 (length tg)) ?\ ))
10454 (when (= (setq cnt (1+ cnt)) ncol)
10455 (insert "\n")
10456 (if ingroup (insert " "))
10457 (setq cnt 0)))))
10458 (insert "\n")
10459 (goto-char (point-min))
10460 (if (not expert) (org-fit-window-to-buffer))
10461 (message "[a-z..]:Set [SPC]:clear")
10462 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10463 (cond
10464 ((or (= c ?\C-g)
10465 (and (= c ?q) (not (rassoc c fulltable))))
10466 (setq quit-flag t))
10467 ((= c ?\ ) nil)
10468 ((setq e (rassoc c fulltable) tg (car e))
10470 (t (setq quit-flag t)))))))
10472 (defun org-entry-is-todo-p ()
10473 (member (org-get-todo-state) org-not-done-keywords))
10475 (defun org-entry-is-done-p ()
10476 (member (org-get-todo-state) org-done-keywords))
10478 (defun org-get-todo-state ()
10479 (save-excursion
10480 (org-back-to-heading t)
10481 (and (looking-at org-todo-line-regexp)
10482 (match-end 2)
10483 (match-string 2))))
10485 (defun org-at-date-range-p (&optional inactive-ok)
10486 "Is the cursor inside a date range?"
10487 (interactive)
10488 (save-excursion
10489 (catch 'exit
10490 (let ((pos (point)))
10491 (skip-chars-backward "^[<\r\n")
10492 (skip-chars-backward "<[")
10493 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10494 (>= (match-end 0) pos)
10495 (throw 'exit t))
10496 (skip-chars-backward "^<[\r\n")
10497 (skip-chars-backward "<[")
10498 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10499 (>= (match-end 0) pos)
10500 (throw 'exit t)))
10501 nil)))
10503 (defun org-get-repeat (&optional tagline)
10504 "Check if there is a deadline/schedule with repeater in this entry."
10505 (save-match-data
10506 (save-excursion
10507 (org-back-to-heading t)
10508 (and (re-search-forward (if tagline
10509 (concat tagline "\\s-*" org-repeat-re)
10510 org-repeat-re)
10511 (org-entry-end-position) t)
10512 (match-string-no-properties 1)))))
10514 (defvar org-last-changed-timestamp)
10515 (defvar org-last-inserted-timestamp)
10516 (defvar org-log-post-message)
10517 (defvar org-log-note-purpose)
10518 (defvar org-log-note-how)
10519 (defvar org-log-note-extra)
10520 (defun org-auto-repeat-maybe (done-word)
10521 "Check if the current headline contains a repeated deadline/schedule.
10522 If yes, set TODO state back to what it was and change the base date
10523 of repeating deadline/scheduled time stamps to new date.
10524 This function is run automatically after each state change to a DONE state."
10525 ;; last-state is dynamically scoped into this function
10526 (let* ((repeat (org-get-repeat))
10527 (aa (assoc last-state org-todo-kwd-alist))
10528 (interpret (nth 1 aa))
10529 (head (nth 2 aa))
10530 (whata '(("d" . day) ("m" . month) ("y" . year)))
10531 (msg "Entry repeats: ")
10532 (org-log-done nil)
10533 (org-todo-log-states nil)
10534 (nshiftmax 10) (nshift 0)
10535 re type n what ts time)
10536 (when repeat
10537 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10538 (org-todo (if (eq interpret 'type) last-state head))
10539 (org-entry-put nil "LAST_REPEAT" (format-time-string
10540 (org-time-stamp-format t t)))
10541 (when org-log-repeat
10542 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10543 (memq 'org-add-log-note post-command-hook))
10544 ;; OK, we are already setup for some record
10545 (if (eq org-log-repeat 'note)
10546 ;; make sure we take a note, not only a time stamp
10547 (setq org-log-note-how 'note))
10548 ;; Set up for taking a record
10549 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10550 last-state
10551 'findpos org-log-repeat)))
10552 (org-back-to-heading t)
10553 (org-add-planning-info nil nil 'closed)
10554 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10555 org-deadline-time-regexp "\\)\\|\\("
10556 org-ts-regexp "\\)"))
10557 (while (re-search-forward
10558 re (save-excursion (outline-next-heading) (point)) t)
10559 (setq type (if (match-end 1) org-scheduled-string
10560 (if (match-end 3) org-deadline-string "Plain:"))
10561 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10562 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10563 (setq n (string-to-number (match-string 2 ts))
10564 what (match-string 3 ts))
10565 (if (equal what "w") (setq n (* n 7) what "d"))
10566 ;; Preparation, see if we need to modify the start date for the change
10567 (when (match-end 1)
10568 (setq time (save-match-data (org-time-string-to-time ts)))
10569 (cond
10570 ((equal (match-string 1 ts) ".")
10571 ;; Shift starting date to today
10572 (org-timestamp-change
10573 (- (time-to-days (current-time)) (time-to-days time))
10574 'day))
10575 ((equal (match-string 1 ts) "+")
10576 (while (or (= nshift 0)
10577 (<= (time-to-days time) (time-to-days (current-time))))
10578 (when (= (incf nshift) nshiftmax)
10579 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10580 (error "Abort")))
10581 (org-timestamp-change n (cdr (assoc what whata)))
10582 (org-at-timestamp-p t)
10583 (setq ts (match-string 1))
10584 (setq time (save-match-data (org-time-string-to-time ts))))
10585 (org-timestamp-change (- n) (cdr (assoc what whata)))
10586 ;; rematch, so that we have everything in place for the real shift
10587 (org-at-timestamp-p t)
10588 (setq ts (match-string 1))
10589 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10590 (org-timestamp-change n (cdr (assoc what whata)))
10591 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10592 (setq org-log-post-message msg)
10593 (message "%s" msg))))
10595 (defun org-show-todo-tree (arg)
10596 "Make a compact tree which shows all headlines marked with TODO.
10597 The tree will show the lines where the regexp matches, and all higher
10598 headlines above the match.
10599 With a \\[universal-argument] prefix, prompt for a regexp to match.
10600 With a numeric prefix N, construct a sparse tree for the Nth element
10601 of `org-todo-keywords-1'."
10602 (interactive "P")
10603 (let ((case-fold-search nil)
10604 (kwd-re
10605 (cond ((null arg) org-not-done-regexp)
10606 ((equal arg '(4))
10607 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10608 (mapcar 'list org-todo-keywords-1))))
10609 (concat "\\("
10610 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10611 "\\)\\>")))
10612 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10613 (regexp-quote (nth (1- (prefix-numeric-value arg))
10614 org-todo-keywords-1)))
10615 (t (error "Invalid prefix argument: %s" arg)))))
10616 (message "%d TODO entries found"
10617 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10619 (defun org-deadline (&optional remove time)
10620 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10621 With argument REMOVE, remove any deadline from the item.
10622 When TIME is set, it should be an internal time specification, and the
10623 scheduling will use the corresponding date."
10624 (interactive "P")
10625 (let ((old-date (org-entry-get nil "DEADLINE")))
10626 (if remove
10627 (progn
10628 (org-remove-timestamp-with-keyword org-deadline-string)
10629 (message "Item no longer has a deadline."))
10630 (if (org-get-repeat)
10631 (error "Cannot change deadline on task with repeater, please do that by hand")
10632 (org-add-planning-info 'deadline time 'closed)
10633 (when (and old-date org-log-redeadline
10634 (not (equal old-date
10635 (substring org-last-inserted-timestamp 1 -1))))
10636 (org-add-log-setup 'redeadline nil old-date 'findpos
10637 org-log-redeadline))
10638 (message "Deadline on %s" org-last-inserted-timestamp)))))
10640 (defun org-schedule (&optional remove time)
10641 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10642 With argument REMOVE, remove any scheduling date from the item.
10643 When TIME is set, it should be an internal time specification, and the
10644 scheduling will use the corresponding date."
10645 (interactive "P")
10646 (let ((old-date (org-entry-get nil "SCHEDULED")))
10647 (if remove
10648 (progn
10649 (org-remove-timestamp-with-keyword org-scheduled-string)
10650 (message "Item is no longer scheduled."))
10651 (if (org-get-repeat)
10652 (error "Cannot reschedule task with repeater, please do that by hand")
10653 (org-add-planning-info 'scheduled time 'closed)
10654 (when (and old-date org-log-reschedule
10655 (not (equal old-date
10656 (substring org-last-inserted-timestamp 1 -1))))
10657 (org-add-log-setup 'reschedule nil old-date 'findpos
10658 org-log-reschedule))
10659 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10661 (defun org-get-scheduled-time (pom &optional inherit)
10662 "Get the scheduled time as a time tuple, of a format suitable
10663 for calling org-schedule with, or if there is no scheduling,
10664 returns nil."
10665 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10666 (when time
10667 (apply 'encode-time (org-parse-time-string time)))))
10669 (defun org-get-deadline-time (pom &optional inherit)
10670 "Get the deadine as a time tuple, of a format suitable for
10671 calling org-deadline with, or if there is no scheduling, returns
10672 nil."
10673 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10674 (when time
10675 (apply 'encode-time (org-parse-time-string time)))))
10677 (defun org-remove-timestamp-with-keyword (keyword)
10678 "Remove all time stamps with KEYWORD in the current entry."
10679 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10680 beg)
10681 (save-excursion
10682 (org-back-to-heading t)
10683 (setq beg (point))
10684 (outline-next-heading)
10685 (while (re-search-backward re beg t)
10686 (replace-match "")
10687 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10688 (equal (char-before) ?\ ))
10689 (backward-delete-char 1)
10690 (if (string-match "^[ \t]*$" (buffer-substring
10691 (point-at-bol) (point-at-eol)))
10692 (delete-region (point-at-bol)
10693 (min (point-max) (1+ (point-at-eol))))))))))
10695 (defun org-add-planning-info (what &optional time &rest remove)
10696 "Insert new timestamp with keyword in the line directly after the headline.
10697 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10698 If non is given, the user is prompted for a date.
10699 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10700 be removed."
10701 (interactive)
10702 (let (org-time-was-given org-end-time-was-given ts
10703 end default-time default-input)
10705 (catch 'exit
10706 (when (and (not time) (memq what '(scheduled deadline)))
10707 ;; Try to get a default date/time from existing timestamp
10708 (save-excursion
10709 (org-back-to-heading t)
10710 (setq end (save-excursion (outline-next-heading) (point)))
10711 (when (re-search-forward (if (eq what 'scheduled)
10712 org-scheduled-time-regexp
10713 org-deadline-time-regexp)
10714 end t)
10715 (setq ts (match-string 1)
10716 default-time
10717 (apply 'encode-time (org-parse-time-string ts))
10718 default-input (and ts (org-get-compact-tod ts))))))
10719 (when what
10720 ;; If necessary, get the time from the user
10721 (setq time (or time (org-read-date nil 'to-time nil nil
10722 default-time default-input))))
10724 (when (and org-insert-labeled-timestamps-at-point
10725 (member what '(scheduled deadline)))
10726 (insert
10727 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10728 (org-insert-time-stamp time org-time-was-given
10729 nil nil nil (list org-end-time-was-given))
10730 (setq what nil))
10731 (save-excursion
10732 (save-restriction
10733 (let (col list elt ts buffer-invisibility-spec)
10734 (org-back-to-heading t)
10735 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10736 (goto-char (match-end 1))
10737 (setq col (current-column))
10738 (goto-char (match-end 0))
10739 (if (eobp) (insert "\n") (forward-char 1))
10740 (when (and (not what)
10741 (not (looking-at
10742 (concat "[ \t]*"
10743 org-keyword-time-not-clock-regexp))))
10744 ;; Nothing to add, nothing to remove...... :-)
10745 (throw 'exit nil))
10746 (if (and (not (looking-at outline-regexp))
10747 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10748 "[^\r\n]*"))
10749 (not (equal (match-string 1) org-clock-string)))
10750 (narrow-to-region (match-beginning 0) (match-end 0))
10751 (insert-before-markers "\n")
10752 (backward-char 1)
10753 (narrow-to-region (point) (point))
10754 (and org-adapt-indentation (org-indent-to-column col)))
10755 ;; Check if we have to remove something.
10756 (setq list (cons what remove))
10757 (while list
10758 (setq elt (pop list))
10759 (goto-char (point-min))
10760 (when (or (and (eq elt 'scheduled)
10761 (re-search-forward org-scheduled-time-regexp nil t))
10762 (and (eq elt 'deadline)
10763 (re-search-forward org-deadline-time-regexp nil t))
10764 (and (eq elt 'closed)
10765 (re-search-forward org-closed-time-regexp nil t)))
10766 (replace-match "")
10767 (if (looking-at "--+<[^>]+>") (replace-match ""))
10768 (skip-chars-backward " ")
10769 (if (looking-at " +") (replace-match ""))))
10770 (goto-char (point-max))
10771 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10772 (when what
10773 (insert
10774 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10775 (cond ((eq what 'scheduled) org-scheduled-string)
10776 ((eq what 'deadline) org-deadline-string)
10777 ((eq what 'closed) org-closed-string))
10778 " ")
10779 (setq ts (org-insert-time-stamp
10780 time
10781 (or org-time-was-given
10782 (and (eq what 'closed) org-log-done-with-time))
10783 (eq what 'closed)
10784 nil nil (list org-end-time-was-given)))
10785 (end-of-line 1))
10786 (goto-char (point-min))
10787 (widen)
10788 (if (and (looking-at "[ \t]+\n")
10789 (equal (char-before) ?\n))
10790 (delete-region (1- (point)) (point-at-eol)))
10791 ts))))))
10793 (defvar org-log-note-marker (make-marker))
10794 (defvar org-log-note-purpose nil)
10795 (defvar org-log-note-state nil)
10796 (defvar org-log-note-previous-state nil)
10797 (defvar org-log-note-how nil)
10798 (defvar org-log-note-extra nil)
10799 (defvar org-log-note-window-configuration nil)
10800 (defvar org-log-note-return-to (make-marker))
10801 (defvar org-log-post-message nil
10802 "Message to be displayed after a log note has been stored.
10803 The auto-repeater uses this.")
10805 (defun org-add-note ()
10806 "Add a note to the current entry.
10807 This is done in the same way as adding a state change note."
10808 (interactive)
10809 (org-add-log-setup 'note nil nil 'findpos nil))
10811 (defvar org-property-end-re)
10812 (defun org-add-log-setup (&optional purpose state prev-state
10813 findpos how &optional extra)
10814 "Set up the post command hook to take a note.
10815 If this is about to TODO state change, the new state is expected in STATE.
10816 When FINDPOS is non-nil, find the correct position for the note in
10817 the current entry. If not, assume that it can be inserted at point.
10818 HOW is an indicator what kind of note should be created.
10819 EXTRA is additional text that will be inserted into the notes buffer."
10820 (let* ((org-log-into-drawer (org-log-into-drawer))
10821 (drawer (cond ((stringp org-log-into-drawer)
10822 org-log-into-drawer)
10823 (org-log-into-drawer "LOGBOOK")
10824 (t nil))))
10825 (save-restriction
10826 (save-excursion
10827 (when findpos
10828 (org-back-to-heading t)
10829 (narrow-to-region (point) (save-excursion
10830 (outline-next-heading) (point)))
10831 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10832 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10833 "[^\r\n]*\\)?"))
10834 (goto-char (match-end 0))
10835 (cond
10836 (drawer
10837 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10838 nil t)
10839 (progn
10840 (goto-char (match-end 0))
10841 (or org-log-states-order-reversed
10842 (and (re-search-forward org-property-end-re nil t)
10843 (goto-char (1- (match-beginning 0))))))
10844 (insert "\n:" drawer ":\n:END:")
10845 (beginning-of-line 0)
10846 (org-indent-line-function)
10847 (beginning-of-line 2)
10848 (org-indent-line-function)
10849 (end-of-line 0)))
10850 ((and org-log-state-notes-insert-after-drawers
10851 (save-excursion
10852 (forward-line) (looking-at org-drawer-regexp)))
10853 (forward-line)
10854 (while (looking-at org-drawer-regexp)
10855 (goto-char (match-end 0))
10856 (re-search-forward org-property-end-re (point-max) t)
10857 (forward-line))
10858 (forward-line -1)))
10859 (unless org-log-states-order-reversed
10860 (and (= (char-after) ?\n) (forward-char 1))
10861 (org-skip-over-state-notes)
10862 (skip-chars-backward " \t\n\r")))
10863 (move-marker org-log-note-marker (point))
10864 (setq org-log-note-purpose purpose
10865 org-log-note-state state
10866 org-log-note-previous-state prev-state
10867 org-log-note-how how
10868 org-log-note-extra extra)
10869 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10871 (defun org-skip-over-state-notes ()
10872 "Skip past the list of State notes in an entry."
10873 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10874 (while (looking-at "[ \t]*- State")
10875 (condition-case nil
10876 (org-next-item)
10877 (error (org-end-of-item)))))
10879 (defun org-add-log-note (&optional purpose)
10880 "Pop up a window for taking a note, and add this note later at point."
10881 (remove-hook 'post-command-hook 'org-add-log-note)
10882 (setq org-log-note-window-configuration (current-window-configuration))
10883 (delete-other-windows)
10884 (move-marker org-log-note-return-to (point))
10885 (switch-to-buffer (marker-buffer org-log-note-marker))
10886 (goto-char org-log-note-marker)
10887 (org-switch-to-buffer-other-window "*Org Note*")
10888 (erase-buffer)
10889 (if (memq org-log-note-how '(time state))
10890 (let (current-prefix-arg) (org-store-log-note))
10891 (let ((org-inhibit-startup t)) (org-mode))
10892 (insert (format "# Insert note for %s.
10893 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10894 (cond
10895 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10896 ((eq org-log-note-purpose 'done) "closed todo item")
10897 ((eq org-log-note-purpose 'state)
10898 (format "state change from \"%s\" to \"%s\""
10899 (or org-log-note-previous-state "")
10900 (or org-log-note-state "")))
10901 ((eq org-log-note-purpose 'reschedule)
10902 "rescheduling")
10903 ((eq org-log-note-purpose 'redeadline)
10904 "changing deadline")
10905 ((eq org-log-note-purpose 'note)
10906 "this entry")
10907 (t (error "This should not happen")))))
10908 (if org-log-note-extra (insert org-log-note-extra))
10909 (org-set-local 'org-finish-function 'org-store-log-note)))
10911 (defvar org-note-abort nil) ; dynamically scoped
10912 (defun org-store-log-note ()
10913 "Finish taking a log note, and insert it to where it belongs."
10914 (let ((txt (buffer-string))
10915 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10916 lines ind)
10917 (kill-buffer (current-buffer))
10918 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10919 (setq txt (replace-match "" t t txt)))
10920 (if (string-match "\\s-+\\'" txt)
10921 (setq txt (replace-match "" t t txt)))
10922 (setq lines (org-split-string txt "\n"))
10923 (when (and note (string-match "\\S-" note))
10924 (setq note
10925 (org-replace-escapes
10926 note
10927 (list (cons "%u" (user-login-name))
10928 (cons "%U" user-full-name)
10929 (cons "%t" (format-time-string
10930 (org-time-stamp-format 'long 'inactive)
10931 (current-time)))
10932 (cons "%s" (if org-log-note-state
10933 (concat "\"" org-log-note-state "\"")
10934 ""))
10935 (cons "%S" (if org-log-note-previous-state
10936 (concat "\"" org-log-note-previous-state "\"")
10937 "\"\"")))))
10938 (if lines (setq note (concat note " \\\\")))
10939 (push note lines))
10940 (when (or current-prefix-arg org-note-abort)
10941 (when org-log-into-drawer
10942 (org-remove-empty-drawer-at
10943 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10944 org-log-note-marker))
10945 (setq lines nil))
10946 (when lines
10947 (with-current-buffer (marker-buffer org-log-note-marker)
10948 (save-excursion
10949 (goto-char org-log-note-marker)
10950 (move-marker org-log-note-marker nil)
10951 (end-of-line 1)
10952 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10953 (insert "- " (pop lines))
10954 (org-indent-line-function)
10955 (beginning-of-line 1)
10956 (looking-at "[ \t]*")
10957 (setq ind (concat (match-string 0) " "))
10958 (end-of-line 1)
10959 (while lines (insert "\n" ind (pop lines)))
10960 (message "Note stored")
10961 (org-back-to-heading t)
10962 (org-cycle-hide-drawers 'children)))))
10963 (set-window-configuration org-log-note-window-configuration)
10964 (with-current-buffer (marker-buffer org-log-note-return-to)
10965 (goto-char org-log-note-return-to))
10966 (move-marker org-log-note-return-to nil)
10967 (and org-log-post-message (message "%s" org-log-post-message)))
10969 (defun org-remove-empty-drawer-at (drawer pos)
10970 "Remove an empty drawer DRAWER at position POS.
10971 POS may also be a marker."
10972 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10973 (save-excursion
10974 (save-restriction
10975 (widen)
10976 (goto-char pos)
10977 (if (org-in-regexp
10978 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10979 (replace-match ""))))))
10981 (defun org-sparse-tree (&optional arg)
10982 "Create a sparse tree, prompt for the details.
10983 This command can create sparse trees. You first need to select the type
10984 of match used to create the tree:
10986 t Show entries with a specific TODO keyword.
10987 m Show entries selected by a tags/property match.
10988 p Enter a property name and its value (both with completion on existing
10989 names/values) and show entries with that property.
10990 / Show entries matching a regular expression (`r' can be used as well)
10991 d Show deadlines due within `org-deadline-warning-days'.
10992 b Show deadlines and scheduled items before a date.
10993 a Show deadlines and scheduled items after a date."
10994 (interactive "P")
10995 (let (ans kwd value)
10996 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10997 (setq ans (read-char-exclusive))
10998 (cond
10999 ((equal ans ?d)
11000 (call-interactively 'org-check-deadlines))
11001 ((equal ans ?b)
11002 (call-interactively 'org-check-before-date))
11003 ((equal ans ?a)
11004 (call-interactively 'org-check-after-date))
11005 ((equal ans ?t)
11006 (org-show-todo-tree '(4)))
11007 ((member ans '(?T ?m))
11008 (call-interactively 'org-match-sparse-tree))
11009 ((member ans '(?p ?P))
11010 (setq kwd (org-icompleting-read "Property: "
11011 (mapcar 'list (org-buffer-property-keys))))
11012 (setq value (org-icompleting-read "Value: "
11013 (mapcar 'list (org-property-values kwd))))
11014 (unless (string-match "\\`{.*}\\'" value)
11015 (setq value (concat "\"" value "\"")))
11016 (org-match-sparse-tree arg (concat kwd "=" value)))
11017 ((member ans '(?r ?R ?/))
11018 (call-interactively 'org-occur))
11019 (t (error "No such sparse tree command \"%c\"" ans)))))
11021 (defvar org-occur-highlights nil
11022 "List of overlays used for occur matches.")
11023 (make-variable-buffer-local 'org-occur-highlights)
11024 (defvar org-occur-parameters nil
11025 "Parameters of the active org-occur calls.
11026 This is a list, each call to org-occur pushes as cons cell,
11027 containing the regular expression and the callback, onto the list.
11028 The list can contain several entries if `org-occur' has been called
11029 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11030 will only contain one set of parameters. When the highlights are
11031 removed (for example with `C-c C-c', or with the next edit (depending
11032 on `org-remove-highlights-with-change'), this variable is emptied
11033 as well.")
11034 (make-variable-buffer-local 'org-occur-parameters)
11036 (defun org-occur (regexp &optional keep-previous callback)
11037 "Make a compact tree which shows all matches of REGEXP.
11038 The tree will show the lines where the regexp matches, and all higher
11039 headlines above the match. It will also show the heading after the match,
11040 to make sure editing the matching entry is easy.
11041 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11042 call to `org-occur' will be kept, to allow stacking of calls to this
11043 command.
11044 If CALLBACK is non-nil, it is a function which is called to confirm
11045 that the match should indeed be shown."
11046 (interactive "sRegexp: \nP")
11047 (when (equal regexp "")
11048 (error "Regexp cannot be empty"))
11049 (unless keep-previous
11050 (org-remove-occur-highlights nil nil t))
11051 (push (cons regexp callback) org-occur-parameters)
11052 (let ((cnt 0))
11053 (save-excursion
11054 (goto-char (point-min))
11055 (if (or (not keep-previous) ; do not want to keep
11056 (not org-occur-highlights)) ; no previous matches
11057 ;; hide everything
11058 (org-overview))
11059 (while (re-search-forward regexp nil t)
11060 (when (or (not callback)
11061 (save-match-data (funcall callback)))
11062 (setq cnt (1+ cnt))
11063 (when org-highlight-sparse-tree-matches
11064 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11065 (org-show-context 'occur-tree))))
11066 (when org-remove-highlights-with-change
11067 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11068 nil 'local))
11069 (unless org-sparse-tree-open-archived-trees
11070 (org-hide-archived-subtrees (point-min) (point-max)))
11071 (run-hooks 'org-occur-hook)
11072 (if (interactive-p)
11073 (message "%d match(es) for regexp %s" cnt regexp))
11074 cnt))
11076 (defun org-show-context (&optional key)
11077 "Make sure point and context and visible.
11078 How much context is shown depends upon the variables
11079 `org-show-hierarchy-above', `org-show-following-heading'. and
11080 `org-show-siblings'."
11081 (let ((heading-p (org-on-heading-p t))
11082 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11083 (following-p (org-get-alist-option org-show-following-heading key))
11084 (entry-p (org-get-alist-option org-show-entry-below key))
11085 (siblings-p (org-get-alist-option org-show-siblings key)))
11086 (catch 'exit
11087 ;; Show heading or entry text
11088 (if (and heading-p (not entry-p))
11089 (org-flag-heading nil) ; only show the heading
11090 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11091 (org-show-hidden-entry))) ; show entire entry
11092 (when following-p
11093 ;; Show next sibling, or heading below text
11094 (save-excursion
11095 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11096 (org-flag-heading nil))))
11097 (when siblings-p (org-show-siblings))
11098 (when hierarchy-p
11099 ;; show all higher headings, possibly with siblings
11100 (save-excursion
11101 (while (and (condition-case nil
11102 (progn (org-up-heading-all 1) t)
11103 (error nil))
11104 (not (bobp)))
11105 (org-flag-heading nil)
11106 (when siblings-p (org-show-siblings))))))))
11108 (defun org-reveal (&optional siblings)
11109 "Show current entry, hierarchy above it, and the following headline.
11110 This can be used to show a consistent set of context around locations
11111 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11112 not t for the search context.
11114 With optional argument SIBLINGS, on each level of the hierarchy all
11115 siblings are shown. This repairs the tree structure to what it would
11116 look like when opened with hierarchical calls to `org-cycle'."
11117 (interactive "P")
11118 (let ((org-show-hierarchy-above t)
11119 (org-show-following-heading t)
11120 (org-show-siblings (if siblings t org-show-siblings)))
11121 (org-show-context nil)))
11123 (defun org-highlight-new-match (beg end)
11124 "Highlight from BEG to END and mark the highlight is an occur headline."
11125 (let ((ov (org-make-overlay beg end)))
11126 (org-overlay-put ov 'face 'secondary-selection)
11127 (push ov org-occur-highlights)))
11129 (defun org-remove-occur-highlights (&optional beg end noremove)
11130 "Remove the occur highlights from the buffer.
11131 BEG and END are ignored. If NOREMOVE is nil, remove this function
11132 from the `before-change-functions' in the current buffer."
11133 (interactive)
11134 (unless org-inhibit-highlight-removal
11135 (mapc 'org-delete-overlay org-occur-highlights)
11136 (setq org-occur-highlights nil)
11137 (setq org-occur-parameters nil)
11138 (unless noremove
11139 (remove-hook 'before-change-functions
11140 'org-remove-occur-highlights 'local))))
11142 ;;;; Priorities
11144 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11145 "Regular expression matching the priority indicator.")
11147 (defvar org-remove-priority-next-time nil)
11149 (defun org-priority-up ()
11150 "Increase the priority of the current item."
11151 (interactive)
11152 (org-priority 'up))
11154 (defun org-priority-down ()
11155 "Decrease the priority of the current item."
11156 (interactive)
11157 (org-priority 'down))
11159 (defun org-priority (&optional action)
11160 "Change the priority of an item by ARG.
11161 ACTION can be `set', `up', `down', or a character."
11162 (interactive)
11163 (unless org-enable-priority-commands
11164 (error "Priority commands are disabled"))
11165 (setq action (or action 'set))
11166 (let (current new news have remove)
11167 (save-excursion
11168 (org-back-to-heading t)
11169 (if (looking-at org-priority-regexp)
11170 (setq current (string-to-char (match-string 2))
11171 have t)
11172 (setq current org-default-priority))
11173 (cond
11174 ((eq action 'remove)
11175 (setq remove t new ?\ ))
11176 ((or (eq action 'set)
11177 (if (featurep 'xemacs) (characterp action) (integerp action)))
11178 (if (not (eq action 'set))
11179 (setq new action)
11180 (message "Priority %c-%c, SPC to remove: "
11181 org-highest-priority org-lowest-priority)
11182 (setq new (read-char-exclusive)))
11183 (if (and (= (upcase org-highest-priority) org-highest-priority)
11184 (= (upcase org-lowest-priority) org-lowest-priority))
11185 (setq new (upcase new)))
11186 (cond ((equal new ?\ ) (setq remove t))
11187 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11188 (error "Priority must be between `%c' and `%c'"
11189 org-highest-priority org-lowest-priority))))
11190 ((eq action 'up)
11191 (if (and (not have) (eq last-command this-command))
11192 (setq new org-lowest-priority)
11193 (setq new (if (and org-priority-start-cycle-with-default (not have))
11194 org-default-priority (1- current)))))
11195 ((eq action 'down)
11196 (if (and (not have) (eq last-command this-command))
11197 (setq new org-highest-priority)
11198 (setq new (if (and org-priority-start-cycle-with-default (not have))
11199 org-default-priority (1+ current)))))
11200 (t (error "Invalid action")))
11201 (if (or (< (upcase new) org-highest-priority)
11202 (> (upcase new) org-lowest-priority))
11203 (setq remove t))
11204 (setq news (format "%c" new))
11205 (if have
11206 (if remove
11207 (replace-match "" t t nil 1)
11208 (replace-match news t t nil 2))
11209 (if remove
11210 (error "No priority cookie found in line")
11211 (let ((case-fold-search nil))
11212 (looking-at org-todo-line-regexp))
11213 (if (match-end 2)
11214 (progn
11215 (goto-char (match-end 2))
11216 (insert " [#" news "]"))
11217 (goto-char (match-beginning 3))
11218 (insert "[#" news "] "))))
11219 (org-preserve-lc (org-set-tags nil 'align)))
11220 (if remove
11221 (message "Priority removed")
11222 (message "Priority of current item set to %s" news))))
11224 (defun org-get-priority (s)
11225 "Find priority cookie and return priority."
11226 (save-match-data
11227 (if (not (string-match org-priority-regexp s))
11228 (* 1000 (- org-lowest-priority org-default-priority))
11229 (* 1000 (- org-lowest-priority
11230 (string-to-char (match-string 2 s)))))))
11232 ;;;; Tags
11234 (defvar org-agenda-archives-mode)
11235 (defvar org-map-continue-from nil
11236 "Position from where mapping should continue.
11237 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11239 (defvar org-scanner-tags nil
11240 "The current tag list while the tags scanner is running.")
11241 (defvar org-trust-scanner-tags nil
11242 "Should `org-get-tags-at' use the tags fro the scanner.
11243 This is for internal dynamical scoping only.
11244 When this is non-nil, the function `org-get-tags-at' will return the value
11245 of `org-scanner-tags' instead of building the list by itself. This
11246 can lead to large speed-ups when the tags scanner is used in a file with
11247 many entries, and when the list of tags is retrieved, for example to
11248 obtain a list of properties. Building the tags list for each entry in such
11249 a file becomes an N^2 operation - but with this variable set, it scales
11250 as N.")
11252 (defun org-scan-tags (action matcher &optional todo-only)
11253 "Scan headline tags with inheritance and produce output ACTION.
11255 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11256 or `agenda' to produce an entry list for an agenda view. It can also be
11257 a Lisp form or a function that should be called at each matched headline, in
11258 this case the return value is a list of all return values from these calls.
11260 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11261 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11262 only lines with a TODO keyword are included in the output."
11263 (require 'org-agenda)
11264 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11265 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11266 (org-re
11267 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11268 (props (list 'face 'default
11269 'done-face 'org-agenda-done
11270 'undone-face 'default
11271 'mouse-face 'highlight
11272 'org-not-done-regexp org-not-done-regexp
11273 'org-todo-regexp org-todo-regexp
11274 'help-echo
11275 (format "mouse-2 or RET jump to org file %s"
11276 (abbreviate-file-name
11277 (or (buffer-file-name (buffer-base-buffer))
11278 (buffer-name (buffer-base-buffer)))))))
11279 (case-fold-search nil)
11280 (org-map-continue-from nil)
11281 lspos tags tags-list
11282 (tags-alist (list (cons 0 org-file-tags)))
11283 (llast 0) rtn rtn1 level category i txt
11284 todo marker entry priority)
11285 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11286 (setq action (list 'lambda nil action)))
11287 (save-excursion
11288 (goto-char (point-min))
11289 (when (eq action 'sparse-tree)
11290 (org-overview)
11291 (org-remove-occur-highlights))
11292 (while (re-search-forward re nil t)
11293 (catch :skip
11294 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11295 tags (if (match-end 4) (org-match-string-no-properties 4)))
11296 (goto-char (setq lspos (match-beginning 0)))
11297 (setq level (org-reduced-level (funcall outline-level))
11298 category (org-get-category))
11299 (setq i llast llast level)
11300 ;; remove tag lists from same and sublevels
11301 (while (>= i level)
11302 (when (setq entry (assoc i tags-alist))
11303 (setq tags-alist (delete entry tags-alist)))
11304 (setq i (1- i)))
11305 ;; add the next tags
11306 (when tags
11307 (setq tags (org-split-string tags ":")
11308 tags-alist
11309 (cons (cons level tags) tags-alist)))
11310 ;; compile tags for current headline
11311 (setq tags-list
11312 (if org-use-tag-inheritance
11313 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11314 tags)
11315 org-scanner-tags tags-list)
11316 (when org-use-tag-inheritance
11317 (setcdr (car tags-alist)
11318 (mapcar (lambda (x)
11319 (setq x (copy-sequence x))
11320 (org-add-prop-inherited x))
11321 (cdar tags-alist))))
11322 (when (and tags org-use-tag-inheritance
11323 (or (not (eq t org-use-tag-inheritance))
11324 org-tags-exclude-from-inheritance))
11325 ;; selective inheritance, remove uninherited ones
11326 (setcdr (car tags-alist)
11327 (org-remove-uniherited-tags (cdar tags-alist))))
11328 (when (and (or (not todo-only)
11329 (and (member todo org-not-done-keywords)
11330 (or (not org-agenda-tags-todo-honor-ignore-options)
11331 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11332 (let ((case-fold-search t)) (eval matcher))
11334 (not (member org-archive-tag tags-list))
11335 ;; we have an archive tag, should we use this anyway?
11336 (or (not org-agenda-skip-archived-trees)
11337 (and (eq action 'agenda) org-agenda-archives-mode))))
11338 (unless (eq action 'sparse-tree) (org-agenda-skip))
11340 ;; select this headline
11342 (cond
11343 ((eq action 'sparse-tree)
11344 (and org-highlight-sparse-tree-matches
11345 (org-get-heading) (match-end 0)
11346 (org-highlight-new-match
11347 (match-beginning 0) (match-beginning 1)))
11348 (org-show-context 'tags-tree))
11349 ((eq action 'agenda)
11350 (setq txt (org-format-agenda-item
11352 (concat
11353 (if (eq org-tags-match-list-sublevels 'indented)
11354 (make-string (1- level) ?.) "")
11355 (org-get-heading))
11356 category
11357 tags-list
11359 priority (org-get-priority txt))
11360 (goto-char lspos)
11361 (setq marker (org-agenda-new-marker))
11362 (org-add-props txt props
11363 'org-marker marker 'org-hd-marker marker 'org-category category
11364 'todo-state todo
11365 'priority priority 'type "tagsmatch")
11366 (push txt rtn))
11367 ((functionp action)
11368 (setq org-map-continue-from nil)
11369 (save-excursion
11370 (setq rtn1 (funcall action))
11371 (push rtn1 rtn)))
11372 (t (error "Invalid action")))
11374 ;; if we are to skip sublevels, jump to end of subtree
11375 (unless org-tags-match-list-sublevels
11376 (org-end-of-subtree t)
11377 (backward-char 1))))
11378 ;; Get the correct position from where to continue
11379 (if org-map-continue-from
11380 (goto-char org-map-continue-from)
11381 (and (= (point) lspos) (end-of-line 1)))))
11382 (when (and (eq action 'sparse-tree)
11383 (not org-sparse-tree-open-archived-trees))
11384 (org-hide-archived-subtrees (point-min) (point-max)))
11385 (nreverse rtn)))
11387 (defun org-remove-uniherited-tags (tags)
11388 "Remove all tags that are not inherited from the list TAGS."
11389 (cond
11390 ((eq org-use-tag-inheritance t)
11391 (if org-tags-exclude-from-inheritance
11392 (org-delete-all org-tags-exclude-from-inheritance tags)
11393 tags))
11394 ((not org-use-tag-inheritance) nil)
11395 ((stringp org-use-tag-inheritance)
11396 (delq nil (mapcar
11397 (lambda (x)
11398 (if (and (string-match org-use-tag-inheritance x)
11399 (not (member x org-tags-exclude-from-inheritance)))
11400 x nil))
11401 tags)))
11402 ((listp org-use-tag-inheritance)
11403 (delq nil (mapcar
11404 (lambda (x)
11405 (if (member x org-use-tag-inheritance) x nil))
11406 tags)))))
11408 (defvar todo-only) ;; dynamically scoped
11410 (defun org-match-sparse-tree (&optional todo-only match)
11411 "Create a sparse tree according to tags string MATCH.
11412 MATCH can contain positive and negative selection of tags, like
11413 \"+WORK+URGENT-WITHBOSS\".
11414 If optional argument TODO-ONLY is non-nil, only select lines that are
11415 also TODO lines."
11416 (interactive "P")
11417 (org-prepare-agenda-buffers (list (current-buffer)))
11418 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11420 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11422 (defvar org-cached-props nil)
11423 (defun org-cached-entry-get (pom property)
11424 (if (or (eq t org-use-property-inheritance)
11425 (and (stringp org-use-property-inheritance)
11426 (string-match org-use-property-inheritance property))
11427 (and (listp org-use-property-inheritance)
11428 (member property org-use-property-inheritance)))
11429 ;; Caching is not possible, check it directly
11430 (org-entry-get pom property 'inherit)
11431 ;; Get all properties, so that we can do complicated checks easily
11432 (cdr (assoc property (or org-cached-props
11433 (setq org-cached-props
11434 (org-entry-properties pom)))))))
11436 (defun org-global-tags-completion-table (&optional files)
11437 "Return the list of all tags in all agenda buffer/files."
11438 (save-excursion
11439 (org-uniquify
11440 (delq nil
11441 (apply 'append
11442 (mapcar
11443 (lambda (file)
11444 (set-buffer (find-file-noselect file))
11445 (append (org-get-buffer-tags)
11446 (mapcar (lambda (x) (if (stringp (car-safe x))
11447 (list (car-safe x)) nil))
11448 org-tag-alist)))
11449 (if (and files (car files))
11450 files
11451 (org-agenda-files))))))))
11453 (defun org-make-tags-matcher (match)
11454 "Create the TAGS//TODO matcher form for the selection string MATCH."
11455 ;; todo-only is scoped dynamically into this function, and the function
11456 ;; may change it if the matcher asks for it.
11457 (unless match
11458 ;; Get a new match request, with completion
11459 (let ((org-last-tags-completion-table
11460 (org-global-tags-completion-table)))
11461 (setq match (org-completing-read-no-i
11462 "Match: " 'org-tags-completion-function nil nil nil
11463 'org-tags-history))))
11465 ;; Parse the string and create a lisp form
11466 (let ((match0 match)
11467 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11468 minus tag mm
11469 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11470 orterms term orlist re-p str-p level-p level-op time-p
11471 prop-p pn pv po cat-p gv rest)
11472 (if (string-match "/+" match)
11473 ;; match contains also a todo-matching request
11474 (progn
11475 (setq tagsmatch (substring match 0 (match-beginning 0))
11476 todomatch (substring match (match-end 0)))
11477 (if (string-match "^!" todomatch)
11478 (setq todo-only t todomatch (substring todomatch 1)))
11479 (if (string-match "^\\s-*$" todomatch)
11480 (setq todomatch nil)))
11481 ;; only matching tags
11482 (setq tagsmatch match todomatch nil))
11484 ;; Make the tags matcher
11485 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11486 (setq tagsmatcher t)
11487 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11488 (while (setq term (pop orterms))
11489 (while (and (equal (substring term -1) "\\") orterms)
11490 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11491 (while (string-match re term)
11492 (setq rest (substring term (match-end 0))
11493 minus (and (match-end 1)
11494 (equal (match-string 1 term) "-"))
11495 tag (match-string 2 term)
11496 re-p (equal (string-to-char tag) ?{)
11497 level-p (match-end 4)
11498 prop-p (match-end 5)
11499 mm (cond
11500 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11501 (level-p
11502 (setq level-op (org-op-to-function (match-string 3 term)))
11503 `(,level-op level ,(string-to-number
11504 (match-string 4 term))))
11505 (prop-p
11506 (setq pn (match-string 5 term)
11507 po (match-string 6 term)
11508 pv (match-string 7 term)
11509 cat-p (equal pn "CATEGORY")
11510 re-p (equal (string-to-char pv) ?{)
11511 str-p (equal (string-to-char pv) ?\")
11512 time-p (save-match-data
11513 (string-match "^\"[[<].*[]>]\"$" pv))
11514 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11515 (if time-p (setq pv (org-matcher-time pv)))
11516 (setq po (org-op-to-function po (if time-p 'time str-p)))
11517 (cond
11518 ((equal pn "CATEGORY")
11519 (setq gv '(get-text-property (point) 'org-category)))
11520 ((equal pn "TODO")
11521 (setq gv 'todo))
11523 (setq gv `(org-cached-entry-get nil ,pn))))
11524 (if re-p
11525 (if (eq po 'org<>)
11526 `(not (string-match ,pv (or ,gv "")))
11527 `(string-match ,pv (or ,gv "")))
11528 (if str-p
11529 `(,po (or ,gv "") ,pv)
11530 `(,po (string-to-number (or ,gv ""))
11531 ,(string-to-number pv) ))))
11532 (t `(member ,tag tags-list)))
11533 mm (if minus (list 'not mm) mm)
11534 term rest)
11535 (push mm tagsmatcher))
11536 (push (if (> (length tagsmatcher) 1)
11537 (cons 'and tagsmatcher)
11538 (car tagsmatcher))
11539 orlist)
11540 (setq tagsmatcher nil))
11541 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11542 (setq tagsmatcher
11543 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11544 ;; Make the todo matcher
11545 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11546 (setq todomatcher t)
11547 (setq orterms (org-split-string todomatch "|") orlist nil)
11548 (while (setq term (pop orterms))
11549 (while (string-match re term)
11550 (setq minus (and (match-end 1)
11551 (equal (match-string 1 term) "-"))
11552 kwd (match-string 2 term)
11553 re-p (equal (string-to-char kwd) ?{)
11554 term (substring term (match-end 0))
11555 mm (if re-p
11556 `(string-match ,(substring kwd 1 -1) todo)
11557 (list 'equal 'todo kwd))
11558 mm (if minus (list 'not mm) mm))
11559 (push mm todomatcher))
11560 (push (if (> (length todomatcher) 1)
11561 (cons 'and todomatcher)
11562 (car todomatcher))
11563 orlist)
11564 (setq todomatcher nil))
11565 (setq todomatcher (if (> (length orlist) 1)
11566 (cons 'or orlist) (car orlist))))
11568 ;; Return the string and lisp forms of the matcher
11569 (setq matcher (if todomatcher
11570 (list 'and tagsmatcher todomatcher)
11571 tagsmatcher))
11572 (cons match0 matcher)))
11574 (defun org-op-to-function (op &optional stringp)
11575 "Turn an operator into the appropriate function."
11576 (setq op
11577 (cond
11578 ((equal op "<" ) '(< string< org-time<))
11579 ((equal op ">" ) '(> org-string> org-time>))
11580 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11581 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11582 ((member op '("=" "==")) '(= string= org-time=))
11583 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11584 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11586 (defun org<> (a b) (not (= a b)))
11587 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11588 (defun org-string>= (a b) (not (string< a b)))
11589 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11590 (defun org-string<> (a b) (not (string= a b)))
11591 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11592 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11593 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11594 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11595 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11596 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11597 (defun org-2ft (s)
11598 "Convert S to a floating point time.
11599 If S is already a number, just return it. If it is a string, parse
11600 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11601 (cond
11602 ((numberp s) s)
11603 ((stringp s)
11604 (condition-case nil
11605 (float-time (apply 'encode-time (org-parse-time-string s)))
11606 (error 0.)))
11607 (t 0.)))
11609 (defun org-time-today ()
11610 "Time in seconds today at 0:00.
11611 Returns the float number of seconds since the beginning of the
11612 epoch to the beginning of today (00:00)."
11613 (float-time (apply 'encode-time
11614 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11616 (defun org-matcher-time (s)
11617 "Interpret a time comparison value."
11618 (save-match-data
11619 (cond
11620 ((string= s "<now>") (float-time))
11621 ((string= s "<today>") (org-time-today))
11622 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11623 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11624 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11625 (+ (org-time-today)
11626 (* (string-to-number (match-string 1 s))
11627 (cdr (assoc (match-string 2 s)
11628 '(("d" . 86400.0) ("w" . 604800.0)
11629 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11630 (t (org-2ft s)))))
11632 (defun org-match-any-p (re list)
11633 "Does re match any element of list?"
11634 (setq list (mapcar (lambda (x) (string-match re x)) list))
11635 (delq nil list))
11637 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11638 (defvar org-tags-overlay (org-make-overlay 1 1))
11639 (org-detach-overlay org-tags-overlay)
11641 (defun org-get-local-tags-at (&optional pos)
11642 "Get a list of tags defined in the current headline."
11643 (org-get-tags-at pos 'local))
11645 (defun org-get-local-tags ()
11646 "Get a list of tags defined in the current headline."
11647 (org-get-tags-at nil 'local))
11649 (defun org-get-tags-at (&optional pos local)
11650 "Get a list of all headline tags applicable at POS.
11651 POS defaults to point. If tags are inherited, the list contains
11652 the targets in the same sequence as the headlines appear, i.e.
11653 the tags of the current headline come last.
11654 When LOCAL is non-nil, only return tags from the current headline,
11655 ignore inherited ones."
11656 (interactive)
11657 (if (and org-trust-scanner-tags
11658 (or (not pos) (equal pos (point)))
11659 (not local))
11660 org-scanner-tags
11661 (let (tags ltags lastpos parent)
11662 (save-excursion
11663 (save-restriction
11664 (widen)
11665 (goto-char (or pos (point)))
11666 (save-match-data
11667 (catch 'done
11668 (condition-case nil
11669 (progn
11670 (org-back-to-heading t)
11671 (while (not (equal lastpos (point)))
11672 (setq lastpos (point))
11673 (when (looking-at
11674 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11675 (setq ltags (org-split-string
11676 (org-match-string-no-properties 1) ":"))
11677 (when parent
11678 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11679 (setq tags (append
11680 (if parent
11681 (org-remove-uniherited-tags ltags)
11682 ltags)
11683 tags)))
11684 (or org-use-tag-inheritance (throw 'done t))
11685 (if local (throw 'done t))
11686 (or (org-up-heading-safe) (error nil))
11687 (setq parent t)))
11688 (error nil)))))
11689 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11691 (defun org-add-prop-inherited (s)
11692 (add-text-properties 0 (length s) '(inherited t) s)
11695 (defun org-toggle-tag (tag &optional onoff)
11696 "Toggle the tag TAG for the current line.
11697 If ONOFF is `on' or `off', don't toggle but set to this state."
11698 (let (res current)
11699 (save-excursion
11700 (org-back-to-heading t)
11701 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11702 (point-at-eol) t)
11703 (progn
11704 (setq current (match-string 1))
11705 (replace-match ""))
11706 (setq current ""))
11707 (setq current (nreverse (org-split-string current ":")))
11708 (cond
11709 ((eq onoff 'on)
11710 (setq res t)
11711 (or (member tag current) (push tag current)))
11712 ((eq onoff 'off)
11713 (or (not (member tag current)) (setq current (delete tag current))))
11714 (t (if (member tag current)
11715 (setq current (delete tag current))
11716 (setq res t)
11717 (push tag current))))
11718 (end-of-line 1)
11719 (if current
11720 (progn
11721 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11722 (org-set-tags nil t))
11723 (delete-horizontal-space))
11724 (run-hooks 'org-after-tags-change-hook))
11725 res))
11727 (defun org-align-tags-here (to-col)
11728 ;; Assumes that this is a headline
11729 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11730 (beginning-of-line 1)
11731 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11732 (< pos (match-beginning 2)))
11733 (progn
11734 (setq tags-l (- (match-end 2) (match-beginning 2)))
11735 (goto-char (match-beginning 1))
11736 (insert " ")
11737 (delete-region (point) (1+ (match-beginning 2)))
11738 (setq ncol (max (1+ (current-column))
11739 (1+ col)
11740 (if (> to-col 0)
11741 to-col
11742 (- (abs to-col) tags-l))))
11743 (setq p (point))
11744 (insert (make-string (- ncol (current-column)) ?\ ))
11745 (setq ncol (current-column))
11746 (when indent-tabs-mode (tabify p (point-at-eol)))
11747 (org-move-to-column (min ncol col) t))
11748 (goto-char pos))))
11750 (defun org-set-tags-command (&optional arg just-align)
11751 "Call the set-tags command for the current entry."
11752 (interactive "P")
11753 (if (org-on-heading-p)
11754 (org-set-tags arg just-align)
11755 (save-excursion
11756 (org-back-to-heading t)
11757 (org-set-tags arg just-align))))
11759 (defun org-set-tags-to (data)
11760 "Set the tags of the current entry to DATA, replacing the current tags.
11761 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11762 If DATA is nil or the empty string, any tags will be removed."
11763 (interactive "sTags: ")
11764 (setq data
11765 (cond
11766 ((eq data nil) "")
11767 ((equal data "") "")
11768 ((stringp data)
11769 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11770 ":"))
11771 ((listp data)
11772 (concat ":" (mapconcat 'identity data ":") ":"))
11773 (t nil)))
11774 (when data
11775 (save-excursion
11776 (org-back-to-heading t)
11777 (when (looking-at org-complex-heading-regexp)
11778 (if (match-end 5)
11779 (progn
11780 (goto-char (match-beginning 5))
11781 (insert data)
11782 (delete-region (point) (point-at-eol))
11783 (org-set-tags nil 'align))
11784 (goto-char (point-at-eol))
11785 (insert " " data)
11786 (org-set-tags nil 'align)))
11787 (beginning-of-line 1)
11788 (if (looking-at ".*?\\([ \t]+\\)$")
11789 (delete-region (match-beginning 1) (match-end 1))))))
11791 (defun org-set-tags (&optional arg just-align)
11792 "Set the tags for the current headline.
11793 With prefix ARG, realign all tags in headings in the current buffer."
11794 (interactive "P")
11795 (let* ((re (concat "^" outline-regexp))
11796 (current (org-get-tags-string))
11797 (col (current-column))
11798 (org-setting-tags t)
11799 table current-tags inherited-tags ; computed below when needed
11800 tags p0 c0 c1 rpl)
11801 (if arg
11802 (save-excursion
11803 (goto-char (point-min))
11804 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11805 (while (re-search-forward re nil t)
11806 (org-set-tags nil t)
11807 (end-of-line 1)))
11808 (message "All tags realigned to column %d" org-tags-column))
11809 (if just-align
11810 (setq tags current)
11811 ;; Get a new set of tags from the user
11812 (save-excursion
11813 (setq table (append org-tag-persistent-alist
11814 (or org-tag-alist (org-get-buffer-tags))
11815 (and org-complete-tags-always-offer-all-agenda-tags
11816 (org-global-tags-completion-table (org-agenda-files))))
11817 org-last-tags-completion-table table
11818 current-tags (org-split-string current ":")
11819 inherited-tags (nreverse
11820 (nthcdr (length current-tags)
11821 (nreverse (org-get-tags-at))))
11822 tags
11823 (if (or (eq t org-use-fast-tag-selection)
11824 (and org-use-fast-tag-selection
11825 (delq nil (mapcar 'cdr table))))
11826 (org-fast-tag-selection
11827 current-tags inherited-tags table
11828 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11829 (let ((org-add-colon-after-tag-completion t))
11830 (org-trim
11831 (org-without-partial-completion
11832 (org-icompleting-read "Tags: " 'org-tags-completion-function
11833 nil nil current 'org-tags-history)))))))
11834 (while (string-match "[-+&]+" tags)
11835 ;; No boolean logic, just a list
11836 (setq tags (replace-match ":" t t tags))))
11838 (if org-tags-sort-function
11839 (setq tags (mapconcat 'identity
11840 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11841 org-tags-sort-function) ":")))
11843 (if (string-match "\\`[\t ]*\\'" tags)
11844 (setq tags "")
11845 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11846 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11848 ;; Insert new tags at the correct column
11849 (beginning-of-line 1)
11850 (cond
11851 ((and (equal current "") (equal tags "")))
11852 ((re-search-forward
11853 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11854 (point-at-eol) t)
11855 (if (equal tags "")
11856 (setq rpl "")
11857 (goto-char (match-beginning 0))
11858 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11859 (1+ (point)) (point))
11860 c1 (max (1+ c0) (if (> org-tags-column 0)
11861 org-tags-column
11862 (- (- org-tags-column) (length tags))))
11863 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11864 (replace-match rpl t t)
11865 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11866 tags)
11867 (t (error "Tags alignment failed")))
11868 (org-move-to-column col)
11869 (unless just-align
11870 (run-hooks 'org-after-tags-change-hook)))))
11872 (defun org-change-tag-in-region (beg end tag off)
11873 "Add or remove TAG for each entry in the region.
11874 This works in the agenda, and also in an org-mode buffer."
11875 (interactive
11876 (list (region-beginning) (region-end)
11877 (let ((org-last-tags-completion-table
11878 (if (org-mode-p)
11879 (org-get-buffer-tags)
11880 (org-global-tags-completion-table))))
11881 (org-icompleting-read
11882 "Tag: " 'org-tags-completion-function nil nil nil
11883 'org-tags-history))
11884 (progn
11885 (message "[s]et or [r]emove? ")
11886 (equal (read-char-exclusive) ?r))))
11887 (if (fboundp 'deactivate-mark) (deactivate-mark))
11888 (let ((agendap (equal major-mode 'org-agenda-mode))
11889 l1 l2 m buf pos newhead (cnt 0))
11890 (goto-char end)
11891 (setq l2 (1- (org-current-line)))
11892 (goto-char beg)
11893 (setq l1 (org-current-line))
11894 (loop for l from l1 to l2 do
11895 (org-goto-line l)
11896 (setq m (get-text-property (point) 'org-hd-marker))
11897 (when (or (and (org-mode-p) (org-on-heading-p))
11898 (and agendap m))
11899 (setq buf (if agendap (marker-buffer m) (current-buffer))
11900 pos (if agendap m (point)))
11901 (with-current-buffer buf
11902 (save-excursion
11903 (save-restriction
11904 (goto-char pos)
11905 (setq cnt (1+ cnt))
11906 (org-toggle-tag tag (if off 'off 'on))
11907 (setq newhead (org-get-heading)))))
11908 (and agendap (org-agenda-change-all-lines newhead m))))
11909 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11911 (defun org-tags-completion-function (string predicate &optional flag)
11912 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11913 (confirm (lambda (x) (stringp (car x)))))
11914 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11915 (setq s1 (match-string 1 string)
11916 s2 (match-string 2 string))
11917 (setq s1 "" s2 string))
11918 (cond
11919 ((eq flag nil)
11920 ;; try completion
11921 (setq rtn (try-completion s2 ctable confirm))
11922 (if (stringp rtn)
11923 (setq rtn
11924 (concat s1 s2 (substring rtn (length s2))
11925 (if (and org-add-colon-after-tag-completion
11926 (assoc rtn ctable))
11927 ":" ""))))
11928 rtn)
11929 ((eq flag t)
11930 ;; all-completions
11931 (all-completions s2 ctable confirm)
11933 ((eq flag 'lambda)
11934 ;; exact match?
11935 (assoc s2 ctable)))
11938 (defun org-fast-tag-insert (kwd tags face &optional end)
11939 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11940 (insert (format "%-12s" (concat kwd ":"))
11941 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11942 (or end "")))
11944 (defun org-fast-tag-show-exit (flag)
11945 (save-excursion
11946 (org-goto-line 3)
11947 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11948 (replace-match ""))
11949 (when flag
11950 (end-of-line 1)
11951 (org-move-to-column (- (window-width) 19) t)
11952 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11954 (defun org-set-current-tags-overlay (current prefix)
11955 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11956 (if (featurep 'xemacs)
11957 (org-overlay-display org-tags-overlay (concat prefix s)
11958 'secondary-selection)
11959 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11960 (org-overlay-display org-tags-overlay (concat prefix s)))))
11962 (defvar org-last-tag-selection-key nil)
11963 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11964 "Fast tag selection with single keys.
11965 CURRENT is the current list of tags in the headline, INHERITED is the
11966 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11967 possibly with grouping information. TODO-TABLE is a similar table with
11968 TODO keywords, should these have keys assigned to them.
11969 If the keys are nil, a-z are automatically assigned.
11970 Returns the new tags string, or nil to not change the current settings."
11971 (let* ((fulltable (append table todo-table))
11972 (maxlen (apply 'max (mapcar
11973 (lambda (x)
11974 (if (stringp (car x)) (string-width (car x)) 0))
11975 fulltable)))
11976 (buf (current-buffer))
11977 (expert (eq org-fast-tag-selection-single-key 'expert))
11978 (buffer-tags nil)
11979 (fwidth (+ maxlen 3 1 3))
11980 (ncol (/ (- (window-width) 4) fwidth))
11981 (i-face 'org-done)
11982 (c-face 'org-todo)
11983 tg cnt e c char c1 c2 ntable tbl rtn
11984 ov-start ov-end ov-prefix
11985 (exit-after-next org-fast-tag-selection-single-key)
11986 (done-keywords org-done-keywords)
11987 groups ingroup)
11988 (save-excursion
11989 (beginning-of-line 1)
11990 (if (looking-at
11991 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11992 (setq ov-start (match-beginning 1)
11993 ov-end (match-end 1)
11994 ov-prefix "")
11995 (setq ov-start (1- (point-at-eol))
11996 ov-end (1+ ov-start))
11997 (skip-chars-forward "^\n\r")
11998 (setq ov-prefix
11999 (concat
12000 (buffer-substring (1- (point)) (point))
12001 (if (> (current-column) org-tags-column)
12003 (make-string (- org-tags-column (current-column)) ?\ ))))))
12004 (org-move-overlay org-tags-overlay ov-start ov-end)
12005 (save-window-excursion
12006 (if expert
12007 (set-buffer (get-buffer-create " *Org tags*"))
12008 (delete-other-windows)
12009 (split-window-vertically)
12010 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12011 (erase-buffer)
12012 (org-set-local 'org-done-keywords done-keywords)
12013 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12014 (org-fast-tag-insert "Current" current c-face "\n\n")
12015 (org-fast-tag-show-exit exit-after-next)
12016 (org-set-current-tags-overlay current ov-prefix)
12017 (setq tbl fulltable char ?a cnt 0)
12018 (while (setq e (pop tbl))
12019 (cond
12020 ((equal (car e) :startgroup)
12021 (push '() groups) (setq ingroup t)
12022 (when (not (= cnt 0))
12023 (setq cnt 0)
12024 (insert "\n"))
12025 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12026 ((equal (car e) :endgroup)
12027 (setq ingroup nil cnt 0)
12028 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12029 ((equal e '(:newline))
12030 (when (not (= cnt 0))
12031 (setq cnt 0)
12032 (insert "\n")
12033 (setq e (car tbl))
12034 (while (equal (car tbl) '(:newline))
12035 (insert "\n")
12036 (setq tbl (cdr tbl)))))
12038 (setq tg (copy-sequence (car e)) c2 nil)
12039 (if (cdr e)
12040 (setq c (cdr e))
12041 ;; automatically assign a character.
12042 (setq c1 (string-to-char
12043 (downcase (substring
12044 tg (if (= (string-to-char tg) ?@) 1 0)))))
12045 (if (or (rassoc c1 ntable) (rassoc c1 table))
12046 (while (or (rassoc char ntable) (rassoc char table))
12047 (setq char (1+ char)))
12048 (setq c2 c1))
12049 (setq c (or c2 char)))
12050 (if ingroup (push tg (car groups)))
12051 (setq tg (org-add-props tg nil 'face
12052 (cond
12053 ((not (assoc tg table))
12054 (org-get-todo-face tg))
12055 ((member tg current) c-face)
12056 ((member tg inherited) i-face)
12057 (t nil))))
12058 (if (and (= cnt 0) (not ingroup)) (insert " "))
12059 (insert "[" c "] " tg (make-string
12060 (- fwidth 4 (length tg)) ?\ ))
12061 (push (cons tg c) ntable)
12062 (when (= (setq cnt (1+ cnt)) ncol)
12063 (insert "\n")
12064 (if ingroup (insert " "))
12065 (setq cnt 0)))))
12066 (setq ntable (nreverse ntable))
12067 (insert "\n")
12068 (goto-char (point-min))
12069 (if (not expert) (org-fit-window-to-buffer))
12070 (setq rtn
12071 (catch 'exit
12072 (while t
12073 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12074 (if (not groups) "no " "")
12075 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12076 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12077 (setq org-last-tag-selection-key c)
12078 (cond
12079 ((= c ?\r) (throw 'exit t))
12080 ((= c ?!)
12081 (setq groups (not groups))
12082 (goto-char (point-min))
12083 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12084 ((= c ?\C-c)
12085 (if (not expert)
12086 (org-fast-tag-show-exit
12087 (setq exit-after-next (not exit-after-next)))
12088 (setq expert nil)
12089 (delete-other-windows)
12090 (split-window-vertically)
12091 (org-switch-to-buffer-other-window " *Org tags*")
12092 (org-fit-window-to-buffer)))
12093 ((or (= c ?\C-g)
12094 (and (= c ?q) (not (rassoc c ntable))))
12095 (org-detach-overlay org-tags-overlay)
12096 (setq quit-flag t))
12097 ((= c ?\ )
12098 (setq current nil)
12099 (if exit-after-next (setq exit-after-next 'now)))
12100 ((= c ?\t)
12101 (condition-case nil
12102 (setq tg (org-icompleting-read
12103 "Tag: "
12104 (or buffer-tags
12105 (with-current-buffer buf
12106 (org-get-buffer-tags)))))
12107 (quit (setq tg "")))
12108 (when (string-match "\\S-" tg)
12109 (add-to-list 'buffer-tags (list tg))
12110 (if (member tg current)
12111 (setq current (delete tg current))
12112 (push tg current)))
12113 (if exit-after-next (setq exit-after-next 'now)))
12114 ((setq e (rassoc c todo-table) tg (car e))
12115 (with-current-buffer buf
12116 (save-excursion (org-todo tg)))
12117 (if exit-after-next (setq exit-after-next 'now)))
12118 ((setq e (rassoc c ntable) tg (car e))
12119 (if (member tg current)
12120 (setq current (delete tg current))
12121 (loop for g in groups do
12122 (if (member tg g)
12123 (mapc (lambda (x)
12124 (setq current (delete x current)))
12125 g)))
12126 (push tg current))
12127 (if exit-after-next (setq exit-after-next 'now))))
12129 ;; Create a sorted list
12130 (setq current
12131 (sort current
12132 (lambda (a b)
12133 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12134 (if (eq exit-after-next 'now) (throw 'exit t))
12135 (goto-char (point-min))
12136 (beginning-of-line 2)
12137 (delete-region (point) (point-at-eol))
12138 (org-fast-tag-insert "Current" current c-face)
12139 (org-set-current-tags-overlay current ov-prefix)
12140 (while (re-search-forward
12141 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12142 (setq tg (match-string 1))
12143 (add-text-properties
12144 (match-beginning 1) (match-end 1)
12145 (list 'face
12146 (cond
12147 ((member tg current) c-face)
12148 ((member tg inherited) i-face)
12149 (t (get-text-property (match-beginning 1) 'face))))))
12150 (goto-char (point-min)))))
12151 (org-detach-overlay org-tags-overlay)
12152 (if rtn
12153 (mapconcat 'identity current ":")
12154 nil))))
12156 (defun org-get-tags-string ()
12157 "Get the TAGS string in the current headline."
12158 (unless (org-on-heading-p t)
12159 (error "Not on a heading"))
12160 (save-excursion
12161 (beginning-of-line 1)
12162 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12163 (org-match-string-no-properties 1)
12164 "")))
12166 (defun org-get-tags ()
12167 "Get the list of tags specified in the current headline."
12168 (org-split-string (org-get-tags-string) ":"))
12170 (defun org-get-buffer-tags ()
12171 "Get a table of all tags used in the buffer, for completion."
12172 (let (tags)
12173 (save-excursion
12174 (goto-char (point-min))
12175 (while (re-search-forward
12176 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12177 (when (equal (char-after (point-at-bol 0)) ?*)
12178 (mapc (lambda (x) (add-to-list 'tags x))
12179 (org-split-string (org-match-string-no-properties 1) ":")))))
12180 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12181 (mapcar 'list tags)))
12183 ;;;; The mapping API
12185 ;;;###autoload
12186 (defun org-map-entries (func &optional match scope &rest skip)
12187 "Call FUNC at each headline selected by MATCH in SCOPE.
12189 FUNC is a function or a lisp form. The function will be called without
12190 arguments, with the cursor positioned at the beginning of the headline.
12191 The return values of all calls to the function will be collected and
12192 returned as a list.
12194 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12195 does not need to preserve point. After evaluation, the cursor will be
12196 moved to the end of the line (presumably of the headline of the
12197 processed entry) and search continues from there. Under some
12198 circumstances, this may not produce the wanted results. For example,
12199 if you have removed (e.g. archived) the current (sub)tree it could
12200 mean that the next entry will be skipped entirely. In such cases, you
12201 can specify the position from where search should continue by making
12202 FUNC set the variable `org-map-continue-from' to the desired buffer
12203 position.
12205 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12206 Only headlines that are matched by this query will be considered during
12207 the iteration. When MATCH is nil or t, all headlines will be
12208 visited by the iteration.
12210 SCOPE determines the scope of this command. It can be any of:
12212 nil The current buffer, respecting the restriction if any
12213 tree The subtree started with the entry at point
12214 file The current buffer, without restriction
12215 file-with-archives
12216 The current buffer, and any archives associated with it
12217 agenda All agenda files
12218 agenda-with-archives
12219 All agenda files with any archive files associated with them
12220 \(file1 file2 ...)
12221 If this is a list, all files in the list will be scanned
12223 The remaining args are treated as settings for the skipping facilities of
12224 the scanner. The following items can be given here:
12226 archive skip trees with the archive tag.
12227 comment skip trees with the COMMENT keyword
12228 function or Emacs Lisp form:
12229 will be used as value for `org-agenda-skip-function', so whenever
12230 the function returns t, FUNC will not be called for that
12231 entry and search will continue from the point where the
12232 function leaves it.
12234 If your function needs to retrieve the tags including inherited tags
12235 at the *current* entry, you can use the value of the variable
12236 `org-scanner-tags' which will be much faster than getting the value
12237 with `org-get-tags-at'. If your function gets properties with
12238 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12239 to t around the call to `org-entry-properties' to get the same speedup.
12240 Note that if your function moves around to retrieve tags and properties at
12241 a *different* entry, you cannot use these techniques."
12242 (let* ((org-agenda-archives-mode nil) ; just to make sure
12243 (org-agenda-skip-archived-trees (memq 'archive skip))
12244 (org-agenda-skip-comment-trees (memq 'comment skip))
12245 (org-agenda-skip-function
12246 (car (org-delete-all '(comment archive) skip)))
12247 (org-tags-match-list-sublevels t)
12248 matcher file res
12249 org-todo-keywords-for-agenda
12250 org-done-keywords-for-agenda
12251 org-todo-keyword-alist-for-agenda
12252 org-drawers-for-agenda
12253 org-tag-alist-for-agenda)
12255 (cond
12256 ((eq match t) (setq matcher t))
12257 ((eq match nil) (setq matcher t))
12258 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12260 (save-excursion
12261 (save-restriction
12262 (when (eq scope 'tree)
12263 (org-back-to-heading t)
12264 (org-narrow-to-subtree)
12265 (setq scope nil))
12267 (if (not scope)
12268 (progn
12269 (org-prepare-agenda-buffers
12270 (list (buffer-file-name (current-buffer))))
12271 (setq res (org-scan-tags func matcher)))
12272 ;; Get the right scope
12273 (cond
12274 ((and scope (listp scope) (symbolp (car scope)))
12275 (setq scope (eval scope)))
12276 ((eq scope 'agenda)
12277 (setq scope (org-agenda-files t)))
12278 ((eq scope 'agenda-with-archives)
12279 (setq scope (org-agenda-files t))
12280 (setq scope (org-add-archive-files scope)))
12281 ((eq scope 'file)
12282 (setq scope (list (buffer-file-name))))
12283 ((eq scope 'file-with-archives)
12284 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12285 (org-prepare-agenda-buffers scope)
12286 (while (setq file (pop scope))
12287 (with-current-buffer (org-find-base-buffer-visiting file)
12288 (save-excursion
12289 (save-restriction
12290 (widen)
12291 (goto-char (point-min))
12292 (setq res (append res (org-scan-tags func matcher))))))))))
12293 res))
12295 ;;;; Properties
12297 ;;; Setting and retrieving properties
12299 (defconst org-special-properties
12300 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12301 "TIMESTAMP" "TIMESTAMP_IA")
12302 "The special properties valid in Org-mode.
12304 These are properties that are not defined in the property drawer,
12305 but in some other way.")
12307 (defconst org-default-properties
12308 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12309 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12310 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12311 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12312 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12313 "CLOCK_MODELINE_TOTAL" "STYLE")
12314 "Some properties that are used by Org-mode for various purposes.
12315 Being in this list makes sure that they are offered for completion.")
12317 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12318 "Regular expression matching the first line of a property drawer.")
12320 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12321 "Regular expression matching the first line of a property drawer.")
12323 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12324 "Regular expression matching the first line of a property drawer.")
12326 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12327 "Regular expression matching the first line of a property drawer.")
12329 (defconst org-property-drawer-re
12330 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12331 org-property-end-re "\\)\n?")
12332 "Matches an entire property drawer.")
12334 (defconst org-clock-drawer-re
12335 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12336 org-property-end-re "\\)\n?")
12337 "Matches an entire clock drawer.")
12339 (defun org-property-action ()
12340 "Do an action on properties."
12341 (interactive)
12342 (let (c)
12343 (org-at-property-p)
12344 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12345 (setq c (read-char-exclusive))
12346 (cond
12347 ((equal c ?s)
12348 (call-interactively 'org-set-property))
12349 ((equal c ?d)
12350 (call-interactively 'org-delete-property))
12351 ((equal c ?D)
12352 (call-interactively 'org-delete-property-globally))
12353 ((equal c ?c)
12354 (call-interactively 'org-compute-property-at-point))
12355 (t (error "No such property action %c" c)))))
12357 (defun org-set-effort (&optional value)
12358 "Set the effort property of the current entry.
12359 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12360 allowed value."
12361 (interactive "P")
12362 (if (equal value 0) (setq value 10))
12363 (let* ((completion-ignore-case t)
12364 (prop org-effort-property)
12365 (cur (org-entry-get nil prop))
12366 (allowed (org-property-get-allowed-values nil prop 'table))
12367 (existing (mapcar 'list (org-property-values prop)))
12369 (val (cond
12370 ((stringp value) value)
12371 ((and allowed (integerp value))
12372 (or (car (nth (1- value) allowed))
12373 (car (org-last allowed))))
12374 (allowed
12375 (message "Select 1-9,0, [RET%s]: %s"
12376 (if cur (concat "=" cur) "")
12377 (mapconcat 'car allowed " "))
12378 (setq rpl (read-char-exclusive))
12379 (if (equal rpl ?\r)
12381 (setq rpl (- rpl ?0))
12382 (if (equal rpl 0) (setq rpl 10))
12383 (if (and (> rpl 0) (<= rpl (length allowed)))
12384 (car (nth (1- rpl) allowed))
12385 (org-completing-read "Effort: " allowed nil))))
12387 (let (org-completion-use-ido org-completion-use-iswitchb)
12388 (org-completing-read
12389 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12390 (concat "[" cur "]") "")
12391 ": ")
12392 existing nil nil "" nil cur))))))
12393 (unless (equal (org-entry-get nil prop) val)
12394 (org-entry-put nil prop val))
12395 (message "%s is now %s" prop val)))
12397 (defun org-at-property-p ()
12398 "Is the cursor in a property line?"
12399 ;; FIXME: Does not check if we are actually in the drawer.
12400 ;; FIXME: also returns true on any drawers.....
12401 ;; This is used by C-c C-c for property action.
12402 (save-excursion
12403 (beginning-of-line 1)
12404 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12406 (defun org-get-property-block (&optional beg end force)
12407 "Return the (beg . end) range of the body of the property drawer.
12408 BEG and END can be beginning and end of subtree, if not given
12409 they will be found.
12410 If the drawer does not exist and FORCE is non-nil, create the drawer."
12411 (catch 'exit
12412 (save-excursion
12413 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12414 (end (or end (progn (outline-next-heading) (point)))))
12415 (goto-char beg)
12416 (if (re-search-forward org-property-start-re end t)
12417 (setq beg (1+ (match-end 0)))
12418 (if force
12419 (save-excursion
12420 (org-insert-property-drawer)
12421 (setq end (progn (outline-next-heading) (point))))
12422 (throw 'exit nil))
12423 (goto-char beg)
12424 (if (re-search-forward org-property-start-re end t)
12425 (setq beg (1+ (match-end 0)))))
12426 (if (re-search-forward org-property-end-re end t)
12427 (setq end (match-beginning 0))
12428 (or force (throw 'exit nil))
12429 (goto-char beg)
12430 (setq end beg)
12431 (org-indent-line-function)
12432 (insert ":END:\n"))
12433 (cons beg end)))))
12435 (defun org-entry-properties (&optional pom which)
12436 "Get all properties of the entry at point-or-marker POM.
12437 This includes the TODO keyword, the tags, time strings for deadline,
12438 scheduled, and clocking, and any additional properties defined in the
12439 entry. The return value is an alist, keys may occur multiple times
12440 if the property key was used several times.
12441 POM may also be nil, in which case the current entry is used.
12442 If WHICH is nil or `all', get all properties. If WHICH is
12443 `special' or `standard', only get that subclass."
12444 (setq which (or which 'all))
12445 (org-with-point-at pom
12446 (let ((clockstr (substring org-clock-string 0 -1))
12447 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12448 beg end range props sum-props key value string clocksum)
12449 (save-excursion
12450 (when (condition-case nil
12451 (and (org-mode-p) (org-back-to-heading t))
12452 (error nil))
12453 (setq beg (point))
12454 (setq sum-props (get-text-property (point) 'org-summaries))
12455 (setq clocksum (get-text-property (point) :org-clock-minutes))
12456 (outline-next-heading)
12457 (setq end (point))
12458 (when (memq which '(all special))
12459 ;; Get the special properties, like TODO and tags
12460 (goto-char beg)
12461 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12462 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12463 (when (looking-at org-priority-regexp)
12464 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12465 (when (and (setq value (org-get-tags-string))
12466 (string-match "\\S-" value))
12467 (push (cons "TAGS" value) props))
12468 (when (setq value (org-get-tags-at))
12469 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12470 props))
12471 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12472 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12473 string (if (equal key clockstr)
12474 (org-no-properties
12475 (org-trim
12476 (buffer-substring
12477 (match-beginning 3) (goto-char (point-at-eol)))))
12478 (substring (org-match-string-no-properties 3) 1 -1)))
12479 (unless key
12480 (if (= (char-after (match-beginning 3)) ?\[)
12481 (setq key "TIMESTAMP_IA")
12482 (setq key "TIMESTAMP")))
12483 (when (or (equal key clockstr) (not (assoc key props)))
12484 (push (cons key string) props)))
12488 (when (memq which '(all standard))
12489 ;; Get the standard properties, like :PROP: ...
12490 (setq range (org-get-property-block beg end))
12491 (when range
12492 (goto-char (car range))
12493 (while (re-search-forward
12494 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12495 (cdr range) t)
12496 (setq key (org-match-string-no-properties 1)
12497 value (org-trim (or (org-match-string-no-properties 2) "")))
12498 (unless (member key excluded)
12499 (push (cons key (or value "")) props)))))
12500 (if clocksum
12501 (push (cons "CLOCKSUM"
12502 (org-columns-number-to-string (/ (float clocksum) 60.)
12503 'add_times))
12504 props))
12505 (unless (assoc "CATEGORY" props)
12506 (setq value (or (org-get-category)
12507 (progn (org-refresh-category-properties)
12508 (org-get-category))))
12509 (push (cons "CATEGORY" value) props))
12510 (append sum-props (nreverse props)))))))
12512 (defun org-entry-get (pom property &optional inherit)
12513 "Get value of PROPERTY for entry at point-or-marker POM.
12514 If INHERIT is non-nil and the entry does not have the property,
12515 then also check higher levels of the hierarchy.
12516 If INHERIT is the symbol `selective', use inheritance only if the setting
12517 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12518 If the property is present but empty, the return value is the empty string.
12519 If the property is not present at all, nil is returned."
12520 (org-with-point-at pom
12521 (if (and inherit (if (eq inherit 'selective)
12522 (org-property-inherit-p property)
12524 (org-entry-get-with-inheritance property)
12525 (if (member property org-special-properties)
12526 ;; We need a special property. Use brute force, get all properties.
12527 (cdr (assoc property (org-entry-properties nil 'special)))
12528 (let ((range (org-get-property-block)))
12529 (if (and range
12530 (goto-char (car range))
12531 (re-search-forward
12532 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12533 (cdr range) t))
12534 ;; Found the property, return it.
12535 (if (match-end 1)
12536 (org-match-string-no-properties 1)
12537 "")))))))
12539 (defun org-property-or-variable-value (var &optional inherit)
12540 "Check if there is a property fixing the value of VAR.
12541 If yes, return this value. If not, return the current value of the variable."
12542 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12543 (if (and prop (stringp prop) (string-match "\\S-" prop))
12544 (read prop)
12545 (symbol-value var))))
12547 (defun org-entry-delete (pom property)
12548 "Delete the property PROPERTY from entry at point-or-marker POM."
12549 (org-with-point-at pom
12550 (if (member property org-special-properties)
12551 nil ; cannot delete these properties.
12552 (let ((range (org-get-property-block)))
12553 (if (and range
12554 (goto-char (car range))
12555 (re-search-forward
12556 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12557 (cdr range) t))
12558 (progn
12559 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12561 nil)))))
12563 ;; Multi-values properties are properties that contain multiple values
12564 ;; These values are assumed to be single words, separated by whitespace.
12565 (defun org-entry-add-to-multivalued-property (pom property value)
12566 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12567 (let* ((old (org-entry-get pom property))
12568 (values (and old (org-split-string old "[ \t]"))))
12569 (setq value (org-entry-protect-space value))
12570 (unless (member value values)
12571 (setq values (cons value values))
12572 (org-entry-put pom property
12573 (mapconcat 'identity values " ")))))
12575 (defun org-entry-remove-from-multivalued-property (pom property value)
12576 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12577 (let* ((old (org-entry-get pom property))
12578 (values (and old (org-split-string old "[ \t]"))))
12579 (setq value (org-entry-protect-space value))
12580 (when (member value values)
12581 (setq values (delete value values))
12582 (org-entry-put pom property
12583 (mapconcat 'identity values " ")))))
12585 (defun org-entry-member-in-multivalued-property (pom property value)
12586 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12587 (let* ((old (org-entry-get pom property))
12588 (values (and old (org-split-string old "[ \t]"))))
12589 (setq value (org-entry-protect-space value))
12590 (member value values)))
12592 (defun org-entry-get-multivalued-property (pom property)
12593 "Return a list of values in a multivalued property."
12594 (let* ((value (org-entry-get pom property))
12595 (values (and value (org-split-string value "[ \t]"))))
12596 (mapcar 'org-entry-restore-space values)))
12598 (defun org-entry-put-multivalued-property (pom property &rest values)
12599 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12600 VALUES should be a list of strings. Spaces will be protected."
12601 (org-entry-put pom property
12602 (mapconcat 'org-entry-protect-space values " "))
12603 (let* ((value (org-entry-get pom property))
12604 (values (and value (org-split-string value "[ \t]"))))
12605 (mapcar 'org-entry-restore-space values)))
12607 (defun org-entry-protect-space (s)
12608 "Protect spaces and newline in string S."
12609 (while (string-match " " s)
12610 (setq s (replace-match "%20" t t s)))
12611 (while (string-match "\n" s)
12612 (setq s (replace-match "%0A" t t s)))
12615 (defun org-entry-restore-space (s)
12616 "Restore spaces and newline in string S."
12617 (while (string-match "%20" s)
12618 (setq s (replace-match " " t t s)))
12619 (while (string-match "%0A" s)
12620 (setq s (replace-match "\n" t t s)))
12623 (defvar org-entry-property-inherited-from (make-marker)
12624 "Marker pointing to the entry from where a property was inherited.
12625 Each call to `org-entry-get-with-inheritance' will set this marker to the
12626 location of the entry where the inheritance search matched. If there was
12627 no match, the marker will point nowhere.
12628 Note that also `org-entry-get' calls this function, if the INHERIT flag
12629 is set.")
12631 (defun org-entry-get-with-inheritance (property)
12632 "Get entry property, and search higher levels if not present."
12633 (move-marker org-entry-property-inherited-from nil)
12634 (let (tmp)
12635 (save-excursion
12636 (save-restriction
12637 (widen)
12638 (catch 'ex
12639 (while t
12640 (when (setq tmp (org-entry-get nil property))
12641 (org-back-to-heading t)
12642 (move-marker org-entry-property-inherited-from (point))
12643 (throw 'ex tmp))
12644 (or (org-up-heading-safe) (throw 'ex nil)))))
12645 (or tmp
12646 (cdr (assoc property org-file-properties))
12647 (cdr (assoc property org-global-properties))
12648 (cdr (assoc property org-global-properties-fixed))))))
12650 (defvar org-property-changed-functions nil
12651 "Hook called when the value of a property has changed.
12652 Each hook function should accept two arguments, the name of the property
12653 and the new value.")
12655 (defun org-entry-put (pom property value)
12656 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12657 (org-with-point-at pom
12658 (org-back-to-heading t)
12659 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12660 range)
12661 (cond
12662 ((equal property "TODO")
12663 (when (and (stringp value) (string-match "\\S-" value)
12664 (not (member value org-todo-keywords-1)))
12665 (error "\"%s\" is not a valid TODO state" value))
12666 (if (or (not value)
12667 (not (string-match "\\S-" value)))
12668 (setq value 'none))
12669 (org-todo value)
12670 (org-set-tags nil 'align))
12671 ((equal property "PRIORITY")
12672 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12673 (string-to-char value) ?\ ))
12674 (org-set-tags nil 'align))
12675 ((equal property "SCHEDULED")
12676 (if (re-search-forward org-scheduled-time-regexp end t)
12677 (cond
12678 ((eq value 'earlier) (org-timestamp-change -1 'day))
12679 ((eq value 'later) (org-timestamp-change 1 'day))
12680 (t (call-interactively 'org-schedule)))
12681 (call-interactively 'org-schedule)))
12682 ((equal property "DEADLINE")
12683 (if (re-search-forward org-deadline-time-regexp end t)
12684 (cond
12685 ((eq value 'earlier) (org-timestamp-change -1 'day))
12686 ((eq value 'later) (org-timestamp-change 1 'day))
12687 (t (call-interactively 'org-deadline)))
12688 (call-interactively 'org-deadline)))
12689 ((member property org-special-properties)
12690 (error "The %s property can not yet be set with `org-entry-put'"
12691 property))
12692 (t ; a non-special property
12693 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12694 (setq range (org-get-property-block beg end 'force))
12695 (goto-char (car range))
12696 (if (re-search-forward
12697 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12698 (progn
12699 (delete-region (match-beginning 1) (match-end 1))
12700 (goto-char (match-beginning 1)))
12701 (goto-char (cdr range))
12702 (insert "\n")
12703 (backward-char 1)
12704 (org-indent-line-function)
12705 (insert ":" property ":"))
12706 (and value (insert " " value))
12707 (org-indent-line-function)))))
12708 (run-hook-with-args 'org-property-changed-functions property value)))
12710 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12711 "Get all property keys in the current buffer.
12712 With INCLUDE-SPECIALS, also list the special properties that reflect things
12713 like tags and TODO state.
12714 With INCLUDE-DEFAULTS, also include properties that has special meaning
12715 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12716 With INCLUDE-COLUMNS, also include property names given in COLUMN
12717 formats in the current buffer."
12718 (let (rtn range cfmt s p)
12719 (save-excursion
12720 (save-restriction
12721 (widen)
12722 (goto-char (point-min))
12723 (while (re-search-forward org-property-start-re nil t)
12724 (setq range (org-get-property-block))
12725 (goto-char (car range))
12726 (while (re-search-forward
12727 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12728 (cdr range) t)
12729 (add-to-list 'rtn (org-match-string-no-properties 1)))
12730 (outline-next-heading))))
12732 (when include-specials
12733 (setq rtn (append org-special-properties rtn)))
12735 (when include-defaults
12736 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12737 (add-to-list 'rtn org-effort-property))
12739 (when include-columns
12740 (save-excursion
12741 (save-restriction
12742 (widen)
12743 (goto-char (point-min))
12744 (while (re-search-forward
12745 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12746 nil t)
12747 (setq cfmt (match-string 2) s 0)
12748 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12749 cfmt s)
12750 (setq s (match-end 0)
12751 p (match-string 1 cfmt))
12752 (unless (or (equal p "ITEM")
12753 (member p org-special-properties))
12754 (add-to-list 'rtn (match-string 1 cfmt))))))))
12756 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12758 (defun org-property-values (key)
12759 "Return a list of all values of property KEY."
12760 (save-excursion
12761 (save-restriction
12762 (widen)
12763 (goto-char (point-min))
12764 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12765 values)
12766 (while (re-search-forward re nil t)
12767 (add-to-list 'values (org-trim (match-string 1))))
12768 (delete "" values)))))
12770 (defun org-insert-property-drawer ()
12771 "Insert a property drawer into the current entry."
12772 (interactive)
12773 (org-back-to-heading t)
12774 (looking-at outline-regexp)
12775 (let ((indent (if org-adapt-indentation
12776 (- (match-end 0)(match-beginning 0))
12778 (beg (point))
12779 (re (concat "^[ \t]*" org-keyword-time-regexp))
12780 end hiddenp)
12781 (outline-next-heading)
12782 (setq end (point))
12783 (goto-char beg)
12784 (while (re-search-forward re end t))
12785 (setq hiddenp (org-invisible-p))
12786 (end-of-line 1)
12787 (and (equal (char-after) ?\n) (forward-char 1))
12788 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12789 (if (member (match-string 1) '("CLOCK:" ":END:"))
12790 ;; just skip this line
12791 (beginning-of-line 2)
12792 ;; Drawer start, find the end
12793 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12794 (beginning-of-line 1)))
12795 (org-skip-over-state-notes)
12796 (skip-chars-backward " \t\n\r")
12797 (if (eq (char-before) ?*) (forward-char 1))
12798 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12799 (beginning-of-line 0)
12800 (org-indent-to-column indent)
12801 (beginning-of-line 2)
12802 (org-indent-to-column indent)
12803 (beginning-of-line 0)
12804 (if hiddenp
12805 (save-excursion
12806 (org-back-to-heading t)
12807 (hide-entry))
12808 (org-flag-drawer t))))
12810 (defun org-set-property (property value)
12811 "In the current entry, set PROPERTY to VALUE.
12812 When called interactively, this will prompt for a property name, offering
12813 completion on existing and default properties. And then it will prompt
12814 for a value, offering completion either on allowed values (via an inherited
12815 xxx_ALL property) or on existing values in other instances of this property
12816 in the current file."
12817 (interactive
12818 (let* ((completion-ignore-case t)
12819 (keys (org-buffer-property-keys nil t t))
12820 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12821 (prop (if (member prop0 keys)
12822 prop0
12823 (or (cdr (assoc (downcase prop0)
12824 (mapcar (lambda (x) (cons (downcase x) x))
12825 keys)))
12826 prop0)))
12827 (cur (org-entry-get nil prop))
12828 (allowed (org-property-get-allowed-values nil prop 'table))
12829 (existing (mapcar 'list (org-property-values prop)))
12830 (val (if allowed
12831 (org-completing-read "Value: " allowed nil
12832 (not (get-text-property 0 'org-unrestricted
12833 (caar allowed))))
12834 (let (org-completion-use-ido org-completion-use-iswitchb)
12835 (org-completing-read
12836 (concat "Value " (if (and cur (string-match "\\S-" cur))
12837 (concat "[" cur "]") "")
12838 ": ")
12839 existing nil nil "" nil cur)))))
12840 (list prop (if (equal val "") cur val))))
12841 (unless (equal (org-entry-get nil property) value)
12842 (org-entry-put nil property value)))
12844 (defun org-delete-property (property)
12845 "In the current entry, delete PROPERTY."
12846 (interactive
12847 (let* ((completion-ignore-case t)
12848 (prop (org-icompleting-read
12849 "Property: " (org-entry-properties nil 'standard))))
12850 (list prop)))
12851 (message "Property %s %s" property
12852 (if (org-entry-delete nil property)
12853 "deleted"
12854 "was not present in the entry")))
12856 (defun org-delete-property-globally (property)
12857 "Remove PROPERTY globally, from all entries."
12858 (interactive
12859 (let* ((completion-ignore-case t)
12860 (prop (org-icompleting-read
12861 "Globally remove property: "
12862 (mapcar 'list (org-buffer-property-keys)))))
12863 (list prop)))
12864 (save-excursion
12865 (save-restriction
12866 (widen)
12867 (goto-char (point-min))
12868 (let ((cnt 0))
12869 (while (re-search-forward
12870 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12871 nil t)
12872 (setq cnt (1+ cnt))
12873 (replace-match ""))
12874 (message "Property \"%s\" removed from %d entries" property cnt)))))
12876 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12878 (defun org-compute-property-at-point ()
12879 "Compute the property at point.
12880 This looks for an enclosing column format, extracts the operator and
12881 then applies it to the property in the column format's scope."
12882 (interactive)
12883 (unless (org-at-property-p)
12884 (error "Not at a property"))
12885 (let ((prop (org-match-string-no-properties 2)))
12886 (org-columns-get-format-and-top-level)
12887 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12888 (error "No operator defined for property %s" prop))
12889 (org-columns-compute prop)))
12891 (defvar org-property-allowed-value-functions nil
12892 "Hook for functions supplying allowed values for specific.
12893 The functions must take a single argument, the name of the property, and
12894 return a flat list of allowed values. If \":ETC\" is one of
12895 the values, this means that these values are intended as defaults for
12896 completion, but that other values should be allowed too.
12897 The functions must return nil if they are now responsible for this
12898 prioerty.")
12900 (defun org-property-get-allowed-values (pom property &optional table)
12901 "Get allowed values for the property PROPERTY.
12902 When TABLE is non-nil, return an alist that can directly be used for
12903 completion."
12904 (let (vals)
12905 (cond
12906 ((equal property "TODO")
12907 (setq vals (org-with-point-at pom
12908 (append org-todo-keywords-1 '("")))))
12909 ((equal property "PRIORITY")
12910 (let ((n org-lowest-priority))
12911 (while (>= n org-highest-priority)
12912 (push (char-to-string n) vals)
12913 (setq n (1- n)))))
12914 ((member property org-special-properties))
12915 ((setq vals (run-hook-with-args-until-success
12916 'org-property-allowed-value-functions property)))
12918 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12919 (when (and vals (string-match "\\S-" vals))
12920 (setq vals (car (read-from-string (concat "(" vals ")"))))
12921 (setq vals (mapcar (lambda (x)
12922 (cond ((stringp x) x)
12923 ((numberp x) (number-to-string x))
12924 ((symbolp x) (symbol-name x))
12925 (t "???")))
12926 vals)))))
12927 (when (member ":ETC" vals)
12928 (setq vals (remove ":ETC" vals))
12929 (org-add-props (car vals) '(org-unrestricted t)))
12930 (if table (mapcar 'list vals) vals)))
12932 (defun org-property-previous-allowed-value (&optional previous)
12933 "Switch to the next allowed value for this property."
12934 (interactive)
12935 (org-property-next-allowed-value t))
12937 (defun org-property-next-allowed-value (&optional previous)
12938 "Switch to the next allowed value for this property."
12939 (interactive)
12940 (unless (org-at-property-p)
12941 (error "Not at a property"))
12942 (let* ((key (match-string 2))
12943 (value (match-string 3))
12944 (allowed (or (org-property-get-allowed-values (point) key)
12945 (and (member value '("[ ]" "[-]" "[X]"))
12946 '("[ ]" "[X]"))))
12947 nval)
12948 (unless allowed
12949 (error "Allowed values for this property have not been defined"))
12950 (if previous (setq allowed (reverse allowed)))
12951 (if (member value allowed)
12952 (setq nval (car (cdr (member value allowed)))))
12953 (setq nval (or nval (car allowed)))
12954 (if (equal nval value)
12955 (error "Only one allowed value for this property"))
12956 (org-at-property-p)
12957 (replace-match (concat " :" key ": " nval) t t)
12958 (org-indent-line-function)
12959 (beginning-of-line 1)
12960 (skip-chars-forward " \t")
12961 (run-hook-with-args 'org-property-changed-functions key nval)))
12963 (defun org-find-entry-with-id (ident)
12964 "Locate the entry that contains the ID property with exact value IDENT.
12965 IDENT can be a string, a symbol or a number, this function will search for
12966 the string representation of it.
12967 Return the position where this entry starts, or nil if there is no such entry."
12968 (interactive "sID: ")
12969 (let ((id (cond
12970 ((stringp ident) ident)
12971 ((symbol-name ident) (symbol-name ident))
12972 ((numberp ident) (number-to-string ident))
12973 (t (error "IDENT %s must be a string, symbol or number" ident))))
12974 (case-fold-search nil))
12975 (save-excursion
12976 (save-restriction
12977 (widen)
12978 (goto-char (point-min))
12979 (when (re-search-forward
12980 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12981 nil t)
12982 (org-back-to-heading t)
12983 (point))))))
12985 ;;;; Timestamps
12987 (defvar org-last-changed-timestamp nil)
12988 (defvar org-last-inserted-timestamp nil
12989 "The last time stamp inserted with `org-insert-time-stamp'.")
12990 (defvar org-time-was-given) ; dynamically scoped parameter
12991 (defvar org-end-time-was-given) ; dynamically scoped parameter
12992 (defvar org-ts-what) ; dynamically scoped parameter
12994 (defun org-time-stamp (arg &optional inactive)
12995 "Prompt for a date/time and insert a time stamp.
12996 If the user specifies a time like HH:MM, or if this command is called
12997 with a prefix argument, the time stamp will contain date and time.
12998 Otherwise, only the date will be included. All parts of a date not
12999 specified by the user will be filled in from the current date/time.
13000 So if you press just return without typing anything, the time stamp
13001 will represent the current date/time. If there is already a timestamp
13002 at the cursor, it will be modified."
13003 (interactive "P")
13004 (let* ((ts nil)
13005 (default-time
13006 ;; Default time is either today, or, when entering a range,
13007 ;; the range start.
13008 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13009 (save-excursion
13010 (re-search-backward
13011 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13012 (- (point) 20) t)))
13013 (apply 'encode-time (org-parse-time-string (match-string 1)))
13014 (current-time)))
13015 (default-input (and ts (org-get-compact-tod ts)))
13016 org-time-was-given org-end-time-was-given time)
13017 (cond
13018 ((and (org-at-timestamp-p t)
13019 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13020 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13021 (insert "--")
13022 (setq time (let ((this-command this-command))
13023 (org-read-date arg 'totime nil nil
13024 default-time default-input)))
13025 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13026 ((org-at-timestamp-p t)
13027 (setq time (let ((this-command this-command))
13028 (org-read-date arg 'totime nil nil default-time default-input)))
13029 (when (org-at-timestamp-p t) ; just to get the match data
13030 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13031 (replace-match "")
13032 (setq org-last-changed-timestamp
13033 (org-insert-time-stamp
13034 time (or org-time-was-given arg)
13035 inactive nil nil (list org-end-time-was-given))))
13036 (message "Timestamp updated"))
13038 (setq time (let ((this-command this-command))
13039 (org-read-date arg 'totime nil nil default-time default-input)))
13040 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13041 nil nil (list org-end-time-was-given))))))
13043 ;; FIXME: can we use this for something else, like computing time differences?
13044 (defun org-get-compact-tod (s)
13045 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13046 (let* ((t1 (match-string 1 s))
13047 (h1 (string-to-number (match-string 2 s)))
13048 (m1 (string-to-number (match-string 3 s)))
13049 (t2 (and (match-end 4) (match-string 5 s)))
13050 (h2 (and t2 (string-to-number (match-string 6 s))))
13051 (m2 (and t2 (string-to-number (match-string 7 s))))
13052 dh dm)
13053 (if (not t2)
13055 (setq dh (- h2 h1) dm (- m2 m1))
13056 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13057 (concat t1 "+" (number-to-string dh)
13058 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13060 (defun org-time-stamp-inactive (&optional arg)
13061 "Insert an inactive time stamp.
13062 An inactive time stamp is enclosed in square brackets instead of angle
13063 brackets. It is inactive in the sense that it does not trigger agenda entries,
13064 does not link to the calendar and cannot be changed with the S-cursor keys.
13065 So these are more for recording a certain time/date."
13066 (interactive "P")
13067 (org-time-stamp arg 'inactive))
13069 (defvar org-date-ovl (org-make-overlay 1 1))
13070 (org-overlay-put org-date-ovl 'face 'org-warning)
13071 (org-detach-overlay org-date-ovl)
13073 (defvar org-ans1) ; dynamically scoped parameter
13074 (defvar org-ans2) ; dynamically scoped parameter
13076 (defvar org-plain-time-of-day-regexp) ; defined below
13078 (defvar org-overriding-default-time nil) ; dynamically scoped
13079 (defvar org-read-date-overlay nil)
13080 (defvar org-dcst nil) ; dynamically scoped
13081 (defvar org-read-date-history nil)
13082 (defvar org-read-date-final-answer nil)
13084 (defun org-read-date (&optional with-time to-time from-string prompt
13085 default-time default-input)
13086 "Read a date, possibly a time, and make things smooth for the user.
13087 The prompt will suggest to enter an ISO date, but you can also enter anything
13088 which will at least partially be understood by `parse-time-string'.
13089 Unrecognized parts of the date will default to the current day, month, year,
13090 hour and minute. If this command is called to replace a timestamp at point,
13091 of to enter the second timestamp of a range, the default time is taken from the
13092 existing stamp. For example,
13093 3-2-5 --> 2003-02-05
13094 feb 15 --> currentyear-02-15
13095 sep 12 9 --> 2009-09-12
13096 12:45 --> today 12:45
13097 22 sept 0:34 --> currentyear-09-22 0:34
13098 12 --> currentyear-currentmonth-12
13099 Fri --> nearest Friday (today or later)
13100 etc.
13102 Furthermore you can specify a relative date by giving, as the *first* thing
13103 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13104 change in days weeks, months, years.
13105 With a single plus or minus, the date is relative to today. With a double
13106 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13107 +4d --> four days from today
13108 +4 --> same as above
13109 +2w --> two weeks from today
13110 ++5 --> five days from default date
13112 The function understands only English month and weekday abbreviations,
13113 but this can be configured with the variables `parse-time-months' and
13114 `parse-time-weekdays'.
13116 While prompting, a calendar is popped up - you can also select the
13117 date with the mouse (button 1). The calendar shows a period of three
13118 months. To scroll it to other months, use the keys `>' and `<'.
13119 If you don't like the calendar, turn it off with
13120 \(setq org-read-date-popup-calendar nil)
13122 With optional argument TO-TIME, the date will immediately be converted
13123 to an internal time.
13124 With an optional argument WITH-TIME, the prompt will suggest to also
13125 insert a time. Note that when WITH-TIME is not set, you can still
13126 enter a time, and this function will inform the calling routine about
13127 this change. The calling routine may then choose to change the format
13128 used to insert the time stamp into the buffer to include the time.
13129 With optional argument FROM-STRING, read from this string instead from
13130 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13131 the time/date that is used for everything that is not specified by the
13132 user."
13133 (require 'parse-time)
13134 (let* ((org-time-stamp-rounding-minutes
13135 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13136 (org-dcst org-display-custom-times)
13137 (ct (org-current-time))
13138 (def (or org-overriding-default-time default-time ct))
13139 (defdecode (decode-time def))
13140 (dummy (progn
13141 (when (< (nth 2 defdecode) org-extend-today-until)
13142 (setcar (nthcdr 2 defdecode) -1)
13143 (setcar (nthcdr 1 defdecode) 59)
13144 (setq def (apply 'encode-time defdecode)
13145 defdecode (decode-time def)))))
13146 (calendar-frame-setup nil)
13147 (calendar-move-hook nil)
13148 (calendar-view-diary-initially-flag nil)
13149 (view-diary-entries-initially nil)
13150 (calendar-view-holidays-initially-flag nil)
13151 (view-calendar-holidays-initially nil)
13152 (timestr (format-time-string
13153 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13154 (prompt (concat (if prompt (concat prompt " ") "")
13155 (format "Date+time [%s]: " timestr)))
13156 ans (org-ans0 "") org-ans1 org-ans2 final)
13158 (cond
13159 (from-string (setq ans from-string))
13160 (org-read-date-popup-calendar
13161 (save-excursion
13162 (save-window-excursion
13163 (calendar)
13164 (calendar-forward-day (- (time-to-days def)
13165 (calendar-absolute-from-gregorian
13166 (calendar-current-date))))
13167 (org-eval-in-calendar nil t)
13168 (let* ((old-map (current-local-map))
13169 (map (copy-keymap calendar-mode-map))
13170 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13171 (org-defkey map (kbd "RET") 'org-calendar-select)
13172 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13173 'org-calendar-select-mouse)
13174 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13175 'org-calendar-select-mouse)
13176 (org-defkey minibuffer-local-map [(meta shift left)]
13177 (lambda () (interactive)
13178 (org-eval-in-calendar '(calendar-backward-month 1))))
13179 (org-defkey minibuffer-local-map [(meta shift right)]
13180 (lambda () (interactive)
13181 (org-eval-in-calendar '(calendar-forward-month 1))))
13182 (org-defkey minibuffer-local-map [(meta shift up)]
13183 (lambda () (interactive)
13184 (org-eval-in-calendar '(calendar-backward-year 1))))
13185 (org-defkey minibuffer-local-map [(meta shift down)]
13186 (lambda () (interactive)
13187 (org-eval-in-calendar '(calendar-forward-year 1))))
13188 (org-defkey minibuffer-local-map [?\e (shift left)]
13189 (lambda () (interactive)
13190 (org-eval-in-calendar '(calendar-backward-month 1))))
13191 (org-defkey minibuffer-local-map [?\e (shift right)]
13192 (lambda () (interactive)
13193 (org-eval-in-calendar '(calendar-forward-month 1))))
13194 (org-defkey minibuffer-local-map [?\e (shift up)]
13195 (lambda () (interactive)
13196 (org-eval-in-calendar '(calendar-backward-year 1))))
13197 (org-defkey minibuffer-local-map [?\e (shift down)]
13198 (lambda () (interactive)
13199 (org-eval-in-calendar '(calendar-forward-year 1))))
13200 (org-defkey minibuffer-local-map [(shift up)]
13201 (lambda () (interactive)
13202 (org-eval-in-calendar '(calendar-backward-week 1))))
13203 (org-defkey minibuffer-local-map [(shift down)]
13204 (lambda () (interactive)
13205 (org-eval-in-calendar '(calendar-forward-week 1))))
13206 (org-defkey minibuffer-local-map [(shift left)]
13207 (lambda () (interactive)
13208 (org-eval-in-calendar '(calendar-backward-day 1))))
13209 (org-defkey minibuffer-local-map [(shift right)]
13210 (lambda () (interactive)
13211 (org-eval-in-calendar '(calendar-forward-day 1))))
13212 (org-defkey minibuffer-local-map ">"
13213 (lambda () (interactive)
13214 (org-eval-in-calendar '(scroll-calendar-left 1))))
13215 (org-defkey minibuffer-local-map "<"
13216 (lambda () (interactive)
13217 (org-eval-in-calendar '(scroll-calendar-right 1))))
13218 (run-hooks 'org-read-date-minibuffer-setup-hook)
13219 (unwind-protect
13220 (progn
13221 (use-local-map map)
13222 (add-hook 'post-command-hook 'org-read-date-display)
13223 (setq org-ans0 (read-string prompt default-input
13224 'org-read-date-history nil))
13225 ;; org-ans0: from prompt
13226 ;; org-ans1: from mouse click
13227 ;; org-ans2: from calendar motion
13228 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13229 (remove-hook 'post-command-hook 'org-read-date-display)
13230 (use-local-map old-map)
13231 (when org-read-date-overlay
13232 (org-delete-overlay org-read-date-overlay)
13233 (setq org-read-date-overlay nil)))))))
13235 (t ; Naked prompt only
13236 (unwind-protect
13237 (setq ans (read-string prompt default-input
13238 'org-read-date-history timestr))
13239 (when org-read-date-overlay
13240 (org-delete-overlay org-read-date-overlay)
13241 (setq org-read-date-overlay nil)))))
13243 (setq final (org-read-date-analyze ans def defdecode))
13244 (setq org-read-date-final-answer ans)
13246 (if to-time
13247 (apply 'encode-time final)
13248 (if (and (boundp 'org-time-was-given) org-time-was-given)
13249 (format "%04d-%02d-%02d %02d:%02d"
13250 (nth 5 final) (nth 4 final) (nth 3 final)
13251 (nth 2 final) (nth 1 final))
13252 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13254 (defvar def)
13255 (defvar defdecode)
13256 (defvar with-time)
13257 (defvar org-read-date-analyze-futurep nil)
13258 (defun org-read-date-display ()
13259 "Display the current date prompt interpretation in the minibuffer."
13260 (when org-read-date-display-live
13261 (when org-read-date-overlay
13262 (org-delete-overlay org-read-date-overlay))
13263 (let ((p (point)))
13264 (end-of-line 1)
13265 (while (not (equal (buffer-substring
13266 (max (point-min) (- (point) 4)) (point))
13267 " "))
13268 (insert " "))
13269 (goto-char p))
13270 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13271 " " (or org-ans1 org-ans2)))
13272 (org-end-time-was-given nil)
13273 (f (org-read-date-analyze ans def defdecode))
13274 (fmts (if org-dcst
13275 org-time-stamp-custom-formats
13276 org-time-stamp-formats))
13277 (fmt (if (or with-time
13278 (and (boundp 'org-time-was-given) org-time-was-given))
13279 (cdr fmts)
13280 (car fmts)))
13281 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13282 (when (and org-end-time-was-given
13283 (string-match org-plain-time-of-day-regexp txt))
13284 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13285 org-end-time-was-given
13286 (substring txt (match-end 0)))))
13287 (when org-read-date-analyze-futurep
13288 (setq txt (concat txt " (=>F)")))
13289 (setq org-read-date-overlay
13290 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13291 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13293 (defun org-read-date-analyze (ans def defdecode)
13294 "Analyse the combined answer of the date prompt."
13295 ;; FIXME: cleanup and comment
13296 (let (delta deltan deltaw deltadef year month day
13297 hour minute second wday pm h2 m2 tl wday1
13298 iso-year iso-weekday iso-week iso-year iso-date futurep)
13299 (setq org-read-date-analyze-futurep nil)
13300 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13301 (setq ans "+0"))
13303 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13304 (setq ans (replace-match "" t t ans)
13305 deltan (car delta)
13306 deltaw (nth 1 delta)
13307 deltadef (nth 2 delta)))
13309 ;; Check if there is an iso week date in there
13310 ;; If yes, store the info and postpone interpreting it until the rest
13311 ;; of the parsing is done
13312 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13313 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13314 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13315 iso-week (string-to-number (match-string 2 ans)))
13316 (setq ans (replace-match "" t t ans)))
13318 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13319 (when (string-match
13320 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13321 (setq year (if (match-end 2)
13322 (string-to-number (match-string 2 ans))
13323 (string-to-number (format-time-string "%Y")))
13324 month (string-to-number (match-string 3 ans))
13325 day (string-to-number (match-string 4 ans)))
13326 (if (< year 100) (setq year (+ 2000 year)))
13327 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13328 t nil ans)))
13329 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13330 ;; If there is a time with am/pm, and *no* time without it, we convert
13331 ;; so that matching will be successful.
13332 (loop for i from 1 to 2 do ; twice, for end time as well
13333 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13334 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13335 (setq hour (string-to-number (match-string 1 ans))
13336 minute (if (match-end 3)
13337 (string-to-number (match-string 3 ans))
13339 pm (equal ?p
13340 (string-to-char (downcase (match-string 4 ans)))))
13341 (if (and (= hour 12) (not pm))
13342 (setq hour 0)
13343 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13344 (setq ans (replace-match (format "%02d:%02d" hour minute)
13345 t t ans))))
13347 ;; Check if a time range is given as a duration
13348 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13349 (setq hour (string-to-number (match-string 1 ans))
13350 h2 (+ hour (string-to-number (match-string 3 ans)))
13351 minute (string-to-number (match-string 2 ans))
13352 m2 (+ minute (if (match-end 5) (string-to-number
13353 (match-string 5 ans))0)))
13354 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13355 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13356 t t ans)))
13358 ;; Check if there is a time range
13359 (when (boundp 'org-end-time-was-given)
13360 (setq org-time-was-given nil)
13361 (when (and (string-match org-plain-time-of-day-regexp ans)
13362 (match-end 8))
13363 (setq org-end-time-was-given (match-string 8 ans))
13364 (setq ans (concat (substring ans 0 (match-beginning 7))
13365 (substring ans (match-end 7))))))
13367 (setq tl (parse-time-string ans)
13368 day (or (nth 3 tl) (nth 3 defdecode))
13369 month (or (nth 4 tl)
13370 (if (and org-read-date-prefer-future
13371 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13372 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13373 (nth 4 defdecode)))
13374 year (or (nth 5 tl)
13375 (if (and org-read-date-prefer-future
13376 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13377 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13378 (nth 5 defdecode)))
13379 hour (or (nth 2 tl) (nth 2 defdecode))
13380 minute (or (nth 1 tl) (nth 1 defdecode))
13381 second (or (nth 0 tl) 0)
13382 wday (nth 6 tl))
13384 (when (and (eq org-read-date-prefer-future 'time)
13385 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13386 (equal day (nth 3 defdecode))
13387 (equal month (nth 4 defdecode))
13388 (equal year (nth 5 defdecode))
13389 (nth 2 tl)
13390 (or (< (nth 2 tl) (nth 2 defdecode))
13391 (and (= (nth 2 tl) (nth 2 defdecode))
13392 (nth 1 tl)
13393 (< (nth 1 tl) (nth 1 defdecode)))))
13394 (setq day (1+ day)
13395 futurep t))
13397 ;; Special date definitions below
13398 (cond
13399 (iso-week
13400 ;; There was an iso week
13401 (setq futurep nil)
13402 (setq year (or iso-year year)
13403 day (or iso-weekday wday 1)
13404 wday nil ; to make sure that the trigger below does not match
13405 iso-date (calendar-gregorian-from-absolute
13406 (calendar-absolute-from-iso
13407 (list iso-week day year))))
13408 ; FIXME: Should we also push ISO weeks into the future?
13409 ; (when (and org-read-date-prefer-future
13410 ; (not iso-year)
13411 ; (< (calendar-absolute-from-gregorian iso-date)
13412 ; (time-to-days (current-time))))
13413 ; (setq year (1+ year)
13414 ; iso-date (calendar-gregorian-from-absolute
13415 ; (calendar-absolute-from-iso
13416 ; (list iso-week day year)))))
13417 (setq month (car iso-date)
13418 year (nth 2 iso-date)
13419 day (nth 1 iso-date)))
13420 (deltan
13421 (setq futurep nil)
13422 (unless deltadef
13423 (let ((now (decode-time (current-time))))
13424 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13425 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13426 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13427 ((equal deltaw "m") (setq month (+ month deltan)))
13428 ((equal deltaw "y") (setq year (+ year deltan)))))
13429 ((and wday (not (nth 3 tl)))
13430 (setq futurep nil)
13431 ;; Weekday was given, but no day, so pick that day in the week
13432 ;; on or after the derived date.
13433 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13434 (unless (equal wday wday1)
13435 (setq day (+ day (% (- wday wday1 -7) 7))))))
13436 (if (and (boundp 'org-time-was-given)
13437 (nth 2 tl))
13438 (setq org-time-was-given t))
13439 (if (< year 100) (setq year (+ 2000 year)))
13440 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13441 (setq org-read-date-analyze-futurep futurep)
13442 (list second minute hour day month year)))
13444 (defvar parse-time-weekdays)
13446 (defun org-read-date-get-relative (s today default)
13447 "Check string S for special relative date string.
13448 TODAY and DEFAULT are internal times, for today and for a default.
13449 Return shift list (N what def-flag)
13450 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13451 N is the number of WHATs to shift.
13452 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13453 the DEFAULT date rather than TODAY."
13454 (when (and
13455 (string-match
13456 (concat
13457 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13458 "\\([0-9]+\\)?"
13459 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13460 "\\([ \t]\\|$\\)") s)
13461 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13462 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13463 (string-to-char (substring (match-string 1 s) -1))
13464 ?+))
13465 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13466 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13467 (what (if (match-end 3) (match-string 3 s) "d"))
13468 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13469 (date (if rel default today))
13470 (wday (nth 6 (decode-time date)))
13471 delta)
13472 (if wday1
13473 (progn
13474 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13475 (if (= dir ?-) (setq delta (- delta 7)))
13476 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13477 (list delta "d" rel))
13478 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13480 (defun org-eval-in-calendar (form &optional keepdate)
13481 "Eval FORM in the calendar window and return to current window.
13482 Also, store the cursor date in variable org-ans2."
13483 (let ((sf (selected-frame))
13484 (sw (selected-window)))
13485 (select-window (get-buffer-window "*Calendar*" t))
13486 (eval form)
13487 (when (and (not keepdate) (calendar-cursor-to-date))
13488 (let* ((date (calendar-cursor-to-date))
13489 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13490 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13491 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13492 (select-window sw)
13493 (org-select-frame-set-input-focus sf)))
13495 (defun org-calendar-select ()
13496 "Return to `org-read-date' with the date currently selected.
13497 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13498 (interactive)
13499 (when (calendar-cursor-to-date)
13500 (let* ((date (calendar-cursor-to-date))
13501 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13502 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13503 (if (active-minibuffer-window) (exit-minibuffer))))
13505 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13506 "Insert a date stamp for the date given by the internal TIME.
13507 WITH-HM means, use the stamp format that includes the time of the day.
13508 INACTIVE means use square brackets instead of angular ones, so that the
13509 stamp will not contribute to the agenda.
13510 PRE and POST are optional strings to be inserted before and after the
13511 stamp.
13512 The command returns the inserted time stamp."
13513 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13514 stamp)
13515 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13516 (insert-before-markers (or pre ""))
13517 (insert-before-markers (setq stamp (format-time-string fmt time)))
13518 (when (listp extra)
13519 (setq extra (car extra))
13520 (if (and (stringp extra)
13521 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13522 (setq extra (format "-%02d:%02d"
13523 (string-to-number (match-string 1 extra))
13524 (string-to-number (match-string 2 extra))))
13525 (setq extra nil)))
13526 (when extra
13527 (backward-char 1)
13528 (insert-before-markers extra)
13529 (forward-char 1))
13530 (insert-before-markers (or post ""))
13531 (setq org-last-inserted-timestamp stamp)))
13533 (defun org-toggle-time-stamp-overlays ()
13534 "Toggle the use of custom time stamp formats."
13535 (interactive)
13536 (setq org-display-custom-times (not org-display-custom-times))
13537 (unless org-display-custom-times
13538 (let ((p (point-min)) (bmp (buffer-modified-p)))
13539 (while (setq p (next-single-property-change p 'display))
13540 (if (and (get-text-property p 'display)
13541 (eq (get-text-property p 'face) 'org-date))
13542 (remove-text-properties
13543 p (setq p (next-single-property-change p 'display))
13544 '(display t))))
13545 (set-buffer-modified-p bmp)))
13546 (if (featurep 'xemacs)
13547 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13548 (org-restart-font-lock)
13549 (setq org-table-may-need-update t)
13550 (if org-display-custom-times
13551 (message "Time stamps are overlayed with custom format")
13552 (message "Time stamp overlays removed")))
13554 (defun org-display-custom-time (beg end)
13555 "Overlay modified time stamp format over timestamp between BEG and END."
13556 (let* ((ts (buffer-substring beg end))
13557 t1 w1 with-hm tf time str w2 (off 0))
13558 (save-match-data
13559 (setq t1 (org-parse-time-string ts t))
13560 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13561 (setq off (- (match-end 0) (match-beginning 0)))))
13562 (setq end (- end off))
13563 (setq w1 (- end beg)
13564 with-hm (and (nth 1 t1) (nth 2 t1))
13565 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13566 time (org-fix-decoded-time t1)
13567 str (org-add-props
13568 (format-time-string
13569 (substring tf 1 -1) (apply 'encode-time time))
13570 nil 'mouse-face 'highlight)
13571 w2 (length str))
13572 (if (not (= w2 w1))
13573 (add-text-properties (1+ beg) (+ 2 beg)
13574 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13575 (if (featurep 'xemacs)
13576 (progn
13577 (put-text-property beg end 'invisible t)
13578 (put-text-property beg end 'end-glyph (make-glyph str)))
13579 (put-text-property beg end 'display str))))
13581 (defun org-translate-time (string)
13582 "Translate all timestamps in STRING to custom format.
13583 But do this only if the variable `org-display-custom-times' is set."
13584 (when org-display-custom-times
13585 (save-match-data
13586 (let* ((start 0)
13587 (re org-ts-regexp-both)
13588 t1 with-hm inactive tf time str beg end)
13589 (while (setq start (string-match re string start))
13590 (setq beg (match-beginning 0)
13591 end (match-end 0)
13592 t1 (save-match-data
13593 (org-parse-time-string (substring string beg end) t))
13594 with-hm (and (nth 1 t1) (nth 2 t1))
13595 inactive (equal (substring string beg (1+ beg)) "[")
13596 tf (funcall (if with-hm 'cdr 'car)
13597 org-time-stamp-custom-formats)
13598 time (org-fix-decoded-time t1)
13599 str (format-time-string
13600 (concat
13601 (if inactive "[" "<") (substring tf 1 -1)
13602 (if inactive "]" ">"))
13603 (apply 'encode-time time))
13604 string (replace-match str t t string)
13605 start (+ start (length str)))))))
13606 string)
13608 (defun org-fix-decoded-time (time)
13609 "Set 0 instead of nil for the first 6 elements of time.
13610 Don't touch the rest."
13611 (let ((n 0))
13612 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13614 (defun org-days-to-time (timestamp-string)
13615 "Difference between TIMESTAMP-STRING and now in days."
13616 (- (time-to-days (org-time-string-to-time timestamp-string))
13617 (time-to-days (current-time))))
13619 (defun org-deadline-close (timestamp-string &optional ndays)
13620 "Is the time in TIMESTAMP-STRING close to the current date?"
13621 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13622 (and (< (org-days-to-time timestamp-string) ndays)
13623 (not (org-entry-is-done-p))))
13625 (defun org-get-wdays (ts)
13626 "Get the deadline lead time appropriate for timestring TS."
13627 (cond
13628 ((<= org-deadline-warning-days 0)
13629 ;; 0 or negative, enforce this value no matter what
13630 (- org-deadline-warning-days))
13631 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13632 ;; lead time is specified.
13633 (floor (* (string-to-number (match-string 1 ts))
13634 (cdr (assoc (match-string 2 ts)
13635 '(("d" . 1) ("w" . 7)
13636 ("m" . 30.4) ("y" . 365.25)))))))
13637 ;; go for the default.
13638 (t org-deadline-warning-days)))
13640 (defun org-calendar-select-mouse (ev)
13641 "Return to `org-read-date' with the date currently selected.
13642 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13643 (interactive "e")
13644 (mouse-set-point ev)
13645 (when (calendar-cursor-to-date)
13646 (let* ((date (calendar-cursor-to-date))
13647 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13648 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13649 (if (active-minibuffer-window) (exit-minibuffer))))
13651 (defun org-check-deadlines (ndays)
13652 "Check if there are any deadlines due or past due.
13653 A deadline is considered due if it happens within `org-deadline-warning-days'
13654 days from today's date. If the deadline appears in an entry marked DONE,
13655 it is not shown. The prefix arg NDAYS can be used to test that many
13656 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13657 (interactive "P")
13658 (let* ((org-warn-days
13659 (cond
13660 ((equal ndays '(4)) 100000)
13661 (ndays (prefix-numeric-value ndays))
13662 (t (abs org-deadline-warning-days))))
13663 (case-fold-search nil)
13664 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13665 (callback
13666 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13668 (message "%d deadlines past-due or due within %d days"
13669 (org-occur regexp nil callback)
13670 org-warn-days)))
13672 (defun org-check-before-date (date)
13673 "Check if there are deadlines or scheduled entries before DATE."
13674 (interactive (list (org-read-date)))
13675 (let ((case-fold-search nil)
13676 (regexp (concat "\\<\\(" org-deadline-string
13677 "\\|" org-scheduled-string
13678 "\\) *<\\([^>]+\\)>"))
13679 (callback
13680 (lambda () (time-less-p
13681 (org-time-string-to-time (match-string 2))
13682 (org-time-string-to-time date)))))
13683 (message "%d entries before %s"
13684 (org-occur regexp nil callback) date)))
13686 (defun org-check-after-date (date)
13687 "Check if there are deadlines or scheduled entries after DATE."
13688 (interactive (list (org-read-date)))
13689 (let ((case-fold-search nil)
13690 (regexp (concat "\\<\\(" org-deadline-string
13691 "\\|" org-scheduled-string
13692 "\\) *<\\([^>]+\\)>"))
13693 (callback
13694 (lambda () (not
13695 (time-less-p
13696 (org-time-string-to-time (match-string 2))
13697 (org-time-string-to-time date))))))
13698 (message "%d entries after %s"
13699 (org-occur regexp nil callback) date)))
13701 (defun org-evaluate-time-range (&optional to-buffer)
13702 "Evaluate a time range by computing the difference between start and end.
13703 Normally the result is just printed in the echo area, but with prefix arg
13704 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13705 If the time range is actually in a table, the result is inserted into the
13706 next column.
13707 For time difference computation, a year is assumed to be exactly 365
13708 days in order to avoid rounding problems."
13709 (interactive "P")
13711 (org-clock-update-time-maybe)
13712 (save-excursion
13713 (unless (org-at-date-range-p t)
13714 (goto-char (point-at-bol))
13715 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13716 (if (not (org-at-date-range-p t))
13717 (error "Not at a time-stamp range, and none found in current line")))
13718 (let* ((ts1 (match-string 1))
13719 (ts2 (match-string 2))
13720 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13721 (match-end (match-end 0))
13722 (time1 (org-time-string-to-time ts1))
13723 (time2 (org-time-string-to-time ts2))
13724 (t1 (org-float-time time1))
13725 (t2 (org-float-time time2))
13726 (diff (abs (- t2 t1)))
13727 (negative (< (- t2 t1) 0))
13728 ;; (ys (floor (* 365 24 60 60)))
13729 (ds (* 24 60 60))
13730 (hs (* 60 60))
13731 (fy "%dy %dd %02d:%02d")
13732 (fy1 "%dy %dd")
13733 (fd "%dd %02d:%02d")
13734 (fd1 "%dd")
13735 (fh "%02d:%02d")
13736 y d h m align)
13737 (if havetime
13738 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13740 d (floor (/ diff ds)) diff (mod diff ds)
13741 h (floor (/ diff hs)) diff (mod diff hs)
13742 m (floor (/ diff 60)))
13743 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13745 d (floor (+ (/ diff ds) 0.5))
13746 h 0 m 0))
13747 (if (not to-buffer)
13748 (message "%s" (org-make-tdiff-string y d h m))
13749 (if (org-at-table-p)
13750 (progn
13751 (goto-char match-end)
13752 (setq align t)
13753 (and (looking-at " *|") (goto-char (match-end 0))))
13754 (goto-char match-end))
13755 (if (looking-at
13756 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13757 (replace-match ""))
13758 (if negative (insert " -"))
13759 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13760 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13761 (insert " " (format fh h m))))
13762 (if align (org-table-align))
13763 (message "Time difference inserted")))))
13765 (defun org-make-tdiff-string (y d h m)
13766 (let ((fmt "")
13767 (l nil))
13768 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13769 l (push y l)))
13770 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13771 l (push d l)))
13772 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13773 l (push h l)))
13774 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13775 l (push m l)))
13776 (apply 'format fmt (nreverse l))))
13778 (defun org-time-string-to-time (s)
13779 (apply 'encode-time (org-parse-time-string s)))
13780 (defun org-time-string-to-seconds (s)
13781 (org-float-time (org-time-string-to-time s)))
13783 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13784 "Convert a time stamp to an absolute day number.
13785 If there is a specifyer for a cyclic time stamp, get the closest date to
13786 DAYNR.
13787 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13788 the variable date is bound by the calendar when this is called."
13789 (cond
13790 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13791 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13792 daynr
13793 (+ daynr 1000)))
13794 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13795 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13796 (time-to-days (current-time))) (match-string 0 s)
13797 prefer show-all))
13798 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13800 (defun org-days-to-iso-week (days)
13801 "Return the iso week number."
13802 (require 'cal-iso)
13803 (car (calendar-iso-from-absolute days)))
13805 (defun org-small-year-to-year (year)
13806 "Convert 2-digit years into 4-digit years.
13807 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13808 The year 2000 cannot be abbreviated. Any year larger than 99
13809 is returned unchanged."
13810 (if (< year 38)
13811 (setq year (+ 2000 year))
13812 (if (< year 100)
13813 (setq year (+ 1900 year))))
13814 year)
13816 (defun org-time-from-absolute (d)
13817 "Return the time corresponding to date D.
13818 D may be an absolute day number, or a calendar-type list (month day year)."
13819 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13820 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13822 (defun org-calendar-holiday ()
13823 "List of holidays, for Diary display in Org-mode."
13824 (require 'holidays)
13825 (let ((hl (funcall
13826 (if (fboundp 'calendar-check-holidays)
13827 'calendar-check-holidays 'check-calendar-holidays) date)))
13828 (if hl (mapconcat 'identity hl "; "))))
13830 (defun org-diary-sexp-entry (sexp entry date)
13831 "Process a SEXP diary ENTRY for DATE."
13832 (require 'diary-lib)
13833 (let ((result (if calendar-debug-sexp
13834 (let ((stack-trace-on-error t))
13835 (eval (car (read-from-string sexp))))
13836 (condition-case nil
13837 (eval (car (read-from-string sexp)))
13838 (error
13839 (beep)
13840 (message "Bad sexp at line %d in %s: %s"
13841 (org-current-line)
13842 (buffer-file-name) sexp)
13843 (sleep-for 2))))))
13844 (cond ((stringp result) result)
13845 ((and (consp result)
13846 (stringp (cdr result))) (cdr result))
13847 (result entry)
13848 (t nil))))
13850 (defun org-diary-to-ical-string (frombuf)
13851 "Get iCalendar entries from diary entries in buffer FROMBUF.
13852 This uses the icalendar.el library."
13853 (let* ((tmpdir (if (featurep 'xemacs)
13854 (temp-directory)
13855 temporary-file-directory))
13856 (tmpfile (make-temp-name
13857 (expand-file-name "orgics" tmpdir)))
13858 buf rtn b e)
13859 (with-current-buffer frombuf
13860 (icalendar-export-region (point-min) (point-max) tmpfile)
13861 (setq buf (find-buffer-visiting tmpfile))
13862 (set-buffer buf)
13863 (goto-char (point-min))
13864 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13865 (setq b (match-beginning 0)))
13866 (goto-char (point-max))
13867 (if (re-search-backward "^END:VEVENT" nil t)
13868 (setq e (match-end 0)))
13869 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13870 (kill-buffer buf)
13871 (delete-file tmpfile)
13872 rtn))
13874 (defun org-closest-date (start current change prefer show-all)
13875 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13876 When PREFER is `past' return a date that is either CURRENT or past.
13877 When PREFER is `future', return a date that is either CURRENT or future.
13878 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13879 ;; Make the proper lists from the dates
13880 (catch 'exit
13881 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13882 dn dw sday cday n1 n2 n0
13883 d m y y1 y2 date1 date2 nmonths nm ny m2)
13885 (setq start (org-date-to-gregorian start)
13886 current (org-date-to-gregorian
13887 (if show-all
13888 current
13889 (time-to-days (current-time))))
13890 sday (calendar-absolute-from-gregorian start)
13891 cday (calendar-absolute-from-gregorian current))
13893 (if (<= cday sday) (throw 'exit sday))
13895 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13896 (setq dn (string-to-number (match-string 1 change))
13897 dw (cdr (assoc (match-string 2 change) a1)))
13898 (error "Invalid change specifyer: %s" change))
13899 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13900 (cond
13901 ((eq dw 'day)
13902 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13903 n2 (+ n1 dn)))
13904 ((eq dw 'year)
13905 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13906 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13907 (setq date1 (list m d y1)
13908 n1 (calendar-absolute-from-gregorian date1)
13909 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13910 n2 (calendar-absolute-from-gregorian date2)))
13911 ((eq dw 'month)
13912 ;; approx number of month between the two dates
13913 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13914 ;; How often does dn fit in there?
13915 (setq d (nth 1 start) m (car start) y (nth 2 start)
13916 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13917 m (+ m nm)
13918 ny (floor (/ m 12))
13919 y (+ y ny)
13920 m (- m (* ny 12)))
13921 (while (> m 12) (setq m (- m 12) y (1+ y)))
13922 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13923 (setq m2 (+ m dn) y2 y)
13924 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13925 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13926 (while (<= n2 cday)
13927 (setq n1 n2 m m2 y y2)
13928 (setq m2 (+ m dn) y2 y)
13929 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13930 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13931 ;; Make sure n1 is the earlier date
13932 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13933 (if show-all
13934 (cond
13935 ((eq prefer 'past) (if (= cday n2) n2 n1))
13936 ((eq prefer 'future) (if (= cday n1) n1 n2))
13937 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13938 (cond
13939 ((eq prefer 'past) (if (= cday n2) n2 n1))
13940 ((eq prefer 'future) (if (= cday n1) n1 n2))
13941 (t (if (= cday n1) n1 n2)))))))
13943 (defun org-date-to-gregorian (date)
13944 "Turn any specification of DATE into a gregorian date for the calendar."
13945 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13946 ((and (listp date) (= (length date) 3)) date)
13947 ((stringp date)
13948 (setq date (org-parse-time-string date))
13949 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13950 ((listp date)
13951 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13953 (defun org-parse-time-string (s &optional nodefault)
13954 "Parse the standard Org-mode time string.
13955 This should be a lot faster than the normal `parse-time-string'.
13956 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13957 hour and minute fields will be nil if not given."
13958 (if (string-match org-ts-regexp0 s)
13959 (list 0
13960 (if (or (match-beginning 8) (not nodefault))
13961 (string-to-number (or (match-string 8 s) "0")))
13962 (if (or (match-beginning 7) (not nodefault))
13963 (string-to-number (or (match-string 7 s) "0")))
13964 (string-to-number (match-string 4 s))
13965 (string-to-number (match-string 3 s))
13966 (string-to-number (match-string 2 s))
13967 nil nil nil)
13968 (error "Not a standard Org-mode time string: %s" s)))
13970 (defun org-timestamp-up (&optional arg)
13971 "Increase the date item at the cursor by one.
13972 If the cursor is on the year, change the year. If it is on the month or
13973 the day, change that.
13974 With prefix ARG, change by that many units."
13975 (interactive "p")
13976 (org-timestamp-change (prefix-numeric-value arg)))
13978 (defun org-timestamp-down (&optional arg)
13979 "Decrease the date item at the cursor by one.
13980 If the cursor is on the year, change the year. If it is on the month or
13981 the day, change that.
13982 With prefix ARG, change by that many units."
13983 (interactive "p")
13984 (org-timestamp-change (- (prefix-numeric-value arg))))
13986 (defun org-timestamp-up-day (&optional arg)
13987 "Increase the date in the time stamp by one day.
13988 With prefix ARG, change that many days."
13989 (interactive "p")
13990 (if (and (not (org-at-timestamp-p t))
13991 (org-on-heading-p))
13992 (org-todo 'up)
13993 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13995 (defun org-timestamp-down-day (&optional arg)
13996 "Decrease the date in the time stamp by one day.
13997 With prefix ARG, change that many days."
13998 (interactive "p")
13999 (if (and (not (org-at-timestamp-p t))
14000 (org-on-heading-p))
14001 (org-todo 'down)
14002 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14004 (defun org-at-timestamp-p (&optional inactive-ok)
14005 "Determine if the cursor is in or at a timestamp."
14006 (interactive)
14007 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14008 (pos (point))
14009 (ans (or (looking-at tsr)
14010 (save-excursion
14011 (skip-chars-backward "^[<\n\r\t")
14012 (if (> (point) (point-min)) (backward-char 1))
14013 (and (looking-at tsr)
14014 (> (- (match-end 0) pos) -1))))))
14015 (and ans
14016 (boundp 'org-ts-what)
14017 (setq org-ts-what
14018 (cond
14019 ((= pos (match-beginning 0)) 'bracket)
14020 ((= pos (1- (match-end 0))) 'bracket)
14021 ((org-pos-in-match-range pos 2) 'year)
14022 ((org-pos-in-match-range pos 3) 'month)
14023 ((org-pos-in-match-range pos 7) 'hour)
14024 ((org-pos-in-match-range pos 8) 'minute)
14025 ((or (org-pos-in-match-range pos 4)
14026 (org-pos-in-match-range pos 5)) 'day)
14027 ((and (> pos (or (match-end 8) (match-end 5)))
14028 (< pos (match-end 0)))
14029 (- pos (or (match-end 8) (match-end 5))))
14030 (t 'day))))
14031 ans))
14033 (defun org-toggle-timestamp-type ()
14034 "Toggle the type (<active> or [inactive]) of a time stamp."
14035 (interactive)
14036 (when (org-at-timestamp-p t)
14037 (let ((beg (match-beginning 0)) (end (match-end 0))
14038 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14039 (save-excursion
14040 (goto-char beg)
14041 (while (re-search-forward "[][<>]" end t)
14042 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14043 t t)))
14044 (message "Timestamp is now %sactive"
14045 (if (equal (char-after beg) ?<) "" "in")))))
14047 (defun org-timestamp-change (n &optional what)
14048 "Change the date in the time stamp at point.
14049 The date will be changed by N times WHAT. WHAT can be `day', `month',
14050 `year', `minute', `second'. If WHAT is not given, the cursor position
14051 in the timestamp determines what will be changed."
14052 (let ((pos (point))
14053 with-hm inactive
14054 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14055 org-ts-what
14056 extra rem
14057 ts time time0)
14058 (if (not (org-at-timestamp-p t))
14059 (error "Not at a timestamp"))
14060 (if (and (not what) (eq org-ts-what 'bracket))
14061 (org-toggle-timestamp-type)
14062 (if (and (not what) (not (eq org-ts-what 'day))
14063 org-display-custom-times
14064 (get-text-property (point) 'display)
14065 (not (get-text-property (1- (point)) 'display)))
14066 (setq org-ts-what 'day))
14067 (setq org-ts-what (or what org-ts-what)
14068 inactive (= (char-after (match-beginning 0)) ?\[)
14069 ts (match-string 0))
14070 (replace-match "")
14071 (if (string-match
14072 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14074 (setq extra (match-string 1 ts)))
14075 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14076 (setq with-hm t))
14077 (setq time0 (org-parse-time-string ts))
14078 (when (and (eq org-ts-what 'minute)
14079 (eq current-prefix-arg nil))
14080 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14081 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14082 (setcar (cdr time0) (+ (nth 1 time0)
14083 (if (> n 0) (- rem) (- dm rem))))))
14084 (setq time
14085 (encode-time (or (car time0) 0)
14086 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14087 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14088 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14089 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14090 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14091 (nthcdr 6 time0)))
14092 (when (and (member org-ts-what '(hour minute))
14093 extra
14094 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14095 (setq extra (org-modify-ts-extra
14096 extra
14097 (if (eq org-ts-what 'hour) 2 5)
14098 n dm)))
14099 (when (integerp org-ts-what)
14100 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14101 (if (eq what 'calendar)
14102 (let ((cal-date (org-get-date-from-calendar)))
14103 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14104 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14105 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14106 (setcar time0 (or (car time0) 0))
14107 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14108 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14109 (setq time (apply 'encode-time time0))))
14110 (setq org-last-changed-timestamp
14111 (org-insert-time-stamp time with-hm inactive nil nil extra))
14112 (org-clock-update-time-maybe)
14113 (goto-char pos)
14114 ;; Try to recenter the calendar window, if any
14115 (if (and org-calendar-follow-timestamp-change
14116 (get-buffer-window "*Calendar*" t)
14117 (memq org-ts-what '(day month year)))
14118 (org-recenter-calendar (time-to-days time))))))
14120 (defun org-modify-ts-extra (s pos n dm)
14121 "Change the different parts of the lead-time and repeat fields in timestamp."
14122 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14123 ng h m new rem)
14124 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14125 (cond
14126 ((or (org-pos-in-match-range pos 2)
14127 (org-pos-in-match-range pos 3))
14128 (setq m (string-to-number (match-string 3 s))
14129 h (string-to-number (match-string 2 s)))
14130 (if (org-pos-in-match-range pos 2)
14131 (setq h (+ h n))
14132 (setq n (* dm (org-no-warnings (signum n))))
14133 (when (not (= 0 (setq rem (% m dm))))
14134 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14135 (setq m (+ m n)))
14136 (if (< m 0) (setq m (+ m 60) h (1- h)))
14137 (if (> m 59) (setq m (- m 60) h (1+ h)))
14138 (setq h (min 24 (max 0 h)))
14139 (setq ng 1 new (format "-%02d:%02d" h m)))
14140 ((org-pos-in-match-range pos 6)
14141 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14142 ((org-pos-in-match-range pos 5)
14143 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14145 ((org-pos-in-match-range pos 9)
14146 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14147 ((org-pos-in-match-range pos 8)
14148 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14150 (when ng
14151 (setq s (concat
14152 (substring s 0 (match-beginning ng))
14154 (substring s (match-end ng))))))
14157 (defun org-recenter-calendar (date)
14158 "If the calendar is visible, recenter it to DATE."
14159 (let* ((win (selected-window))
14160 (cwin (get-buffer-window "*Calendar*" t))
14161 (calendar-move-hook nil))
14162 (when cwin
14163 (select-window cwin)
14164 (calendar-goto-date (if (listp date) date
14165 (calendar-gregorian-from-absolute date)))
14166 (select-window win))))
14168 (defun org-goto-calendar (&optional arg)
14169 "Go to the Emacs calendar at the current date.
14170 If there is a time stamp in the current line, go to that date.
14171 A prefix ARG can be used to force the current date."
14172 (interactive "P")
14173 (let ((tsr org-ts-regexp) diff
14174 (calendar-move-hook nil)
14175 (calendar-view-holidays-initially-flag nil)
14176 (view-calendar-holidays-initially nil)
14177 (calendar-view-diary-initially-flag nil)
14178 (view-diary-entries-initially nil))
14179 (if (or (org-at-timestamp-p)
14180 (save-excursion
14181 (beginning-of-line 1)
14182 (looking-at (concat ".*" tsr))))
14183 (let ((d1 (time-to-days (current-time)))
14184 (d2 (time-to-days
14185 (org-time-string-to-time (match-string 1)))))
14186 (setq diff (- d2 d1))))
14187 (calendar)
14188 (calendar-goto-today)
14189 (if (and diff (not arg)) (calendar-forward-day diff))))
14191 (defun org-get-date-from-calendar ()
14192 "Return a list (month day year) of date at point in calendar."
14193 (with-current-buffer "*Calendar*"
14194 (save-match-data
14195 (calendar-cursor-to-date))))
14197 (defun org-date-from-calendar ()
14198 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14199 If there is already a time stamp at the cursor position, update it."
14200 (interactive)
14201 (if (org-at-timestamp-p t)
14202 (org-timestamp-change 0 'calendar)
14203 (let ((cal-date (org-get-date-from-calendar)))
14204 (org-insert-time-stamp
14205 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14207 (defun org-minutes-to-hh:mm-string (m)
14208 "Compute H:MM from a number of minutes."
14209 (let ((h (/ m 60)))
14210 (setq m (- m (* 60 h)))
14211 (format org-time-clocksum-format h m)))
14213 (defun org-hh:mm-string-to-minutes (s)
14214 "Convert a string H:MM to a number of minutes.
14215 If the string is just a number, interpret it as minutes.
14216 In fact, the first hh:mm or number in the string will be taken,
14217 there can be extra stuff in the string.
14218 If no number is found, the return value is 0."
14219 (cond
14220 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14221 (+ (* (string-to-number (match-string 1 s)) 60)
14222 (string-to-number (match-string 2 s))))
14223 ((string-match "\\([0-9]+\\)" s)
14224 (string-to-number (match-string 1 s)))
14225 (t 0)))
14227 ;;;; Files
14229 (defun org-save-all-org-buffers ()
14230 "Save all Org-mode buffers without user confirmation."
14231 (interactive)
14232 (message "Saving all Org-mode buffers...")
14233 (save-some-buffers t 'org-mode-p)
14234 (when (featurep 'org-id) (org-id-locations-save))
14235 (message "Saving all Org-mode buffers... done"))
14237 (defun org-revert-all-org-buffers ()
14238 "Revert all Org-mode buffers.
14239 Prompt for confirmation when there are unsaved changes.
14240 Be sure you know what you are doing before letting this function
14241 overwrite your changes.
14243 This function is useful in a setup where one tracks org files
14244 with a version control system, to revert on one machine after pulling
14245 changes from another. I believe the procedure must be like this:
14247 1. M-x org-save-all-org-buffers
14248 2. Pull changes from the other machine, resolve conflicts
14249 3. M-x org-revert-all-org-buffers"
14250 (interactive)
14251 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14252 (error "Abort"))
14253 (save-excursion
14254 (save-window-excursion
14255 (mapc
14256 (lambda (b)
14257 (when (and (with-current-buffer b (org-mode-p))
14258 (with-current-buffer b buffer-file-name))
14259 (switch-to-buffer b)
14260 (revert-buffer t 'no-confirm)))
14261 (buffer-list))
14262 (when (and (featurep 'org-id) org-id-track-globally)
14263 (org-id-locations-load)))))
14265 ;;;; Agenda files
14267 ;;;###autoload
14268 (defun org-iswitchb (&optional arg)
14269 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14270 With a prefix argument, restrict available to files.
14271 With two prefix arguments, restrict available buffers to agenda files."
14272 (interactive "P")
14273 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14274 ((equal arg '(16)) (org-buffer-list 'agenda))
14275 (t (org-buffer-list)))))
14276 (switch-to-buffer
14277 (org-icompleting-read "Org buffer: "
14278 (mapcar 'list (mapcar 'buffer-name blist))
14279 nil t))))
14281 ;;;###autoload
14282 (defalias 'org-ido-switchb 'org-iswitchb)
14284 (defun org-buffer-list (&optional predicate exclude-tmp)
14285 "Return a list of Org buffers.
14286 PREDICATE can be `export', `files' or `agenda'.
14288 export restrict the list to Export buffers.
14289 files restrict the list to buffers visiting Org files.
14290 agenda restrict the list to buffers visiting agenda files.
14292 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14293 (let* ((bfn nil)
14294 (agenda-files (and (eq predicate 'agenda)
14295 (mapcar 'file-truename (org-agenda-files t))))
14296 (filter
14297 (cond
14298 ((eq predicate 'files)
14299 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14300 ((eq predicate 'export)
14301 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14302 ((eq predicate 'agenda)
14303 (lambda (b)
14304 (with-current-buffer b
14305 (and (eq major-mode 'org-mode)
14306 (setq bfn (buffer-file-name b))
14307 (member (file-truename bfn) agenda-files)))))
14308 (t (lambda (b) (with-current-buffer b
14309 (or (eq major-mode 'org-mode)
14310 (string-match "\*Org .*Export"
14311 (buffer-name b)))))))))
14312 (delq nil
14313 (mapcar
14314 (lambda(b)
14315 (if (and (funcall filter b)
14316 (or (not exclude-tmp)
14317 (not (string-match "tmp" (buffer-name b)))))
14319 nil))
14320 (buffer-list)))))
14322 (defun org-agenda-files (&optional unrestricted archives)
14323 "Get the list of agenda files.
14324 Optional UNRESTRICTED means return the full list even if a restriction
14325 is currently in place.
14326 When ARCHIVES is t, include all archive files hat are really being
14327 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14328 `org-agenda-archives-mode' is t."
14329 (let ((files
14330 (cond
14331 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14332 ((stringp org-agenda-files) (org-read-agenda-file-list))
14333 ((listp org-agenda-files) org-agenda-files)
14334 (t (error "Invalid value of `org-agenda-files'")))))
14335 (setq files (apply 'append
14336 (mapcar (lambda (f)
14337 (if (file-directory-p f)
14338 (directory-files
14339 f t org-agenda-file-regexp)
14340 (list f)))
14341 files)))
14342 (when org-agenda-skip-unavailable-files
14343 (setq files (delq nil
14344 (mapcar (function
14345 (lambda (file)
14346 (and (file-readable-p file) file)))
14347 files))))
14348 (when (or (eq archives t)
14349 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14350 (setq files (org-add-archive-files files)))
14351 files))
14353 (defun org-edit-agenda-file-list ()
14354 "Edit the list of agenda files.
14355 Depending on setup, this either uses customize to edit the variable
14356 `org-agenda-files', or it visits the file that is holding the list. In the
14357 latter case, the buffer is set up in a way that saving it automatically kills
14358 the buffer and restores the previous window configuration."
14359 (interactive)
14360 (if (stringp org-agenda-files)
14361 (let ((cw (current-window-configuration)))
14362 (find-file org-agenda-files)
14363 (org-set-local 'org-window-configuration cw)
14364 (org-add-hook 'after-save-hook
14365 (lambda ()
14366 (set-window-configuration
14367 (prog1 org-window-configuration
14368 (kill-buffer (current-buffer))))
14369 (org-install-agenda-files-menu)
14370 (message "New agenda file list installed"))
14371 nil 'local)
14372 (message "%s" (substitute-command-keys
14373 "Edit list and finish with \\[save-buffer]")))
14374 (customize-variable 'org-agenda-files)))
14376 (defun org-store-new-agenda-file-list (list)
14377 "Set new value for the agenda file list and save it correctly."
14378 (if (stringp org-agenda-files)
14379 (let ((f org-agenda-files) b)
14380 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14381 (with-temp-file f
14382 (insert (mapconcat 'identity list "\n") "\n")))
14383 (let ((org-mode-hook nil) (org-inhibit-startup t)
14384 (org-insert-mode-line-in-empty-file nil))
14385 (setq org-agenda-files list)
14386 (customize-save-variable 'org-agenda-files org-agenda-files))))
14388 (defun org-read-agenda-file-list ()
14389 "Read the list of agenda files from a file."
14390 (when (file-directory-p org-agenda-files)
14391 (error "`org-agenda-files' cannot be a single directory"))
14392 (when (stringp org-agenda-files)
14393 (with-temp-buffer
14394 (insert-file-contents org-agenda-files)
14395 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14398 ;;;###autoload
14399 (defun org-cycle-agenda-files ()
14400 "Cycle through the files in `org-agenda-files'.
14401 If the current buffer visits an agenda file, find the next one in the list.
14402 If the current buffer does not, find the first agenda file."
14403 (interactive)
14404 (let* ((fs (org-agenda-files t))
14405 (files (append fs (list (car fs))))
14406 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14407 file)
14408 (unless files (error "No agenda files"))
14409 (catch 'exit
14410 (while (setq file (pop files))
14411 (if (equal (file-truename file) tcf)
14412 (when (car files)
14413 (find-file (car files))
14414 (throw 'exit t))))
14415 (find-file (car fs)))
14416 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14418 (defun org-agenda-file-to-front (&optional to-end)
14419 "Move/add the current file to the top of the agenda file list.
14420 If the file is not present in the list, it is added to the front. If it is
14421 present, it is moved there. With optional argument TO-END, add/move to the
14422 end of the list."
14423 (interactive "P")
14424 (let ((org-agenda-skip-unavailable-files nil)
14425 (file-alist (mapcar (lambda (x)
14426 (cons (file-truename x) x))
14427 (org-agenda-files t)))
14428 (ctf (file-truename buffer-file-name))
14429 x had)
14430 (setq x (assoc ctf file-alist) had x)
14432 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14433 (if to-end
14434 (setq file-alist (append (delq x file-alist) (list x)))
14435 (setq file-alist (cons x (delq x file-alist))))
14436 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14437 (org-install-agenda-files-menu)
14438 (message "File %s to %s of agenda file list"
14439 (if had "moved" "added") (if to-end "end" "front"))))
14441 (defun org-remove-file (&optional file)
14442 "Remove current file from the list of files in variable `org-agenda-files'.
14443 These are the files which are being checked for agenda entries.
14444 Optional argument FILE means, use this file instead of the current."
14445 (interactive)
14446 (let* ((org-agenda-skip-unavailable-files nil)
14447 (file (or file buffer-file-name))
14448 (true-file (file-truename file))
14449 (afile (abbreviate-file-name file))
14450 (files (delq nil (mapcar
14451 (lambda (x)
14452 (if (equal true-file
14453 (file-truename x))
14454 nil x))
14455 (org-agenda-files t)))))
14456 (if (not (= (length files) (length (org-agenda-files t))))
14457 (progn
14458 (org-store-new-agenda-file-list files)
14459 (org-install-agenda-files-menu)
14460 (message "Removed file: %s" afile))
14461 (message "File was not in list: %s (not removed)" afile))))
14463 (defun org-file-menu-entry (file)
14464 (vector file (list 'find-file file) t))
14466 (defun org-check-agenda-file (file)
14467 "Make sure FILE exists. If not, ask user what to do."
14468 (when (not (file-exists-p file))
14469 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14470 (abbreviate-file-name file))
14471 (let ((r (downcase (read-char-exclusive))))
14472 (cond
14473 ((equal r ?r)
14474 (org-remove-file file)
14475 (throw 'nextfile t))
14476 (t (error "Abort"))))))
14478 (defun org-get-agenda-file-buffer (file)
14479 "Get a buffer visiting FILE. If the buffer needs to be created, add
14480 it to the list of buffers which might be released later."
14481 (let ((buf (org-find-base-buffer-visiting file)))
14482 (if buf
14483 buf ; just return it
14484 ;; Make a new buffer and remember it
14485 (setq buf (find-file-noselect file))
14486 (if buf (push buf org-agenda-new-buffers))
14487 buf)))
14489 (defun org-release-buffers (blist)
14490 "Release all buffers in list, asking the user for confirmation when needed.
14491 When a buffer is unmodified, it is just killed. When modified, it is saved
14492 \(if the user agrees) and then killed."
14493 (let (buf file)
14494 (while (setq buf (pop blist))
14495 (setq file (buffer-file-name buf))
14496 (when (and (buffer-modified-p buf)
14497 file
14498 (y-or-n-p (format "Save file %s? " file)))
14499 (with-current-buffer buf (save-buffer)))
14500 (kill-buffer buf))))
14502 (defun org-prepare-agenda-buffers (files)
14503 "Create buffers for all agenda files, protect archived trees and comments."
14504 (interactive)
14505 (let ((pa '(:org-archived t))
14506 (pc '(:org-comment t))
14507 (pall '(:org-archived t :org-comment t))
14508 (inhibit-read-only t)
14509 (rea (concat ":" org-archive-tag ":"))
14510 bmp file re)
14511 (save-excursion
14512 (save-restriction
14513 (while (setq file (pop files))
14514 (catch 'nextfile
14515 (if (bufferp file)
14516 (set-buffer file)
14517 (org-check-agenda-file file)
14518 (set-buffer (org-get-agenda-file-buffer file)))
14519 (widen)
14520 (setq bmp (buffer-modified-p))
14521 (org-refresh-category-properties)
14522 (setq org-todo-keywords-for-agenda
14523 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14524 (setq org-done-keywords-for-agenda
14525 (append org-done-keywords-for-agenda org-done-keywords))
14526 (setq org-todo-keyword-alist-for-agenda
14527 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14528 (setq org-drawers-for-agenda
14529 (append org-drawers-for-agenda org-drawers))
14530 (setq org-tag-alist-for-agenda
14531 (append org-tag-alist-for-agenda org-tag-alist))
14533 (save-excursion
14534 (remove-text-properties (point-min) (point-max) pall)
14535 (when org-agenda-skip-archived-trees
14536 (goto-char (point-min))
14537 (while (re-search-forward rea nil t)
14538 (if (org-on-heading-p t)
14539 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14540 (goto-char (point-min))
14541 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14542 (while (re-search-forward re nil t)
14543 (add-text-properties
14544 (match-beginning 0) (org-end-of-subtree t) pc)))
14545 (set-buffer-modified-p bmp)))))
14546 (setq org-todo-keyword-alist-for-agenda
14547 (org-uniquify org-todo-keyword-alist-for-agenda)
14548 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14550 ;;;; Embedded LaTeX
14552 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14553 "Keymap for the minor `org-cdlatex-mode'.")
14555 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14556 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14557 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14558 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14559 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14561 (defvar org-cdlatex-texmathp-advice-is-done nil
14562 "Flag remembering if we have applied the advice to texmathp already.")
14564 (define-minor-mode org-cdlatex-mode
14565 "Toggle the minor `org-cdlatex-mode'.
14566 This mode supports entering LaTeX environment and math in LaTeX fragments
14567 in Org-mode.
14568 \\{org-cdlatex-mode-map}"
14569 nil " OCDL" nil
14570 (when org-cdlatex-mode (require 'cdlatex))
14571 (unless org-cdlatex-texmathp-advice-is-done
14572 (setq org-cdlatex-texmathp-advice-is-done t)
14573 (defadvice texmathp (around org-math-always-on activate)
14574 "Always return t in org-mode buffers.
14575 This is because we want to insert math symbols without dollars even outside
14576 the LaTeX math segments. If Orgmode thinks that point is actually inside
14577 an embedded LaTeX fragment, let texmathp do its job.
14578 \\[org-cdlatex-mode-map]"
14579 (interactive)
14580 (let (p)
14581 (cond
14582 ((not (org-mode-p)) ad-do-it)
14583 ((eq this-command 'cdlatex-math-symbol)
14584 (setq ad-return-value t
14585 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14587 (let ((p (org-inside-LaTeX-fragment-p)))
14588 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14589 (setq ad-return-value t
14590 texmathp-why '("Org-mode embedded math" . 0))
14591 (if p ad-do-it)))))))))
14593 (defun turn-on-org-cdlatex ()
14594 "Unconditionally turn on `org-cdlatex-mode'."
14595 (org-cdlatex-mode 1))
14597 (defun org-inside-LaTeX-fragment-p ()
14598 "Test if point is inside a LaTeX fragment.
14599 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14600 sequence appearing also before point.
14601 Even though the matchers for math are configurable, this function assumes
14602 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14603 delimiters are skipped when they have been removed by customization.
14604 The return value is nil, or a cons cell with the delimiter and
14605 and the position of this delimiter.
14607 This function does a reasonably good job, but can locally be fooled by
14608 for example currency specifications. For example it will assume being in
14609 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14610 fragments that are properly closed, but during editing, we have to live
14611 with the uncertainty caused by missing closing delimiters. This function
14612 looks only before point, not after."
14613 (catch 'exit
14614 (let ((pos (point))
14615 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14616 (lim (progn
14617 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14618 (point)))
14619 dd-on str (start 0) m re)
14620 (goto-char pos)
14621 (when dodollar
14622 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14623 re (nth 1 (assoc "$" org-latex-regexps)))
14624 (while (string-match re str start)
14625 (cond
14626 ((= (match-end 0) (length str))
14627 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14628 ((= (match-end 0) (- (length str) 5))
14629 (throw 'exit nil))
14630 (t (setq start (match-end 0))))))
14631 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14632 (goto-char pos)
14633 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14634 (and (match-beginning 2) (throw 'exit nil))
14635 ;; count $$
14636 (while (re-search-backward "\\$\\$" lim t)
14637 (setq dd-on (not dd-on)))
14638 (goto-char pos)
14639 (if dd-on (cons "$$" m))))))
14641 (defun org-inside-latex-macro-p ()
14642 "Is point inside a LaTeX macro or its arguments?"
14643 (save-match-data
14644 (org-in-regexp
14645 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14647 (defun org-try-cdlatex-tab ()
14648 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14649 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14650 - inside a LaTeX fragment, or
14651 - after the first word in a line, where an abbreviation expansion could
14652 insert a LaTeX environment."
14653 (when org-cdlatex-mode
14654 (cond
14655 ((save-excursion
14656 (skip-chars-backward "a-zA-Z0-9*")
14657 (skip-chars-backward " \t")
14658 (bolp))
14659 (cdlatex-tab) t)
14660 ((org-inside-LaTeX-fragment-p)
14661 (cdlatex-tab) t)
14662 (t nil))))
14664 (defun org-cdlatex-underscore-caret (&optional arg)
14665 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14666 Revert to the normal definition outside of these fragments."
14667 (interactive "P")
14668 (if (org-inside-LaTeX-fragment-p)
14669 (call-interactively 'cdlatex-sub-superscript)
14670 (let (org-cdlatex-mode)
14671 (call-interactively (key-binding (vector last-input-event))))))
14673 (defun org-cdlatex-math-modify (&optional arg)
14674 "Execute `cdlatex-math-modify' in LaTeX fragments.
14675 Revert to the normal definition outside of these fragments."
14676 (interactive "P")
14677 (if (org-inside-LaTeX-fragment-p)
14678 (call-interactively 'cdlatex-math-modify)
14679 (let (org-cdlatex-mode)
14680 (call-interactively (key-binding (vector last-input-event))))))
14682 (defvar org-latex-fragment-image-overlays nil
14683 "List of overlays carrying the images of latex fragments.")
14684 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14686 (defun org-remove-latex-fragment-image-overlays ()
14687 "Remove all overlays with LaTeX fragment images in current buffer."
14688 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14689 (setq org-latex-fragment-image-overlays nil))
14691 (defun org-preview-latex-fragment (&optional subtree)
14692 "Preview the LaTeX fragment at point, or all locally or globally.
14693 If the cursor is in a LaTeX fragment, create the image and overlay
14694 it over the source code. If there is no fragment at point, display
14695 all fragments in the current text, from one headline to the next. With
14696 prefix SUBTREE, display all fragments in the current subtree. With a
14697 double prefix `C-u C-u', or when the cursor is before the first headline,
14698 display all fragments in the buffer.
14699 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14700 (interactive "P")
14701 (org-remove-latex-fragment-image-overlays)
14702 (save-excursion
14703 (save-restriction
14704 (let (beg end at msg)
14705 (cond
14706 ((or (equal subtree '(16))
14707 (not (save-excursion
14708 (re-search-backward (concat "^" outline-regexp) nil t))))
14709 (setq beg (point-min) end (point-max)
14710 msg "Creating images for buffer...%s"))
14711 ((equal subtree '(4))
14712 (org-back-to-heading)
14713 (setq beg (point) end (org-end-of-subtree t)
14714 msg "Creating images for subtree...%s"))
14716 (if (setq at (org-inside-LaTeX-fragment-p))
14717 (goto-char (max (point-min) (- (cdr at) 2)))
14718 (org-back-to-heading))
14719 (setq beg (point) end (progn (outline-next-heading) (point))
14720 msg (if at "Creating image...%s"
14721 "Creating images for entry...%s"))))
14722 (message msg "")
14723 (narrow-to-region beg end)
14724 (goto-char beg)
14725 (org-format-latex
14726 (concat "ltxpng/" (file-name-sans-extension
14727 (file-name-nondirectory
14728 buffer-file-name)))
14729 default-directory 'overlays msg at 'forbuffer)
14730 (message msg "done. Use `C-c C-c' to remove images.")))))
14732 (defvar org-latex-regexps
14733 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14734 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14735 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14736 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14737 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14738 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14739 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14740 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14741 "Regular expressions for matching embedded LaTeX.")
14743 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14744 "Replace LaTeX fragments with links to an image, and produce images.
14745 Some of the options can be changed using the variable
14746 `org-format-latex-options'."
14747 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14748 (let* ((prefixnodir (file-name-nondirectory prefix))
14749 (absprefix (expand-file-name prefix dir))
14750 (todir (file-name-directory absprefix))
14751 (opt org-format-latex-options)
14752 (matchers (plist-get opt :matchers))
14753 (re-list org-latex-regexps)
14754 (cnt 0) txt hash link beg end re e checkdir
14755 executables-checked
14756 m n block linkfile movefile ov)
14757 ;; Check the different regular expressions
14758 (while (setq e (pop re-list))
14759 (setq m (car e) re (nth 1 e) n (nth 2 e)
14760 block (if (nth 3 e) "\n\n" ""))
14761 (when (member m matchers)
14762 (goto-char (point-min))
14763 (while (re-search-forward re nil t)
14764 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14765 (not (get-text-property (match-beginning n)
14766 'org-protected))
14767 (or (not overlays)
14768 (not (eq (get-char-property (match-beginning n)
14769 'org-overlay-type)
14770 'org-latex-overlay))))
14771 (setq txt (match-string n)
14772 beg (match-beginning n) end (match-end n)
14773 cnt (1+ cnt))
14774 (let (print-length print-level) ; make sure full list is printed
14775 (setq hash (sha1 (prin1-to-string
14776 (list org-format-latex-header
14777 org-export-latex-packages-alist
14778 org-format-latex-options
14779 forbuffer txt)))
14780 linkfile (format "%s_%s.png" prefix hash)
14781 movefile (format "%s_%s.png" absprefix hash)))
14782 (setq link (concat block "[[file:" linkfile "]]" block))
14783 (if msg (message msg cnt))
14784 (goto-char beg)
14785 (unless checkdir ; make sure the directory exists
14786 (setq checkdir t)
14787 (or (file-directory-p todir) (make-directory todir)))
14789 (unless executables-checked
14790 (org-check-external-command
14791 "latex" "needed to convert LaTeX fragments to images")
14792 (org-check-external-command
14793 "dvipng" "needed to convert LaTeX fragments to images")
14794 (setq executables-checked t))
14796 (unless (file-exists-p movefile)
14797 (org-create-formula-image
14798 txt movefile opt forbuffer))
14799 (if overlays
14800 (progn
14801 (mapc (lambda (o)
14802 (if (eq (org-overlay-get o 'org-overlay-type)
14803 'org-latex-overlay)
14804 (org-delete-overlay o)))
14805 (org-overlays-in beg end))
14806 (setq ov (org-make-overlay beg end))
14807 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14808 (if (featurep 'xemacs)
14809 (progn
14810 (org-overlay-put ov 'invisible t)
14811 (org-overlay-put
14812 ov 'end-glyph
14813 (make-glyph (vector 'png :file movefile))))
14814 (org-overlay-put
14815 ov 'display
14816 (list 'image :type 'png :file movefile :ascent 'center)))
14817 (push ov org-latex-fragment-image-overlays)
14818 (goto-char end))
14819 (delete-region beg end)
14820 (insert link))))))))
14822 ;; This function borrows from Ganesh Swami's latex2png.el
14823 (defun org-create-formula-image (string tofile options buffer)
14824 "This calls dvipng."
14825 (require 'org-latex)
14826 (let* ((tmpdir (if (featurep 'xemacs)
14827 (temp-directory)
14828 temporary-file-directory))
14829 (texfilebase (make-temp-name
14830 (expand-file-name "orgtex" tmpdir)))
14831 (texfile (concat texfilebase ".tex"))
14832 (dvifile (concat texfilebase ".dvi"))
14833 (pngfile (concat texfilebase ".png"))
14834 (fnh (if (featurep 'xemacs)
14835 (font-height (get-face-font 'default))
14836 (face-attribute 'default :height nil)))
14837 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14838 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14839 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14840 "Black"))
14841 (bg (or (plist-get options (if buffer :background :html-background))
14842 "Transparent")))
14843 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14844 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14845 (with-temp-file texfile
14846 (insert org-format-latex-header
14847 (if org-export-latex-packages-alist
14848 (concat "\n"
14849 (mapconcat (lambda(p)
14850 (if (equal "" (car p))
14851 (format "\\usepackage{%s}" (cadr p))
14852 (format "\\usepackage[%s]{%s}"
14853 (car p) (cadr p))))
14854 org-export-latex-packages-alist "\n"))
14856 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14857 (let ((dir default-directory))
14858 (condition-case nil
14859 (progn
14860 (cd tmpdir)
14861 (call-process "latex" nil nil nil texfile))
14862 (error nil))
14863 (cd dir))
14864 (if (not (file-exists-p dvifile))
14865 (progn (message "Failed to create dvi file from %s" texfile) nil)
14866 (condition-case nil
14867 (call-process "dvipng" nil nil nil
14868 "-fg" fg "-bg" bg
14869 "-D" dpi
14870 ;;"-x" scale "-y" scale
14871 "-T" "tight"
14872 "-o" pngfile
14873 dvifile)
14874 (error nil))
14875 (if (not (file-exists-p pngfile))
14876 (progn (message "Failed to create png file from %s" texfile) nil)
14877 ;; Use the requested file name and clean up
14878 (copy-file pngfile tofile 'replace)
14879 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14880 (delete-file (concat texfilebase e)))
14881 pngfile))))
14883 (defun org-dvipng-color (attr)
14884 "Return an rgb color specification for dvipng."
14885 (apply 'format "rgb %s %s %s"
14886 (mapcar 'org-normalize-color
14887 (color-values (face-attribute 'default attr nil)))))
14889 (defun org-normalize-color (value)
14890 "Return string to be used as color value for an RGB component."
14891 (format "%g" (/ value 65535.0)))
14893 ;;;; Key bindings
14895 ;; Make `C-c C-x' a prefix key
14896 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14898 ;; TAB key with modifiers
14899 (org-defkey org-mode-map "\C-i" 'org-cycle)
14900 (org-defkey org-mode-map [(tab)] 'org-cycle)
14901 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14902 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14903 (org-defkey org-mode-map "\M-\t" 'org-complete)
14904 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14905 ;; The following line is necessary under Suse GNU/Linux
14906 (unless (featurep 'xemacs)
14907 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14908 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14909 (define-key org-mode-map [backtab] 'org-shifttab)
14911 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14912 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14913 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14915 ;; Cursor keys with modifiers
14916 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14917 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14918 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14919 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14921 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14922 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14923 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14924 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14926 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14927 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14928 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14929 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14931 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14932 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14934 ;;; Extra keys for tty access.
14935 ;; We only set them when really needed because otherwise the
14936 ;; menus don't show the simple keys
14938 (when (or org-use-extra-keys
14939 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14940 (not window-system))
14941 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14942 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14943 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14944 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14945 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14946 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14947 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14948 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14949 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14950 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14951 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14952 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14953 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14954 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14955 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14956 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14957 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14958 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14959 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14960 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14961 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14962 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14963 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14964 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14965 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14966 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14967 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14968 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14970 ;; All the other keys
14972 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14973 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14974 (if (boundp 'narrow-map)
14975 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14976 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14977 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14978 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14979 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14980 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14981 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14982 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14983 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14984 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14985 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14986 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14987 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14988 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14989 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14990 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14991 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14992 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14993 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14994 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14995 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14996 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14997 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14998 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14999 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15000 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15001 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15002 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15003 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15004 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15005 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15006 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15007 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15008 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15009 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15010 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15011 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15012 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15013 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15014 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15015 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15016 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15017 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15018 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15019 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15020 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15021 (org-defkey org-mode-map "\C-c^" 'org-sort)
15022 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15023 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15024 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15025 (org-defkey org-mode-map "\C-m" 'org-return)
15026 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15027 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15028 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15029 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15030 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15031 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15032 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15033 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15034 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15035 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15036 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15037 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15038 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15039 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15040 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15041 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15042 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15043 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15044 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15045 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15046 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15048 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15049 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15050 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15051 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15053 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15054 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15055 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15056 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15057 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15058 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15059 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15060 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15061 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15062 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15063 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15064 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15065 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15066 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15067 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15069 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15070 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15071 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15072 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15074 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15076 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15078 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15079 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15081 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15084 (when (featurep 'xemacs)
15085 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15088 (defconst org-speed-commands-default
15090 ("Outline Navigation")
15091 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15092 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15093 ("f" . (org-speed-move-safe 'org-forward-same-level))
15094 ("b" . (org-speed-move-safe 'org-backward-same-level))
15095 ("u" . (org-speed-move-safe 'outline-up-heading))
15096 ("j" . org-goto)
15097 ("g" . (org-refile t))
15098 ("Outline Visibility")
15099 ("c" . org-cycle)
15100 ("C" . org-shifttab)
15101 (" " . org-display-outline-path)
15102 ("Outline Structure Editing")
15103 ("U" . org-shiftmetaup)
15104 ("D" . org-shiftmetadown)
15105 ("r" . org-metaright)
15106 ("l" . org-metaleft)
15107 ("R" . org-shiftmetaright)
15108 ("L" . org-shiftmetaleft)
15109 ("i" . (progn (forward-char 1) (call-interactively
15110 'org-insert-heading-respect-content)))
15111 ("^" . org-sort)
15112 ("w" . org-refile)
15113 ("a" . org-archive-subtree-default-with-confirmation)
15114 ("." . outline-mark-subtree)
15115 ("Clock Commands")
15116 ("I" . org-clock-in)
15117 ("O" . org-clock-out)
15118 ("Meta Data Editing")
15119 ("t" . org-todo)
15120 ("0" . (org-priority ?\ ))
15121 ("1" . (org-priority ?A))
15122 ("2" . (org-priority ?B))
15123 ("3" . (org-priority ?C))
15124 (";" . org-set-tags-command)
15125 ("e" . org-set-effort)
15126 ("Agenda Views etc")
15127 ("v" . org-agenda)
15128 ("/" . org-sparse-tree)
15129 ("Misc")
15130 ("o" . org-open-at-point)
15131 ("?" . org-speed-command-help)
15133 "The default speed commands.")
15135 (defun org-print-speed-command (e)
15136 (if (> (length (car e)) 1)
15137 (progn
15138 (princ "\n")
15139 (princ (car e))
15140 (princ "\n")
15141 (princ (make-string (length (car e)) ?-))
15142 (princ "\n"))
15143 (princ (car e))
15144 (princ " ")
15145 (if (symbolp (cdr e))
15146 (princ (symbol-name (cdr e)))
15147 (prin1 (cdr e)))
15148 (princ "\n")))
15150 (defun org-speed-command-help ()
15151 "Show the available speed commands."
15152 (interactive)
15153 (if (not org-use-speed-commands)
15154 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15155 (with-output-to-temp-buffer "*Help*"
15156 (princ "User-defined Speed commands\n===========================\n")
15157 (mapc 'org-print-speed-command org-speed-commands-user)
15158 (princ "\n")
15159 (princ "Built-in Speed commands\n=======================\n")
15160 (mapc 'org-print-speed-command org-speed-commands-default))
15161 (with-current-buffer "*Help*"
15162 (setq truncate-lines t))))
15164 (defun org-speed-move-safe (cmd)
15165 "Execute CMD, but make sure that the cursor always ends up in a headline.
15166 If not, return to the original position and throw an error."
15167 (interactive)
15168 (let ((pos (point)))
15169 (call-interactively cmd)
15170 (unless (and (bolp) (org-on-heading-p))
15171 (goto-char pos)
15172 (error "Boundary reached while executing %s" cmd))))
15174 (defvar org-self-insert-command-undo-counter 0)
15176 (defvar org-table-auto-blank-field) ; defined in org-table.el
15177 (defvar org-speed-command nil)
15178 (defun org-self-insert-command (N)
15179 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15180 If the cursor is in a table looking at whitespace, the whitespace is
15181 overwritten, and the table is not marked as requiring realignment."
15182 (interactive "p")
15183 (cond
15184 ((and org-use-speed-commands
15185 (or (and (bolp) (looking-at outline-regexp))
15186 (and (functionp org-use-speed-commands)
15187 (funcall org-use-speed-commands)))
15188 (setq
15189 org-speed-command
15190 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15191 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15192 (cond
15193 ((commandp org-speed-command)
15194 (setq this-command org-speed-command)
15195 (call-interactively org-speed-command))
15196 ((functionp org-speed-command)
15197 (funcall org-speed-command))
15198 ((and org-speed-command (listp org-speed-command))
15199 (eval org-speed-command))
15200 (t (let (org-use-speed-commands)
15201 (call-interactively 'org-self-insert-command)))))
15202 ((and
15203 (org-table-p)
15204 (progn
15205 ;; check if we blank the field, and if that triggers align
15206 (and (featurep 'org-table) org-table-auto-blank-field
15207 (member last-command
15208 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15209 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15210 ;; got extra space, this field does not determine column width
15211 (let (org-table-may-need-update) (org-table-blank-field))
15212 ;; no extra space, this field may determine column width
15213 (org-table-blank-field)))
15215 (eq N 1)
15216 (looking-at "[^|\n]* |"))
15217 (let (org-table-may-need-update)
15218 (goto-char (1- (match-end 0)))
15219 (delete-backward-char 1)
15220 (goto-char (match-beginning 0))
15221 (self-insert-command N)))
15223 (setq org-table-may-need-update t)
15224 (self-insert-command N)
15225 (org-fix-tags-on-the-fly)
15226 (if org-self-insert-cluster-for-undo
15227 (if (not (eq last-command 'org-self-insert-command))
15228 (setq org-self-insert-command-undo-counter 1)
15229 (if (>= org-self-insert-command-undo-counter 20)
15230 (setq org-self-insert-command-undo-counter 1)
15231 (and (> org-self-insert-command-undo-counter 0)
15232 buffer-undo-list
15233 (not (cadr buffer-undo-list)) ; remove nil entry
15234 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15235 (setq org-self-insert-command-undo-counter
15236 (1+ org-self-insert-command-undo-counter))))))))
15238 (defun org-fix-tags-on-the-fly ()
15239 (when (and (equal (char-after (point-at-bol)) ?*)
15240 (org-on-heading-p))
15241 (org-align-tags-here org-tags-column)))
15243 (defun org-delete-backward-char (N)
15244 "Like `delete-backward-char', insert whitespace at field end in tables.
15245 When deleting backwards, in tables this function will insert whitespace in
15246 front of the next \"|\" separator, to keep the table aligned. The table will
15247 still be marked for re-alignment if the field did fill the entire column,
15248 because, in this case the deletion might narrow the column."
15249 (interactive "p")
15250 (if (and (org-table-p)
15251 (eq N 1)
15252 (string-match "|" (buffer-substring (point-at-bol) (point)))
15253 (looking-at ".*?|"))
15254 (let ((pos (point))
15255 (noalign (looking-at "[^|\n\r]* |"))
15256 (c org-table-may-need-update))
15257 (backward-delete-char N)
15258 (skip-chars-forward "^|")
15259 (insert " ")
15260 (goto-char (1- pos))
15261 ;; noalign: if there were two spaces at the end, this field
15262 ;; does not determine the width of the column.
15263 (if noalign (setq org-table-may-need-update c)))
15264 (backward-delete-char N)
15265 (org-fix-tags-on-the-fly)))
15267 (defun org-delete-char (N)
15268 "Like `delete-char', but insert whitespace at field end in tables.
15269 When deleting characters, in tables this function will insert whitespace in
15270 front of the next \"|\" separator, to keep the table aligned. The table will
15271 still be marked for re-alignment if the field did fill the entire column,
15272 because, in this case the deletion might narrow the column."
15273 (interactive "p")
15274 (if (and (org-table-p)
15275 (not (bolp))
15276 (not (= (char-after) ?|))
15277 (eq N 1))
15278 (if (looking-at ".*?|")
15279 (let ((pos (point))
15280 (noalign (looking-at "[^|\n\r]* |"))
15281 (c org-table-may-need-update))
15282 (replace-match (concat
15283 (substring (match-string 0) 1 -1)
15284 " |"))
15285 (goto-char pos)
15286 ;; noalign: if there were two spaces at the end, this field
15287 ;; does not determine the width of the column.
15288 (if noalign (setq org-table-may-need-update c)))
15289 (delete-char N))
15290 (delete-char N)
15291 (org-fix-tags-on-the-fly)))
15293 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15294 (put 'org-self-insert-command 'delete-selection t)
15295 (put 'orgtbl-self-insert-command 'delete-selection t)
15296 (put 'org-delete-char 'delete-selection 'supersede)
15297 (put 'org-delete-backward-char 'delete-selection 'supersede)
15298 (put 'org-yank 'delete-selection 'yank)
15300 ;; Make `flyspell-mode' delay after some commands
15301 (put 'org-self-insert-command 'flyspell-delayed t)
15302 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15303 (put 'org-delete-char 'flyspell-delayed t)
15304 (put 'org-delete-backward-char 'flyspell-delayed t)
15306 ;; Make pabbrev-mode expand after org-mode commands
15307 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15308 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15310 ;; How to do this: Measure non-white length of current string
15311 ;; If equal to column width, we should realign.
15313 (defun org-remap (map &rest commands)
15314 "In MAP, remap the functions given in COMMANDS.
15315 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15316 (let (new old)
15317 (while commands
15318 (setq old (pop commands) new (pop commands))
15319 (if (fboundp 'command-remapping)
15320 (org-defkey map (vector 'remap old) new)
15321 (substitute-key-definition old new map global-map)))))
15323 (when (eq org-enable-table-editor 'optimized)
15324 ;; If the user wants maximum table support, we need to hijack
15325 ;; some standard editing functions
15326 (org-remap org-mode-map
15327 'self-insert-command 'org-self-insert-command
15328 'delete-char 'org-delete-char
15329 'delete-backward-char 'org-delete-backward-char)
15330 (org-defkey org-mode-map "|" 'org-force-self-insert))
15332 (defvar org-ctrl-c-ctrl-c-hook nil
15333 "Hook for functions attaching themselves to `C-c C-c'.
15334 This can be used to add additional functionality to the C-c C-c key which
15335 executes context-dependent commands.
15336 Each function will be called with no arguments. The function must check
15337 if the context is appropriate for it to act. If yes, it should do its
15338 thing and then return a non-nil value. If the context is wrong,
15339 just do nothing and return nil.")
15341 (defvar org-tab-first-hook nil
15342 "Hook for functions to attach themselves to TAB.
15343 See `org-ctrl-c-ctrl-c-hook' for more information.
15344 This hook runs as the first action when TAB is pressed, even before
15345 `org-cycle' messes around with the `outline-regexp' to cater for
15346 inline tasks and plain list item folding.
15347 If any function in this hook returns t, not other actions like table
15348 field motion visibility cycling will be done.")
15350 (defvar org-tab-after-check-for-table-hook nil
15351 "Hook for functions to attach themselves to TAB.
15352 See `org-ctrl-c-ctrl-c-hook' for more information.
15353 This hook runs after it has been established that the cursor is not in a
15354 table, but before checking if the cursor is in a headline or if global cycling
15355 should be done.
15356 If any function in this hook returns t, not other actions like visibility
15357 cycling will be done.")
15359 (defvar org-tab-after-check-for-cycling-hook nil
15360 "Hook for functions to attach themselves to TAB.
15361 See `org-ctrl-c-ctrl-c-hook' for more information.
15362 This hook runs after it has been established that not table field motion and
15363 not visibility should be done because of current context. This is probably
15364 the place where a package like yasnippets can hook in.")
15366 (defvar org-tab-before-tab-emulation-hook nil
15367 "Hook for functions to attach themselves to TAB.
15368 See `org-ctrl-c-ctrl-c-hook' for more information.
15369 This hook runs after every other options for TAB have been exhausted, but
15370 before indentation and \t insertion takes place.")
15372 (defvar org-metaleft-hook nil
15373 "Hook for functions attaching themselves to `M-left'.
15374 See `org-ctrl-c-ctrl-c-hook' for more information.")
15375 (defvar org-metaright-hook nil
15376 "Hook for functions attaching themselves to `M-right'.
15377 See `org-ctrl-c-ctrl-c-hook' for more information.")
15378 (defvar org-metaup-hook nil
15379 "Hook for functions attaching themselves to `M-up'.
15380 See `org-ctrl-c-ctrl-c-hook' for more information.")
15381 (defvar org-metadown-hook nil
15382 "Hook for functions attaching themselves to `M-down'.
15383 See `org-ctrl-c-ctrl-c-hook' for more information.")
15384 (defvar org-shiftmetaleft-hook nil
15385 "Hook for functions attaching themselves to `M-S-left'.
15386 See `org-ctrl-c-ctrl-c-hook' for more information.")
15387 (defvar org-shiftmetaright-hook nil
15388 "Hook for functions attaching themselves to `M-S-right'.
15389 See `org-ctrl-c-ctrl-c-hook' for more information.")
15390 (defvar org-shiftmetaup-hook nil
15391 "Hook for functions attaching themselves to `M-S-up'.
15392 See `org-ctrl-c-ctrl-c-hook' for more information.")
15393 (defvar org-shiftmetadown-hook nil
15394 "Hook for functions attaching themselves to `M-S-down'.
15395 See `org-ctrl-c-ctrl-c-hook' for more information.")
15396 (defvar org-metareturn-hook nil
15397 "Hook for functions attaching themselves to `M-RET'.
15398 See `org-ctrl-c-ctrl-c-hook' for more information.")
15400 (defun org-modifier-cursor-error ()
15401 "Throw an error, a modified cursor command was applied in wrong context."
15402 (error "This command is active in special context like tables, headlines or items"))
15404 (defun org-shiftselect-error ()
15405 "Throw an error because Shift-Cursor command was applied in wrong context."
15406 (if (and (boundp 'shift-select-mode) shift-select-mode)
15407 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15408 (error "This command works only in special context like headlines or timestamps")))
15410 (defun org-call-for-shift-select (cmd)
15411 (let ((this-command-keys-shift-translated t))
15412 (call-interactively cmd)))
15414 (defun org-shifttab (&optional arg)
15415 "Global visibility cycling or move to previous table field.
15416 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15417 on context.
15418 See the individual commands for more information."
15419 (interactive "P")
15420 (cond
15421 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15422 ((integerp arg)
15423 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15424 (message "Content view to level: %d" arg)
15425 (org-content (prefix-numeric-value arg2))
15426 (setq org-cycle-global-status 'overview)))
15427 (t (call-interactively 'org-global-cycle))))
15429 (defun org-shiftmetaleft ()
15430 "Promote subtree or delete table column.
15431 Calls `org-promote-subtree', `org-outdent-item',
15432 or `org-table-delete-column', depending on context.
15433 See the individual commands for more information."
15434 (interactive)
15435 (cond
15436 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15437 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15438 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15439 ((org-at-item-p) (call-interactively 'org-outdent-item))
15440 (t (org-modifier-cursor-error))))
15442 (defun org-shiftmetaright ()
15443 "Demote subtree or insert table column.
15444 Calls `org-demote-subtree', `org-indent-item',
15445 or `org-table-insert-column', depending on context.
15446 See the individual commands for more information."
15447 (interactive)
15448 (cond
15449 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15450 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15451 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15452 ((org-at-item-p) (call-interactively 'org-indent-item))
15453 (t (org-modifier-cursor-error))))
15455 (defun org-shiftmetaup (&optional arg)
15456 "Move subtree up or kill table row.
15457 Calls `org-move-subtree-up' or `org-table-kill-row' or
15458 `org-move-item-up' depending on context. See the individual commands
15459 for more information."
15460 (interactive "P")
15461 (cond
15462 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15463 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15464 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15465 ((org-at-item-p) (call-interactively 'org-move-item-up))
15466 (t (org-modifier-cursor-error))))
15468 (defun org-shiftmetadown (&optional arg)
15469 "Move subtree down or insert table row.
15470 Calls `org-move-subtree-down' or `org-table-insert-row' or
15471 `org-move-item-down', depending on context. See the individual
15472 commands for more information."
15473 (interactive "P")
15474 (cond
15475 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15476 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15477 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15478 ((org-at-item-p) (call-interactively 'org-move-item-down))
15479 (t (org-modifier-cursor-error))))
15481 (defun org-metaleft (&optional arg)
15482 "Promote heading or move table column to left.
15483 Calls `org-do-promote' or `org-table-move-column', depending on context.
15484 With no specific context, calls the Emacs default `backward-word'.
15485 See the individual commands for more information."
15486 (interactive "P")
15487 (cond
15488 ((run-hook-with-args-until-success 'org-metaleft-hook))
15489 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15490 ((or (org-on-heading-p)
15491 (and (org-region-active-p)
15492 (save-excursion
15493 (goto-char (region-beginning))
15494 (org-on-heading-p))))
15495 (call-interactively 'org-do-promote))
15496 ((or (org-at-item-p)
15497 (and (org-region-active-p)
15498 (save-excursion
15499 (goto-char (region-beginning))
15500 (org-at-item-p))))
15501 (call-interactively 'org-outdent-item))
15502 (t (call-interactively 'backward-word))))
15504 (defun org-metaright (&optional arg)
15505 "Demote subtree or move table column to right.
15506 Calls `org-do-demote' or `org-table-move-column', depending on context.
15507 With no specific context, calls the Emacs default `forward-word'.
15508 See the individual commands for more information."
15509 (interactive "P")
15510 (cond
15511 ((run-hook-with-args-until-success 'org-metaright-hook))
15512 ((org-at-table-p) (call-interactively 'org-table-move-column))
15513 ((or (org-on-heading-p)
15514 (and (org-region-active-p)
15515 (save-excursion
15516 (goto-char (region-beginning))
15517 (org-on-heading-p))))
15518 (call-interactively 'org-do-demote))
15519 ((or (org-at-item-p)
15520 (and (org-region-active-p)
15521 (save-excursion
15522 (goto-char (region-beginning))
15523 (org-at-item-p))))
15524 (call-interactively 'org-indent-item))
15525 (t (call-interactively 'forward-word))))
15527 (defun org-metaup (&optional arg)
15528 "Move subtree up or move table row up.
15529 Calls `org-move-subtree-up' or `org-table-move-row' or
15530 `org-move-item-up', depending on context. See the individual commands
15531 for more information."
15532 (interactive "P")
15533 (cond
15534 ((run-hook-with-args-until-success 'org-metaup-hook))
15535 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15536 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15537 ((org-at-item-p) (call-interactively 'org-move-item-up))
15538 (t (transpose-lines 1) (beginning-of-line -1))))
15540 (defun org-metadown (&optional arg)
15541 "Move subtree down or move table row down.
15542 Calls `org-move-subtree-down' or `org-table-move-row' or
15543 `org-move-item-down', depending on context. See the individual
15544 commands for more information."
15545 (interactive "P")
15546 (cond
15547 ((run-hook-with-args-until-success 'org-metadown-hook))
15548 ((org-at-table-p) (call-interactively 'org-table-move-row))
15549 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15550 ((org-at-item-p) (call-interactively 'org-move-item-down))
15551 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15553 (defun org-shiftup (&optional arg)
15554 "Increase item in timestamp or increase priority of current headline.
15555 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15556 depending on context. See the individual commands for more information."
15557 (interactive "P")
15558 (cond
15559 ((and org-support-shift-select (org-region-active-p))
15560 (org-call-for-shift-select 'previous-line))
15561 ((org-at-timestamp-p t)
15562 (call-interactively (if org-edit-timestamp-down-means-later
15563 'org-timestamp-down 'org-timestamp-up)))
15564 ((and (not (eq org-support-shift-select 'always))
15565 org-enable-priority-commands
15566 (org-on-heading-p))
15567 (call-interactively 'org-priority-up))
15568 ((and (not org-support-shift-select) (org-at-item-p))
15569 (call-interactively 'org-previous-item))
15570 ((org-clocktable-try-shift 'up arg))
15571 (org-support-shift-select
15572 (org-call-for-shift-select 'previous-line))
15573 (t (org-shiftselect-error))))
15575 (defun org-shiftdown (&optional arg)
15576 "Decrease item in timestamp or decrease priority of current headline.
15577 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15578 depending on context. See the individual commands for more information."
15579 (interactive "P")
15580 (cond
15581 ((and org-support-shift-select (org-region-active-p))
15582 (org-call-for-shift-select 'next-line))
15583 ((org-at-timestamp-p t)
15584 (call-interactively (if org-edit-timestamp-down-means-later
15585 'org-timestamp-up 'org-timestamp-down)))
15586 ((and (not (eq org-support-shift-select 'always))
15587 org-enable-priority-commands
15588 (org-on-heading-p))
15589 (call-interactively 'org-priority-down))
15590 ((and (not org-support-shift-select) (org-at-item-p))
15591 (call-interactively 'org-next-item))
15592 ((org-clocktable-try-shift 'down arg))
15593 (org-support-shift-select
15594 (org-call-for-shift-select 'next-line))
15595 (t (org-shiftselect-error))))
15597 (defun org-shiftright (&optional arg)
15598 "Cycle the thing at point or in the current line, depending on context.
15599 Depending on context, this does one of the following:
15601 - switch a timestamp at point one day into the future
15602 - on a headline, switch to the next TODO keyword.
15603 - on an item, switch entire list to the next bullet type
15604 - on a property line, switch to the next allowed value
15605 - on a clocktable definition line, move time block into the future"
15606 (interactive "P")
15607 (cond
15608 ((and org-support-shift-select (org-region-active-p))
15609 (org-call-for-shift-select 'forward-char))
15610 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15611 ((and (not (eq org-support-shift-select 'always))
15612 (org-on-heading-p))
15613 (let ((org-inhibit-logging
15614 (not org-treat-S-cursor-todo-selection-as-state-change))
15615 (org-inhibit-blocking
15616 (not org-treat-S-cursor-todo-selection-as-state-change)))
15617 (org-call-with-arg 'org-todo 'right)))
15618 ((or (and org-support-shift-select
15619 (not (eq org-support-shift-select 'always))
15620 (org-at-item-bullet-p))
15621 (and (not org-support-shift-select) (org-at-item-p)))
15622 (org-call-with-arg 'org-cycle-list-bullet nil))
15623 ((and (not (eq org-support-shift-select 'always))
15624 (org-at-property-p))
15625 (call-interactively 'org-property-next-allowed-value))
15626 ((org-clocktable-try-shift 'right arg))
15627 (org-support-shift-select
15628 (org-call-for-shift-select 'forward-char))
15629 (t (org-shiftselect-error))))
15631 (defun org-shiftleft (&optional arg)
15632 "Cycle the thing at point or in the current line, depending on context.
15633 Depending on context, this does one of the following:
15635 - switch a timestamp at point one day into the past
15636 - on a headline, switch to the previous TODO keyword.
15637 - on an item, switch entire list to the previous bullet type
15638 - on a property line, switch to the previous allowed value
15639 - on a clocktable definition line, move time block into the past"
15640 (interactive "P")
15641 (cond
15642 ((and org-support-shift-select (org-region-active-p))
15643 (org-call-for-shift-select 'backward-char))
15644 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15645 ((and (not (eq org-support-shift-select 'always))
15646 (org-on-heading-p))
15647 (let ((org-inhibit-logging
15648 (not org-treat-S-cursor-todo-selection-as-state-change))
15649 (org-inhibit-blocking
15650 (not org-treat-S-cursor-todo-selection-as-state-change)))
15651 (org-call-with-arg 'org-todo 'left)))
15652 ((or (and org-support-shift-select
15653 (not (eq org-support-shift-select 'always))
15654 (org-at-item-bullet-p))
15655 (and (not org-support-shift-select) (org-at-item-p)))
15656 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15657 ((and (not (eq org-support-shift-select 'always))
15658 (org-at-property-p))
15659 (call-interactively 'org-property-previous-allowed-value))
15660 ((org-clocktable-try-shift 'left arg))
15661 (org-support-shift-select
15662 (org-call-for-shift-select 'backward-char))
15663 (t (org-shiftselect-error))))
15665 (defun org-shiftcontrolright ()
15666 "Switch to next TODO set."
15667 (interactive)
15668 (cond
15669 ((and org-support-shift-select (org-region-active-p))
15670 (org-call-for-shift-select 'forward-word))
15671 ((and (not (eq org-support-shift-select 'always))
15672 (org-on-heading-p))
15673 (org-call-with-arg 'org-todo 'nextset))
15674 (org-support-shift-select
15675 (org-call-for-shift-select 'forward-word))
15676 (t (org-shiftselect-error))))
15678 (defun org-shiftcontrolleft ()
15679 "Switch to previous TODO set."
15680 (interactive)
15681 (cond
15682 ((and org-support-shift-select (org-region-active-p))
15683 (org-call-for-shift-select 'backward-word))
15684 ((and (not (eq org-support-shift-select 'always))
15685 (org-on-heading-p))
15686 (org-call-with-arg 'org-todo 'previousset))
15687 (org-support-shift-select
15688 (org-call-for-shift-select 'backward-word))
15689 (t (org-shiftselect-error))))
15691 (defun org-ctrl-c-ret ()
15692 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15693 (interactive)
15694 (cond
15695 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15696 (t (call-interactively 'org-insert-heading))))
15698 (defun org-copy-special ()
15699 "Copy region in table or copy current subtree.
15700 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15701 See the individual commands for more information."
15702 (interactive)
15703 (call-interactively
15704 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15706 (defun org-cut-special ()
15707 "Cut region in table or cut current subtree.
15708 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15709 See the individual commands for more information."
15710 (interactive)
15711 (call-interactively
15712 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15714 (defun org-paste-special (arg)
15715 "Paste rectangular region into table, or past subtree relative to level.
15716 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15717 See the individual commands for more information."
15718 (interactive "P")
15719 (if (org-at-table-p)
15720 (org-table-paste-rectangle)
15721 (org-paste-subtree arg)))
15723 (defun org-edit-special ()
15724 "Call a special editor for the stuff at point.
15725 When at a table, call the formula editor with `org-table-edit-formulas'.
15726 When at the first line of an src example, call `org-edit-src-code'.
15727 When in an #+include line, visit the include file. Otherwise call
15728 `ffap' to visit the file at point."
15729 (interactive)
15730 (cond
15731 ((org-at-table-p)
15732 (call-interactively 'org-table-edit-formulas))
15733 ((save-excursion
15734 (beginning-of-line 1)
15735 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15736 (find-file (org-trim (match-string 1))))
15737 ((org-edit-src-code))
15738 ((org-edit-fixed-width-region))
15739 (t (call-interactively 'ffap))))
15742 (defun org-ctrl-c-ctrl-c (&optional arg)
15743 "Set tags in headline, or update according to changed information at point.
15745 This command does many different things, depending on context:
15747 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15748 this is what we do.
15750 - If the cursor is on a statistics cookie, update it.
15752 - If the cursor is in a headline, prompt for tags and insert them
15753 into the current line, aligned to `org-tags-column'. When called
15754 with prefix arg, realign all tags in the current buffer.
15756 - If the cursor is in one of the special #+KEYWORD lines, this
15757 triggers scanning the buffer for these lines and updating the
15758 information.
15760 - If the cursor is inside a table, realign the table. This command
15761 works even if the automatic table editor has been turned off.
15763 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15764 the entire table.
15766 - If the cursor is at a footnote reference or definition, jump to
15767 the corresponding definition or references, respectively.
15769 - If the cursor is a the beginning of a dynamic block, update it.
15771 - If the cursor is inside a table created by the table.el package,
15772 activate that table.
15774 - If the current buffer is a remember buffer, close note and file
15775 it. A prefix argument of 1 files to the default location
15776 without further interaction. A prefix argument of 2 files to
15777 the currently clocking task.
15779 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15780 links in this buffer.
15782 - If the cursor is on a numbered item in a plain list, renumber the
15783 ordered list.
15785 - If the cursor is on a checkbox, toggle it."
15786 (interactive "P")
15787 (let ((org-enable-table-editor t))
15788 (cond
15789 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15790 org-occur-highlights
15791 org-latex-fragment-image-overlays)
15792 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15793 (org-remove-occur-highlights)
15794 (org-remove-latex-fragment-image-overlays)
15795 (message "Temporary highlights/overlays removed from current buffer"))
15796 ((and (local-variable-p 'org-finish-function (current-buffer))
15797 (fboundp org-finish-function))
15798 (funcall org-finish-function))
15799 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15800 ((org-at-property-p)
15801 (call-interactively 'org-property-action))
15802 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15803 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15804 (or (org-on-heading-p) (org-at-item-p)))
15805 (call-interactively 'org-update-statistics-cookies))
15806 ((org-on-heading-p) (call-interactively 'org-set-tags))
15807 ((org-at-table.el-p)
15808 (require 'table)
15809 (beginning-of-line 1)
15810 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15811 (call-interactively 'table-recognize-table))
15812 ((org-at-table-p)
15813 (org-table-maybe-eval-formula)
15814 (if arg
15815 (call-interactively 'org-table-recalculate)
15816 (org-table-maybe-recalculate-line))
15817 (call-interactively 'org-table-align))
15818 ((or (org-footnote-at-reference-p)
15819 (org-footnote-at-definition-p))
15820 (call-interactively 'org-footnote-action))
15821 ((org-at-item-checkbox-p)
15822 (call-interactively 'org-toggle-checkbox))
15823 ((org-at-item-p)
15824 (if arg
15825 (call-interactively 'org-toggle-checkbox)
15826 (call-interactively 'org-maybe-renumber-ordered-list)))
15827 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15828 ;; Dynamic block
15829 (beginning-of-line 1)
15830 (save-excursion (org-update-dblock)))
15831 ((save-excursion
15832 (beginning-of-line 1)
15833 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15834 (cond
15835 ((equal (match-string 1) "TBLFM")
15836 ;; Recalculate the table before this line
15837 (save-excursion
15838 (beginning-of-line 1)
15839 (skip-chars-backward " \r\n\t")
15840 (if (org-at-table-p)
15841 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15843 (let ((org-inhibit-startup-visibility-stuff t)
15844 (org-startup-align-all-tables nil))
15845 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15846 (message "Local setup has been refreshed"))))
15847 ((org-clock-update-time-maybe))
15848 (t (error "C-c C-c can do nothing useful at this location")))))
15850 (defun org-mode-restart ()
15851 "Restart Org-mode, to scan again for special lines.
15852 Also updates the keyword regular expressions."
15853 (interactive)
15854 (org-mode)
15855 (message "Org-mode restarted"))
15857 (defun org-kill-note-or-show-branches ()
15858 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15859 (interactive)
15860 (if (not org-finish-function)
15861 (call-interactively 'show-branches)
15862 (let ((org-note-abort t))
15863 (funcall org-finish-function))))
15865 (defun org-return (&optional indent)
15866 "Goto next table row or insert a newline.
15867 Calls `org-table-next-row' or `newline', depending on context.
15868 See the individual commands for more information."
15869 (interactive)
15870 (cond
15871 ((bobp) (if indent (newline-and-indent) (newline)))
15872 ((org-at-table-p)
15873 (org-table-justify-field-maybe)
15874 (call-interactively 'org-table-next-row))
15875 ((and org-return-follows-link
15876 (eq (get-text-property (point) 'face) 'org-link))
15877 (call-interactively 'org-open-at-point))
15878 ((and (org-at-heading-p)
15879 (looking-at
15880 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15881 (org-show-entry)
15882 (end-of-line 1)
15883 (newline))
15884 (t (if indent (newline-and-indent) (newline)))))
15886 (defun org-return-indent ()
15887 "Goto next table row or insert a newline and indent.
15888 Calls `org-table-next-row' or `newline-and-indent', depending on
15889 context. See the individual commands for more information."
15890 (interactive)
15891 (org-return t))
15893 (defun org-ctrl-c-star ()
15894 "Compute table, or change heading status of lines.
15895 Calls `org-table-recalculate' or `org-toggle-heading',
15896 depending on context."
15897 (interactive)
15898 (cond
15899 ((org-at-table-p)
15900 (call-interactively 'org-table-recalculate))
15902 ;; Convert all lines in region to list items
15903 (call-interactively 'org-toggle-heading))))
15905 (defun org-ctrl-c-minus ()
15906 "Insert separator line in table or modify bullet status of line.
15907 Also turns a plain line or a region of lines into list items.
15908 Calls `org-table-insert-hline', `org-toggle-item', or
15909 `org-cycle-list-bullet', depending on context."
15910 (interactive)
15911 (cond
15912 ((org-at-table-p)
15913 (call-interactively 'org-table-insert-hline))
15914 ((org-region-active-p)
15915 (call-interactively 'org-toggle-item))
15916 ((org-in-item-p)
15917 (call-interactively 'org-cycle-list-bullet))
15919 (call-interactively 'org-toggle-item))))
15921 (defun org-toggle-item ()
15922 "Convert headings or normal lines to items, items to normal lines.
15923 If there is no active region, only the current line is considered.
15925 If the first line in the region is a headline, convert all headlines to items.
15927 If the first line in the region is an item, convert all items to normal lines.
15929 If the first line is normal text, add an item bullet to each line."
15930 (interactive)
15931 (let (l2 l beg end)
15932 (if (org-region-active-p)
15933 (setq beg (region-beginning) end (region-end))
15934 (setq beg (point-at-bol)
15935 end (min (1+ (point-at-eol)) (point-max))))
15936 (save-excursion
15937 (goto-char end)
15938 (setq l2 (org-current-line))
15939 (goto-char beg)
15940 (beginning-of-line 1)
15941 (setq l (1- (org-current-line)))
15942 (if (org-at-item-p)
15943 ;; We already have items, de-itemize
15944 (while (< (setq l (1+ l)) l2)
15945 (when (org-at-item-p)
15946 (goto-char (match-beginning 2))
15947 (delete-region (match-beginning 2) (match-end 2))
15948 (and (looking-at "[ \t]+") (replace-match "")))
15949 (beginning-of-line 2))
15950 (if (org-on-heading-p)
15951 ;; Headings, convert to items
15952 (while (< (setq l (1+ l)) l2)
15953 (if (looking-at org-outline-regexp)
15954 (replace-match "- " t t))
15955 (beginning-of-line 2))
15956 ;; normal lines, turn them into items
15957 (while (< (setq l (1+ l)) l2)
15958 (unless (org-at-item-p)
15959 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15960 (replace-match "\\1- \\2")))
15961 (beginning-of-line 2)))))))
15963 (defun org-toggle-heading (&optional nstars)
15964 "Convert headings to normal text, or items or text to headings.
15965 If there is no active region, only the current line is considered.
15967 If the first line is a heading, remove the stars from all headlines
15968 in the region.
15970 If the first line is a plain list item, turn all plain list items
15971 into headings.
15973 If the first line is a normal line, turn each and every line in the
15974 region into a heading.
15976 When converting a line into a heading, the number of stars is chosen
15977 such that the lines become children of the current entry. However,
15978 when a prefix argument is given, its value determines the number of
15979 stars to add."
15980 (interactive "P")
15981 (let (l2 l itemp beg end)
15982 (if (org-region-active-p)
15983 (setq beg (region-beginning) end (region-end))
15984 (setq beg (point-at-bol)
15985 end (min (1+ (point-at-eol)) (point-max))))
15986 (save-excursion
15987 (goto-char end)
15988 (setq l2 (org-current-line))
15989 (goto-char beg)
15990 (beginning-of-line 1)
15991 (setq l (1- (org-current-line)))
15992 (if (org-on-heading-p)
15993 ;; We already have headlines, de-star them
15994 (while (< (setq l (1+ l)) l2)
15995 (when (org-on-heading-p t)
15996 (and (looking-at outline-regexp) (replace-match "")))
15997 (beginning-of-line 2))
15998 (setq itemp (org-at-item-p))
15999 (let* ((stars
16000 (if nstars
16001 (make-string (prefix-numeric-value current-prefix-arg)
16003 (save-excursion
16004 (if (re-search-backward org-complex-heading-regexp nil t)
16005 (match-string 1) ""))))
16006 (add-stars (cond (nstars "")
16007 ((equal stars "") "*")
16008 (org-odd-levels-only "**")
16009 (t "*")))
16010 (rpl (concat stars add-stars " ")))
16011 (while (< (setq l (1+ l)) l2)
16012 (if itemp
16013 (and (org-at-item-p) (replace-match rpl t t))
16014 (unless (org-on-heading-p)
16015 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16016 (replace-match (concat rpl (match-string 2))))))
16017 (beginning-of-line 2)))))))
16019 (defun org-meta-return (&optional arg)
16020 "Insert a new heading or wrap a region in a table.
16021 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16022 See the individual commands for more information."
16023 (interactive "P")
16024 (cond
16025 ((run-hook-with-args-until-success 'org-metareturn-hook))
16026 ((org-at-table-p)
16027 (call-interactively 'org-table-wrap-region))
16028 (t (call-interactively 'org-insert-heading))))
16030 ;;; Menu entries
16032 ;; Define the Org-mode menus
16033 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16034 '("Tbl"
16035 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16036 ["Next Field" org-cycle (org-at-table-p)]
16037 ["Previous Field" org-shifttab (org-at-table-p)]
16038 ["Next Row" org-return (org-at-table-p)]
16039 "--"
16040 ["Blank Field" org-table-blank-field (org-at-table-p)]
16041 ["Edit Field" org-table-edit-field (org-at-table-p)]
16042 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16043 "--"
16044 ("Column"
16045 ["Move Column Left" org-metaleft (org-at-table-p)]
16046 ["Move Column Right" org-metaright (org-at-table-p)]
16047 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16048 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16049 ("Row"
16050 ["Move Row Up" org-metaup (org-at-table-p)]
16051 ["Move Row Down" org-metadown (org-at-table-p)]
16052 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16053 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16054 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16055 "--"
16056 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16057 ("Rectangle"
16058 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16059 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16060 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16061 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16062 "--"
16063 ("Calculate"
16064 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16065 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16066 ["Edit Formulas" org-edit-special (org-at-table-p)]
16067 "--"
16068 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16069 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16070 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16071 "--"
16072 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16073 "--"
16074 ["Sum Column/Rectangle" org-table-sum
16075 (or (org-at-table-p) (org-region-active-p))]
16076 ["Which Column?" org-table-current-column (org-at-table-p)])
16077 ["Debug Formulas"
16078 org-table-toggle-formula-debugger
16079 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16080 ["Show Col/Row Numbers"
16081 org-table-toggle-coordinate-overlays
16082 :style toggle
16083 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16084 "--"
16085 ["Create" org-table-create (and (not (org-at-table-p))
16086 org-enable-table-editor)]
16087 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16088 ["Import from File" org-table-import (not (org-at-table-p))]
16089 ["Export to File" org-table-export (org-at-table-p)]
16090 "--"
16091 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16093 (easy-menu-define org-org-menu org-mode-map "Org menu"
16094 '("Org"
16095 ("Show/Hide"
16096 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16097 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16098 ["Sparse Tree..." org-sparse-tree t]
16099 ["Reveal Context" org-reveal t]
16100 ["Show All" show-all t]
16101 "--"
16102 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16103 "--"
16104 ["New Heading" org-insert-heading t]
16105 ("Navigate Headings"
16106 ["Up" outline-up-heading t]
16107 ["Next" outline-next-visible-heading t]
16108 ["Previous" outline-previous-visible-heading t]
16109 ["Next Same Level" outline-forward-same-level t]
16110 ["Previous Same Level" outline-backward-same-level t]
16111 "--"
16112 ["Jump" org-goto t])
16113 ("Edit Structure"
16114 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16115 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16116 "--"
16117 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16118 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16119 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16120 "--"
16121 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16122 "--"
16123 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16124 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16125 ["Demote Heading" org-metaright (not (org-at-table-p))]
16126 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16127 "--"
16128 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16129 "--"
16130 ["Convert to odd levels" org-convert-to-odd-levels t]
16131 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16132 ("Editing"
16133 ["Emphasis..." org-emphasize t]
16134 ["Edit Source Example" org-edit-special t]
16135 "--"
16136 ["Footnote new/jump" org-footnote-action t]
16137 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16138 ("Archive"
16139 ["Archive (default method)" org-archive-subtree-default t]
16140 "--"
16141 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16142 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16143 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16145 "--"
16146 ("Hyperlinks"
16147 ["Store Link (Global)" org-store-link t]
16148 ["Find existing link to here" org-occur-link-in-agenda-files t]
16149 ["Insert Link" org-insert-link t]
16150 ["Follow Link" org-open-at-point t]
16151 "--"
16152 ["Next link" org-next-link t]
16153 ["Previous link" org-previous-link t]
16154 "--"
16155 ["Descriptive Links"
16156 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16157 :style radio
16158 :selected (member '(org-link) buffer-invisibility-spec)]
16159 ["Literal Links"
16160 (progn
16161 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16162 :style radio
16163 :selected (not (member '(org-link) buffer-invisibility-spec))])
16164 "--"
16165 ("TODO Lists"
16166 ["TODO/DONE/-" org-todo t]
16167 ("Select keyword"
16168 ["Next keyword" org-shiftright (org-on-heading-p)]
16169 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16170 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16171 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16172 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16173 ["Show TODO Tree" org-show-todo-tree t]
16174 ["Global TODO list" org-todo-list t]
16175 "--"
16176 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16177 :selected org-enforce-todo-dependencies :style toggle :active t]
16178 "Settings for tree at point"
16179 ["Do Children sequentially" org-toggle-ordered-property :style radio
16180 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16181 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16182 ["Do Children parallel" org-toggle-ordered-property :style radio
16183 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16184 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16185 "--"
16186 ["Set Priority" org-priority t]
16187 ["Priority Up" org-shiftup t]
16188 ["Priority Down" org-shiftdown t]
16189 "--"
16190 ["Get news from all feeds" org-feed-update-all t]
16191 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16192 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16193 ("TAGS and Properties"
16194 ["Set Tags" org-set-tags-command t]
16195 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16196 "--"
16197 ["Set property" org-set-property t]
16198 ["Column view of properties" org-columns t]
16199 ["Insert Column View DBlock" org-insert-columns-dblock t])
16200 ("Dates and Scheduling"
16201 ["Timestamp" org-time-stamp t]
16202 ["Timestamp (inactive)" org-time-stamp-inactive t]
16203 ("Change Date"
16204 ["1 Day Later" org-shiftright t]
16205 ["1 Day Earlier" org-shiftleft t]
16206 ["1 ... Later" org-shiftup t]
16207 ["1 ... Earlier" org-shiftdown t])
16208 ["Compute Time Range" org-evaluate-time-range t]
16209 ["Schedule Item" org-schedule t]
16210 ["Deadline" org-deadline t]
16211 "--"
16212 ["Custom time format" org-toggle-time-stamp-overlays
16213 :style radio :selected org-display-custom-times]
16214 "--"
16215 ["Goto Calendar" org-goto-calendar t]
16216 ["Date from Calendar" org-date-from-calendar t]
16217 "--"
16218 ["Start/Restart Timer" org-timer-start t]
16219 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16220 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16221 ["Insert Timer String" org-timer t]
16222 ["Insert Timer Item" org-timer-item t])
16223 ("Logging work"
16224 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16225 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16226 ["Clock out" org-clock-out t]
16227 ["Clock cancel" org-clock-cancel t]
16228 "--"
16229 ["Mark as default task" org-clock-mark-default-task t]
16230 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16231 ["Goto running clock" org-clock-goto t]
16232 "--"
16233 ["Display times" org-clock-display t]
16234 ["Create clock table" org-clock-report t]
16235 "--"
16236 ["Record DONE time"
16237 (progn (setq org-log-done (not org-log-done))
16238 (message "Switching to %s will %s record a timestamp"
16239 (car org-done-keywords)
16240 (if org-log-done "automatically" "not")))
16241 :style toggle :selected org-log-done])
16242 "--"
16243 ["Agenda Command..." org-agenda t]
16244 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16245 ("File List for Agenda")
16246 ("Special views current file"
16247 ["TODO Tree" org-show-todo-tree t]
16248 ["Check Deadlines" org-check-deadlines t]
16249 ["Timeline" org-timeline t]
16250 ["Tags/Property tree" org-match-sparse-tree t])
16251 "--"
16252 ["Export/Publish..." org-export t]
16253 ("LaTeX"
16254 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16255 :selected org-cdlatex-mode]
16256 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16257 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16258 ["Modify math symbol" org-cdlatex-math-modify
16259 (org-inside-LaTeX-fragment-p)]
16260 ["Insert citation" org-reftex-citation t]
16261 "--"
16262 ["Export LaTeX fragments as images"
16263 (if (featurep 'org-exp)
16264 (setq org-export-with-LaTeX-fragments
16265 (not org-export-with-LaTeX-fragments))
16266 (require 'org-exp))
16267 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16268 org-export-with-LaTeX-fragments)]
16269 "--"
16270 ["Template for BEAMER" org-beamer-settings-template t])
16271 "--"
16272 ("MobileOrg"
16273 ["Push Files and Views" org-mobile-push t]
16274 ["Get Captured and Flagged" org-mobile-pull t]
16275 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16276 "--"
16277 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16278 "--"
16279 ("Documentation"
16280 ["Show Version" org-version t]
16281 ["Info Documentation" org-info t])
16282 ("Customize"
16283 ["Browse Org Group" org-customize t]
16284 "--"
16285 ["Expand This Menu" org-create-customize-menu
16286 (fboundp 'customize-menu-create)])
16287 ["Send bug report" org-submit-bug-report t]
16288 "--"
16289 ("Refresh/Reload"
16290 ["Refresh setup current buffer" org-mode-restart t]
16291 ["Reload Org (after update)" org-reload t]
16292 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16295 (defun org-info (&optional node)
16296 "Read documentation for Org-mode in the info system.
16297 With optional NODE, go directly to that node."
16298 (interactive)
16299 (info (format "(org)%s" (or node ""))))
16301 ;;;###autoload
16302 (defun org-submit-bug-report ()
16303 "Submit a bug report on Org-mode via mail.
16305 Don't hesitate to report any problems or inaccurate documentation.
16307 If you don't have setup sending mail from (X)Emacs, please copy the
16308 output buffer into your mail program, as it gives us important
16309 information about your Org-mode version and configuration."
16310 (interactive)
16311 (require 'reporter)
16312 (org-load-modules-maybe)
16313 (org-require-autoloaded-modules)
16314 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16315 (reporter-submit-bug-report
16316 "emacs-orgmode@gnu.org"
16317 (org-version)
16318 (let (list)
16319 (save-window-excursion
16320 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16321 (delete-other-windows)
16322 (erase-buffer)
16323 (insert "You are about to submit a bug report to the Org-mode mailing list.
16325 We would like to add your full Org-mode and Outline configuration to the
16326 bug report. This greatly simplifies the work of the maintainer and
16327 other experts on the mailing list.
16329 HOWEVER, some variables you have customized may contain private
16330 information. The names of customers, colleagues, or friends, might
16331 appear in the form of file names, tags, todo states, or search strings.
16332 If you answer yes to the prompt, you might want to check and remove
16333 such private information before sending the email.")
16334 (add-text-properties (point-min) (point-max) '(face org-warning))
16335 (when (yes-or-no-p "Include your Org-mode configuration ")
16336 (mapatoms
16337 (lambda (v)
16338 (and (boundp v)
16339 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16340 (or (and (symbol-value v)
16341 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16342 (and
16343 (get v 'custom-type) (get v 'standard-value)
16344 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16345 (push v list)))))
16346 (kill-buffer (get-buffer "*Warn about privacy*"))
16347 list))
16348 nil nil
16349 "Remember to cover the basics, that is, what you expected to happen and
16350 what in fact did happen. You don't know how to make a good report? See
16352 http://orgmode.org/manual/Feedback.html#Feedback
16354 Your bug report will be posted to the Org-mode mailing list.
16355 ------------------------------------------------------------------------")
16356 (save-excursion
16357 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16358 (replace-match "\\1Bug: \\3 [\\2]")))))
16361 (defun org-install-agenda-files-menu ()
16362 (let ((bl (buffer-list)))
16363 (save-excursion
16364 (while bl
16365 (set-buffer (pop bl))
16366 (if (org-mode-p) (setq bl nil)))
16367 (when (org-mode-p)
16368 (easy-menu-change
16369 '("Org") "File List for Agenda"
16370 (append
16371 (list
16372 ["Edit File List" (org-edit-agenda-file-list) t]
16373 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16374 ["Remove Current File from List" org-remove-file t]
16375 ["Cycle through agenda files" org-cycle-agenda-files t]
16376 ["Occur in all agenda files" org-occur-in-agenda-files t]
16377 "--")
16378 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16380 ;;;; Documentation
16382 ;;;###autoload
16383 (defun org-require-autoloaded-modules ()
16384 (interactive)
16385 (mapc 'require
16386 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16387 org-docbook org-exp org-html org-icalendar
16388 org-id org-latex
16389 org-publish org-remember org-table
16390 org-timer org-xoxo)))
16392 ;;;###autoload
16393 (defun org-reload (&optional uncompiled)
16394 "Reload all org lisp files.
16395 With prefix arg UNCOMPILED, load the uncompiled versions."
16396 (interactive "P")
16397 (require 'find-func)
16398 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16399 (dir-org (file-name-directory (org-find-library-name "org")))
16400 (dir-org-contrib (ignore-errors
16401 (file-name-directory
16402 (org-find-library-name "org-contribdir"))))
16403 (files
16404 (append (directory-files dir-org t file-re)
16405 (and dir-org-contrib
16406 (directory-files dir-org-contrib t file-re))))
16407 (remove-re (concat (if (featurep 'xemacs)
16408 "org-colview" "org-colview-xemacs")
16409 "\\'")))
16410 (setq files (mapcar 'file-name-sans-extension files))
16411 (setq files (mapcar
16412 (lambda (x) (if (string-match remove-re x) nil x))
16413 files))
16414 (setq files (delq nil files))
16415 (mapc
16416 (lambda (f)
16417 (when (featurep (intern (file-name-nondirectory f)))
16418 (if (and (not uncompiled)
16419 (file-exists-p (concat f ".elc")))
16420 (load (concat f ".elc") nil nil t)
16421 (load (concat f ".el") nil nil t))))
16422 files))
16423 (org-version))
16425 ;;;###autoload
16426 (defun org-customize ()
16427 "Call the customize function with org as argument."
16428 (interactive)
16429 (org-load-modules-maybe)
16430 (org-require-autoloaded-modules)
16431 (customize-browse 'org))
16433 (defun org-create-customize-menu ()
16434 "Create a full customization menu for Org-mode, insert it into the menu."
16435 (interactive)
16436 (org-load-modules-maybe)
16437 (org-require-autoloaded-modules)
16438 (if (fboundp 'customize-menu-create)
16439 (progn
16440 (easy-menu-change
16441 '("Org") "Customize"
16442 `(["Browse Org group" org-customize t]
16443 "--"
16444 ,(customize-menu-create 'org)
16445 ["Set" Custom-set t]
16446 ["Save" Custom-save t]
16447 ["Reset to Current" Custom-reset-current t]
16448 ["Reset to Saved" Custom-reset-saved t]
16449 ["Reset to Standard Settings" Custom-reset-standard t]))
16450 (message "\"Org\"-menu now contains full customization menu"))
16451 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16453 ;;;; Miscellaneous stuff
16455 ;;; Generally useful functions
16457 (defun org-get-at-bol (property)
16458 "Get text property PROPERTY at beginning of line."
16459 (get-text-property (point-at-bol) property))
16461 (defun org-find-text-property-in-string (prop s)
16462 "Return the first non-nil value of property PROP in string S."
16463 (or (get-text-property 0 prop s)
16464 (get-text-property (or (next-single-property-change 0 prop s) 0)
16465 prop s)))
16467 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16468 "Display the given MESSAGE as a warning."
16469 (if (fboundp 'display-warning)
16470 (display-warning 'org message
16471 (if (featurep 'xemacs)
16472 'warning
16473 :warning))
16474 (let ((buf (get-buffer-create "*Org warnings*")))
16475 (with-current-buffer buf
16476 (goto-char (point-max))
16477 (insert "Warning (Org): " message)
16478 (unless (bolp)
16479 (newline)))
16480 (display-buffer buf)
16481 (sit-for 0))))
16483 (defun org-in-commented-line ()
16484 "Is point in a line starting with `#'?"
16485 (equal (char-after (point-at-bol)) ?#))
16487 (defun org-in-verbatim-emphasis ()
16488 (save-match-data
16489 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16491 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16492 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16493 (if (and marker (marker-buffer marker)
16494 (buffer-live-p (marker-buffer marker)))
16495 (progn
16496 (switch-to-buffer (marker-buffer marker))
16497 (if (or (> marker (point-max)) (< marker (point-min)))
16498 (widen))
16499 (goto-char marker)
16500 (org-show-context 'org-goto))
16501 (if bookmark
16502 (bookmark-jump bookmark)
16503 (error "Cannot find location"))))
16505 (defun org-quote-csv-field (s)
16506 "Quote field for inclusion in CSV material."
16507 (if (string-match "[\",]" s)
16508 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16511 (defun org-plist-delete (plist property)
16512 "Delete PROPERTY from PLIST.
16513 This is in contrast to merely setting it to 0."
16514 (let (p)
16515 (while plist
16516 (if (not (eq property (car plist)))
16517 (setq p (plist-put p (car plist) (nth 1 plist))))
16518 (setq plist (cddr plist)))
16521 (defun org-force-self-insert (N)
16522 "Needed to enforce self-insert under remapping."
16523 (interactive "p")
16524 (self-insert-command N))
16526 (defun org-string-width (s)
16527 "Compute width of string, ignoring invisible characters.
16528 This ignores character with invisibility property `org-link', and also
16529 characters with property `org-cwidth', because these will become invisible
16530 upon the next fontification round."
16531 (let (b l)
16532 (when (or (eq t buffer-invisibility-spec)
16533 (assq 'org-link buffer-invisibility-spec))
16534 (while (setq b (text-property-any 0 (length s)
16535 'invisible 'org-link s))
16536 (setq s (concat (substring s 0 b)
16537 (substring s (or (next-single-property-change
16538 b 'invisible s) (length s)))))))
16539 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16540 (setq s (concat (substring s 0 b)
16541 (substring s (or (next-single-property-change
16542 b 'org-cwidth s) (length s))))))
16543 (setq l (string-width s) b -1)
16544 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16545 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16548 (defun org-get-indentation (&optional line)
16549 "Get the indentation of the current line, interpreting tabs.
16550 When LINE is given, assume it represents a line and compute its indentation."
16551 (if line
16552 (if (string-match "^ *" (org-remove-tabs line))
16553 (match-end 0))
16554 (save-excursion
16555 (beginning-of-line 1)
16556 (skip-chars-forward " \t")
16557 (current-column))))
16559 (defun org-remove-tabs (s &optional width)
16560 "Replace tabulators in S with spaces.
16561 Assumes that s is a single line, starting in column 0."
16562 (setq width (or width tab-width))
16563 (while (string-match "\t" s)
16564 (setq s (replace-match
16565 (make-string
16566 (- (* width (/ (+ (match-beginning 0) width) width))
16567 (match-beginning 0)) ?\ )
16568 t t s)))
16571 (defun org-fix-indentation (line ind)
16572 "Fix indentation in LINE.
16573 IND is a cons cell with target and minimum indentation.
16574 If the current indentation in LINE is smaller than the minimum,
16575 leave it alone. If it is larger than ind, set it to the target."
16576 (let* ((l (org-remove-tabs line))
16577 (i (org-get-indentation l))
16578 (i1 (car ind)) (i2 (cdr ind)))
16579 (if (>= i i2) (setq l (substring line i2)))
16580 (if (> i1 0)
16581 (concat (make-string i1 ?\ ) l)
16582 l)))
16584 (defun org-remove-indentation (code &optional n)
16585 "Remove the maximum common indentation from the lines in CODE.
16586 N may optionally be the number of spaces to remove."
16587 (with-temp-buffer
16588 (insert code)
16589 (org-do-remove-indentation n)
16590 (buffer-string)))
16592 (defun org-do-remove-indentation (&optional n)
16593 "Remove the maximum common indentation from the buffer."
16594 (untabify (point-min) (point-max))
16595 (let ((min 10000) re)
16596 (if n
16597 (setq min n)
16598 (goto-char (point-min))
16599 (while (re-search-forward "^ *[^ \n]" nil t)
16600 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16601 (unless (or (= min 0) (= min 10000))
16602 (setq re (format "^ \\{%d\\}" min))
16603 (goto-char (point-min))
16604 (while (re-search-forward re nil t)
16605 (replace-match "")
16606 (end-of-line 1))
16607 min)))
16609 (defun org-fill-template (template alist)
16610 "Find each %key of ALIST in TEMPLATE and replace it."
16611 (let ((case-fold-search nil)
16612 entry key value)
16613 (setq alist (sort (copy-sequence alist)
16614 (lambda (a b) (< (length (car a)) (length (car b))))))
16615 (while (setq entry (pop alist))
16616 (setq template
16617 (replace-regexp-in-string
16618 (concat "%" (regexp-quote (car entry)))
16619 (cdr entry) template t t)))
16620 template))
16622 (defun org-base-buffer (buffer)
16623 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16624 (if (not buffer)
16625 buffer
16626 (or (buffer-base-buffer buffer)
16627 buffer)))
16629 (defun org-trim (s)
16630 "Remove whitespace at beginning and end of string."
16631 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16632 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16635 (defun org-wrap (string &optional width lines)
16636 "Wrap string to either a number of lines, or a width in characters.
16637 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16638 that costs. If there is a word longer than WIDTH, the text is actually
16639 wrapped to the length of that word.
16640 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16641 many lines, whatever width that takes.
16642 The return value is a list of lines, without newlines at the end."
16643 (let* ((words (org-split-string string "[ \t\n]+"))
16644 (maxword (apply 'max (mapcar 'org-string-width words)))
16645 w ll)
16646 (cond (width
16647 (org-do-wrap words (max maxword width)))
16648 (lines
16649 (setq w maxword)
16650 (setq ll (org-do-wrap words maxword))
16651 (if (<= (length ll) lines)
16653 (setq ll words)
16654 (while (> (length ll) lines)
16655 (setq w (1+ w))
16656 (setq ll (org-do-wrap words w)))
16657 ll))
16658 (t (error "Cannot wrap this")))))
16660 (defun org-do-wrap (words width)
16661 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16662 (let (lines line)
16663 (while words
16664 (setq line (pop words))
16665 (while (and words (< (+ (length line) (length (car words))) width))
16666 (setq line (concat line " " (pop words))))
16667 (setq lines (push line lines)))
16668 (nreverse lines)))
16670 (defun org-split-string (string &optional separators)
16671 "Splits STRING into substrings at SEPARATORS.
16672 No empty strings are returned if there are matches at the beginning
16673 and end of string."
16674 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16675 (start 0)
16676 notfirst
16677 (list nil))
16678 (while (and (string-match rexp string
16679 (if (and notfirst
16680 (= start (match-beginning 0))
16681 (< start (length string)))
16682 (1+ start) start))
16683 (< (match-beginning 0) (length string)))
16684 (setq notfirst t)
16685 (or (eq (match-beginning 0) 0)
16686 (and (eq (match-beginning 0) (match-end 0))
16687 (eq (match-beginning 0) start))
16688 (setq list
16689 (cons (substring string start (match-beginning 0))
16690 list)))
16691 (setq start (match-end 0)))
16692 (or (eq start (length string))
16693 (setq list
16694 (cons (substring string start)
16695 list)))
16696 (nreverse list)))
16698 (defun org-quote-vert (s)
16699 "Replace \"|\" with \"\\vert\"."
16700 (while (string-match "|" s)
16701 (setq s (replace-match "\\vert" t t s)))
16704 (defun org-uuidgen-p (s)
16705 "Is S an ID created by UUIDGEN?"
16706 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16708 (defun org-context ()
16709 "Return a list of contexts of the current cursor position.
16710 If several contexts apply, all are returned.
16711 Each context entry is a list with a symbol naming the context, and
16712 two positions indicating start and end of the context. Possible
16713 contexts are:
16715 :headline anywhere in a headline
16716 :headline-stars on the leading stars in a headline
16717 :todo-keyword on a TODO keyword (including DONE) in a headline
16718 :tags on the TAGS in a headline
16719 :priority on the priority cookie in a headline
16720 :item on the first line of a plain list item
16721 :item-bullet on the bullet/number of a plain list item
16722 :checkbox on the checkbox in a plain list item
16723 :table in an org-mode table
16724 :table-special on a special filed in a table
16725 :table-table in a table.el table
16726 :link on a hyperlink
16727 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16728 :target on a <<target>>
16729 :radio-target on a <<<radio-target>>>
16730 :latex-fragment on a LaTeX fragment
16731 :latex-preview on a LaTeX fragment with overlayed preview image
16733 This function expects the position to be visible because it uses font-lock
16734 faces as a help to recognize the following contexts: :table-special, :link,
16735 and :keyword."
16736 (let* ((f (get-text-property (point) 'face))
16737 (faces (if (listp f) f (list f)))
16738 (p (point)) clist o)
16739 ;; First the large context
16740 (cond
16741 ((org-on-heading-p t)
16742 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16743 (when (progn
16744 (beginning-of-line 1)
16745 (looking-at org-todo-line-tags-regexp))
16746 (push (org-point-in-group p 1 :headline-stars) clist)
16747 (push (org-point-in-group p 2 :todo-keyword) clist)
16748 (push (org-point-in-group p 4 :tags) clist))
16749 (goto-char p)
16750 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16751 (if (looking-at "\\[#[A-Z0-9]\\]")
16752 (push (org-point-in-group p 0 :priority) clist)))
16754 ((org-at-item-p)
16755 (push (org-point-in-group p 2 :item-bullet) clist)
16756 (push (list :item (point-at-bol)
16757 (save-excursion (org-end-of-item) (point)))
16758 clist)
16759 (and (org-at-item-checkbox-p)
16760 (push (org-point-in-group p 0 :checkbox) clist)))
16762 ((org-at-table-p)
16763 (push (list :table (org-table-begin) (org-table-end)) clist)
16764 (if (memq 'org-formula faces)
16765 (push (list :table-special
16766 (previous-single-property-change p 'face)
16767 (next-single-property-change p 'face)) clist)))
16768 ((org-at-table-p 'any)
16769 (push (list :table-table) clist)))
16770 (goto-char p)
16772 ;; Now the small context
16773 (cond
16774 ((org-at-timestamp-p)
16775 (push (org-point-in-group p 0 :timestamp) clist))
16776 ((memq 'org-link faces)
16777 (push (list :link
16778 (previous-single-property-change p 'face)
16779 (next-single-property-change p 'face)) clist))
16780 ((memq 'org-special-keyword faces)
16781 (push (list :keyword
16782 (previous-single-property-change p 'face)
16783 (next-single-property-change p 'face)) clist))
16784 ((org-on-target-p)
16785 (push (org-point-in-group p 0 :target) clist)
16786 (goto-char (1- (match-beginning 0)))
16787 (if (looking-at org-radio-target-regexp)
16788 (push (org-point-in-group p 0 :radio-target) clist))
16789 (goto-char p))
16790 ((setq o (car (delq nil
16791 (mapcar
16792 (lambda (x)
16793 (if (memq x org-latex-fragment-image-overlays) x))
16794 (org-overlays-at (point))))))
16795 (push (list :latex-fragment
16796 (org-overlay-start o) (org-overlay-end o)) clist)
16797 (push (list :latex-preview
16798 (org-overlay-start o) (org-overlay-end o)) clist))
16799 ((org-inside-LaTeX-fragment-p)
16800 ;; FIXME: positions wrong.
16801 (push (list :latex-fragment (point) (point)) clist)))
16803 (setq clist (nreverse (delq nil clist)))
16804 clist))
16806 ;; FIXME: Compare with at-regexp-p Do we need both?
16807 (defun org-in-regexp (re &optional nlines visually)
16808 "Check if point is inside a match of regexp.
16809 Normally only the current line is checked, but you can include NLINES extra
16810 lines both before and after point into the search.
16811 If VISUALLY is set, require that the cursor is not after the match but
16812 really on, so that the block visually is on the match."
16813 (catch 'exit
16814 (let ((pos (point))
16815 (eol (point-at-eol (+ 1 (or nlines 0))))
16816 (inc (if visually 1 0)))
16817 (save-excursion
16818 (beginning-of-line (- 1 (or nlines 0)))
16819 (while (re-search-forward re eol t)
16820 (if (and (<= (match-beginning 0) pos)
16821 (>= (+ inc (match-end 0)) pos))
16822 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16824 (defun org-at-regexp-p (regexp)
16825 "Is point inside a match of REGEXP in the current line?"
16826 (catch 'exit
16827 (save-excursion
16828 (let ((pos (point)) (end (point-at-eol)))
16829 (beginning-of-line 1)
16830 (while (re-search-forward regexp end t)
16831 (if (and (<= (match-beginning 0) pos)
16832 (>= (match-end 0) pos))
16833 (throw 'exit t)))
16834 nil))))
16836 (defun org-occur-in-agenda-files (regexp &optional nlines)
16837 "Call `multi-occur' with buffers for all agenda files."
16838 (interactive "sOrg-files matching: \np")
16839 (let* ((files (org-agenda-files))
16840 (tnames (mapcar 'file-truename files))
16841 (extra org-agenda-text-search-extra-files)
16843 (when (eq (car extra) 'agenda-archives)
16844 (setq extra (cdr extra))
16845 (setq files (org-add-archive-files files)))
16846 (while (setq f (pop extra))
16847 (unless (member (file-truename f) tnames)
16848 (add-to-list 'files f 'append)
16849 (add-to-list 'tnames (file-truename f) 'append)))
16850 (multi-occur
16851 (mapcar (lambda (x)
16852 (with-current-buffer
16853 (or (get-file-buffer x) (find-file-noselect x))
16854 (widen)
16855 (current-buffer)))
16856 files)
16857 regexp)))
16859 (if (boundp 'occur-mode-find-occurrence-hook)
16860 ;; Emacs 23
16861 (add-hook 'occur-mode-find-occurrence-hook
16862 (lambda ()
16863 (when (org-mode-p)
16864 (org-reveal))))
16865 ;; Emacs 22
16866 (defadvice occur-mode-goto-occurrence
16867 (after org-occur-reveal activate)
16868 (and (org-mode-p) (org-reveal)))
16869 (defadvice occur-mode-goto-occurrence-other-window
16870 (after org-occur-reveal activate)
16871 (and (org-mode-p) (org-reveal)))
16872 (defadvice occur-mode-display-occurrence
16873 (after org-occur-reveal activate)
16874 (when (org-mode-p)
16875 (let ((pos (occur-mode-find-occurrence)))
16876 (with-current-buffer (marker-buffer pos)
16877 (save-excursion
16878 (goto-char pos)
16879 (org-reveal)))))))
16881 (defun org-occur-link-in-agenda-files ()
16882 "Create a link and search for it in the agendas.
16883 The link is not stored in `org-stored-links', it is just created
16884 for the search purpose."
16885 (interactive)
16886 (let ((link (condition-case nil
16887 (org-store-link nil)
16888 (error "Unable to create a link to here"))))
16889 (org-occur-in-agenda-files (regexp-quote link))))
16891 (defun org-uniquify (list)
16892 "Remove duplicate elements from LIST."
16893 (let (res)
16894 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16895 res))
16897 (defun org-delete-all (elts list)
16898 "Remove all elements in ELTS from LIST."
16899 (while elts
16900 (setq list (delete (pop elts) list)))
16901 list)
16903 (defun org-back-over-empty-lines ()
16904 "Move backwards over whitespace, to the beginning of the first empty line.
16905 Returns the number of empty lines passed."
16906 (let ((pos (point)))
16907 (skip-chars-backward " \t\n\r")
16908 (beginning-of-line 2)
16909 (goto-char (min (point) pos))
16910 (count-lines (point) pos)))
16912 (defun org-skip-whitespace ()
16913 (skip-chars-forward " \t\n\r"))
16915 (defun org-point-in-group (point group &optional context)
16916 "Check if POINT is in match-group GROUP.
16917 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16918 match. If the match group does ot exist or point is not inside it,
16919 return nil."
16920 (and (match-beginning group)
16921 (>= point (match-beginning group))
16922 (<= point (match-end group))
16923 (if context
16924 (list context (match-beginning group) (match-end group))
16925 t)))
16927 (defun org-switch-to-buffer-other-window (&rest args)
16928 "Switch to buffer in a second window on the current frame.
16929 In particular, do not allow pop-up frames."
16930 (let (pop-up-frames special-display-buffer-names special-display-regexps
16931 special-display-function)
16932 (apply 'switch-to-buffer-other-window args)))
16934 (defun org-combine-plists (&rest plists)
16935 "Create a single property list from all plists in PLISTS.
16936 The process starts by copying the first list, and then setting properties
16937 from the other lists. Settings in the last list are the most significant
16938 ones and overrule settings in the other lists."
16939 (let ((rtn (copy-sequence (pop plists)))
16940 p v ls)
16941 (while plists
16942 (setq ls (pop plists))
16943 (while ls
16944 (setq p (pop ls) v (pop ls))
16945 (setq rtn (plist-put rtn p v))))
16946 rtn))
16948 (defun org-move-line-down (arg)
16949 "Move the current line down. With prefix argument, move it past ARG lines."
16950 (interactive "p")
16951 (let ((col (current-column))
16952 beg end pos)
16953 (beginning-of-line 1) (setq beg (point))
16954 (beginning-of-line 2) (setq end (point))
16955 (beginning-of-line (+ 1 arg))
16956 (setq pos (move-marker (make-marker) (point)))
16957 (insert (delete-and-extract-region beg end))
16958 (goto-char pos)
16959 (org-move-to-column col)))
16961 (defun org-move-line-up (arg)
16962 "Move the current line up. With prefix argument, move it past ARG lines."
16963 (interactive "p")
16964 (let ((col (current-column))
16965 beg end pos)
16966 (beginning-of-line 1) (setq beg (point))
16967 (beginning-of-line 2) (setq end (point))
16968 (beginning-of-line (- arg))
16969 (setq pos (move-marker (make-marker) (point)))
16970 (insert (delete-and-extract-region beg end))
16971 (goto-char pos)
16972 (org-move-to-column col)))
16974 (defun org-replace-escapes (string table)
16975 "Replace %-escapes in STRING with values in TABLE.
16976 TABLE is an association list with keys like \"%a\" and string values.
16977 The sequences in STRING may contain normal field width and padding information,
16978 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16979 so values can contain further %-escapes if they are define later in TABLE."
16980 (let ((case-fold-search nil)
16981 e re rpl)
16982 (while (setq e (pop table))
16983 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16984 (while (string-match re string)
16985 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16986 (cdr e)))
16987 (setq string (replace-match rpl t t string))))
16988 string))
16991 (defun org-sublist (list start end)
16992 "Return a section of LIST, from START to END.
16993 Counting starts at 1."
16994 (let (rtn (c start))
16995 (setq list (nthcdr (1- start) list))
16996 (while (and list (<= c end))
16997 (push (pop list) rtn)
16998 (setq c (1+ c)))
16999 (nreverse rtn)))
17001 (defun org-find-base-buffer-visiting (file)
17002 "Like `find-buffer-visiting' but always return the base buffer and
17003 not an indirect buffer."
17004 (let ((buf (or (get-file-buffer file)
17005 (find-buffer-visiting file))))
17006 (if buf
17007 (or (buffer-base-buffer buf) buf)
17008 nil)))
17010 (defun org-image-file-name-regexp (&optional extensions)
17011 "Return regexp matching the file names of images.
17012 If EXTENSIONS is given, only match these."
17013 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17014 (image-file-name-regexp)
17015 (let ((image-file-name-extensions
17016 (or extensions
17017 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17018 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17019 (concat "\\."
17020 (regexp-opt (nconc (mapcar 'upcase
17021 image-file-name-extensions)
17022 image-file-name-extensions)
17024 "\\'"))))
17026 (defun org-file-image-p (file &optional extensions)
17027 "Return non-nil if FILE is an image."
17028 (save-match-data
17029 (string-match (org-image-file-name-regexp extensions) file)))
17031 (defun org-get-cursor-date ()
17032 "Return the date at cursor in as a time.
17033 This works in the calendar and in the agenda, anywhere else it just
17034 returns the current time."
17035 (let (date day defd)
17036 (cond
17037 ((eq major-mode 'calendar-mode)
17038 (setq date (calendar-cursor-to-date)
17039 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17040 ((eq major-mode 'org-agenda-mode)
17041 (setq day (get-text-property (point) 'day))
17042 (if day
17043 (setq date (calendar-gregorian-from-absolute day)
17044 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17045 (nth 2 date))))))
17046 (or defd (current-time))))
17048 (defvar org-agenda-action-marker (make-marker)
17049 "Marker pointing to the entry for the next agenda action.")
17051 (defun org-mark-entry-for-agenda-action ()
17052 "Mark the current entry as target of an agenda action.
17053 Agenda actions are actions executed from the agenda with the key `k',
17054 which make use of the date at the cursor."
17055 (interactive)
17056 (move-marker org-agenda-action-marker
17057 (save-excursion (org-back-to-heading t) (point))
17058 (current-buffer))
17059 (message
17060 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17062 ;;; Paragraph filling stuff.
17063 ;; We want this to be just right, so use the full arsenal.
17065 (defun org-indent-line-function ()
17066 "Indent line like previous, but further if previous was headline or item."
17067 (interactive)
17068 (let* ((pos (point))
17069 (itemp (org-at-item-p))
17070 (case-fold-search t)
17071 (org-drawer-regexp (or org-drawer-regexp "\000"))
17072 column bpos bcol tpos tcol bullet btype bullet-type)
17073 ;; Find the previous relevant line
17074 (beginning-of-line 1)
17075 (cond
17076 ((looking-at "#") (setq column 0))
17077 ((looking-at "\\*+ ") (setq column 0))
17078 ((and (looking-at "[ \t]*:END:")
17079 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17080 (save-excursion
17081 (goto-char (1- (match-beginning 1)))
17082 (setq column (current-column))))
17083 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17084 (save-excursion
17085 (re-search-backward
17086 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17087 (setq column (org-get-indentation (match-string 0))))
17089 (beginning-of-line 0)
17090 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17091 (not (looking-at "[ \t]*:END:"))
17092 (not (looking-at org-drawer-regexp)))
17093 (beginning-of-line 0))
17094 (cond
17095 ((looking-at "\\*+[ \t]+")
17096 (if (not org-adapt-indentation)
17097 (setq column 0)
17098 (goto-char (match-end 0))
17099 (setq column (current-column))))
17100 ((looking-at org-drawer-regexp)
17101 (goto-char (1- (match-beginning 1)))
17102 (setq column (current-column)))
17103 ((looking-at "\\([ \t]*\\):END:")
17104 (goto-char (match-end 1))
17105 (setq column (current-column)))
17106 ((org-in-item-p)
17107 (org-beginning-of-item)
17108 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17109 (setq bpos (match-beginning 1) tpos (match-end 0)
17110 bcol (progn (goto-char bpos) (current-column))
17111 tcol (progn (goto-char tpos) (current-column))
17112 bullet (match-string 1)
17113 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17114 (if (> tcol (+ bcol org-description-max-indent))
17115 (setq tcol (+ bcol 5)))
17116 (if (not itemp)
17117 (setq column tcol)
17118 (goto-char pos)
17119 (beginning-of-line 1)
17120 (if (looking-at "\\S-")
17121 (progn
17122 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17123 (setq bullet (match-string 1)
17124 btype (if (string-match "[0-9]" bullet) "n" bullet))
17125 (setq column (if (equal btype bullet-type) bcol tcol)))
17126 (setq column (org-get-indentation)))))
17127 (t (setq column (org-get-indentation))))))
17128 (goto-char pos)
17129 (if (<= (current-column) (current-indentation))
17130 (org-indent-line-to column)
17131 (save-excursion (org-indent-line-to column)))
17132 (setq column (current-column))
17133 (beginning-of-line 1)
17134 (if (looking-at
17135 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17136 (replace-match (concat (match-string 1)
17137 (format org-property-format
17138 (match-string 2) (match-string 3)))
17139 t t))
17140 (org-move-to-column column)))
17142 (defun org-set-autofill-regexps ()
17143 (interactive)
17144 ;; In the paragraph separator we include headlines, because filling
17145 ;; text in a line directly attached to a headline would otherwise
17146 ;; fill the headline as well.
17147 (org-set-local 'comment-start-skip "^#+[ \t]*")
17148 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17149 ;; The paragraph starter includes hand-formatted lists.
17150 (org-set-local
17151 'paragraph-start
17152 (concat
17153 "\f" "\\|"
17154 "[ ]*$" "\\|"
17155 "\\*+ " "\\|"
17156 "[ \t]*#" "\\|"
17157 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17158 "[ \t]*[:|]" "\\|"
17159 "\\$\\$" "\\|"
17160 "\\\\\\(begin\\|end\\|[][]\\)"))
17161 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17162 ;; But only if the user has not turned off tables or fixed-width regions
17163 (org-set-local
17164 'auto-fill-inhibit-regexp
17165 (concat "\\*+ \\|#\\+"
17166 "\\|[ \t]*" org-keyword-time-regexp
17167 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17168 (concat
17169 "\\|[ \t]*["
17170 (if org-enable-table-editor "|" "")
17171 (if org-enable-fixed-width-editor ":" "")
17172 "]"))))
17173 ;; We use our own fill-paragraph function, to make sure that tables
17174 ;; and fixed-width regions are not wrapped. That function will pass
17175 ;; through to `fill-paragraph' when appropriate.
17176 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17177 ; Adaptive filling: To get full control, first make sure that
17178 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17179 (org-set-local 'adaptive-fill-regexp "\000")
17180 (org-set-local 'adaptive-fill-function
17181 'org-adaptive-fill-function)
17182 (org-set-local
17183 'align-mode-rules-list
17184 '((org-in-buffer-settings
17185 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17186 (modes . '(org-mode))))))
17188 (defun org-fill-paragraph (&optional justify)
17189 "Re-align a table, pass through to fill-paragraph if no table."
17190 (let ((table-p (org-at-table-p))
17191 (table.el-p (org-at-table.el-p)))
17192 (cond ((and (equal (char-after (point-at-bol)) ?*)
17193 (save-excursion (goto-char (point-at-bol))
17194 (looking-at outline-regexp)))
17195 t) ; skip headlines
17196 (table.el-p t) ; skip table.el tables
17197 (table-p (org-table-align) t) ; align org-mode tables
17198 (t nil)))) ; call paragraph-fill
17200 ;; For reference, this is the default value of adaptive-fill-regexp
17201 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17203 (defun org-adaptive-fill-function ()
17204 "Return a fill prefix for org-mode files.
17205 In particular, this makes sure hanging paragraphs for hand-formatted lists
17206 work correctly."
17207 (cond ((looking-at "#[ \t]+")
17208 (match-string 0))
17209 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17210 (save-excursion
17211 (if (> (match-end 1) (+ (match-beginning 1)
17212 org-description-max-indent))
17213 (goto-char (+ (match-beginning 1) 5))
17214 (goto-char (match-end 0)))
17215 (make-string (current-column) ?\ )))
17216 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17217 (save-excursion
17218 (goto-char (match-end 0))
17219 (make-string (current-column) ?\ )))
17220 (t nil)))
17222 ;;; Other stuff.
17224 (defun org-toggle-fixed-width-section (arg)
17225 "Toggle the fixed-width export.
17226 If there is no active region, the QUOTE keyword at the current headline is
17227 inserted or removed. When present, it causes the text between this headline
17228 and the next to be exported as fixed-width text, and unmodified.
17229 If there is an active region, this command adds or removes a colon as the
17230 first character of this line. If the first character of a line is a colon,
17231 this line is also exported in fixed-width font."
17232 (interactive "P")
17233 (let* ((cc 0)
17234 (regionp (org-region-active-p))
17235 (beg (if regionp (region-beginning) (point)))
17236 (end (if regionp (region-end)))
17237 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17238 (case-fold-search nil)
17239 (re "[ \t]*\\(: \\)")
17240 off)
17241 (if regionp
17242 (save-excursion
17243 (goto-char beg)
17244 (setq cc (current-column))
17245 (beginning-of-line 1)
17246 (setq off (looking-at re))
17247 (while (> nlines 0)
17248 (setq nlines (1- nlines))
17249 (beginning-of-line 1)
17250 (cond
17251 (arg
17252 (org-move-to-column cc t)
17253 (insert ": \n")
17254 (forward-line -1))
17255 ((and off (looking-at re))
17256 (replace-match "" t t nil 1))
17257 ((not off) (org-move-to-column cc t) (insert ": ")))
17258 (forward-line 1)))
17259 (save-excursion
17260 (org-back-to-heading)
17261 (if (looking-at (concat outline-regexp
17262 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17263 (replace-match "" t t nil 1)
17264 (if (looking-at outline-regexp)
17265 (progn
17266 (goto-char (match-end 0))
17267 (insert org-quote-string " "))))))))
17269 (defun org-reftex-citation ()
17270 "Use reftex-citation to insert a citation into the buffer.
17271 This looks for a line like
17273 #+BIBLIOGRAPHY: foo plain option:-d
17275 and derives from it that foo.bib is the bibliography file relevant
17276 for this document. It then installs the necessary environment for RefTeX
17277 to work in this buffer and calls `reftex-citation' to insert a citation
17278 into the buffer.
17280 Export of such citations to both LaTeX and HTML is handled by the contributed
17281 package org-exp-bibtex by Taru Karttunen."
17282 (interactive)
17283 (let ((reftex-docstruct-symbol 'rds)
17284 (reftex-cite-format "\\cite{%l}")
17285 rds bib)
17286 (save-excursion
17287 (save-restriction
17288 (widen)
17289 (let ((case-fold-search t)
17290 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17291 (if (not (save-excursion
17292 (or (re-search-forward re nil t)
17293 (re-search-backward re nil t))))
17294 (error "No bibliography defined in file")
17295 (setq bib (concat (match-string 1) ".bib")
17296 rds (list (list 'bib bib)))))))
17297 (call-interactively 'reftex-citation)))
17299 ;;;; Functions extending outline functionality
17301 (defun org-beginning-of-line (&optional arg)
17302 "Go to the beginning of the current line. If that is invisible, continue
17303 to a visible line beginning. This makes the function of C-a more intuitive.
17304 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17305 first attempt, and only move to after the tags when the cursor is already
17306 beyond the end of the headline."
17307 (interactive "P")
17308 (let ((pos (point))
17309 (special (if (consp org-special-ctrl-a/e)
17310 (car org-special-ctrl-a/e)
17311 org-special-ctrl-a/e))
17312 refpos)
17313 (if (org-bound-and-true-p line-move-visual)
17314 (beginning-of-visual-line 1)
17315 (beginning-of-line 1))
17316 (if (and arg (fboundp 'move-beginning-of-line))
17317 (call-interactively 'move-beginning-of-line)
17318 (if (bobp)
17320 (backward-char 1)
17321 (if (org-invisible-p)
17322 (while (and (not (bobp)) (org-invisible-p))
17323 (backward-char 1)
17324 (beginning-of-line 1))
17325 (forward-char 1))))
17326 (when special
17327 (cond
17328 ((and (looking-at org-complex-heading-regexp)
17329 (= (char-after (match-end 1)) ?\ ))
17330 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17331 (point-at-eol)))
17332 (goto-char
17333 (if (eq special t)
17334 (cond ((> pos refpos) refpos)
17335 ((= pos (point)) refpos)
17336 (t (point)))
17337 (cond ((> pos (point)) (point))
17338 ((not (eq last-command this-command)) (point))
17339 (t refpos)))))
17340 ((org-at-item-p)
17341 (goto-char
17342 (if (eq special t)
17343 (cond ((> pos (match-end 4)) (match-end 4))
17344 ((= pos (point)) (match-end 4))
17345 (t (point)))
17346 (cond ((> pos (point)) (point))
17347 ((not (eq last-command this-command)) (point))
17348 (t (match-end 4))))))))
17349 (org-no-warnings
17350 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17352 (defun org-end-of-line (&optional arg)
17353 "Go to the end of the line.
17354 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17355 first attempt, and only move to after the tags when the cursor is already
17356 beyond the end of the headline."
17357 (interactive "P")
17358 (let ((special (if (consp org-special-ctrl-a/e)
17359 (cdr org-special-ctrl-a/e)
17360 org-special-ctrl-a/e)))
17361 (if (or (not special)
17362 (not (org-on-heading-p))
17363 arg)
17364 (call-interactively
17365 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17366 ((fboundp 'move-end-of-line) 'move-end-of-line)
17367 (t 'end-of-line)))
17368 (let ((pos (point)))
17369 (beginning-of-line 1)
17370 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17371 (if (eq special t)
17372 (if (or (< pos (match-beginning 1))
17373 (= pos (match-end 0)))
17374 (goto-char (match-beginning 1))
17375 (goto-char (match-end 0)))
17376 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17377 (goto-char (match-end 0))
17378 (goto-char (match-beginning 1))))
17379 (call-interactively (if (fboundp 'move-end-of-line)
17380 'move-end-of-line
17381 'end-of-line)))))
17382 (org-no-warnings
17383 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17385 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17386 (define-key org-mode-map "\C-e" 'org-end-of-line)
17387 (define-key org-mode-map [home] 'org-beginning-of-line)
17388 (define-key org-mode-map [end] 'org-end-of-line)
17390 (defun org-backward-sentence (&optional arg)
17391 "Go to beginning of sentence, or beginning of table field.
17392 This will call `backward-sentence' or `org-table-beginning-of-field',
17393 depending on context."
17394 (interactive "P")
17395 (cond
17396 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17397 (t (call-interactively 'backward-sentence))))
17399 (defun org-forward-sentence (&optional arg)
17400 "Go to end of sentence, or end of table field.
17401 This will call `forward-sentence' or `org-table-end-of-field',
17402 depending on context."
17403 (interactive "P")
17404 (cond
17405 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17406 (t (call-interactively 'forward-sentence))))
17408 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17409 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17411 (defun org-kill-line (&optional arg)
17412 "Kill line, to tags or end of line."
17413 (interactive "P")
17414 (cond
17415 ((or (not org-special-ctrl-k)
17416 (bolp)
17417 (not (org-on-heading-p)))
17418 (call-interactively 'kill-line))
17419 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17420 (kill-region (point) (match-beginning 1))
17421 (org-set-tags nil t))
17422 (t (kill-region (point) (point-at-eol)))))
17424 (define-key org-mode-map "\C-k" 'org-kill-line)
17426 (defun org-yank (&optional arg)
17427 "Yank. If the kill is a subtree, treat it specially.
17428 This command will look at the current kill and check if is a single
17429 subtree, or a series of subtrees[1]. If it passes the test, and if the
17430 cursor is at the beginning of a line or after the stars of a currently
17431 empty headline, then the yank is handled specially. How exactly depends
17432 on the value of the following variables, both set by default.
17434 org-yank-folded-subtrees
17435 When set, the subtree(s) will be folded after insertion, but only
17436 if doing so would now swallow text after the yanked text.
17438 org-yank-adjusted-subtrees
17439 When set, the subtree will be promoted or demoted in order to
17440 fit into the local outline tree structure, which means that the level
17441 will be adjusted so that it becomes the smaller one of the two
17442 *visible* surrounding headings.
17444 Any prefix to this command will cause `yank' to be called directly with
17445 no special treatment. In particular, a simple `C-u' prefix will just
17446 plainly yank the text as it is.
17448 \[1] The test checks if the first non-white line is a heading
17449 and if there are no other headings with fewer stars."
17450 (interactive "P")
17451 (org-yank-generic 'yank arg))
17453 (defun org-yank-generic (command arg)
17454 "Perform some yank-like command.
17456 This function implements the behavior described in the `org-yank'
17457 documentation. However, it has been generalized to work for any
17458 interactive command with similar behavior."
17460 ;; pretend to be command COMMAND
17461 (setq this-command command)
17463 (if arg
17464 (call-interactively command)
17466 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17467 (and (org-kill-is-subtree-p)
17468 (or (bolp)
17469 (and (looking-at "[ \t]*$")
17470 (string-match
17471 "\\`\\*+\\'"
17472 (buffer-substring (point-at-bol) (point)))))))
17473 swallowp)
17474 (cond
17475 ((and subtreep org-yank-folded-subtrees)
17476 (let ((beg (point))
17477 end)
17478 (if (and subtreep org-yank-adjusted-subtrees)
17479 (org-paste-subtree nil nil 'for-yank)
17480 (call-interactively command))
17482 (setq end (point))
17483 (goto-char beg)
17484 (when (and (bolp) subtreep
17485 (not (setq swallowp
17486 (org-yank-folding-would-swallow-text beg end))))
17487 (or (looking-at outline-regexp)
17488 (re-search-forward (concat "^" outline-regexp) end t))
17489 (while (and (< (point) end) (looking-at outline-regexp))
17490 (hide-subtree)
17491 (org-cycle-show-empty-lines 'folded)
17492 (condition-case nil
17493 (outline-forward-same-level 1)
17494 (error (goto-char end)))))
17495 (when swallowp
17496 (message
17497 "Inserted text not folded because that would swallow text"))
17499 (goto-char end)
17500 (skip-chars-forward " \t\n\r")
17501 (beginning-of-line 1)
17502 (push-mark beg 'nomsg)))
17503 ((and subtreep org-yank-adjusted-subtrees)
17504 (let ((beg (point-at-bol)))
17505 (org-paste-subtree nil nil 'for-yank)
17506 (push-mark beg 'nomsg)))
17508 (call-interactively command))))))
17510 (defun org-yank-folding-would-swallow-text (beg end)
17511 "Would hide-subtree at BEG swallow any text after END?"
17512 (let (level)
17513 (save-excursion
17514 (goto-char beg)
17515 (when (or (looking-at outline-regexp)
17516 (re-search-forward (concat "^" outline-regexp) end t))
17517 (setq level (org-outline-level)))
17518 (goto-char end)
17519 (skip-chars-forward " \t\r\n\v\f")
17520 (if (or (eobp)
17521 (and (bolp) (looking-at org-outline-regexp)
17522 (<= (org-outline-level) level)))
17523 nil ; Nothing would be swallowed
17524 t)))) ; something would swallow
17526 (define-key org-mode-map "\C-y" 'org-yank)
17528 (defun org-invisible-p ()
17529 "Check if point is at a character currently not visible."
17530 ;; Early versions of noutline don't have `outline-invisible-p'.
17531 (if (fboundp 'outline-invisible-p)
17532 (outline-invisible-p)
17533 (get-char-property (point) 'invisible)))
17535 (defun org-invisible-p2 ()
17536 "Check if point is at a character currently not visible."
17537 (save-excursion
17538 (if (and (eolp) (not (bobp))) (backward-char 1))
17539 ;; Early versions of noutline don't have `outline-invisible-p'.
17540 (if (fboundp 'outline-invisible-p)
17541 (outline-invisible-p)
17542 (get-char-property (point) 'invisible))))
17544 (defun org-back-to-heading (&optional invisible-ok)
17545 "Call `outline-back-to-heading', but provide a better error message."
17546 (condition-case nil
17547 (outline-back-to-heading invisible-ok)
17548 (error (error "Before first headline at position %d in buffer %s"
17549 (point) (current-buffer)))))
17551 (defun org-before-first-heading-p ()
17552 "Before first heading?"
17553 (save-excursion
17554 (null (re-search-backward "^\\*+ " nil t))))
17556 (defun org-on-heading-p (&optional ignored)
17557 (outline-on-heading-p t))
17558 (defun org-at-heading-p (&optional ignored)
17559 (outline-on-heading-p t))
17561 (defun org-at-heading-or-item-p ()
17562 (or (org-on-heading-p) (org-at-item-p)))
17564 (defun org-on-target-p ()
17565 (or (org-in-regexp org-radio-target-regexp)
17566 (org-in-regexp org-target-regexp)))
17568 (defun org-up-heading-all (arg)
17569 "Move to the heading line of which the present line is a subheading.
17570 This function considers both visible and invisible heading lines.
17571 With argument, move up ARG levels."
17572 (if (fboundp 'outline-up-heading-all)
17573 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17574 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17576 (defun org-up-heading-safe ()
17577 "Move to the heading line of which the present line is a subheading.
17578 This version will not throw an error. It will return the level of the
17579 headline found, or nil if no higher level is found.
17581 Also, this function will be a lot faster than `outline-up-heading',
17582 because it relies on stars being the outline starters. This can really
17583 make a significant difference in outlines with very many siblings."
17584 (let (start-level re)
17585 (org-back-to-heading t)
17586 (setq start-level (funcall outline-level))
17587 (if (equal start-level 1)
17589 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17590 (if (re-search-backward re nil t)
17591 (funcall outline-level)))))
17593 (defun org-first-sibling-p ()
17594 "Is this heading the first child of its parents?"
17595 (interactive)
17596 (let ((re (concat "^" outline-regexp))
17597 level l)
17598 (unless (org-at-heading-p t)
17599 (error "Not at a heading"))
17600 (setq level (funcall outline-level))
17601 (save-excursion
17602 (if (not (re-search-backward re nil t))
17604 (setq l (funcall outline-level))
17605 (< l level)))))
17607 (defun org-goto-sibling (&optional previous)
17608 "Goto the next sibling, even if it is invisible.
17609 When PREVIOUS is set, go to the previous sibling instead. Returns t
17610 when a sibling was found. When none is found, return nil and don't
17611 move point."
17612 (let ((fun (if previous 're-search-backward 're-search-forward))
17613 (pos (point))
17614 (re (concat "^" outline-regexp))
17615 level l)
17616 (when (condition-case nil (org-back-to-heading t) (error nil))
17617 (setq level (funcall outline-level))
17618 (catch 'exit
17619 (or previous (forward-char 1))
17620 (while (funcall fun re nil t)
17621 (setq l (funcall outline-level))
17622 (when (< l level) (goto-char pos) (throw 'exit nil))
17623 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17624 (goto-char pos)
17625 nil))))
17627 (defun org-show-siblings ()
17628 "Show all siblings of the current headline."
17629 (save-excursion
17630 (while (org-goto-sibling) (org-flag-heading nil)))
17631 (save-excursion
17632 (while (org-goto-sibling 'previous)
17633 (org-flag-heading nil))))
17635 (defun org-show-hidden-entry ()
17636 "Show an entry where even the heading is hidden."
17637 (save-excursion
17638 (org-show-entry)))
17640 (defun org-flag-heading (flag &optional entry)
17641 "Flag the current heading. FLAG non-nil means make invisible.
17642 When ENTRY is non-nil, show the entire entry."
17643 (save-excursion
17644 (org-back-to-heading t)
17645 ;; Check if we should show the entire entry
17646 (if entry
17647 (progn
17648 (org-show-entry)
17649 (save-excursion
17650 (and (outline-next-heading)
17651 (org-flag-heading nil))))
17652 (outline-flag-region (max (point-min) (1- (point)))
17653 (save-excursion (outline-end-of-heading) (point))
17654 flag))))
17656 (defun org-get-next-sibling ()
17657 "Move to next heading of the same level, and return point.
17658 If there is no such heading, return nil.
17659 This is like outline-next-sibling, but invisible headings are ok."
17660 (let ((level (funcall outline-level)))
17661 (outline-next-heading)
17662 (while (and (not (eobp)) (> (funcall outline-level) level))
17663 (outline-next-heading))
17664 (if (or (eobp) (< (funcall outline-level) level))
17666 (point))))
17668 (defun org-get-last-sibling ()
17669 "Move to previous heading of the same level, and return point.
17670 If there is no such heading, return nil."
17671 (let ((opoint (point))
17672 (level (funcall outline-level)))
17673 (outline-previous-heading)
17674 (when (and (/= (point) opoint) (outline-on-heading-p t))
17675 (while (and (> (funcall outline-level) level)
17676 (not (bobp)))
17677 (outline-previous-heading))
17678 (if (< (funcall outline-level) level)
17680 (point)))))
17682 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17683 ;; This contains an exact copy of the original function, but it uses
17684 ;; `org-back-to-heading', to make it work also in invisible
17685 ;; trees. And is uses an invisible-OK argument.
17686 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17687 ;; Furthermore, when used inside Org, finding the end of a large subtree
17688 ;; with many children and grandchildren etc, this can be much faster
17689 ;; than the outline version.
17690 (org-back-to-heading invisible-OK)
17691 (let ((first t)
17692 (level (funcall outline-level)))
17693 (if (and (org-mode-p) (< level 1000))
17694 ;; A true heading (not a plain list item), in Org-mode
17695 ;; This means we can easily find the end by looking
17696 ;; only for the right number of stars. Using a regexp to do
17697 ;; this is so much faster than using a Lisp loop.
17698 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17699 (forward-char 1)
17700 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17701 ;; something else, do it the slow way
17702 (while (and (not (eobp))
17703 (or first (> (funcall outline-level) level)))
17704 (setq first nil)
17705 (outline-next-heading)))
17706 (unless to-heading
17707 (if (memq (preceding-char) '(?\n ?\^M))
17708 (progn
17709 ;; Go to end of line before heading
17710 (forward-char -1)
17711 (if (memq (preceding-char) '(?\n ?\^M))
17712 ;; leave blank line before heading
17713 (forward-char -1))))))
17714 (point))
17716 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17717 "Use Org version in org-mode, for dramatic speed-up."
17718 (if (eq major-mode 'org-mode)
17719 (progn
17720 (org-end-of-subtree nil t)
17721 (unless (eobp) (backward-char 1)))
17722 ad-do-it))
17724 (defun org-forward-same-level (arg &optional invisible-ok)
17725 "Move forward to the arg'th subheading at same level as this one.
17726 Stop at the first and last subheadings of a superior heading."
17727 (interactive "p")
17728 (org-back-to-heading invisible-ok)
17729 (org-on-heading-p)
17730 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17731 (re (format "^\\*\\{1,%d\\} " level))
17733 (forward-char 1)
17734 (while (> arg 0)
17735 (while (and (re-search-forward re nil 'move)
17736 (setq l (- (match-end 0) (match-beginning 0) 1))
17737 (= l level)
17738 (not invisible-ok)
17739 (progn (backward-char 1) (org-invisible-p)))
17740 (if (< l level) (setq arg 1)))
17741 (setq arg (1- arg)))
17742 (beginning-of-line 1)))
17744 (defun org-backward-same-level (arg &optional invisible-ok)
17745 "Move backward to the arg'th subheading at same level as this one.
17746 Stop at the first and last subheadings of a superior heading."
17747 (interactive "p")
17748 (org-back-to-heading)
17749 (org-on-heading-p)
17750 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17751 (re (format "^\\*\\{1,%d\\} " level))
17753 (while (> arg 0)
17754 (while (and (re-search-backward re nil 'move)
17755 (setq l (- (match-end 0) (match-beginning 0) 1))
17756 (= l level)
17757 (not invisible-ok)
17758 (org-invisible-p))
17759 (if (< l level) (setq arg 1)))
17760 (setq arg (1- arg)))))
17762 (defun org-show-subtree ()
17763 "Show everything after this heading at deeper levels."
17764 (outline-flag-region
17765 (point)
17766 (save-excursion
17767 (org-end-of-subtree t t))
17768 nil))
17770 (defun org-show-entry ()
17771 "Show the body directly following this heading.
17772 Show the heading too, if it is currently invisible."
17773 (interactive)
17774 (save-excursion
17775 (condition-case nil
17776 (progn
17777 (org-back-to-heading t)
17778 (outline-flag-region
17779 (max (point-min) (1- (point)))
17780 (save-excursion
17781 (if (re-search-forward
17782 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17783 (match-beginning 1)
17784 (point-max)))
17785 nil)
17786 (org-cycle-hide-drawers 'children))
17787 (error nil))))
17789 (defun org-make-options-regexp (kwds &optional extra)
17790 "Make a regular expression for keyword lines."
17791 (concat
17793 "#?[ \t]*\\+\\("
17794 (mapconcat 'regexp-quote kwds "\\|")
17795 (if extra (concat "\\|" extra))
17796 "\\):[ \t]*"
17797 "\\(.*\\)"))
17799 ;; Make isearch reveal the necessary context
17800 (defun org-isearch-end ()
17801 "Reveal context after isearch exits."
17802 (when isearch-success ; only if search was successful
17803 (if (featurep 'xemacs)
17804 ;; Under XEmacs, the hook is run in the correct place,
17805 ;; we directly show the context.
17806 (org-show-context 'isearch)
17807 ;; In Emacs the hook runs *before* restoring the overlays.
17808 ;; So we have to use a one-time post-command-hook to do this.
17809 ;; (Emacs 22 has a special variable, see function `org-mode')
17810 (unless (and (boundp 'isearch-mode-end-hook-quit)
17811 isearch-mode-end-hook-quit)
17812 ;; Only when the isearch was not quitted.
17813 (org-add-hook 'post-command-hook 'org-isearch-post-command
17814 'append 'local)))))
17816 (defun org-isearch-post-command ()
17817 "Remove self from hook, and show context."
17818 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17819 (org-show-context 'isearch))
17822 ;;;; Integration with and fixes for other packages
17824 ;;; Imenu support
17826 (defvar org-imenu-markers nil
17827 "All markers currently used by Imenu.")
17828 (make-variable-buffer-local 'org-imenu-markers)
17830 (defun org-imenu-new-marker (&optional pos)
17831 "Return a new marker for use by Imenu, and remember the marker."
17832 (let ((m (make-marker)))
17833 (move-marker m (or pos (point)))
17834 (push m org-imenu-markers)
17837 (defun org-imenu-get-tree ()
17838 "Produce the index for Imenu."
17839 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17840 (setq org-imenu-markers nil)
17841 (let* ((n org-imenu-depth)
17842 (re (concat "^" outline-regexp))
17843 (subs (make-vector (1+ n) nil))
17844 (last-level 0)
17845 m level head)
17846 (save-excursion
17847 (save-restriction
17848 (widen)
17849 (goto-char (point-max))
17850 (while (re-search-backward re nil t)
17851 (setq level (org-reduced-level (funcall outline-level)))
17852 (when (<= level n)
17853 (looking-at org-complex-heading-regexp)
17854 (setq head (org-link-display-format
17855 (org-match-string-no-properties 4))
17856 m (org-imenu-new-marker))
17857 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17858 (if (>= level last-level)
17859 (push (cons head m) (aref subs level))
17860 (push (cons head (aref subs (1+ level))) (aref subs level))
17861 (loop for i from (1+ level) to n do (aset subs i nil)))
17862 (setq last-level level)))))
17863 (aref subs 1)))
17865 (eval-after-load "imenu"
17866 '(progn
17867 (add-hook 'imenu-after-jump-hook
17868 (lambda ()
17869 (if (eq major-mode 'org-mode)
17870 (org-show-context 'org-goto))))))
17872 (defun org-link-display-format (link)
17873 "Replace a link with either the description, or the link target
17874 if no description is present"
17875 (save-match-data
17876 (if (string-match org-bracket-link-analytic-regexp link)
17877 (replace-match (if (match-end 5)
17878 (match-string 5 link)
17879 (concat (match-string 1 link)
17880 (match-string 3 link)))
17881 nil t link)
17882 link)))
17884 ;; Speedbar support
17886 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17887 "Overlay marking the agenda restriction line in speedbar.")
17888 (org-overlay-put org-speedbar-restriction-lock-overlay
17889 'face 'org-agenda-restriction-lock)
17890 (org-overlay-put org-speedbar-restriction-lock-overlay
17891 'help-echo "Agendas are currently limited to this item.")
17892 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17894 (defun org-speedbar-set-agenda-restriction ()
17895 "Restrict future agenda commands to the location at point in speedbar.
17896 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17897 (interactive)
17898 (require 'org-agenda)
17899 (let (p m tp np dir txt)
17900 (cond
17901 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17902 'org-imenu t))
17903 (setq m (get-text-property p 'org-imenu-marker))
17904 (with-current-buffer (marker-buffer m)
17905 (goto-char m)
17906 (org-agenda-set-restriction-lock 'subtree)))
17907 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17908 'speedbar-function 'speedbar-find-file))
17909 (setq tp (previous-single-property-change
17910 (1+ p) 'speedbar-function)
17911 np (next-single-property-change
17912 tp 'speedbar-function)
17913 dir (speedbar-line-directory)
17914 txt (buffer-substring-no-properties (or tp (point-min))
17915 (or np (point-max))))
17916 (with-current-buffer (find-file-noselect
17917 (let ((default-directory dir))
17918 (expand-file-name txt)))
17919 (unless (org-mode-p)
17920 (error "Cannot restrict to non-Org-mode file"))
17921 (org-agenda-set-restriction-lock 'file)))
17922 (t (error "Don't know how to restrict Org-mode's agenda")))
17923 (org-move-overlay org-speedbar-restriction-lock-overlay
17924 (point-at-bol) (point-at-eol))
17925 (setq current-prefix-arg nil)
17926 (org-agenda-maybe-redo)))
17928 (eval-after-load "speedbar"
17929 '(progn
17930 (speedbar-add-supported-extension ".org")
17931 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17932 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17933 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17934 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17935 (add-hook 'speedbar-visiting-tag-hook
17936 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17939 ;;; Fixes and Hacks for problems with other packages
17941 ;; Make flyspell not check words in links, to not mess up our keymap
17942 (defun org-mode-flyspell-verify ()
17943 "Don't let flyspell put overlays at active buttons."
17944 (and (not (get-text-property (point) 'keymap))
17945 (not (get-text-property (point) 'org-no-flyspell))))
17947 (defun org-remove-flyspell-overlays-in (beg end)
17948 "Remove flyspell overlays in region."
17949 (and (org-bound-and-true-p flyspell-mode)
17950 (fboundp 'flyspell-delete-region-overlays)
17951 (flyspell-delete-region-overlays beg end))
17952 (add-text-properties beg end '(org-no-flyspell t)))
17954 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17955 (eval-after-load "bookmark"
17956 '(if (boundp 'bookmark-after-jump-hook)
17957 ;; We can use the hook
17958 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17959 ;; Hook not available, use advice
17960 (defadvice bookmark-jump (after org-make-visible activate)
17961 "Make the position visible."
17962 (org-bookmark-jump-unhide))))
17964 ;; Make sure saveplace shows the location if it was hidden
17965 (eval-after-load "saveplace"
17966 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17967 "Make the position visible."
17968 (org-bookmark-jump-unhide)))
17970 ;; Make sure ecb shows the location if it was hidden
17971 (eval-after-load "ecb"
17972 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17973 "Make hierarchy visible when jumping into location from ECB tree buffer."
17974 (if (eq major-mode 'org-mode)
17975 (org-show-context))))
17977 (defun org-bookmark-jump-unhide ()
17978 "Unhide the current position, to show the bookmark location."
17979 (and (org-mode-p)
17980 (or (org-invisible-p)
17981 (save-excursion (goto-char (max (point-min) (1- (point))))
17982 (org-invisible-p)))
17983 (org-show-context 'bookmark-jump)))
17985 ;; Make session.el ignore our circular variable
17986 (eval-after-load "session"
17987 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17989 ;;;; Experimental code
17991 (defun org-closed-in-range ()
17992 "Sparse tree of items closed in a certain time range.
17993 Still experimental, may disappear in the future."
17994 (interactive)
17995 ;; Get the time interval from the user.
17996 (let* ((time1 (org-float-time
17997 (org-read-date nil 'to-time nil "Starting date: ")))
17998 (time2 (org-float-time
17999 (org-read-date nil 'to-time nil "End date:")))
18000 ;; callback function
18001 (callback (lambda ()
18002 (let ((time
18003 (org-float-time
18004 (apply 'encode-time
18005 (org-parse-time-string
18006 (match-string 1))))))
18007 ;; check if time in interval
18008 (and (>= time time1) (<= time time2))))))
18009 ;; make tree, check each match with the callback
18010 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18012 ;;;; Finish up
18014 (provide 'org)
18016 (run-hooks 'org-load-hook)
18018 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18020 ;;; org.el ends here