Fix bug when hiding archived subtrees
[org-mode.git] / lisp / org.el
blob93e63da44f1eb565470615bd0b605188748b2c04
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.34trans
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.34trans"
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 " ctags: Access to Emacs tags with links" org-ctags)
193 (const :tag " docview: Links to doc-view buffers" org-docview)
194 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
195 (const :tag " id: Global IDs for identifying entries" org-id)
196 (const :tag " info: Links to Info nodes" org-info)
197 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
198 (const :tag " habit: Track your consistency with habits" org-habit)
199 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
200 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
201 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
202 (const :tag " mew Links to Mew folders/messages" org-mew)
203 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
204 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
205 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
206 (const :tag " vm: Links to VM folders/messages" org-vm)
207 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
208 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
209 (const :tag " mouse: Additional mouse support" org-mouse)
211 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
212 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
225 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
227 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
229 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
230 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
231 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
232 (const :tag "C mtags: Support for muse-like tags" org-mtags)
233 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
234 (const :tag "C R: Computation using the R language" org-R)
235 (const :tag "C registry: A registry for Org-mode links" org-registry)
236 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
237 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
238 (const :tag "C secretary: Team management with org-mode" org-secretary)
239 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
240 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
241 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
242 (const :tag "C track: Keep up with Org-mode development" org-track)
243 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
245 (defcustom org-support-shift-select nil
246 "Non-nil means make shift-cursor commands select text when possible.
248 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
249 selecting a region, or enlarge thusly regions started in this way.
250 In Org-mode, in special contexts, these same keys are used for other
251 purposes, important enough to compete with shift selection. Org tries
252 to balance these needs by supporting `shift-select-mode' outside these
253 special contexts, under control of this variable.
255 The default of this variable is nil, to avoid confusing behavior. Shifted
256 cursor keys will then execute Org commands in the following contexts:
257 - on a headline, changing TODO state (left/right) and priority (up/down)
258 - on a time stamp, changing the time
259 - in a plain list item, changing the bullet type
260 - in a property definition line, switching between allowed values
261 - in the BEGIN line of a clock table (changing the time block).
262 Outside these contexts, the commands will throw an error.
264 When this variable is t and the cursor is not in a special context,
265 Org-mode will support shift-selection for making and enlarging regions.
266 To make this more effective, the bullet cycling will no longer happen
267 anywhere in an item line, but only if the cursor is exactly on the bullet.
269 If you set this variable to the symbol `always', then the keys
270 will not be special in headlines, property lines, and item lines, to make
271 shift selection work there as well. If this is what you want, you can
272 use the following alternative commands: `C-c C-t' and `C-c ,' to
273 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
274 TODO sets, `C-c -' to cycle item bullet types, and properties can be
275 edited by hand or in column view.
277 However, when the cursor is on a timestamp, shift-cursor commands
278 will still edit the time stamp - this is just too good to give up.
280 XEmacs user should have this variable set to nil, because shift-select-mode
281 is Emacs 23 only."
282 :group 'org
283 :type '(choice
284 (const :tag "Never" nil)
285 (const :tag "When outside special context" t)
286 (const :tag "Everywhere except timestamps" always)))
288 (defgroup org-startup nil
289 "Options concerning startup of Org-mode."
290 :tag "Org Startup"
291 :group 'org)
293 (defcustom org-startup-folded t
294 "Non-nil means entering Org-mode will switch to OVERVIEW.
295 This can also be configured on a per-file basis by adding one of
296 the following lines anywhere in the buffer:
298 #+STARTUP: fold (or `overview', this is equivalent)
299 #+STARTUP: nofold (or `showall', this is equivalent)
300 #+STARTUP: content
301 #+STARTUP: showeverything"
302 :group 'org-startup
303 :type '(choice
304 (const :tag "nofold: show all" nil)
305 (const :tag "fold: overview" t)
306 (const :tag "content: all headlines" content)
307 (const :tag "show everything, even drawers" showeverything)))
309 (defcustom org-startup-truncated t
310 "Non-nil means entering Org-mode will set `truncate-lines'.
311 This is useful since some lines containing links can be very long and
312 uninteresting. Also tables look terrible when wrapped."
313 :group 'org-startup
314 :type 'boolean)
316 (defcustom org-startup-indented nil
317 "Non-nil means turn on `org-indent-mode' on startup.
318 This can also be configured on a per-file basis by adding one of
319 the following lines anywhere in the buffer:
321 #+STARTUP: indent
322 #+STARTUP: noindent"
323 :group 'org-structure
324 :type '(choice
325 (const :tag "Not" nil)
326 (const :tag "Globally (slow on startup in large files)" t)))
328 (defcustom org-startup-with-beamer-mode nil
329 "Non-nil means turn on `org-beamer-mode' on startup.
330 This can also be configured on a per-file basis by adding one of
331 the following lines anywhere in the buffer:
333 #+STARTUP: beamer"
334 :group 'org-startup
335 :type 'boolean)
337 (defcustom org-startup-align-all-tables nil
338 "Non-nil means align all tables when visiting a file.
339 This is useful when the column width in tables is forced with <N> cookies
340 in table fields. Such tables will look correct only after the first re-align.
341 This can also be configured on a per-file basis by adding one of
342 the following lines anywhere in the buffer:
343 #+STARTUP: align
344 #+STARTUP: noalign"
345 :group 'org-startup
346 :type 'boolean)
348 (defcustom org-insert-mode-line-in-empty-file nil
349 "Non-nil means insert the first line setting Org-mode in empty files.
350 When the function `org-mode' is called interactively in an empty file, this
351 normally means that the file name does not automatically trigger Org-mode.
352 To ensure that the file will always be in Org-mode in the future, a
353 line enforcing Org-mode will be inserted into the buffer, if this option
354 has been set."
355 :group 'org-startup
356 :type 'boolean)
358 (defcustom org-replace-disputed-keys nil
359 "Non-nil means use alternative key bindings for some keys.
360 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
361 These keys are also used by other packages like shift-selection-mode'
362 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
363 If you want to use Org-mode together with one of these other modes,
364 or more generally if you would like to move some Org-mode commands to
365 other keys, set this variable and configure the keys with the variable
366 `org-disputed-keys'.
368 This option is only relevant at load-time of Org-mode, and must be set
369 *before* org.el is loaded. Changing it requires a restart of Emacs to
370 become effective."
371 :group 'org-startup
372 :type 'boolean)
374 (defcustom org-use-extra-keys nil
375 "Non-nil means use extra key sequence definitions for certain
376 commands. This happens automatically if you run XEmacs or if
377 window-system is nil. This variable lets you do the same
378 manually. You must set it before loading org.
380 Example: on Carbon Emacs 22 running graphically, with an external
381 keyboard on a Powerbook, the default way of setting M-left might
382 not work for either Alt or ESC. Setting this variable will make
383 it work for ESC."
384 :group 'org-startup
385 :type 'boolean)
387 (if (fboundp 'defvaralias)
388 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
390 (defcustom org-disputed-keys
391 '(([(shift up)] . [(meta p)])
392 ([(shift down)] . [(meta n)])
393 ([(shift left)] . [(meta -)])
394 ([(shift right)] . [(meta +)])
395 ([(control shift right)] . [(meta shift +)])
396 ([(control shift left)] . [(meta shift -)]))
397 "Keys for which Org-mode and other modes compete.
398 This is an alist, cars are the default keys, second element specifies
399 the alternative to use when `org-replace-disputed-keys' is t.
401 Keys can be specified in any syntax supported by `define-key'.
402 The value of this option takes effect only at Org-mode's startup,
403 therefore you'll have to restart Emacs to apply it after changing."
404 :group 'org-startup
405 :type 'alist)
407 (defun org-key (key)
408 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
409 Or return the original if not disputed."
410 (if org-replace-disputed-keys
411 (let* ((nkey (key-description key))
412 (x (org-find-if (lambda (x)
413 (equal (key-description (car x)) nkey))
414 org-disputed-keys)))
415 (if x (cdr x) key))
416 key))
418 (defun org-find-if (predicate seq)
419 (catch 'exit
420 (while seq
421 (if (funcall predicate (car seq))
422 (throw 'exit (car seq))
423 (pop seq)))))
425 (defun org-defkey (keymap key def)
426 "Define a key, possibly translated, as returned by `org-key'."
427 (define-key keymap (org-key key) def))
429 (defcustom org-ellipsis nil
430 "The ellipsis to use in the Org-mode outline.
431 When nil, just use the standard three dots. When a string, use that instead,
432 When a face, use the standard 3 dots, but with the specified face.
433 The change affects only Org-mode (which will then use its own display table).
434 Changing this requires executing `M-x org-mode' in a buffer to become
435 effective."
436 :group 'org-startup
437 :type '(choice (const :tag "Default" nil)
438 (face :tag "Face" :value org-warning)
439 (string :tag "String" :value "...#")))
441 (defvar org-display-table nil
442 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
444 (defgroup org-keywords nil
445 "Keywords in Org-mode."
446 :tag "Org Keywords"
447 :group 'org)
449 (defcustom org-deadline-string "DEADLINE:"
450 "String to mark deadline entries.
451 A deadline is this string, followed by a time stamp. Should be a word,
452 terminated by a colon. You can insert a schedule keyword and
453 a timestamp with \\[org-deadline].
454 Changes become only effective after restarting Emacs."
455 :group 'org-keywords
456 :type 'string)
458 (defcustom org-scheduled-string "SCHEDULED:"
459 "String to mark scheduled TODO entries.
460 A schedule is this string, followed by a time stamp. Should be a word,
461 terminated by a colon. You can insert a schedule keyword and
462 a timestamp with \\[org-schedule].
463 Changes become only effective after restarting Emacs."
464 :group 'org-keywords
465 :type 'string)
467 (defcustom org-closed-string "CLOSED:"
468 "String used as the prefix for timestamps logging closing a TODO entry."
469 :group 'org-keywords
470 :type 'string)
472 (defcustom org-clock-string "CLOCK:"
473 "String used as prefix for timestamps clocking work hours on an item."
474 :group 'org-keywords
475 :type 'string)
477 (defcustom org-comment-string "COMMENT"
478 "Entries starting with this keyword will never be exported.
479 An entry can be toggled between COMMENT and normal with
480 \\[org-toggle-comment].
481 Changes become only effective after restarting Emacs."
482 :group 'org-keywords
483 :type 'string)
485 (defcustom org-quote-string "QUOTE"
486 "Entries starting with this keyword will be exported in fixed-width font.
487 Quoting applies only to the text in the entry following the headline, and does
488 not extend beyond the next headline, even if that is lower level.
489 An entry can be toggled between QUOTE and normal with
490 \\[org-toggle-fixed-width-section]."
491 :group 'org-keywords
492 :type 'string)
494 (defconst org-repeat-re
495 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
496 "Regular expression for specifying repeated events.
497 After a match, group 1 contains the repeat expression.")
499 (defgroup org-structure nil
500 "Options concerning the general structure of Org-mode files."
501 :tag "Org Structure"
502 :group 'org)
504 (defgroup org-reveal-location nil
505 "Options about how to make context of a location visible."
506 :tag "Org Reveal Location"
507 :group 'org-structure)
509 (defconst org-context-choice
510 '(choice
511 (const :tag "Always" t)
512 (const :tag "Never" nil)
513 (repeat :greedy t :tag "Individual contexts"
514 (cons
515 (choice :tag "Context"
516 (const agenda)
517 (const org-goto)
518 (const occur-tree)
519 (const tags-tree)
520 (const link-search)
521 (const mark-goto)
522 (const bookmark-jump)
523 (const isearch)
524 (const default))
525 (boolean))))
526 "Contexts for the reveal options.")
528 (defcustom org-show-hierarchy-above '((default . t))
529 "Non-nil means show full hierarchy when revealing a location.
530 Org-mode often shows locations in an org-mode file which might have
531 been invisible before. When this is set, the hierarchy of headings
532 above the exposed location is shown.
533 Turning this off for example for sparse trees makes them very compact.
534 Instead of t, this can also be an alist specifying this option for different
535 contexts. Valid contexts are
536 agenda when exposing an entry from the agenda
537 org-goto when using the command `org-goto' on key C-c C-j
538 occur-tree when using the command `org-occur' on key C-c /
539 tags-tree when constructing a sparse tree based on tags matches
540 link-search when exposing search matches associated with a link
541 mark-goto when exposing the jump goal of a mark
542 bookmark-jump when exposing a bookmark location
543 isearch when exiting from an incremental search
544 default default for all contexts not set explicitly"
545 :group 'org-reveal-location
546 :type org-context-choice)
548 (defcustom org-show-following-heading '((default . nil))
549 "Non-nil means show following heading when revealing a location.
550 Org-mode often shows locations in an org-mode file which might have
551 been invisible before. When this is set, the heading following the
552 match is shown.
553 Turning this off for example for sparse trees makes them very compact,
554 but makes it harder to edit the location of the match. In such a case,
555 use the command \\[org-reveal] to show more context.
556 Instead of t, this can also be an alist specifying this option for different
557 contexts. See `org-show-hierarchy-above' for valid contexts."
558 :group 'org-reveal-location
559 :type org-context-choice)
561 (defcustom org-show-siblings '((default . nil) (isearch t))
562 "Non-nil means show all sibling heading when revealing a location.
563 Org-mode often shows locations in an org-mode file which might have
564 been invisible before. When this is set, the sibling of the current entry
565 heading are all made visible. If `org-show-hierarchy-above' is t,
566 the same happens on each level of the hierarchy above the current entry.
568 By default this is on for the isearch context, off for all other contexts.
569 Turning this off for example for sparse trees makes them very compact,
570 but makes it harder to edit the location of the match. In such a case,
571 use the command \\[org-reveal] to show more context.
572 Instead of t, this can also be an alist specifying this option for different
573 contexts. See `org-show-hierarchy-above' for valid contexts."
574 :group 'org-reveal-location
575 :type org-context-choice)
577 (defcustom org-show-entry-below '((default . nil))
578 "Non-nil means show the entry below a headline when revealing a location.
579 Org-mode often shows locations in an org-mode file which might have
580 been invisible before. When this is set, the text below the headline that is
581 exposed is also shown.
583 By default this is off for all contexts.
584 Instead of t, this can also be an alist specifying this option for different
585 contexts. See `org-show-hierarchy-above' for valid contexts."
586 :group 'org-reveal-location
587 :type org-context-choice)
589 (defcustom org-indirect-buffer-display 'other-window
590 "How should indirect tree buffers be displayed?
591 This applies to indirect buffers created with the commands
592 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
593 Valid values are:
594 current-window Display in the current window
595 other-window Just display in another window.
596 dedicated-frame Create one new frame, and re-use it each time.
597 new-frame Make a new frame each time. Note that in this case
598 previously-made indirect buffers are kept, and you need to
599 kill these buffers yourself."
600 :group 'org-structure
601 :group 'org-agenda-windows
602 :type '(choice
603 (const :tag "In current window" current-window)
604 (const :tag "In current frame, other window" other-window)
605 (const :tag "Each time a new frame" new-frame)
606 (const :tag "One dedicated frame" dedicated-frame)))
608 (defcustom org-use-speed-commands nil
609 "Non-nil means activate single letter commands at beginning of a headline.
610 This may also be a function to test for appropriate locations where speed
611 commands should be active."
612 :group 'org-structure
613 :type '(choice
614 (const :tag "Never" nil)
615 (const :tag "At beginning of headline stars" t)
616 (function)))
618 (defcustom org-speed-commands-user nil
619 "Alist of additional speed commands.
620 This list will be checked before `org-speed-commands-default'
621 when the variable `org-use-speed-commands' is non-nil
622 and when the cursor is at the beginning of a headline.
623 The car if each entry is a string with a single letter, which must
624 be assigned to `self-insert-command' in the global map.
625 The cdr is either a command to be called interactively, a function
626 to be called, or a form to be evaluated.
627 An entry that is just a list with a single string will be interpreted
628 as a descriptive headline that will be added when listing the speed
629 copmmands in the Help buffer using the `?' speed command."
630 :group 'org-structure
631 :type '(repeat :value ("k" . ignore)
632 (choice :value ("k" . ignore)
633 (list :tag "Descriptive Headline" (string :tag "Headline"))
634 (cons :tag "Letter and Command"
635 (string :tag "Command letter")
636 (choice
637 (function)
638 (sexp))))))
640 (defgroup org-cycle nil
641 "Options concerning visibility cycling in Org-mode."
642 :tag "Org Cycle"
643 :group 'org-structure)
645 (defcustom org-cycle-skip-children-state-if-no-children t
646 "Non-nil means skip CHILDREN state in entries that don't have any."
647 :group 'org-cycle
648 :type 'boolean)
650 (defcustom org-cycle-max-level nil
651 "Maximum level which should still be subject to visibility cycling.
652 Levels higher than this will, for cycling, be treated as text, not a headline.
653 When `org-odd-levels-only' is set, a value of N in this variable actually
654 means 2N-1 stars as the limiting headline.
655 When nil, cycle all levels.
656 Note that the limiting level of cycling is also influenced by
657 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
658 `org-inlinetask-min-level' is, cycling will be limited to levels one less
659 than its value."
660 :group 'org-cycle
661 :type '(choice
662 (const :tag "No limit" nil)
663 (integer :tag "Maximum level")))
665 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
666 "Names of drawers. Drawers are not opened by cycling on the headline above.
667 Drawers only open with a TAB on the drawer line itself. A drawer looks like
668 this:
669 :DRAWERNAME:
670 .....
671 :END:
672 The drawer \"PROPERTIES\" is special for capturing properties through
673 the property API.
675 Drawers can be defined on the per-file basis with a line like:
677 #+DRAWERS: HIDDEN STATE PROPERTIES"
678 :group 'org-structure
679 :group 'org-cycle
680 :type '(repeat (string :tag "Drawer Name")))
682 (defcustom org-hide-block-startup nil
683 "Non-nil means entering Org-mode will fold all blocks.
684 This can also be set in on a per-file basis with
686 #+STARTUP: hideblocks
687 #+STARTUP: showblocks"
688 :group 'org-startup
689 :group 'org-cycle
690 :type 'boolean)
692 (defcustom org-cycle-global-at-bob nil
693 "Cycle globally if cursor is at beginning of buffer and not at a headline.
694 This makes it possible to do global cycling without having to use S-TAB or
695 C-u TAB. For this special case to work, the first line of the buffer
696 must not be a headline - it may be empty or some other text. When used in
697 this way, `org-cycle-hook' is disables temporarily, to make sure the
698 cursor stays at the beginning of the buffer.
699 When this option is nil, don't do anything special at the beginning
700 of the buffer."
701 :group 'org-cycle
702 :type 'boolean)
704 (defcustom org-cycle-level-after-item/entry-creation t
705 "Non-nil means cycle entry level or item indentation in new empty entries.
707 When the cursor is at the end of an empty headline, i.e with only stars
708 and maybe a TODO keyword, TAB will then switch the entry to become a child,
709 and then all possible anchestor states, before returning to the original state.
710 This makes data entry extremely fast: M-RET to create a new headline,
711 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
713 When the cursor is at the end of an empty plain list item, one TAB will
714 make it a subitem, two or more tabs will back up to make this an item
715 higher up in the item hierarchy."
716 :group 'org-cycle
717 :type 'boolean)
719 (defcustom org-cycle-emulate-tab t
720 "Where should `org-cycle' emulate TAB.
721 nil Never
722 white Only in completely white lines
723 whitestart Only at the beginning of lines, before the first non-white char
724 t Everywhere except in headlines
725 exc-hl-bol Everywhere except at the start of a headline
726 If TAB is used in a place where it does not emulate TAB, the current subtree
727 visibility is cycled."
728 :group 'org-cycle
729 :type '(choice (const :tag "Never" nil)
730 (const :tag "Only in completely white lines" white)
731 (const :tag "Before first char in a line" whitestart)
732 (const :tag "Everywhere except in headlines" t)
733 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
736 (defcustom org-cycle-separator-lines 2
737 "Number of empty lines needed to keep an empty line between collapsed trees.
738 If you leave an empty line between the end of a subtree and the following
739 headline, this empty line is hidden when the subtree is folded.
740 Org-mode will leave (exactly) one empty line visible if the number of
741 empty lines is equal or larger to the number given in this variable.
742 So the default 2 means at least 2 empty lines after the end of a subtree
743 are needed to produce free space between a collapsed subtree and the
744 following headline.
746 If the number is negative, and the number of empty lines is at least -N,
747 all empty lines are shown.
749 Special case: when 0, never leave empty lines in collapsed view."
750 :group 'org-cycle
751 :type 'integer)
752 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
754 (defcustom org-pre-cycle-hook nil
755 "Hook that is run before visibility cycling is happening.
756 The function(s) in this hook must accept a single argument which indicates
757 the new state that will be set right after running this hook. The
758 argument is a symbol. Before a global state change, it can have the values
759 `overview', `content', or `all'. Before a local state change, it can have
760 the values `folded', `children', or `subtree'."
761 :group 'org-cycle
762 :type 'hook)
764 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
765 org-cycle-hide-drawers
766 org-cycle-show-empty-lines
767 org-optimize-window-after-visibility-change)
768 "Hook that is run after `org-cycle' has changed the buffer visibility.
769 The function(s) in this hook must accept a single argument which indicates
770 the new state that was set by the most recent `org-cycle' command. The
771 argument is a symbol. After a global state change, it can have the values
772 `overview', `content', or `all'. After a local state change, it can have
773 the values `folded', `children', or `subtree'."
774 :group 'org-cycle
775 :type 'hook)
777 (defgroup org-edit-structure nil
778 "Options concerning structure editing in Org-mode."
779 :tag "Org Edit Structure"
780 :group 'org-structure)
782 (defcustom org-odd-levels-only nil
783 "Non-nil means skip even levels and only use odd levels for the outline.
784 This has the effect that two stars are being added/taken away in
785 promotion/demotion commands. It also influences how levels are
786 handled by the exporters.
787 Changing it requires restart of `font-lock-mode' to become effective
788 for fontification also in regions already fontified.
789 You may also set this on a per-file basis by adding one of the following
790 lines to the buffer:
792 #+STARTUP: odd
793 #+STARTUP: oddeven"
794 :group 'org-edit-structure
795 :group 'org-font-lock
796 :type 'boolean)
798 (defcustom org-adapt-indentation t
799 "Non-nil means adapt indentation to outline node level.
801 When this variable is set, Org assumes that you write outlines by
802 indenting text in each node to align with the headline (after the stars).
803 The following issues are influenced by this variable:
805 - When this is set and the *entire* text in an entry is indented, the
806 indentation is increased by one space in a demotion command, and
807 decreased by one in a promotion command. If any line in the entry
808 body starts with text at column 0, indentation is not changed at all.
810 - Property drawers and planning information is inserted indented when
811 this variable s set. When nil, they will not be indented.
813 - TAB indents a line relative to context. The lines below a headline
814 will be indented when this variable is set.
816 Note that this is all about true indentation, by adding and removing
817 space characters. See also `org-indent.el' which does level-dependent
818 indentation in a virtual way, i.e. at display time in Emacs."
819 :group 'org-edit-structure
820 :type 'boolean)
822 (defcustom org-special-ctrl-a/e nil
823 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
825 When t, `C-a' will bring back the cursor to the beginning of the
826 headline text, i.e. after the stars and after a possible TODO keyword.
827 In an item, this will be the position after the bullet.
828 When the cursor is already at that position, another `C-a' will bring
829 it to the beginning of the line.
831 `C-e' will jump to the end of the headline, ignoring the presence of tags
832 in the headline. A second `C-e' will then jump to the true end of the
833 line, after any tags. This also means that, when this variable is
834 non-nil, `C-e' also will never jump beyond the end of the heading of a
835 folded section, i.e. not after the ellipses.
837 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
838 going to the true line boundary first. Only a directly following, identical
839 keypress will bring the cursor to the special positions.
841 This may also be a cons cell where the behavior for `C-a' and `C-e' is
842 set separately."
843 :group 'org-edit-structure
844 :type '(choice
845 (const :tag "off" nil)
846 (const :tag "on: after stars/bullet and before tags first" t)
847 (const :tag "reversed: true line boundary first" reversed)
848 (cons :tag "Set C-a and C-e separately"
849 (choice :tag "Special C-a"
850 (const :tag "off" nil)
851 (const :tag "on: after stars/bullet first" t)
852 (const :tag "reversed: before stars/bullet first" reversed))
853 (choice :tag "Special C-e"
854 (const :tag "off" nil)
855 (const :tag "on: before tags first" t)
856 (const :tag "reversed: after tags first" reversed)))))
857 (if (fboundp 'defvaralias)
858 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
860 (defcustom org-special-ctrl-k nil
861 "Non-nil means `C-k' will behave specially in headlines.
862 When nil, `C-k' will call the default `kill-line' command.
863 When t, the following will happen while the cursor is in the headline:
865 - When the cursor is at the beginning of a headline, kill the entire
866 line and possible the folded subtree below the line.
867 - When in the middle of the headline text, kill the headline up to the tags.
868 - When after the headline text, kill the tags."
869 :group 'org-edit-structure
870 :type 'boolean)
872 (defcustom org-yank-folded-subtrees t
873 "Non-nil means when yanking subtrees, fold them.
874 If the kill is a single subtree, or a sequence of subtrees, i.e. if
875 it starts with a heading and all other headings in it are either children
876 or siblings, then fold all the subtrees. However, do this only if no
877 text after the yank would be swallowed into a folded tree by this action."
878 :group 'org-edit-structure
879 :type 'boolean)
881 (defcustom org-yank-adjusted-subtrees nil
882 "Non-nil means when yanking subtrees, adjust the level.
883 With this setting, `org-paste-subtree' is used to insert the subtree, see
884 this function for details."
885 :group 'org-edit-structure
886 :type 'boolean)
888 (defcustom org-M-RET-may-split-line '((default . t))
889 "Non-nil means M-RET will split the line at the cursor position.
890 When nil, it will go to the end of the line before making a
891 new line.
892 You may also set this option in a different way for different
893 contexts. Valid contexts are:
895 headline when creating a new headline
896 item when creating a new item
897 table in a table field
898 default the value to be used for all contexts not explicitly
899 customized"
900 :group 'org-structure
901 :group 'org-table
902 :type '(choice
903 (const :tag "Always" t)
904 (const :tag "Never" nil)
905 (repeat :greedy t :tag "Individual contexts"
906 (cons
907 (choice :tag "Context"
908 (const headline)
909 (const item)
910 (const table)
911 (const default))
912 (boolean)))))
915 (defcustom org-insert-heading-respect-content nil
916 "Non-nil means insert new headings after the current subtree.
917 When nil, the new heading is created directly after the current line.
918 The commands \\[org-insert-heading-respect-content] and
919 \\[org-insert-todo-heading-respect-content] turn this variable on
920 for the duration of the command."
921 :group 'org-structure
922 :type 'boolean)
924 (defcustom org-blank-before-new-entry '((heading . auto)
925 (plain-list-item . auto))
926 "Should `org-insert-heading' leave a blank line before new heading/item?
927 The value is an alist, with `heading' and `plain-list-item' as car,
928 and a boolean flag as cdr. For plain lists, if the variable
929 `org-empty-line-terminates-plain-lists' is set, the setting here
930 is ignored and no empty line is inserted, to keep the list in tact."
931 :group 'org-edit-structure
932 :type '(list
933 (cons (const heading)
934 (choice (const :tag "Never" nil)
935 (const :tag "Always" t)
936 (const :tag "Auto" auto)))
937 (cons (const plain-list-item)
938 (choice (const :tag "Never" nil)
939 (const :tag "Always" t)
940 (const :tag "Auto" auto)))))
942 (defcustom org-insert-heading-hook nil
943 "Hook being run after inserting a new heading."
944 :group 'org-edit-structure
945 :type 'hook)
947 (defcustom org-enable-fixed-width-editor t
948 "Non-nil means lines starting with \":\" are treated as fixed-width.
949 This currently only means they are never auto-wrapped.
950 When nil, such lines will be treated like ordinary lines.
951 See also the QUOTE keyword."
952 :group 'org-edit-structure
953 :type 'boolean)
956 (defcustom org-goto-auto-isearch t
957 "Non-nil means typing characters in org-goto starts incremental search."
958 :group 'org-edit-structure
959 :type 'boolean)
961 (defgroup org-sparse-trees nil
962 "Options concerning sparse trees in Org-mode."
963 :tag "Org Sparse Trees"
964 :group 'org-structure)
966 (defcustom org-highlight-sparse-tree-matches t
967 "Non-nil means highlight all matches that define a sparse tree.
968 The highlights will automatically disappear the next time the buffer is
969 changed by an edit command."
970 :group 'org-sparse-trees
971 :type 'boolean)
973 (defcustom org-remove-highlights-with-change t
974 "Non-nil means any change to the buffer will remove temporary highlights.
975 Such highlights are created by `org-occur' and `org-clock-display'.
976 When nil, `C-c C-c needs to be used to get rid of the highlights.
977 The highlights created by `org-preview-latex-fragment' always need
978 `C-c C-c' to be removed."
979 :group 'org-sparse-trees
980 :group 'org-time
981 :type 'boolean)
984 (defcustom org-occur-hook '(org-first-headline-recenter)
985 "Hook that is run after `org-occur' has constructed a sparse tree.
986 This can be used to recenter the window to show as much of the structure
987 as possible."
988 :group 'org-sparse-trees
989 :type 'hook)
991 (defgroup org-imenu-and-speedbar nil
992 "Options concerning imenu and speedbar in Org-mode."
993 :tag "Org Imenu and Speedbar"
994 :group 'org-structure)
996 (defcustom org-imenu-depth 2
997 "The maximum level for Imenu access to Org-mode headlines.
998 This also applied for speedbar access."
999 :group 'org-imenu-and-speedbar
1000 :type 'integer)
1002 (defgroup org-table nil
1003 "Options concerning tables in Org-mode."
1004 :tag "Org Table"
1005 :group 'org)
1007 (defcustom org-enable-table-editor 'optimized
1008 "Non-nil means lines starting with \"|\" are handled by the table editor.
1009 When nil, such lines will be treated like ordinary lines.
1011 When equal to the symbol `optimized', the table editor will be optimized to
1012 do the following:
1013 - Automatic overwrite mode in front of whitespace in table fields.
1014 This makes the structure of the table stay in tact as long as the edited
1015 field does not exceed the column width.
1016 - Minimize the number of realigns. Normally, the table is aligned each time
1017 TAB or RET are pressed to move to another field. With optimization this
1018 happens only if changes to a field might have changed the column width.
1019 Optimization requires replacing the functions `self-insert-command',
1020 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1021 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1022 very good at guessing when a re-align will be necessary, but you can always
1023 force one with \\[org-ctrl-c-ctrl-c].
1025 If you would like to use the optimized version in Org-mode, but the
1026 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1028 This variable can be used to turn on and off the table editor during a session,
1029 but in order to toggle optimization, a restart is required.
1031 See also the variable `org-table-auto-blank-field'."
1032 :group 'org-table
1033 :type '(choice
1034 (const :tag "off" nil)
1035 (const :tag "on" t)
1036 (const :tag "on, optimized" optimized)))
1038 (defcustom org-self-insert-cluster-for-undo t
1039 "Non-nil means cluster self-insert commands for undo when possible.
1040 If this is set, then, like in the Emacs command loop, 20 consecutive
1041 characters will be undone together.
1042 This is configurable, because there is some impact on typing performance."
1043 :group 'org-table
1044 :type 'boolean)
1046 (defcustom org-table-tab-recognizes-table.el t
1047 "Non-nil means TAB will automatically notice a table.el table.
1048 When it sees such a table, it moves point into it and - if necessary -
1049 calls `table-recognize-table'."
1050 :group 'org-table-editing
1051 :type 'boolean)
1053 (defgroup org-link nil
1054 "Options concerning links in Org-mode."
1055 :tag "Org Link"
1056 :group 'org)
1058 (defvar org-link-abbrev-alist-local nil
1059 "Buffer-local version of `org-link-abbrev-alist', which see.
1060 The value of this is taken from the #+LINK lines.")
1061 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1063 (defcustom org-link-abbrev-alist nil
1064 "Alist of link abbreviations.
1065 The car of each element is a string, to be replaced at the start of a link.
1066 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1067 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1069 [[linkkey:tag][description]]
1071 The 'linkkey' must be a word word, starting with a letter, followed
1072 by letters, numbers, '-' or '_'.
1074 If REPLACE is a string, the tag will simply be appended to create the link.
1075 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1076 the placeholder \"%h\" will cause a url-encoded version of the tag to
1077 be inserted at that point (see the function `url-hexify-string').
1079 REPLACE may also be a function that will be called with the tag as the
1080 only argument to create the link, which should be returned as a string.
1082 See the manual for examples."
1083 :group 'org-link
1084 :type '(repeat
1085 (cons
1086 (string :tag "Protocol")
1087 (choice
1088 (string :tag "Format")
1089 (function)))))
1091 (defcustom org-descriptive-links t
1092 "Non-nil means hide link part and only show description of bracket links.
1093 Bracket links are like [[link][description]]. This variable sets the initial
1094 state in new org-mode buffers. The setting can then be toggled on a
1095 per-buffer basis from the Org->Hyperlinks menu."
1096 :group 'org-link
1097 :type 'boolean)
1099 (defcustom org-link-file-path-type 'adaptive
1100 "How the path name in file links should be stored.
1101 Valid values are:
1103 relative Relative to the current directory, i.e. the directory of the file
1104 into which the link is being inserted.
1105 absolute Absolute path, if possible with ~ for home directory.
1106 noabbrev Absolute path, no abbreviation of home directory.
1107 adaptive Use relative path for files in the current directory and sub-
1108 directories of it. For other files, use an absolute path."
1109 :group 'org-link
1110 :type '(choice
1111 (const relative)
1112 (const absolute)
1113 (const noabbrev)
1114 (const adaptive)))
1116 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1117 "Types of links that should be activated in Org-mode files.
1118 This is a list of symbols, each leading to the activation of a certain link
1119 type. In principle, it does not hurt to turn on most link types - there may
1120 be a small gain when turning off unused link types. The types are:
1122 bracket The recommended [[link][description]] or [[link]] links with hiding.
1123 angular Links in angular brackets that may contain whitespace like
1124 <bbdb:Carsten Dominik>.
1125 plain Plain links in normal text, no whitespace, like http://google.com.
1126 radio Text that is matched by a radio target, see manual for details.
1127 tag Tag settings in a headline (link to tag search).
1128 date Time stamps (link to calendar).
1129 footnote Footnote labels.
1131 Changing this variable requires a restart of Emacs to become effective."
1132 :group 'org-link
1133 :type '(set :greedy t
1134 (const :tag "Double bracket links (new style)" bracket)
1135 (const :tag "Angular bracket links (old style)" angular)
1136 (const :tag "Plain text links" plain)
1137 (const :tag "Radio target matches" radio)
1138 (const :tag "Tags" tag)
1139 (const :tag "Timestamps" date)
1140 (const :tag "Footnotes" footnote)))
1142 (defcustom org-make-link-description-function nil
1143 "Function to use to generate link descriptions from links. If
1144 nil the link location will be used. This function must take two
1145 parameters; the first is the link and the second the description
1146 org-insert-link has generated, and should return the description
1147 to use."
1148 :group 'org-link
1149 :type 'function)
1151 (defgroup org-link-store nil
1152 "Options concerning storing links in Org-mode."
1153 :tag "Org Store Link"
1154 :group 'org-link)
1156 (defcustom org-email-link-description-format "Email %c: %.30s"
1157 "Format of the description part of a link to an email or usenet message.
1158 The following %-escapes will be replaced by corresponding information:
1160 %F full \"From\" field
1161 %f name, taken from \"From\" field, address if no name
1162 %T full \"To\" field
1163 %t first name in \"To\" field, address if no name
1164 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1165 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1166 %s subject
1167 %m message-id.
1169 You may use normal field width specification between the % and the letter.
1170 This is for example useful to limit the length of the subject.
1172 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1173 :group 'org-link-store
1174 :type 'string)
1176 (defcustom org-from-is-user-regexp
1177 (let (r1 r2)
1178 (when (and user-mail-address (not (string= user-mail-address "")))
1179 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1180 (when (and user-full-name (not (string= user-full-name "")))
1181 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1182 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1183 "Regexp matched against the \"From:\" header of an email or usenet message.
1184 It should match if the message is from the user him/herself."
1185 :group 'org-link-store
1186 :type 'regexp)
1188 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1189 "Non-nil means storing a link to an Org file will use entry IDs.
1191 Note that before this variable is even considered, org-id must be loaded,
1192 so please customize `org-modules' and turn it on.
1194 The variable can have the following values:
1196 t Create an ID if needed to make a link to the current entry.
1198 create-if-interactive
1199 If `org-store-link' is called directly (interactively, as a user
1200 command), do create an ID to support the link. But when doing the
1201 job for remember, only use the ID if it already exists. The
1202 purpose of this setting is to avoid proliferation of unwanted
1203 IDs, just because you happen to be in an Org file when you
1204 call `org-remember' that automatically and preemptively
1205 creates a link. If you do want to get an ID link in a remember
1206 template to an entry not having an ID, create it first by
1207 explicitly creating a link to it, using `C-c C-l' first.
1209 create-if-interactive-and-no-custom-id
1210 Like create-if-interactive, but do not create an ID if there is
1211 a CUSTOM_ID property defined in the entry. This is the default.
1213 use-existing
1214 Use existing ID, do not create one.
1216 nil Never use an ID to make a link, instead link using a text search for
1217 the headline text."
1218 :group 'org-link-store
1219 :type '(choice
1220 (const :tag "Create ID to make link" t)
1221 (const :tag "Create if storing link interactively"
1222 create-if-interactive)
1223 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1224 create-if-interactive-and-no-custom-id)
1225 (const :tag "Only use existing" use-existing)
1226 (const :tag "Do not use ID to create link" nil)))
1228 (defcustom org-context-in-file-links t
1229 "Non-nil means file links from `org-store-link' contain context.
1230 A search string will be added to the file name with :: as separator and
1231 used to find the context when the link is activated by the command
1232 `org-open-at-point'.
1233 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1234 negates this setting for the duration of the command."
1235 :group 'org-link-store
1236 :type 'boolean)
1238 (defcustom org-keep-stored-link-after-insertion nil
1239 "Non-nil means keep link in list for entire session.
1241 The command `org-store-link' adds a link pointing to the current
1242 location to an internal list. These links accumulate during a session.
1243 The command `org-insert-link' can be used to insert links into any
1244 Org-mode file (offering completion for all stored links). When this
1245 option is nil, every link which has been inserted once using \\[org-insert-link]
1246 will be removed from the list, to make completing the unused links
1247 more efficient."
1248 :group 'org-link-store
1249 :type 'boolean)
1251 (defgroup org-link-follow nil
1252 "Options concerning following links in Org-mode."
1253 :tag "Org Follow Link"
1254 :group 'org-link)
1256 (defcustom org-link-translation-function nil
1257 "Function to translate links with different syntax to Org syntax.
1258 This can be used to translate links created for example by the Planner
1259 or emacs-wiki packages to Org syntax.
1260 The function must accept two parameters, a TYPE containing the link
1261 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1262 which is everything after the link protocol. It should return a cons
1263 with possibly modified values of type and path.
1264 Org contains a function for this, so if you set this variable to
1265 `org-translate-link-from-planner', you should be able follow many
1266 links created by planner."
1267 :group 'org-link-follow
1268 :type 'function)
1270 (defcustom org-follow-link-hook nil
1271 "Hook that is run after a link has been followed."
1272 :group 'org-link-follow
1273 :type 'hook)
1275 (defcustom org-tab-follows-link nil
1276 "Non-nil means on links TAB will follow the link.
1277 Needs to be set before org.el is loaded.
1278 This really should not be used, it does not make sense, and the
1279 implementation is bad."
1280 :group 'org-link-follow
1281 :type 'boolean)
1283 (defcustom org-return-follows-link nil
1284 "Non-nil means on links RET will follow the link.
1285 Needs to be set before org.el is loaded."
1286 :group 'org-link-follow
1287 :type 'boolean)
1289 (defcustom org-mouse-1-follows-link
1290 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1291 "Non-nil means mouse-1 on a link will follow the link.
1292 A longer mouse click will still set point. Does not work on XEmacs.
1293 Needs to be set before org.el is loaded."
1294 :group 'org-link-follow
1295 :type 'boolean)
1297 (defcustom org-mark-ring-length 4
1298 "Number of different positions to be recorded in the ring
1299 Changing this requires a restart of Emacs to work correctly."
1300 :group 'org-link-follow
1301 :type 'integer)
1303 (defcustom org-link-frame-setup
1304 '((vm . vm-visit-folder-other-frame)
1305 (gnus . gnus-other-frame)
1306 (file . find-file-other-window))
1307 "Setup the frame configuration for following links.
1308 When following a link with Emacs, it may often be useful to display
1309 this link in another window or frame. This variable can be used to
1310 set this up for the different types of links.
1311 For VM, use any of
1312 `vm-visit-folder'
1313 `vm-visit-folder-other-frame'
1314 For Gnus, use any of
1315 `gnus'
1316 `gnus-other-frame'
1317 `org-gnus-no-new-news'
1318 For FILE, use any of
1319 `find-file'
1320 `find-file-other-window'
1321 `find-file-other-frame'
1322 For the calendar, use the variable `calendar-setup'.
1323 For BBDB, it is currently only possible to display the matches in
1324 another window."
1325 :group 'org-link-follow
1326 :type '(list
1327 (cons (const vm)
1328 (choice
1329 (const vm-visit-folder)
1330 (const vm-visit-folder-other-window)
1331 (const vm-visit-folder-other-frame)))
1332 (cons (const gnus)
1333 (choice
1334 (const gnus)
1335 (const gnus-other-frame)
1336 (const org-gnus-no-new-news)))
1337 (cons (const file)
1338 (choice
1339 (const find-file)
1340 (const find-file-other-window)
1341 (const find-file-other-frame)))))
1343 (defcustom org-display-internal-link-with-indirect-buffer nil
1344 "Non-nil means use indirect buffer to display infile links.
1345 Activating internal links (from one location in a file to another location
1346 in the same file) normally just jumps to the location. When the link is
1347 activated with a C-u prefix (or with mouse-3), the link is displayed in
1348 another window. When this option is set, the other window actually displays
1349 an indirect buffer clone of the current buffer, to avoid any visibility
1350 changes to the current buffer."
1351 :group 'org-link-follow
1352 :type 'boolean)
1354 (defcustom org-open-non-existing-files nil
1355 "Non-nil means `org-open-file' will open non-existing files.
1356 When nil, an error will be generated.
1357 This variable applies only to external applications because they
1358 might choke on non-existing files. If the link is to a file that
1359 will be opened in Emacs, the variable is ignored."
1360 :group 'org-link-follow
1361 :type 'boolean)
1363 (defcustom org-open-directory-means-index-dot-org nil
1364 "Non-nil means a link to a directory really means to index.org.
1365 When nil, following a directory link will run dired or open a finder/explorer
1366 window on that directory."
1367 :group 'org-link-follow
1368 :type 'boolean)
1370 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1371 "Function and arguments to call for following mailto links.
1372 This is a list with the first element being a lisp function, and the
1373 remaining elements being arguments to the function. In string arguments,
1374 %a will be replaced by the address, and %s will be replaced by the subject
1375 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1376 :group 'org-link-follow
1377 :type '(choice
1378 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1379 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1380 (const :tag "message-mail" (message-mail "%a" "%s"))
1381 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1383 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1384 "Non-nil means ask for confirmation before executing shell links.
1385 Shell links can be dangerous: just think about a link
1387 [[shell:rm -rf ~/*][Google Search]]
1389 This link would show up in your Org-mode document as \"Google Search\",
1390 but really it would remove your entire home directory.
1391 Therefore we advise against setting this variable to nil.
1392 Just change it to `y-or-n-p' if you want to confirm with a
1393 single keystroke rather than having to type \"yes\"."
1394 :group 'org-link-follow
1395 :type '(choice
1396 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1397 (const :tag "with y-or-n (faster)" y-or-n-p)
1398 (const :tag "no confirmation (dangerous)" nil)))
1400 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1401 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1402 Elisp links can be dangerous: just think about a link
1404 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1406 This link would show up in your Org-mode document as \"Google Search\",
1407 but really it would remove your entire home directory.
1408 Therefore we advise against setting this variable to nil.
1409 Just change it to `y-or-n-p' if you want to confirm with a
1410 single keystroke rather than having to type \"yes\"."
1411 :group 'org-link-follow
1412 :type '(choice
1413 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1414 (const :tag "with y-or-n (faster)" y-or-n-p)
1415 (const :tag "no confirmation (dangerous)" nil)))
1417 (defconst org-file-apps-defaults-gnu
1418 '((remote . emacs)
1419 (system . mailcap)
1420 (t . mailcap))
1421 "Default file applications on a UNIX or GNU/Linux system.
1422 See `org-file-apps'.")
1424 (defconst org-file-apps-defaults-macosx
1425 '((remote . emacs)
1426 (t . "open %s")
1427 (system . "open %s")
1428 ("ps.gz" . "gv %s")
1429 ("eps.gz" . "gv %s")
1430 ("dvi" . "xdvi %s")
1431 ("fig" . "xfig %s"))
1432 "Default file applications on a MacOS X system.
1433 The system \"open\" is known as a default, but we use X11 applications
1434 for some files for which the OS does not have a good default.
1435 See `org-file-apps'.")
1437 (defconst org-file-apps-defaults-windowsnt
1438 (list
1439 '(remote . emacs)
1440 (cons t
1441 (list (if (featurep 'xemacs)
1442 'mswindows-shell-execute
1443 'w32-shell-execute)
1444 "open" 'file))
1445 (cons 'system
1446 (list (if (featurep 'xemacs)
1447 'mswindows-shell-execute
1448 'w32-shell-execute)
1449 "open" 'file)))
1450 "Default file applications on a Windows NT system.
1451 The system \"open\" is used for most files.
1452 See `org-file-apps'.")
1454 (defcustom org-file-apps
1456 (auto-mode . emacs)
1457 ("\\.mm\\'" . default)
1458 ("\\.x?html?\\'" . default)
1459 ("\\.pdf\\'" . default)
1461 "External applications for opening `file:path' items in a document.
1462 Org-mode uses system defaults for different file types, but
1463 you can use this variable to set the application for a given file
1464 extension. The entries in this list are cons cells where the car identifies
1465 files and the cdr the corresponding command. Possible values for the
1466 file identifier are
1467 \"regex\" Regular expression matched against the file name. For backward
1468 compatibility, this can also be a string with only alphanumeric
1469 characters, which is then interpreted as an extension.
1470 `directory' Matches a directory
1471 `remote' Matches a remote file, accessible through tramp or efs.
1472 Remote files most likely should be visited through Emacs
1473 because external applications cannot handle such paths.
1474 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1475 so all files Emacs knows how to handle. Using this with
1476 command `emacs' will open most files in Emacs. Beware that this
1477 will also open html files inside Emacs, unless you add
1478 (\"html\" . default) to the list as well.
1479 t Default for files not matched by any of the other options.
1480 `system' The system command to open files, like `open' on Windows
1481 and Mac OS X, and mailcap under GNU/Linux. This is the command
1482 that will be selected if you call `C-c C-o' with a double
1483 `C-u C-u' prefix.
1485 Possible values for the command are:
1486 `emacs' The file will be visited by the current Emacs process.
1487 `default' Use the default application for this file type, which is the
1488 association for t in the list, most likely in the system-specific
1489 part.
1490 This can be used to overrule an unwanted setting in the
1491 system-specific variable.
1492 `system' Use the system command for opening files, like \"open\".
1493 This command is specified by the entry whose car is `system'.
1494 Most likely, the system-specific version of this variable
1495 does define this command, but you can overrule/replace it
1496 here.
1497 string A command to be executed by a shell; %s will be replaced
1498 by the path to the file.
1499 sexp A Lisp form which will be evaluated. The file path will
1500 be available in the Lisp variable `file'.
1501 For more examples, see the system specific constants
1502 `org-file-apps-defaults-macosx'
1503 `org-file-apps-defaults-windowsnt'
1504 `org-file-apps-defaults-gnu'."
1505 :group 'org-link-follow
1506 :type '(repeat
1507 (cons (choice :value ""
1508 (string :tag "Extension")
1509 (const :tag "System command to open files" system)
1510 (const :tag "Default for unrecognized files" t)
1511 (const :tag "Remote file" remote)
1512 (const :tag "Links to a directory" directory)
1513 (const :tag "Any files that have Emacs modes"
1514 auto-mode))
1515 (choice :value ""
1516 (const :tag "Visit with Emacs" emacs)
1517 (const :tag "Use default" default)
1518 (const :tag "Use the system command" system)
1519 (string :tag "Command")
1520 (sexp :tag "Lisp form")))))
1522 (defgroup org-refile nil
1523 "Options concerning refiling entries in Org-mode."
1524 :tag "Org Refile"
1525 :group 'org)
1527 (defcustom org-directory "~/org"
1528 "Directory with org files.
1529 This is just a default location to look for Org files. There is no need
1530 at all to put your files into this directory. It is only used in the
1531 following situations:
1533 1. When a remember template specifies a target file that is not an
1534 absolute path. The path will then be interpreted relative to
1535 `org-directory'
1536 2. When a remember note is filed away in an interactive way (when exiting the
1537 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1538 with `org-directory' as the default path."
1539 :group 'org-refile
1540 :group 'org-remember
1541 :type 'directory)
1543 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1544 "Default target for storing notes.
1545 Used by the hooks for remember.el. This can be a string, or nil to mean
1546 the value of `remember-data-file'.
1547 You can set this on a per-template basis with the variable
1548 `org-remember-templates'."
1549 :group 'org-refile
1550 :group 'org-remember
1551 :type '(choice
1552 (const :tag "Default from remember-data-file" nil)
1553 file))
1555 (defcustom org-goto-interface 'outline
1556 "The default interface to be used for `org-goto'.
1557 Allowed values are:
1558 outline The interface shows an outline of the relevant file
1559 and the correct heading is found by moving through
1560 the outline or by searching with incremental search.
1561 outline-path-completion Headlines in the current buffer are offered via
1562 completion. This is the interface also used by
1563 the refile command."
1564 :group 'org-refile
1565 :type '(choice
1566 (const :tag "Outline" outline)
1567 (const :tag "Outline-path-completion" outline-path-completion)))
1569 (defcustom org-goto-max-level 5
1570 "Maximum level to be considered when running org-goto with refile interface."
1571 :group 'org-refile
1572 :type 'integer)
1574 (defcustom org-reverse-note-order nil
1575 "Non-nil means store new notes at the beginning of a file or entry.
1576 When nil, new notes will be filed to the end of a file or entry.
1577 This can also be a list with cons cells of regular expressions that
1578 are matched against file names, and values."
1579 :group 'org-remember
1580 :group 'org-refile
1581 :type '(choice
1582 (const :tag "Reverse always" t)
1583 (const :tag "Reverse never" nil)
1584 (repeat :tag "By file name regexp"
1585 (cons regexp boolean))))
1587 (defcustom org-refile-targets nil
1588 "Targets for refiling entries with \\[org-refile].
1589 This is list of cons cells. Each cell contains:
1590 - a specification of the files to be considered, either a list of files,
1591 or a symbol whose function or variable value will be used to retrieve
1592 a file name or a list of file names. If you use `org-agenda-files' for
1593 that, all agenda files will be scanned for targets. Nil means consider
1594 headings in the current buffer.
1595 - A specification of how to find candidate refile targets. This may be
1596 any of:
1597 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1598 This tag has to be present in all target headlines, inheritance will
1599 not be considered.
1600 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1601 todo keyword.
1602 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1603 headlines that are refiling targets.
1604 - a cons cell (:level . N). Any headline of level N is considered a target.
1605 Note that, when `org-odd-levels-only' is set, level corresponds to
1606 order in hierarchy, not to the number of stars.
1607 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1608 Note that, when `org-odd-levels-only' is set, level corresponds to
1609 order in hierarchy, not to the number of stars.
1611 You can set the variable `org-refile-target-verify-function' to a function
1612 to verify each headline found by the simple critery above.
1614 When this variable is nil, all top-level headlines in the current buffer
1615 are used, equivalent to the value `((nil . (:level . 1))'."
1616 :group 'org-refile
1617 :type '(repeat
1618 (cons
1619 (choice :value org-agenda-files
1620 (const :tag "All agenda files" org-agenda-files)
1621 (const :tag "Current buffer" nil)
1622 (function) (variable) (file))
1623 (choice :tag "Identify target headline by"
1624 (cons :tag "Specific tag" (const :value :tag) (string))
1625 (cons :tag "TODO keyword" (const :value :todo) (string))
1626 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1627 (cons :tag "Level number" (const :value :level) (integer))
1628 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1630 (defcustom org-refile-target-verify-function nil
1631 "Function to verify if the headline at point should be a refile target.
1632 The function will be called without arguments, with point at the
1633 beginning of the headline. It should return t and leave point
1634 where it is if the headline is a valid target for refiling.
1636 If the target should not be selected, the function must return nil.
1637 In addition to this, it may move point to a place from where the search
1638 should be continued. For example, the function may decide that the entire
1639 subtree of the current entry should be excluded and move point to the end
1640 of the subtree."
1641 :group 'org-refile
1642 :type 'function)
1644 (defcustom org-refile-use-outline-path nil
1645 "Non-nil means provide refile targets as paths.
1646 So a level 3 headline will be available as level1/level2/level3.
1648 When the value is `file', also include the file name (without directory)
1649 into the path. In this case, you can also stop the completion after
1650 the file name, to get entries inserted as top level in the file.
1652 When `full-file-path', include the full file path."
1653 :group 'org-refile
1654 :type '(choice
1655 (const :tag "Not" nil)
1656 (const :tag "Yes" t)
1657 (const :tag "Start with file name" file)
1658 (const :tag "Start with full file path" full-file-path)))
1660 (defcustom org-outline-path-complete-in-steps t
1661 "Non-nil means complete the outline path in hierarchical steps.
1662 When Org-mode uses the refile interface to select an outline path
1663 \(see variable `org-refile-use-outline-path'), the completion of
1664 the path can be done is a single go, or if can be done in steps down
1665 the headline hierarchy. Going in steps is probably the best if you
1666 do not use a special completion package like `ido' or `icicles'.
1667 However, when using these packages, going in one step can be very
1668 fast, while still showing the whole path to the entry."
1669 :group 'org-refile
1670 :type 'boolean)
1672 (defcustom org-refile-allow-creating-parent-nodes nil
1673 "Non-nil means allow to create new nodes as refile targets.
1674 New nodes are then created by adding \"/new node name\" to the completion
1675 of an existing node. When the value of this variable is `confirm',
1676 new node creation must be confirmed by the user (recommended)
1677 When nil, the completion must match an existing entry.
1679 Note that, if the new heading is not seen by the criteria
1680 listed in `org-refile-targets', multiple instances of the same
1681 heading would be created by trying again to file under the new
1682 heading."
1683 :group 'org-refile
1684 :type '(choice
1685 (const :tag "Never" nil)
1686 (const :tag "Always" t)
1687 (const :tag "Prompt for confirmation" confirm)))
1689 (defgroup org-todo nil
1690 "Options concerning TODO items in Org-mode."
1691 :tag "Org TODO"
1692 :group 'org)
1694 (defgroup org-progress nil
1695 "Options concerning Progress logging in Org-mode."
1696 :tag "Org Progress"
1697 :group 'org-time)
1699 (defvar org-todo-interpretation-widgets
1701 (:tag "Sequence (cycling hits every state)" sequence)
1702 (:tag "Type (cycling directly to DONE)" type))
1703 "The available interpretation symbols for customizing
1704 `org-todo-keywords'.
1705 Interested libraries should add to this list.")
1707 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1708 "List of TODO entry keyword sequences and their interpretation.
1709 \\<org-mode-map>This is a list of sequences.
1711 Each sequence starts with a symbol, either `sequence' or `type',
1712 indicating if the keywords should be interpreted as a sequence of
1713 action steps, or as different types of TODO items. The first
1714 keywords are states requiring action - these states will select a headline
1715 for inclusion into the global TODO list Org-mode produces. If one of
1716 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1717 signify that no further action is necessary. If \"|\" is not found,
1718 the last keyword is treated as the only DONE state of the sequence.
1720 The command \\[org-todo] cycles an entry through these states, and one
1721 additional state where no keyword is present. For details about this
1722 cycling, see the manual.
1724 TODO keywords and interpretation can also be set on a per-file basis with
1725 the special #+SEQ_TODO and #+TYP_TODO lines.
1727 Each keyword can optionally specify a character for fast state selection
1728 \(in combination with the variable `org-use-fast-todo-selection')
1729 and specifiers for state change logging, using the same syntax
1730 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1731 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1732 indicates to record a time stamp each time this state is selected.
1734 Each keyword may also specify if a timestamp or a note should be
1735 recorded when entering or leaving the state, by adding additional
1736 characters in the parenthesis after the keyword. This looks like this:
1737 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1738 record only the time of the state change. With X and Y being either
1739 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1740 Y when leaving the state if and only if the *target* state does not
1741 define X. You may omit any of the fast-selection key or X or /Y,
1742 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1744 For backward compatibility, this variable may also be just a list
1745 of keywords - in this case the interpretation (sequence or type) will be
1746 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1747 :group 'org-todo
1748 :group 'org-keywords
1749 :type '(choice
1750 (repeat :tag "Old syntax, just keywords"
1751 (string :tag "Keyword"))
1752 (repeat :tag "New syntax"
1753 (cons
1754 (choice
1755 :tag "Interpretation"
1756 ;;Quick and dirty way to see
1757 ;;`org-todo-interpretations'. This takes the
1758 ;;place of item arguments
1759 :convert-widget
1760 (lambda (widget)
1761 (widget-put widget
1762 :args (mapcar
1763 #'(lambda (x)
1764 (widget-convert
1765 (cons 'const x)))
1766 org-todo-interpretation-widgets))
1767 widget))
1768 (repeat
1769 (string :tag "Keyword"))))))
1771 (defvar org-todo-keywords-1 nil
1772 "All TODO and DONE keywords active in a buffer.")
1773 (make-variable-buffer-local 'org-todo-keywords-1)
1774 (defvar org-todo-keywords-for-agenda nil)
1775 (defvar org-done-keywords-for-agenda nil)
1776 (defvar org-drawers-for-agenda nil)
1777 (defvar org-todo-keyword-alist-for-agenda nil)
1778 (defvar org-tag-alist-for-agenda nil)
1779 (defvar org-agenda-contributing-files nil)
1780 (defvar org-not-done-keywords nil)
1781 (make-variable-buffer-local 'org-not-done-keywords)
1782 (defvar org-done-keywords nil)
1783 (make-variable-buffer-local 'org-done-keywords)
1784 (defvar org-todo-heads nil)
1785 (make-variable-buffer-local 'org-todo-heads)
1786 (defvar org-todo-sets nil)
1787 (make-variable-buffer-local 'org-todo-sets)
1788 (defvar org-todo-log-states nil)
1789 (make-variable-buffer-local 'org-todo-log-states)
1790 (defvar org-todo-kwd-alist nil)
1791 (make-variable-buffer-local 'org-todo-kwd-alist)
1792 (defvar org-todo-key-alist nil)
1793 (make-variable-buffer-local 'org-todo-key-alist)
1794 (defvar org-todo-key-trigger nil)
1795 (make-variable-buffer-local 'org-todo-key-trigger)
1797 (defcustom org-todo-interpretation 'sequence
1798 "Controls how TODO keywords are interpreted.
1799 This variable is in principle obsolete and is only used for
1800 backward compatibility, if the interpretation of todo keywords is
1801 not given already in `org-todo-keywords'. See that variable for
1802 more information."
1803 :group 'org-todo
1804 :group 'org-keywords
1805 :type '(choice (const sequence)
1806 (const type)))
1808 (defcustom org-use-fast-todo-selection t
1809 "Non-nil means use the fast todo selection scheme with C-c C-t.
1810 This variable describes if and under what circumstances the cycling
1811 mechanism for TODO keywords will be replaced by a single-key, direct
1812 selection scheme.
1814 When nil, fast selection is never used.
1816 When the symbol `prefix', it will be used when `org-todo' is called with
1817 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1818 in an agenda buffer.
1820 When t, fast selection is used by default. In this case, the prefix
1821 argument forces cycling instead.
1823 In all cases, the special interface is only used if access keys have actually
1824 been assigned by the user, i.e. if keywords in the configuration are followed
1825 by a letter in parenthesis, like TODO(t)."
1826 :group 'org-todo
1827 :type '(choice
1828 (const :tag "Never" nil)
1829 (const :tag "By default" t)
1830 (const :tag "Only with C-u C-c C-t" prefix)))
1832 (defcustom org-provide-todo-statistics t
1833 "Non-nil means update todo statistics after insert and toggle.
1834 ALL-HEADLINES means update todo statistics by including headlines
1835 with no TODO keyword as well, counting them as not done.
1836 A list of TODO keywords means the same, but skip keywords that are
1837 not in this list.
1839 When this is set, todo statistics is updated in the parent of the
1840 current entry each time a todo state is changed."
1841 :group 'org-todo
1842 :type '(choice
1843 (const :tag "Yes, only for TODO entries" t)
1844 (const :tag "Yes, including all entries" 'all-headlines)
1845 (repeat :tag "Yes, for TODOs in this list"
1846 (string :tag "TODO keyword"))
1847 (other :tag "No TODO statistics" nil)))
1849 (defcustom org-hierarchical-todo-statistics t
1850 "Non-nil means TODO statistics covers just direct children.
1851 When nil, all entries in the subtree are considered.
1852 This has only an effect if `org-provide-todo-statistics' is set.
1853 To set this to nil for only a single subtree, use a COOKIE_DATA
1854 property and include the word \"recursive\" into the value."
1855 :group 'org-todo
1856 :type 'boolean)
1858 (defcustom org-after-todo-state-change-hook nil
1859 "Hook which is run after the state of a TODO item was changed.
1860 The new state (a string with a TODO keyword, or nil) is available in the
1861 Lisp variable `state'."
1862 :group 'org-todo
1863 :type 'hook)
1865 (defvar org-blocker-hook nil
1866 "Hook for functions that are allowed to block a state change.
1868 Each function gets as its single argument a property list, see
1869 `org-trigger-hook' for more information about this list.
1871 If any of the functions in this hook returns nil, the state change
1872 is blocked.")
1874 (defvar org-trigger-hook nil
1875 "Hook for functions that are triggered by a state change.
1877 Each function gets as its single argument a property list with at least
1878 the following elements:
1880 (:type type-of-change :position pos-at-entry-start
1881 :from old-state :to new-state)
1883 Depending on the type, more properties may be present.
1885 This mechanism is currently implemented for:
1887 TODO state changes
1888 ------------------
1889 :type todo-state-change
1890 :from previous state (keyword as a string), or nil, or a symbol
1891 'todo' or 'done', to indicate the general type of state.
1892 :to new state, like in :from")
1894 (defcustom org-enforce-todo-dependencies nil
1895 "Non-nil means undone TODO entries will block switching the parent to DONE.
1896 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1897 be blocked if any prior sibling is not yet done.
1898 Finally, if the parent is blocked because of ordered siblings of its own,
1899 the child will also be blocked.
1900 This variable needs to be set before org.el is loaded, and you need to
1901 restart Emacs after a change to make the change effective. The only way
1902 to change is while Emacs is running is through the customize interface."
1903 :set (lambda (var val)
1904 (set var val)
1905 (if val
1906 (add-hook 'org-blocker-hook
1907 'org-block-todo-from-children-or-siblings-or-parent)
1908 (remove-hook 'org-blocker-hook
1909 'org-block-todo-from-children-or-siblings-or-parent)))
1910 :group 'org-todo
1911 :type 'boolean)
1913 (defcustom org-enforce-todo-checkbox-dependencies nil
1914 "Non-nil means unchecked boxes will block switching the parent to DONE.
1915 When this is nil, checkboxes have no influence on switching TODO states.
1916 When non-nil, you first need to check off all check boxes before the TODO
1917 entry can be switched to DONE.
1918 This variable needs to be set before org.el is loaded, and you need to
1919 restart Emacs after a change to make the change effective. The only way
1920 to change is while Emacs is running is through the customize interface."
1921 :set (lambda (var val)
1922 (set var val)
1923 (if val
1924 (add-hook 'org-blocker-hook
1925 'org-block-todo-from-checkboxes)
1926 (remove-hook 'org-blocker-hook
1927 'org-block-todo-from-checkboxes)))
1928 :group 'org-todo
1929 :type 'boolean)
1931 (defcustom org-treat-insert-todo-heading-as-state-change nil
1932 "Non-nil means inserting a TODO heading is treated as state change.
1933 So when the command \\[org-insert-todo-heading] is used, state change
1934 logging will apply if appropriate. When nil, the new TODO item will
1935 be inserted directly, and no logging will take place."
1936 :group 'org-todo
1937 :type 'boolean)
1939 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1940 "Non-nil means switching TODO states with S-cursor counts as state change.
1941 This is the default behavior. However, setting this to nil allows a
1942 convenient way to select a TODO state and bypass any logging associated
1943 with that."
1944 :group 'org-todo
1945 :type 'boolean)
1947 (defcustom org-todo-state-tags-triggers nil
1948 "Tag changes that should be triggered by TODO state changes.
1949 This is a list. Each entry is
1951 (state-change (tag . flag) .......)
1953 State-change can be a string with a state, and empty string to indicate the
1954 state that has no TODO keyword, or it can be one of the symbols `todo'
1955 or `done', meaning any not-done or done state, respectively."
1956 :group 'org-todo
1957 :group 'org-tags
1958 :type '(repeat
1959 (cons (choice :tag "When changing to"
1960 (const :tag "Not-done state" todo)
1961 (const :tag "Done state" done)
1962 (string :tag "State"))
1963 (repeat
1964 (cons :tag "Tag action"
1965 (string :tag "Tag")
1966 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1968 (defcustom org-log-done nil
1969 "Information to record when a task moves to the DONE state.
1971 Possible values are:
1973 nil Don't add anything, just change the keyword
1974 time Add a time stamp to the task
1975 note Prompt for a note and add it with template `org-log-note-headings'
1977 This option can also be set with on a per-file-basis with
1979 #+STARTUP: nologdone
1980 #+STARTUP: logdone
1981 #+STARTUP: lognotedone
1983 You can have local logging settings for a subtree by setting the LOGGING
1984 property to one or more of these keywords."
1985 :group 'org-todo
1986 :group 'org-progress
1987 :type '(choice
1988 (const :tag "No logging" nil)
1989 (const :tag "Record CLOSED timestamp" time)
1990 (const :tag "Record CLOSED timestamp with note." note)))
1992 ;; Normalize old uses of org-log-done.
1993 (cond
1994 ((eq org-log-done t) (setq org-log-done 'time))
1995 ((and (listp org-log-done) (memq 'done org-log-done))
1996 (setq org-log-done 'note)))
1998 (defcustom org-log-reschedule nil
1999 "Information to record when the scheduling date of a tasks is modified.
2001 Possible values are:
2003 nil Don't add anything, just change the date
2004 time Add a time stamp to the task
2005 note Prompt for a note and add it with template `org-log-note-headings'
2007 This option can also be set with on a per-file-basis with
2009 #+STARTUP: nologreschedule
2010 #+STARTUP: logreschedule
2011 #+STARTUP: lognotereschedule"
2012 :group 'org-todo
2013 :group 'org-progress
2014 :type '(choice
2015 (const :tag "No logging" nil)
2016 (const :tag "Record timestamp" time)
2017 (const :tag "Record timestamp with note." note)))
2019 (defcustom org-log-redeadline nil
2020 "Information to record when the deadline date of a tasks is modified.
2022 Possible values are:
2024 nil Don't add anything, just change the date
2025 time Add a time stamp to the task
2026 note Prompt for a note and add it with template `org-log-note-headings'
2028 This option can also be set with on a per-file-basis with
2030 #+STARTUP: nologredeadline
2031 #+STARTUP: logredeadline
2032 #+STARTUP: lognoteredeadline
2034 You can have local logging settings for a subtree by setting the LOGGING
2035 property to one or more of these keywords."
2036 :group 'org-todo
2037 :group 'org-progress
2038 :type '(choice
2039 (const :tag "No logging" nil)
2040 (const :tag "Record timestamp" time)
2041 (const :tag "Record timestamp with note." note)))
2043 (defcustom org-log-note-clock-out nil
2044 "Non-nil means record a note when clocking out of an item.
2045 This can also be configured on a per-file basis by adding one of
2046 the following lines anywhere in the buffer:
2048 #+STARTUP: lognoteclock-out
2049 #+STARTUP: nolognoteclock-out"
2050 :group 'org-todo
2051 :group 'org-progress
2052 :type 'boolean)
2054 (defcustom org-log-done-with-time t
2055 "Non-nil means the CLOSED time stamp will contain date and time.
2056 When nil, only the date will be recorded."
2057 :group 'org-progress
2058 :type 'boolean)
2060 (defcustom org-log-note-headings
2061 '((done . "CLOSING NOTE %t")
2062 (state . "State %-12s from %-12S %t")
2063 (note . "Note taken on %t")
2064 (reschedule . "Rescheduled from %S on %t")
2065 (delschedule . "Not scheduled, was %S on %t")
2066 (redeadline . "New deadline from %S on %t")
2067 (deldeadline . "Removed deadline, was %S on %t")
2068 (clock-out . ""))
2069 "Headings for notes added to entries.
2070 The value is an alist, with the car being a symbol indicating the note
2071 context, and the cdr is the heading to be used. The heading may also be the
2072 empty string.
2073 %t in the heading will be replaced by a time stamp.
2074 %s will be replaced by the new TODO state, in double quotes.
2075 %S will be replaced by the old TODO state, in double quotes.
2076 %u will be replaced by the user name.
2077 %U will be replaced by the full user name.
2079 In fact, it is not a good idea to change the `state' entry, because
2080 agenda log mode depends on the format of these entries."
2081 :group 'org-todo
2082 :group 'org-progress
2083 :type '(list :greedy t
2084 (cons (const :tag "Heading when closing an item" done) string)
2085 (cons (const :tag
2086 "Heading when changing todo state (todo sequence only)"
2087 state) string)
2088 (cons (const :tag "Heading when just taking a note" note) string)
2089 (cons (const :tag "Heading when clocking out" clock-out) string)
2090 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2091 (cons (const :tag "Heading when rescheduling" reschedule) string)
2092 (cons (const :tag "Heading when changing deadline" redeadline) string
2093 (cons (const :tag "Heading when deleting a deadline" deldeadline) string))))
2095 (unless (assq 'note org-log-note-headings)
2096 (push '(note . "%t") org-log-note-headings))
2098 (defcustom org-log-into-drawer nil
2099 "Non-nil means insert state change notes and time stamps into a drawer.
2100 When nil, state changes notes will be inserted after the headline and
2101 any scheduling and clock lines, but not inside a drawer.
2103 The value of this variable should be the name of the drawer to use.
2104 LOGBOOK is proposed at the default drawer for this purpose, you can
2105 also set this to a string to define the drawer of your choice.
2107 A value of t is also allowed, representing \"LOGBOOK\".
2109 If this variable is set, `org-log-state-notes-insert-after-drawers'
2110 will be ignored.
2112 You can set the property LOG_INTO_DRAWER to overrule this setting for
2113 a subtree."
2114 :group 'org-todo
2115 :group 'org-progress
2116 :type '(choice
2117 (const :tag "Not into a drawer" nil)
2118 (const :tag "LOGBOOK" t)
2119 (string :tag "Other")))
2121 (if (fboundp 'defvaralias)
2122 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2124 (defun org-log-into-drawer ()
2125 "Return the value of `org-log-into-drawer', but let properties overrule.
2126 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2127 used instead of the default value."
2128 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2129 (cond
2130 ((or (not p) (equal p "nil")) org-log-into-drawer)
2131 ((equal p "t") "LOGBOOK")
2132 (t p))))
2134 (defcustom org-log-state-notes-insert-after-drawers nil
2135 "Non-nil means insert state change notes after any drawers in entry.
2136 Only the drawers that *immediately* follow the headline and the
2137 deadline/scheduled line are skipped.
2138 When nil, insert notes right after the heading and perhaps the line
2139 with deadline/scheduling if present.
2141 This variable will have no effect if `org-log-into-drawer' is
2142 set."
2143 :group 'org-todo
2144 :group 'org-progress
2145 :type 'boolean)
2147 (defcustom org-log-states-order-reversed t
2148 "Non-nil means the latest state change note will be directly after heading.
2149 When nil, the notes will be orderer according to time."
2150 :group 'org-todo
2151 :group 'org-progress
2152 :type 'boolean)
2154 (defcustom org-log-repeat 'time
2155 "Non-nil means record moving through the DONE state when triggering repeat.
2156 An auto-repeating task is immediately switched back to TODO when
2157 marked DONE. If you are not logging state changes (by adding \"@\"
2158 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2159 record a closing note, there will be no record of the task moving
2160 through DONE. This variable forces taking a note anyway.
2162 nil Don't force a record
2163 time Record a time stamp
2164 note Record a note
2166 This option can also be set with on a per-file-basis with
2168 #+STARTUP: logrepeat
2169 #+STARTUP: lognoterepeat
2170 #+STARTUP: nologrepeat
2172 You can have local logging settings for a subtree by setting the LOGGING
2173 property to one or more of these keywords."
2174 :group 'org-todo
2175 :group 'org-progress
2176 :type '(choice
2177 (const :tag "Don't force a record" nil)
2178 (const :tag "Force recording the DONE state" time)
2179 (const :tag "Force recording a note with the DONE state" note)))
2182 (defgroup org-priorities nil
2183 "Priorities in Org-mode."
2184 :tag "Org Priorities"
2185 :group 'org-todo)
2187 (defcustom org-enable-priority-commands t
2188 "Non-nil means priority commands are active.
2189 When nil, these commands will be disabled, so that you never accidentally
2190 set a priority."
2191 :group 'org-priorities
2192 :type 'boolean)
2194 (defcustom org-highest-priority ?A
2195 "The highest priority of TODO items. A character like ?A, ?B etc.
2196 Must have a smaller ASCII number than `org-lowest-priority'."
2197 :group 'org-priorities
2198 :type 'character)
2200 (defcustom org-lowest-priority ?C
2201 "The lowest priority of TODO items. A character like ?A, ?B etc.
2202 Must have a larger ASCII number than `org-highest-priority'."
2203 :group 'org-priorities
2204 :type 'character)
2206 (defcustom org-default-priority ?B
2207 "The default priority of TODO items.
2208 This is the priority an item get if no explicit priority is given."
2209 :group 'org-priorities
2210 :type 'character)
2212 (defcustom org-priority-start-cycle-with-default t
2213 "Non-nil means start with default priority when starting to cycle.
2214 When this is nil, the first step in the cycle will be (depending on the
2215 command used) one higher or lower that the default priority."
2216 :group 'org-priorities
2217 :type 'boolean)
2219 (defgroup org-time nil
2220 "Options concerning time stamps and deadlines in Org-mode."
2221 :tag "Org Time"
2222 :group 'org)
2224 (defcustom org-insert-labeled-timestamps-at-point nil
2225 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2226 When nil, these labeled time stamps are forces into the second line of an
2227 entry, just after the headline. When scheduling from the global TODO list,
2228 the time stamp will always be forced into the second line."
2229 :group 'org-time
2230 :type 'boolean)
2232 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2233 "Formats for `format-time-string' which are used for time stamps.
2234 It is not recommended to change this constant.")
2236 (defcustom org-time-stamp-rounding-minutes '(0 5)
2237 "Number of minutes to round time stamps to.
2238 These are two values, the first applies when first creating a time stamp.
2239 The second applies when changing it with the commands `S-up' and `S-down'.
2240 When changing the time stamp, this means that it will change in steps
2241 of N minutes, as given by the second value.
2243 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2244 numbers should be factors of 60, so for example 5, 10, 15.
2246 When this is larger than 1, you can still force an exact time-stamp by using
2247 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2248 and by using a prefix arg to `S-up/down' to specify the exact number
2249 of minutes to shift."
2250 :group 'org-time
2251 :get '(lambda (var) ; Make sure all entries have 5 elements
2252 (if (integerp (default-value var))
2253 (list (default-value var) 5)
2254 (default-value var)))
2255 :type '(list
2256 (integer :tag "when inserting times")
2257 (integer :tag "when modifying times")))
2259 ;; Normalize old customizations of this variable.
2260 (when (integerp org-time-stamp-rounding-minutes)
2261 (setq org-time-stamp-rounding-minutes
2262 (list org-time-stamp-rounding-minutes
2263 org-time-stamp-rounding-minutes)))
2265 (defcustom org-display-custom-times nil
2266 "Non-nil means overlay custom formats over all time stamps.
2267 The formats are defined through the variable `org-time-stamp-custom-formats'.
2268 To turn this on on a per-file basis, insert anywhere in the file:
2269 #+STARTUP: customtime"
2270 :group 'org-time
2271 :set 'set-default
2272 :type 'sexp)
2273 (make-variable-buffer-local 'org-display-custom-times)
2275 (defcustom org-time-stamp-custom-formats
2276 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2277 "Custom formats for time stamps. See `format-time-string' for the syntax.
2278 These are overlayed over the default ISO format if the variable
2279 `org-display-custom-times' is set. Time like %H:%M should be at the
2280 end of the second format. The custom formats are also honored by export
2281 commands, if custom time display is turned on at the time of export."
2282 :group 'org-time
2283 :type 'sexp)
2285 (defun org-time-stamp-format (&optional long inactive)
2286 "Get the right format for a time string."
2287 (let ((f (if long (cdr org-time-stamp-formats)
2288 (car org-time-stamp-formats))))
2289 (if inactive
2290 (concat "[" (substring f 1 -1) "]")
2291 f)))
2293 (defcustom org-time-clocksum-format "%d:%02d"
2294 "The format string used when creating CLOCKSUM lines, or when
2295 org-mode generates a time duration."
2296 :group 'org-time
2297 :type 'string)
2299 (defcustom org-time-clocksum-use-fractional nil
2300 "If non-nil, \\[org-clock-display] uses fractional times.
2301 org-mode generates a time duration."
2302 :group 'org-time
2303 :type 'boolean)
2305 (defcustom org-time-clocksum-fractional-format "%.2f"
2306 "The format string used when creating CLOCKSUM lines, or when
2307 org-mode generates a time duration."
2308 :group 'org-time
2309 :type 'string)
2311 (defcustom org-deadline-warning-days 14
2312 "No. of days before expiration during which a deadline becomes active.
2313 This variable governs the display in sparse trees and in the agenda.
2314 When 0 or negative, it means use this number (the absolute value of it)
2315 even if a deadline has a different individual lead time specified.
2317 Custom commands can set this variable in the options section."
2318 :group 'org-time
2319 :group 'org-agenda-daily/weekly
2320 :type 'integer)
2322 (defcustom org-read-date-prefer-future t
2323 "Non-nil means assume future for incomplete date input from user.
2324 This affects the following situations:
2325 1. The user gives a month but not a year.
2326 For example, if it is april and you enter \"feb 2\", this will be read
2327 as feb 2, *next* year. \"May 5\", however, will be this year.
2328 2. The user gives a day, but no month.
2329 For example, if today is the 15th, and you enter \"3\", Org-mode will
2330 read this as the third of *next* month. However, if you enter \"17\",
2331 it will be considered as *this* month.
2333 If you set this variable to the symbol `time', then also the following
2334 will work:
2336 3. If the user gives a time, but no day. If the time is before now,
2337 to will be interpreted as tomorrow.
2339 Currently none of this works for ISO week specifications.
2341 When this option is nil, the current day, month and year will always be
2342 used as defaults."
2343 :group 'org-time
2344 :type '(choice
2345 (const :tag "Never" nil)
2346 (const :tag "Check month and day" t)
2347 (const :tag "Check month, day, and time" time)))
2349 (defcustom org-read-date-display-live t
2350 "Non-nil means display current interpretation of date prompt live.
2351 This display will be in an overlay, in the minibuffer."
2352 :group 'org-time
2353 :type 'boolean)
2355 (defcustom org-read-date-popup-calendar t
2356 "Non-nil means pop up a calendar when prompting for a date.
2357 In the calendar, the date can be selected with mouse-1. However, the
2358 minibuffer will also be active, and you can simply enter the date as well.
2359 When nil, only the minibuffer will be available."
2360 :group 'org-time
2361 :type 'boolean)
2362 (if (fboundp 'defvaralias)
2363 (defvaralias 'org-popup-calendar-for-date-prompt
2364 'org-read-date-popup-calendar))
2366 (defcustom org-read-date-minibuffer-setup-hook nil
2367 "Hook to be used to set up keys for the date/time interface.
2368 Add key definitions to `minibuffer-local-map', which will be a temporary
2369 copy."
2370 :group 'org-time
2371 :type 'hook)
2373 (defcustom org-extend-today-until 0
2374 "The hour when your day really ends. Must be an integer.
2375 This has influence for the following applications:
2376 - When switching the agenda to \"today\". It it is still earlier than
2377 the time given here, the day recognized as TODAY is actually yesterday.
2378 - When a date is read from the user and it is still before the time given
2379 here, the current date and time will be assumed to be yesterday, 23:59.
2380 Also, timestamps inserted in remember templates follow this rule.
2382 IMPORTANT: This is a feature whose implementation is and likely will
2383 remain incomplete. Really, it is only here because past midnight seems to
2384 be the favorite working time of John Wiegley :-)"
2385 :group 'org-time
2386 :type 'integer)
2388 (defcustom org-edit-timestamp-down-means-later nil
2389 "Non-nil means S-down will increase the time in a time stamp.
2390 When nil, S-up will increase."
2391 :group 'org-time
2392 :type 'boolean)
2394 (defcustom org-calendar-follow-timestamp-change t
2395 "Non-nil means make the calendar window follow timestamp changes.
2396 When a timestamp is modified and the calendar window is visible, it will be
2397 moved to the new date."
2398 :group 'org-time
2399 :type 'boolean)
2401 (defgroup org-tags nil
2402 "Options concerning tags in Org-mode."
2403 :tag "Org Tags"
2404 :group 'org)
2406 (defcustom org-tag-alist nil
2407 "List of tags allowed in Org-mode files.
2408 When this list is nil, Org-mode will base TAG input on what is already in the
2409 buffer.
2410 The value of this variable is an alist, the car of each entry must be a
2411 keyword as a string, the cdr may be a character that is used to select
2412 that tag through the fast-tag-selection interface.
2413 See the manual for details."
2414 :group 'org-tags
2415 :type '(repeat
2416 (choice
2417 (cons (string :tag "Tag name")
2418 (character :tag "Access char"))
2419 (list :tag "Start radio group"
2420 (const :startgroup)
2421 (option (string :tag "Group description")))
2422 (list :tag "End radio group"
2423 (const :endgroup)
2424 (option (string :tag "Group description")))
2425 (const :tag "New line" (:newline)))))
2427 (defcustom org-tag-persistent-alist nil
2428 "List of tags that will always appear in all Org-mode files.
2429 This is in addition to any in buffer settings or customizations
2430 of `org-tag-alist'.
2431 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2432 The value of this variable is an alist, the car of each entry must be a
2433 keyword as a string, the cdr may be a character that is used to select
2434 that tag through the fast-tag-selection interface.
2435 See the manual for details.
2436 To disable these tags on a per-file basis, insert anywhere in the file:
2437 #+STARTUP: noptag"
2438 :group 'org-tags
2439 :type '(repeat
2440 (choice
2441 (cons (string :tag "Tag name")
2442 (character :tag "Access char"))
2443 (const :tag "Start radio group" (:startgroup))
2444 (const :tag "End radio group" (:endgroup))
2445 (const :tag "New line" (:newline)))))
2447 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2448 "If non-nil, always offer completion for all tags of all agenda files.
2449 Instead of customizing this variable directly, you might want to
2450 set it locally for remember buffers, because there no list of
2451 tags in that file can be created dynamically (there are none).
2453 (add-hook 'org-remember-mode-hook
2454 (lambda ()
2455 (set (make-local-variable
2456 'org-complete-tags-always-offer-all-agenda-tags)
2457 t)))"
2458 :group 'org-tags
2459 :type 'boolean)
2461 (defvar org-file-tags nil
2462 "List of tags that can be inherited by all entries in the file.
2463 The tags will be inherited if the variable `org-use-tag-inheritance'
2464 says they should be.
2465 This variable is populated from #+FILETAGS lines.")
2467 (defcustom org-use-fast-tag-selection 'auto
2468 "Non-nil means use fast tag selection scheme.
2469 This is a special interface to select and deselect tags with single keys.
2470 When nil, fast selection is never used.
2471 When the symbol `auto', fast selection is used if and only if selection
2472 characters for tags have been configured, either through the variable
2473 `org-tag-alist' or through a #+TAGS line in the buffer.
2474 When t, fast selection is always used and selection keys are assigned
2475 automatically if necessary."
2476 :group 'org-tags
2477 :type '(choice
2478 (const :tag "Always" t)
2479 (const :tag "Never" nil)
2480 (const :tag "When selection characters are configured" 'auto)))
2482 (defcustom org-fast-tag-selection-single-key nil
2483 "Non-nil means fast tag selection exits after first change.
2484 When nil, you have to press RET to exit it.
2485 During fast tag selection, you can toggle this flag with `C-c'.
2486 This variable can also have the value `expert'. In this case, the window
2487 displaying the tags menu is not even shown, until you press C-c again."
2488 :group 'org-tags
2489 :type '(choice
2490 (const :tag "No" nil)
2491 (const :tag "Yes" t)
2492 (const :tag "Expert" expert)))
2494 (defvar org-fast-tag-selection-include-todo nil
2495 "Non-nil means fast tags selection interface will also offer TODO states.
2496 This is an undocumented feature, you should not rely on it.")
2498 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2499 "The column to which tags should be indented in a headline.
2500 If this number is positive, it specifies the column. If it is negative,
2501 it means that the tags should be flushright to that column. For example,
2502 -80 works well for a normal 80 character screen."
2503 :group 'org-tags
2504 :type 'integer)
2506 (defcustom org-auto-align-tags t
2507 "Non-nil means realign tags after pro/demotion of TODO state change.
2508 These operations change the length of a headline and therefore shift
2509 the tags around. With this options turned on, after each such operation
2510 the tags are again aligned to `org-tags-column'."
2511 :group 'org-tags
2512 :type 'boolean)
2514 (defcustom org-use-tag-inheritance t
2515 "Non-nil means tags in levels apply also for sublevels.
2516 When nil, only the tags directly given in a specific line apply there.
2517 This may also be a list of tags that should be inherited, or a regexp that
2518 matches tags that should be inherited. Additional control is possible
2519 with the variable `org-tags-exclude-from-inheritance' which gives an
2520 explicit list of tags to be excluded from inheritance., even if the value of
2521 `org-use-tag-inheritance' would select it for inheritance.
2523 If this option is t, a match early-on in a tree can lead to a large
2524 number of matches in the subtree when constructing the agenda or creating
2525 a sparse tree. If you only want to see the first match in a tree during
2526 a search, check out the variable `org-tags-match-list-sublevels'."
2527 :group 'org-tags
2528 :type '(choice
2529 (const :tag "Not" nil)
2530 (const :tag "Always" t)
2531 (repeat :tag "Specific tags" (string :tag "Tag"))
2532 (regexp :tag "Tags matched by regexp")))
2534 (defcustom org-tags-exclude-from-inheritance nil
2535 "List of tags that should never be inherited.
2536 This is a way to exclude a few tags from inheritance. For way to do
2537 the opposite, to actively allow inheritance for selected tags,
2538 see the variable `org-use-tag-inheritance'."
2539 :group 'org-tags
2540 :type '(repeat (string :tag "Tag")))
2542 (defun org-tag-inherit-p (tag)
2543 "Check if TAG is one that should be inherited."
2544 (cond
2545 ((member tag org-tags-exclude-from-inheritance) nil)
2546 ((eq org-use-tag-inheritance t) t)
2547 ((not org-use-tag-inheritance) nil)
2548 ((stringp org-use-tag-inheritance)
2549 (string-match org-use-tag-inheritance tag))
2550 ((listp org-use-tag-inheritance)
2551 (member tag org-use-tag-inheritance))
2552 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2554 (defcustom org-tags-match-list-sublevels t
2555 "Non-nil means list also sublevels of headlines matching a search.
2556 This variable applies to tags/property searches, and also to stuck
2557 projects because this search is based on a tags match as well.
2559 When set to the symbol `indented', sublevels are indented with
2560 leading dots.
2562 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2563 the sublevels of a headline matching a tag search often also match
2564 the same search. Listing all of them can create very long lists.
2565 Setting this variable to nil causes subtrees of a match to be skipped.
2567 This variable is semi-obsolete and probably should always be true. It
2568 is better to limit inheritance to certain tags using the variables
2569 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2570 :group 'org-tags
2571 :type '(choice
2572 (const :tag "No, don't list them" nil)
2573 (const :tag "Yes, do list them" t)
2574 (const :tag "List them, indented with leading dots" indented)))
2576 (defcustom org-tags-sort-function nil
2577 "When set, tags are sorted using this function as a comparator"
2578 :group 'org-tags
2579 :type '(choice
2580 (const :tag "No sorting" nil)
2581 (const :tag "Alphabetical" string<)
2582 (const :tag "Reverse alphabetical" string>)
2583 (function :tag "Custom function" nil)))
2585 (defvar org-tags-history nil
2586 "History of minibuffer reads for tags.")
2587 (defvar org-last-tags-completion-table nil
2588 "The last used completion table for tags.")
2589 (defvar org-after-tags-change-hook nil
2590 "Hook that is run after the tags in a line have changed.")
2592 (defgroup org-properties nil
2593 "Options concerning properties in Org-mode."
2594 :tag "Org Properties"
2595 :group 'org)
2597 (defcustom org-property-format "%-10s %s"
2598 "How property key/value pairs should be formatted by `indent-line'.
2599 When `indent-line' hits a property definition, it will format the line
2600 according to this format, mainly to make sure that the values are
2601 lined-up with respect to each other."
2602 :group 'org-properties
2603 :type 'string)
2605 (defcustom org-use-property-inheritance nil
2606 "Non-nil means properties apply also for sublevels.
2608 This setting is chiefly used during property searches. Turning it on can
2609 cause significant overhead when doing a search, which is why it is not
2610 on by default.
2612 When nil, only the properties directly given in the current entry count.
2613 When t, every property is inherited. The value may also be a list of
2614 properties that should have inheritance, or a regular expression matching
2615 properties that should be inherited.
2617 However, note that some special properties use inheritance under special
2618 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2619 and the properties ending in \"_ALL\" when they are used as descriptor
2620 for valid values of a property.
2622 Note for programmers:
2623 When querying an entry with `org-entry-get', you can control if inheritance
2624 should be used. By default, `org-entry-get' looks only at the local
2625 properties. You can request inheritance by setting the inherit argument
2626 to t (to force inheritance) or to `selective' (to respect the setting
2627 in this variable)."
2628 :group 'org-properties
2629 :type '(choice
2630 (const :tag "Not" nil)
2631 (const :tag "Always" t)
2632 (repeat :tag "Specific properties" (string :tag "Property"))
2633 (regexp :tag "Properties matched by regexp")))
2635 (defun org-property-inherit-p (property)
2636 "Check if PROPERTY is one that should be inherited."
2637 (cond
2638 ((eq org-use-property-inheritance t) t)
2639 ((not org-use-property-inheritance) nil)
2640 ((stringp org-use-property-inheritance)
2641 (string-match org-use-property-inheritance property))
2642 ((listp org-use-property-inheritance)
2643 (member property org-use-property-inheritance))
2644 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2646 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2647 "The default column format, if no other format has been defined.
2648 This variable can be set on the per-file basis by inserting a line
2650 #+COLUMNS: %25ITEM ....."
2651 :group 'org-properties
2652 :type 'string)
2654 (defcustom org-columns-ellipses ".."
2655 "The ellipses to be used when a field in column view is truncated.
2656 When this is the empty string, as many characters as possible are shown,
2657 but then there will be no visual indication that the field has been truncated.
2658 When this is a string of length N, the last N characters of a truncated
2659 field are replaced by this string. If the column is narrower than the
2660 ellipses string, only part of the ellipses string will be shown."
2661 :group 'org-properties
2662 :type 'string)
2664 (defcustom org-columns-modify-value-for-display-function nil
2665 "Function that modifies values for display in column view.
2666 For example, it can be used to cut out a certain part from a time stamp.
2667 The function must take 2 arguments:
2669 column-title The title of the column (*not* the property name)
2670 value The value that should be modified.
2672 The function should return the value that should be displayed,
2673 or nil if the normal value should be used."
2674 :group 'org-properties
2675 :type 'function)
2677 (defcustom org-effort-property "Effort"
2678 "The property that is being used to keep track of effort estimates.
2679 Effort estimates given in this property need to have the format H:MM."
2680 :group 'org-properties
2681 :group 'org-progress
2682 :type '(string :tag "Property"))
2684 (defconst org-global-properties-fixed
2685 '(("VISIBILITY_ALL" . "folded children content all")
2686 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2687 "List of property/value pairs that can be inherited by any entry.
2689 These are fixed values, for the preset properties. The user variable
2690 that can be used to add to this list is `org-global-properties'.
2692 The entries in this list are cons cells where the car is a property
2693 name and cdr is a string with the value. If the value represents
2694 multiple items like an \"_ALL\" property, separate the items by
2695 spaces.")
2697 (defcustom org-global-properties nil
2698 "List of property/value pairs that can be inherited by any entry.
2700 This list will be combined with the constant `org-global-properties-fixed'.
2702 The entries in this list are cons cells where the car is a property
2703 name and cdr is a string with the value.
2705 You can set buffer-local values for the same purpose in the variable
2706 `org-file-properties' this by adding lines like
2708 #+PROPERTY: NAME VALUE"
2709 :group 'org-properties
2710 :type '(repeat
2711 (cons (string :tag "Property")
2712 (string :tag "Value"))))
2714 (defvar org-file-properties nil
2715 "List of property/value pairs that can be inherited by any entry.
2716 Valid for the current buffer.
2717 This variable is populated from #+PROPERTY lines.")
2718 (make-variable-buffer-local 'org-file-properties)
2720 (defgroup org-agenda nil
2721 "Options concerning agenda views in Org-mode."
2722 :tag "Org Agenda"
2723 :group 'org)
2725 (defvar org-category nil
2726 "Variable used by org files to set a category for agenda display.
2727 Such files should use a file variable to set it, for example
2729 # -*- mode: org; org-category: \"ELisp\"
2731 or contain a special line
2733 #+CATEGORY: ELisp
2735 If the file does not specify a category, then file's base name
2736 is used instead.")
2737 (make-variable-buffer-local 'org-category)
2738 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2740 (defcustom org-agenda-files nil
2741 "The files to be used for agenda display.
2742 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2743 \\[org-remove-file]. You can also use customize to edit the list.
2745 If an entry is a directory, all files in that directory that are matched by
2746 `org-agenda-file-regexp' will be part of the file list.
2748 If the value of the variable is not a list but a single file name, then
2749 the list of agenda files is actually stored and maintained in that file, one
2750 agenda file per line."
2751 :group 'org-agenda
2752 :type '(choice
2753 (repeat :tag "List of files and directories" file)
2754 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2756 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2757 "Regular expression to match files for `org-agenda-files'.
2758 If any element in the list in that variable contains a directory instead
2759 of a normal file, all files in that directory that are matched by this
2760 regular expression will be included."
2761 :group 'org-agenda
2762 :type 'regexp)
2764 (defcustom org-agenda-text-search-extra-files nil
2765 "List of extra files to be searched by text search commands.
2766 These files will be search in addition to the agenda files by the
2767 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2768 Note that these files will only be searched for text search commands,
2769 not for the other agenda views like todo lists, tag searches or the weekly
2770 agenda. This variable is intended to list notes and possibly archive files
2771 that should also be searched by these two commands.
2772 In fact, if the first element in the list is the symbol `agenda-archives',
2773 than all archive files of all agenda files will be added to the search
2774 scope."
2775 :group 'org-agenda
2776 :type '(set :greedy t
2777 (const :tag "Agenda Archives" agenda-archives)
2778 (repeat :inline t (file))))
2780 (if (fboundp 'defvaralias)
2781 (defvaralias 'org-agenda-multi-occur-extra-files
2782 'org-agenda-text-search-extra-files))
2784 (defcustom org-agenda-skip-unavailable-files nil
2785 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2786 A nil value means to remove them, after a query, from the list."
2787 :group 'org-agenda
2788 :type 'boolean)
2790 (defcustom org-calendar-to-agenda-key [?c]
2791 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2792 The command `org-calendar-goto-agenda' will be bound to this key. The
2793 default is the character `c' because then `c' can be used to switch back and
2794 forth between agenda and calendar."
2795 :group 'org-agenda
2796 :type 'sexp)
2798 (defcustom org-calendar-agenda-action-key [?k]
2799 "The key to be installed in `calendar-mode-map' for agenda-action.
2800 The command `org-agenda-action' will be bound to this key. The
2801 default is the character `k' because we use the same key in the agenda."
2802 :group 'org-agenda
2803 :type 'sexp)
2805 (defcustom org-calendar-insert-diary-entry-key [?i]
2806 "The key to be installed in `calendar-mode-map' for adding diary entries.
2807 This option is irrelevant until `org-agenda-diary-file' has been configured
2808 to point to an Org-mode file. When that is the case, the command
2809 `org-agenda-diary-entry' will be bound to the key given here, by default
2810 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2811 if you want to continue doing this, you need to change this to a different
2812 key."
2813 :group 'org-agenda
2814 :type 'sexp)
2816 (defcustom org-agenda-diary-file 'diary-file
2817 "File to which to add new entries with the `i' key in agenda and calendar.
2818 When this is the symbol `diary-file', the functionality in the Emacs
2819 calendar will be used to add entries to the `diary-file'. But when this
2820 points to a file, `org-agenda-diary-entry' will be used instead."
2821 :group 'org-agenda
2822 :type '(choice
2823 (const :tag "The standard Emacs diary file" diary-file)
2824 (file :tag "Special Org file diary entries")))
2826 (eval-after-load "calendar"
2827 '(progn
2828 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2829 'org-calendar-goto-agenda)
2830 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2831 'org-agenda-action)
2832 (add-hook 'calendar-mode-hook
2833 (lambda ()
2834 (unless (eq org-agenda-diary-file 'diary-file)
2835 (define-key calendar-mode-map
2836 org-calendar-insert-diary-entry-key
2837 'org-agenda-diary-entry))))))
2839 (defgroup org-latex nil
2840 "Options for embedding LaTeX code into Org-mode."
2841 :tag "Org LaTeX"
2842 :group 'org)
2844 (defcustom org-format-latex-options
2845 '(:foreground default :background default :scale 1.0
2846 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2847 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2848 "Options for creating images from LaTeX fragments.
2849 This is a property list with the following properties:
2850 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2851 `default' means use the foreground of the default face.
2852 :background the background color, or \"Transparent\".
2853 `default' means use the background of the default face.
2854 :scale a scaling factor for the size of the images.
2855 :html-foreground, :html-background, :html-scale
2856 the same numbers for HTML export.
2857 :matchers a list indicating which matchers should be used to
2858 find LaTeX fragments. Valid members of this list are:
2859 \"begin\" find environments
2860 \"$1\" find single characters surrounded by $.$
2861 \"$\" find math expressions surrounded by $...$
2862 \"$$\" find math expressions surrounded by $$....$$
2863 \"\\(\" find math expressions surrounded by \\(...\\)
2864 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2865 :group 'org-latex
2866 :type 'plist)
2868 (defcustom org-format-latex-signal-error t
2869 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2870 When nil, just push out a message."
2871 :group 'org-latex
2872 :type 'boolean)
2874 (defcustom org-format-latex-header "\\documentclass{article}
2875 \\usepackage{amssymb}
2876 \\usepackage[usenames]{color}
2877 \\usepackage{amsmath}
2878 \\usepackage{latexsym}
2879 \\usepackage[mathscr]{eucal}
2880 \\pagestyle{empty} % do not remove
2881 % The settings below are copied from fullpage.sty
2882 \\setlength{\\textwidth}{\\paperwidth}
2883 \\addtolength{\\textwidth}{-3cm}
2884 \\setlength{\\oddsidemargin}{1.5cm}
2885 \\addtolength{\\oddsidemargin}{-2.54cm}
2886 \\setlength{\\evensidemargin}{\\oddsidemargin}
2887 \\setlength{\\textheight}{\\paperheight}
2888 \\addtolength{\\textheight}{-\\headheight}
2889 \\addtolength{\\textheight}{-\\headsep}
2890 \\addtolength{\\textheight}{-\\footskip}
2891 \\addtolength{\\textheight}{-3cm}
2892 \\setlength{\\topmargin}{1.5cm}
2893 \\addtolength{\\topmargin}{-2.54cm}"
2894 "The document header used for processing LaTeX fragments.
2895 It is imperative that this header make sure that no page number
2896 appears on the page."
2897 :group 'org-latex
2898 :type 'string)
2900 (defvar org-format-latex-header-extra nil)
2902 ;; The following variable is defined here because is it also used
2903 ;; when formatting latex fragments. Originally it was part of the
2904 ;; LaTeX exporter, which is why the name includes "export".
2905 (defcustom org-export-latex-packages-alist nil
2906 "Alist of packages to be inserted in the header.
2907 Each cell is of the format \( \"option\" . \"package\" \)."
2908 :group 'org-export-latex
2909 :type '(repeat
2910 (list
2911 (string :tag "option")
2912 (string :tag "package"))))
2914 (defgroup org-font-lock nil
2915 "Font-lock settings for highlighting in Org-mode."
2916 :tag "Org Font Lock"
2917 :group 'org)
2919 (defcustom org-level-color-stars-only nil
2920 "Non-nil means fontify only the stars in each headline.
2921 When nil, the entire headline is fontified.
2922 Changing it requires restart of `font-lock-mode' to become effective
2923 also in regions already fontified."
2924 :group 'org-font-lock
2925 :type 'boolean)
2927 (defcustom org-hide-leading-stars nil
2928 "Non-nil means hide the first N-1 stars in a headline.
2929 This works by using the face `org-hide' for these stars. This
2930 face is white for a light background, and black for a dark
2931 background. You may have to customize the face `org-hide' to
2932 make this work.
2933 Changing it requires restart of `font-lock-mode' to become effective
2934 also in regions already fontified.
2935 You may also set this on a per-file basis by adding one of the following
2936 lines to the buffer:
2938 #+STARTUP: hidestars
2939 #+STARTUP: showstars"
2940 :group 'org-font-lock
2941 :type 'boolean)
2943 (defcustom org-fontify-done-headline nil
2944 "Non-nil means change the face of a headline if it is marked DONE.
2945 Normally, only the TODO/DONE keyword indicates the state of a headline.
2946 When this is non-nil, the headline after the keyword is set to the
2947 `org-headline-done' as an additional indication."
2948 :group 'org-font-lock
2949 :type 'boolean)
2951 (defcustom org-fontify-emphasized-text t
2952 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2953 Changing this variable requires a restart of Emacs to take effect."
2954 :group 'org-font-lock
2955 :type 'boolean)
2957 (defcustom org-fontify-whole-heading-line nil
2958 "Non-nil means fontify the whole line for headings.
2959 This is useful when setting a background color for the
2960 org-level-* faces."
2961 :group 'org-font-lock
2962 :type 'boolean)
2964 (defcustom org-highlight-latex-fragments-and-specials nil
2965 "Non-nil means fontify what is treated specially by the exporters."
2966 :group 'org-font-lock
2967 :type 'boolean)
2969 (defcustom org-hide-emphasis-markers nil
2970 "Non-nil mean font-lock should hide the emphasis marker characters."
2971 :group 'org-font-lock
2972 :type 'boolean)
2974 (defvar org-emph-re nil
2975 "Regular expression for matching emphasis.")
2976 (defvar org-verbatim-re nil
2977 "Regular expression for matching verbatim text.")
2978 (defvar org-emphasis-regexp-components) ; defined just below
2979 (defvar org-emphasis-alist) ; defined just below
2980 (defun org-set-emph-re (var val)
2981 "Set variable and compute the emphasis regular expression."
2982 (set var val)
2983 (when (and (boundp 'org-emphasis-alist)
2984 (boundp 'org-emphasis-regexp-components)
2985 org-emphasis-alist org-emphasis-regexp-components)
2986 (let* ((e org-emphasis-regexp-components)
2987 (pre (car e))
2988 (post (nth 1 e))
2989 (border (nth 2 e))
2990 (body (nth 3 e))
2991 (nl (nth 4 e))
2992 (body1 (concat body "*?"))
2993 (markers (mapconcat 'car org-emphasis-alist ""))
2994 (vmarkers (mapconcat
2995 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2996 org-emphasis-alist "")))
2997 ;; make sure special characters appear at the right position in the class
2998 (if (string-match "\\^" markers)
2999 (setq markers (concat (replace-match "" t t markers) "^")))
3000 (if (string-match "-" markers)
3001 (setq markers (concat (replace-match "" t t markers) "-")))
3002 (if (string-match "\\^" vmarkers)
3003 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3004 (if (string-match "-" vmarkers)
3005 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3006 (if (> nl 0)
3007 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3008 (int-to-string nl) "\\}")))
3009 ;; Make the regexp
3010 (setq org-emph-re
3011 (concat "\\([" pre "]\\|^\\)"
3012 "\\("
3013 "\\([" markers "]\\)"
3014 "\\("
3015 "[^" border "]\\|"
3016 "[^" border "]"
3017 body1
3018 "[^" border "]"
3019 "\\)"
3020 "\\3\\)"
3021 "\\([" post "]\\|$\\)"))
3022 (setq org-verbatim-re
3023 (concat "\\([" pre "]\\|^\\)"
3024 "\\("
3025 "\\([" vmarkers "]\\)"
3026 "\\("
3027 "[^" border "]\\|"
3028 "[^" border "]"
3029 body1
3030 "[^" border "]"
3031 "\\)"
3032 "\\3\\)"
3033 "\\([" post "]\\|$\\)")))))
3035 (defcustom org-emphasis-regexp-components
3036 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3037 "Components used to build the regular expression for emphasis.
3038 This is a list with 6 entries. Terminology: In an emphasis string
3039 like \" *strong word* \", we call the initial space PREMATCH, the final
3040 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3041 and \"trong wor\" is the body. The different components in this variable
3042 specify what is allowed/forbidden in each part:
3044 pre Chars allowed as prematch. Beginning of line will be allowed too.
3045 post Chars allowed as postmatch. End of line will be allowed too.
3046 border The chars *forbidden* as border characters.
3047 body-regexp A regexp like \".\" to match a body character. Don't use
3048 non-shy groups here, and don't allow newline here.
3049 newline The maximum number of newlines allowed in an emphasis exp.
3051 Use customize to modify this, or restart Emacs after changing it."
3052 :group 'org-font-lock
3053 :set 'org-set-emph-re
3054 :type '(list
3055 (sexp :tag "Allowed chars in pre ")
3056 (sexp :tag "Allowed chars in post ")
3057 (sexp :tag "Forbidden chars in border ")
3058 (sexp :tag "Regexp for body ")
3059 (integer :tag "number of newlines allowed")
3060 (option (boolean :tag "Please ignore this button"))))
3062 (defcustom org-emphasis-alist
3063 `(("*" bold "<b>" "</b>")
3064 ("/" italic "<i>" "</i>")
3065 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3066 ("=" org-code "<code>" "</code>" verbatim)
3067 ("~" org-verbatim "<code>" "</code>" verbatim)
3068 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3069 "<del>" "</del>")
3071 "Special syntax for emphasized text.
3072 Text starting and ending with a special character will be emphasized, for
3073 example *bold*, _underlined_ and /italic/. This variable sets the marker
3074 characters, the face to be used by font-lock for highlighting in Org-mode
3075 Emacs buffers, and the HTML tags to be used for this.
3076 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3077 Use customize to modify this, or restart Emacs after changing it."
3078 :group 'org-font-lock
3079 :set 'org-set-emph-re
3080 :type '(repeat
3081 (list
3082 (string :tag "Marker character")
3083 (choice
3084 (face :tag "Font-lock-face")
3085 (plist :tag "Face property list"))
3086 (string :tag "HTML start tag")
3087 (string :tag "HTML end tag")
3088 (option (const verbatim)))))
3090 (defvar org-protecting-blocks
3091 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3092 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3093 This is needed for font-lock setup.")
3095 ;;; Miscellaneous options
3097 (defgroup org-completion nil
3098 "Completion in Org-mode."
3099 :tag "Org Completion"
3100 :group 'org)
3102 (defcustom org-completion-use-ido nil
3103 "Non-nil means use ido completion wherever possible.
3104 Note that `ido-mode' must be active for this variable to be relevant.
3105 If you decide to turn this variable on, you might well want to turn off
3106 `org-outline-path-complete-in-steps'.
3107 See also `org-completion-use-iswitchb'."
3108 :group 'org-completion
3109 :type 'boolean)
3111 (defcustom org-completion-use-iswitchb nil
3112 "Non-nil means use iswitchb completion wherever possible.
3113 Note that `iswitchb-mode' must be active for this variable to be relevant.
3114 If you decide to turn this variable on, you might well want to turn off
3115 `org-outline-path-complete-in-steps'.
3116 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3117 :group 'org-completion
3118 :type 'boolean)
3120 (defcustom org-completion-fallback-command 'hippie-expand
3121 "The expansion command called by \\[org-complete] in normal context.
3122 Normal means no org-mode-specific context."
3123 :group 'org-completion
3124 :type 'function)
3126 ;;; Functions and variables from their packages
3127 ;; Declared here to avoid compiler warnings
3129 ;; XEmacs only
3130 (defvar outline-mode-menu-heading)
3131 (defvar outline-mode-menu-show)
3132 (defvar outline-mode-menu-hide)
3133 (defvar zmacs-regions) ; XEmacs regions
3135 ;; Emacs only
3136 (defvar mark-active)
3138 ;; Various packages
3139 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3140 (declare-function calendar-forward-day "cal-move" (arg))
3141 (declare-function calendar-goto-date "cal-move" (date))
3142 (declare-function calendar-goto-today "cal-move" ())
3143 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3144 (defvar calc-embedded-close-formula)
3145 (defvar calc-embedded-open-formula)
3146 (declare-function cdlatex-tab "ext:cdlatex" ())
3147 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3148 (defvar font-lock-unfontify-region-function)
3149 (declare-function iswitchb-read-buffer "iswitchb"
3150 (prompt &optional default require-match start matches-set))
3151 (defvar iswitchb-temp-buflist)
3152 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3153 (defvar org-agenda-tags-todo-honor-ignore-options)
3154 (declare-function org-agenda-skip "org-agenda" ())
3155 (declare-function
3156 org-format-agenda-item "org-agenda"
3157 (extra txt &optional category tags dotime noprefix remove-re habitp))
3158 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3159 (declare-function org-agenda-change-all-lines "org-agenda"
3160 (newhead hdmarker &optional fixface just-this))
3161 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3162 (declare-function org-agenda-maybe-redo "org-agenda" ())
3163 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3164 (beg end))
3165 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3166 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3167 "org-agenda" (&optional end))
3168 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3169 (declare-function org-indent-mode "org-indent" (&optional arg))
3170 (declare-function parse-time-string "parse-time" (string))
3171 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3172 (defvar remember-data-file)
3173 (defvar texmathp-why)
3174 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3175 (declare-function table--at-cell-p "table" (position &optional object at-column))
3177 (defvar w3m-current-url)
3178 (defvar w3m-current-title)
3180 (defvar org-latex-regexps)
3182 ;;; Autoload and prepare some org modules
3184 ;; Some table stuff that needs to be defined here, because it is used
3185 ;; by the functions setting up org-mode or checking for table context.
3187 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3188 "Detects an org-type or table-type table.")
3189 (defconst org-table-line-regexp "^[ \t]*|"
3190 "Detects an org-type table line.")
3191 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3192 "Detects an org-type table line.")
3193 (defconst org-table-hline-regexp "^[ \t]*|-"
3194 "Detects an org-type table hline.")
3195 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3196 "Detects a table-type table hline.")
3197 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3198 "Searching from within a table (any type) this finds the first line
3199 outside the table.")
3201 ;; Autoload the functions in org-table.el that are needed by functions here.
3203 (eval-and-compile
3204 (org-autoload "org-table"
3205 '(org-table-align org-table-begin org-table-blank-field
3206 org-table-convert org-table-convert-region org-table-copy-down
3207 org-table-copy-region org-table-create
3208 org-table-create-or-convert-from-region
3209 org-table-create-with-table.el org-table-current-dline
3210 org-table-cut-region org-table-delete-column org-table-edit-field
3211 org-table-edit-formulas org-table-end org-table-eval-formula
3212 org-table-export org-table-field-info
3213 org-table-get-stored-formulas org-table-goto-column
3214 org-table-hline-and-move org-table-import org-table-insert-column
3215 org-table-insert-hline org-table-insert-row org-table-iterate
3216 org-table-justify-field-maybe org-table-kill-row
3217 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3218 org-table-move-column org-table-move-column-left
3219 org-table-move-column-right org-table-move-row
3220 org-table-move-row-down org-table-move-row-up
3221 org-table-next-field org-table-next-row org-table-paste-rectangle
3222 org-table-previous-field org-table-recalculate
3223 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3224 org-table-toggle-coordinate-overlays
3225 org-table-toggle-formula-debugger org-table-wrap-region
3226 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3228 (defun org-at-table-p (&optional table-type)
3229 "Return t if the cursor is inside an org-type table.
3230 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3231 (if org-enable-table-editor
3232 (save-excursion
3233 (beginning-of-line 1)
3234 (looking-at (if table-type org-table-any-line-regexp
3235 org-table-line-regexp)))
3236 nil))
3237 (defsubst org-table-p () (org-at-table-p))
3239 (defun org-at-table.el-p ()
3240 "Return t if and only if we are at a table.el table."
3241 (and (org-at-table-p 'any)
3242 (save-excursion
3243 (goto-char (org-table-begin 'any))
3244 (looking-at org-table1-hline-regexp))))
3245 (defun org-table-recognize-table.el ()
3246 "If there is a table.el table nearby, recognize it and move into it."
3247 (if org-table-tab-recognizes-table.el
3248 (if (org-at-table.el-p)
3249 (progn
3250 (beginning-of-line 1)
3251 (if (looking-at org-table-dataline-regexp)
3253 (if (looking-at org-table1-hline-regexp)
3254 (progn
3255 (beginning-of-line 2)
3256 (if (looking-at org-table-any-border-regexp)
3257 (beginning-of-line -1)))))
3258 (if (re-search-forward "|" (org-table-end t) t)
3259 (progn
3260 (require 'table)
3261 (if (table--at-cell-p (point))
3263 (message "recognizing table.el table...")
3264 (table-recognize-table)
3265 (message "recognizing table.el table...done")))
3266 (error "This should not happen..."))
3268 nil)
3269 nil))
3271 (defun org-at-table-hline-p ()
3272 "Return t if the cursor is inside a hline in a table."
3273 (if org-enable-table-editor
3274 (save-excursion
3275 (beginning-of-line 1)
3276 (looking-at org-table-hline-regexp))
3277 nil))
3279 (defvar org-table-clean-did-remove-column nil)
3281 (defun org-table-map-tables (function)
3282 "Apply FUNCTION to the start of all tables in the buffer."
3283 (save-excursion
3284 (save-restriction
3285 (widen)
3286 (goto-char (point-min))
3287 (while (re-search-forward org-table-any-line-regexp nil t)
3288 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3289 (beginning-of-line 1)
3290 (when (looking-at org-table-line-regexp)
3291 (save-excursion (funcall function))
3292 (or (looking-at org-table-line-regexp)
3293 (forward-char 1)))
3294 (re-search-forward org-table-any-border-regexp nil 1))))
3295 (message "Mapping tables: done"))
3297 ;; Declare and autoload functions from org-exp.el & Co
3299 (declare-function org-default-export-plist "org-exp")
3300 (declare-function org-infile-export-plist "org-exp")
3301 (declare-function org-get-current-options "org-exp")
3302 (eval-and-compile
3303 (org-autoload "org-exp"
3304 '(org-export org-export-visible
3305 org-insert-export-options-template
3306 org-table-clean-before-export))
3307 (org-autoload "org-ascii"
3308 '(org-export-as-ascii org-export-ascii-preprocess
3309 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3310 org-export-region-as-ascii))
3311 (org-autoload "org-latex"
3312 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3313 org-replace-region-by-latex org-export-region-as-latex
3314 org-export-as-latex org-export-as-pdf
3315 org-export-as-pdf-and-open))
3316 (org-autoload "org-html"
3317 '(org-export-as-html-and-open
3318 org-export-as-html-batch org-export-as-html-to-buffer
3319 org-replace-region-by-html org-export-region-as-html
3320 org-export-as-html))
3321 (org-autoload "org-docbook"
3322 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3323 org-replace-region-by-docbook org-export-region-as-docbook
3324 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3325 org-export-as-docbook))
3326 (org-autoload "org-icalendar"
3327 '(org-export-icalendar-this-file
3328 org-export-icalendar-all-agenda-files
3329 org-export-icalendar-combine-agenda-files))
3330 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3331 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3333 ;; Declare and autoload functions from org-agenda.el
3335 (eval-and-compile
3336 (org-autoload "org-agenda"
3337 '(org-agenda org-agenda-list org-search-view
3338 org-todo-list org-tags-view org-agenda-list-stuck-projects
3339 org-diary org-agenda-to-appt
3340 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3342 ;; Autoload org-remember
3344 (eval-and-compile
3345 (org-autoload "org-remember"
3346 '(org-remember-insinuate org-remember-annotation
3347 org-remember-apply-template org-remember org-remember-handler)))
3349 ;; Autoload org-clock.el
3352 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3353 (beg end))
3354 (declare-function org-clock-update-mode-line "org-clock" ())
3355 (declare-function org-resolve-clocks "org-clock"
3356 (&optional also-non-dangling-p prompt last-valid))
3357 (defvar org-clock-start-time)
3358 (defvar org-clock-marker (make-marker)
3359 "Marker recording the last clock-in.")
3360 (defvar org-clock-hd-marker (make-marker)
3361 "Marker recording the last clock-in, but the headline position.")
3362 (defvar org-clock-heading ""
3363 "The heading of the current clock entry.")
3364 (defun org-clock-is-active ()
3365 "Return non-nil if clock is currently running.
3366 The return value is actually the clock marker."
3367 (marker-buffer org-clock-marker))
3369 (eval-and-compile
3370 (org-autoload
3371 "org-clock"
3372 '(org-clock-in org-clock-out org-clock-cancel
3373 org-clock-goto org-clock-sum org-clock-display
3374 org-clock-remove-overlays org-clock-report
3375 org-clocktable-shift org-dblock-write:clocktable
3376 org-get-clocktable org-resolve-clocks)))
3378 (defun org-clock-update-time-maybe ()
3379 "If this is a CLOCK line, update it and return t.
3380 Otherwise, return nil."
3381 (interactive)
3382 (save-excursion
3383 (beginning-of-line 1)
3384 (skip-chars-forward " \t")
3385 (when (looking-at org-clock-string)
3386 (let ((re (concat "[ \t]*" org-clock-string
3387 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3388 "\\([ \t]*=>.*\\)?\\)?"))
3389 ts te h m s neg)
3390 (cond
3391 ((not (looking-at re))
3392 nil)
3393 ((not (match-end 2))
3394 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3395 (> org-clock-marker (point))
3396 (<= org-clock-marker (point-at-eol)))
3397 ;; The clock is running here
3398 (setq org-clock-start-time
3399 (apply 'encode-time
3400 (org-parse-time-string (match-string 1))))
3401 (org-clock-update-mode-line)))
3403 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3404 (end-of-line 1)
3405 (setq ts (match-string 1)
3406 te (match-string 3))
3407 (setq s (- (org-float-time
3408 (apply 'encode-time (org-parse-time-string te)))
3409 (org-float-time
3410 (apply 'encode-time (org-parse-time-string ts))))
3411 neg (< s 0)
3412 s (abs s)
3413 h (floor (/ s 3600))
3414 s (- s (* 3600 h))
3415 m (floor (/ s 60))
3416 s (- s (* 60 s)))
3417 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3418 t))))))
3420 (defun org-check-running-clock ()
3421 "Check if the current buffer contains the running clock.
3422 If yes, offer to stop it and to save the buffer with the changes."
3423 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3424 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3425 (buffer-name))))
3426 (org-clock-out)
3427 (when (y-or-n-p "Save changed buffer?")
3428 (save-buffer))))
3430 (defun org-clocktable-try-shift (dir n)
3431 "Check if this line starts a clock table, if yes, shift the time block."
3432 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3433 (org-clocktable-shift dir n)))
3435 ;; Autoload org-timer.el
3437 (eval-and-compile
3438 (org-autoload
3439 "org-timer"
3440 '(org-timer-start org-timer org-timer-item
3441 org-timer-change-times-in-region
3442 org-timer-set-timer
3443 org-timer-reset-timers
3444 org-timer-show-remaining-time)))
3446 ;; Autoload org-feed.el
3448 (eval-and-compile
3449 (org-autoload
3450 "org-feed"
3451 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3454 ;; Autoload org-indent.el
3456 ;; Define the variable already here, to make sure we have it.
3457 (defvar org-indent-mode nil
3458 "Non-nil if Org-Indent mode is enabled.
3459 Use the command `org-indent-mode' to change this variable.")
3461 (eval-and-compile
3462 (org-autoload
3463 "org-indent"
3464 '(org-indent-mode)))
3466 ;; Autoload org-mobile.el
3468 (eval-and-compile
3469 (org-autoload
3470 "org-mobile"
3471 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3473 ;; Autoload archiving code
3474 ;; The stuff that is needed for cycling and tags has to be defined here.
3476 (defgroup org-archive nil
3477 "Options concerning archiving in Org-mode."
3478 :tag "Org Archive"
3479 :group 'org-structure)
3481 (defcustom org-archive-location "%s_archive::"
3482 "The location where subtrees should be archived.
3484 The value of this variable is a string, consisting of two parts,
3485 separated by a double-colon. The first part is a filename and
3486 the second part is a headline.
3488 When the filename is omitted, archiving happens in the same file.
3489 %s in the filename will be replaced by the current file
3490 name (without the directory part). Archiving to a different file
3491 is useful to keep archived entries from contributing to the
3492 Org-mode Agenda.
3494 The archived entries will be filed as subtrees of the specified
3495 headline. When the headline is omitted, the subtrees are simply
3496 filed away at the end of the file, as top-level entries. Also in
3497 the heading you can use %s to represent the file name, this can be
3498 useful when using the same archive for a number of different files.
3500 Here are a few examples:
3501 \"%s_archive::\"
3502 If the current file is Projects.org, archive in file
3503 Projects.org_archive, as top-level trees. This is the default.
3505 \"::* Archived Tasks\"
3506 Archive in the current file, under the top-level headline
3507 \"* Archived Tasks\".
3509 \"~/org/archive.org::\"
3510 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3512 \"~/org/archive.org::From %s\"
3513 Archive in file ~/org/archive.org (absolute path), under headlines
3514 \"From FILENAME\" where file name is the current file name.
3516 \"basement::** Finished Tasks\"
3517 Archive in file ./basement (relative path), as level 3 trees
3518 below the level 2 heading \"** Finished Tasks\".
3520 You may set this option on a per-file basis by adding to the buffer a
3521 line like
3523 #+ARCHIVE: basement::** Finished Tasks
3525 You may also define it locally for a subtree by setting an ARCHIVE property
3526 in the entry. If such a property is found in an entry, or anywhere up
3527 the hierarchy, it will be used."
3528 :group 'org-archive
3529 :type 'string)
3531 (defcustom org-archive-tag "ARCHIVE"
3532 "The tag that marks a subtree as archived.
3533 An archived subtree does not open during visibility cycling, and does
3534 not contribute to the agenda listings.
3535 After changing this, font-lock must be restarted in the relevant buffers to
3536 get the proper fontification."
3537 :group 'org-archive
3538 :group 'org-keywords
3539 :type 'string)
3541 (defcustom org-agenda-skip-archived-trees t
3542 "Non-nil means the agenda will skip any items located in archived trees.
3543 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3544 variable is no longer recommended, you should leave it at the value t.
3545 Instead, use the key `v' to cycle the archives-mode in the agenda."
3546 :group 'org-archive
3547 :group 'org-agenda-skip
3548 :type 'boolean)
3550 (defcustom org-columns-skip-archived-trees t
3551 "Non-nil means ignore archived trees when creating column view."
3552 :group 'org-archive
3553 :group 'org-properties
3554 :type 'boolean)
3556 (defcustom org-cycle-open-archived-trees nil
3557 "Non-nil means `org-cycle' will open archived trees.
3558 An archived tree is a tree marked with the tag ARCHIVE.
3559 When nil, archived trees will stay folded. You can still open them with
3560 normal outline commands like `show-all', but not with the cycling commands."
3561 :group 'org-archive
3562 :group 'org-cycle
3563 :type 'boolean)
3565 (defcustom org-sparse-tree-open-archived-trees nil
3566 "Non-nil means sparse tree construction shows matches in archived trees.
3567 When nil, matches in these trees are highlighted, but the trees are kept in
3568 collapsed state."
3569 :group 'org-archive
3570 :group 'org-sparse-trees
3571 :type 'boolean)
3573 (defun org-cycle-hide-archived-subtrees (state)
3574 "Re-hide all archived subtrees after a visibility state change."
3575 (when (and (not org-cycle-open-archived-trees)
3576 (not (memq state '(overview folded))))
3577 (save-excursion
3578 (let* ((globalp (memq state '(contents all)))
3579 (beg (if globalp (point-min) (point)))
3580 (end (if globalp (point-max) (org-end-of-subtree t))))
3581 (org-hide-archived-subtrees beg end)
3582 (goto-char beg)
3583 (if (looking-at (concat ".*:" org-archive-tag ":"))
3584 (message "%s" (substitute-command-keys
3585 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3587 (defun org-force-cycle-archived ()
3588 "Cycle subtree even if it is archived."
3589 (interactive)
3590 (setq this-command 'org-cycle)
3591 (let ((org-cycle-open-archived-trees t))
3592 (call-interactively 'org-cycle)))
3594 (defun org-hide-archived-subtrees (beg end)
3595 "Re-hide all archived subtrees after a visibility state change."
3596 (save-excursion
3597 (let* ((re (concat ":" org-archive-tag ":")))
3598 (goto-char beg)
3599 (while (re-search-forward re end t)
3600 (when (org-on-heading-p)
3601 (org-flag-subtree t)
3602 (org-end-of-subtree t))))))
3604 (defun org-flag-subtree (flag)
3605 (save-excursion
3606 (org-back-to-heading t)
3607 (outline-end-of-heading)
3608 (outline-flag-region (point)
3609 (progn (org-end-of-subtree t) (point))
3610 flag)))
3612 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3614 (eval-and-compile
3615 (org-autoload "org-archive"
3616 '(org-add-archive-files org-archive-subtree
3617 org-archive-to-archive-sibling org-toggle-archive-tag
3618 org-archive-subtree-default
3619 org-archive-subtree-default-with-confirmation)))
3621 ;; Autoload Column View Code
3623 (declare-function org-columns-number-to-string "org-colview")
3624 (declare-function org-columns-get-format-and-top-level "org-colview")
3625 (declare-function org-columns-compute "org-colview")
3627 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3628 '(org-columns-number-to-string org-columns-get-format-and-top-level
3629 org-columns-compute org-agenda-columns org-columns-remove-overlays
3630 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3632 ;; Autoload ID code
3634 (declare-function org-id-store-link "org-id")
3635 (declare-function org-id-locations-load "org-id")
3636 (declare-function org-id-locations-save "org-id")
3637 (defvar org-id-track-globally)
3638 (org-autoload "org-id"
3639 '(org-id-get-create org-id-new org-id-copy org-id-get
3640 org-id-get-with-outline-path-completion
3641 org-id-get-with-outline-drilling
3642 org-id-goto org-id-find org-id-store-link))
3644 ;; Autoload Plotting Code
3646 (org-autoload "org-plot"
3647 '(org-plot/gnuplot))
3649 ;;; Variables for pre-computed regular expressions, all buffer local
3651 (defvar org-drawer-regexp nil
3652 "Matches first line of a hidden block.")
3653 (make-variable-buffer-local 'org-drawer-regexp)
3654 (defvar org-todo-regexp nil
3655 "Matches any of the TODO state keywords.")
3656 (make-variable-buffer-local 'org-todo-regexp)
3657 (defvar org-not-done-regexp nil
3658 "Matches any of the TODO state keywords except the last one.")
3659 (make-variable-buffer-local 'org-not-done-regexp)
3660 (defvar org-not-done-heading-regexp nil
3661 "Matches a TODO headline that is not done.")
3662 (make-variable-buffer-local 'org-not-done-regexp)
3663 (defvar org-todo-line-regexp nil
3664 "Matches a headline and puts TODO state into group 2 if present.")
3665 (make-variable-buffer-local 'org-todo-line-regexp)
3666 (defvar org-complex-heading-regexp nil
3667 "Matches a headline and puts everything into groups:
3668 group 1: the stars
3669 group 2: The todo keyword, maybe
3670 group 3: Priority cookie
3671 group 4: True headline
3672 group 5: Tags")
3673 (make-variable-buffer-local 'org-complex-heading-regexp)
3674 (defvar org-complex-heading-regexp-format nil)
3675 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3676 (defvar org-todo-line-tags-regexp nil
3677 "Matches a headline and puts TODO state into group 2 if present.
3678 Also put tags into group 4 if tags are present.")
3679 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3680 (defvar org-nl-done-regexp nil
3681 "Matches newline followed by a headline with the DONE keyword.")
3682 (make-variable-buffer-local 'org-nl-done-regexp)
3683 (defvar org-looking-at-done-regexp nil
3684 "Matches the DONE keyword a point.")
3685 (make-variable-buffer-local 'org-looking-at-done-regexp)
3686 (defvar org-ds-keyword-length 12
3687 "Maximum length of the Deadline and SCHEDULED keywords.")
3688 (make-variable-buffer-local 'org-ds-keyword-length)
3689 (defvar org-deadline-regexp nil
3690 "Matches the DEADLINE keyword.")
3691 (make-variable-buffer-local 'org-deadline-regexp)
3692 (defvar org-deadline-time-regexp nil
3693 "Matches the DEADLINE keyword together with a time stamp.")
3694 (make-variable-buffer-local 'org-deadline-time-regexp)
3695 (defvar org-deadline-line-regexp nil
3696 "Matches the DEADLINE keyword and the rest of the line.")
3697 (make-variable-buffer-local 'org-deadline-line-regexp)
3698 (defvar org-scheduled-regexp nil
3699 "Matches the SCHEDULED keyword.")
3700 (make-variable-buffer-local 'org-scheduled-regexp)
3701 (defvar org-scheduled-time-regexp nil
3702 "Matches the SCHEDULED keyword together with a time stamp.")
3703 (make-variable-buffer-local 'org-scheduled-time-regexp)
3704 (defvar org-closed-time-regexp nil
3705 "Matches the CLOSED keyword together with a time stamp.")
3706 (make-variable-buffer-local 'org-closed-time-regexp)
3708 (defvar org-keyword-time-regexp nil
3709 "Matches any of the 4 keywords, together with the time stamp.")
3710 (make-variable-buffer-local 'org-keyword-time-regexp)
3711 (defvar org-keyword-time-not-clock-regexp nil
3712 "Matches any of the 3 keywords, together with the time stamp.")
3713 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3714 (defvar org-maybe-keyword-time-regexp nil
3715 "Matches a timestamp, possibly preceeded by a keyword.")
3716 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3717 (defvar org-planning-or-clock-line-re nil
3718 "Matches a line with planning or clock info.")
3719 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3720 (defvar org-all-time-keywords nil
3721 "List of time keywords.")
3722 (make-variable-buffer-local 'org-all-time-keywords)
3724 (defconst org-plain-time-of-day-regexp
3725 (concat
3726 "\\(\\<[012]?[0-9]"
3727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3728 "\\(--?"
3729 "\\(\\<[012]?[0-9]"
3730 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3731 "\\)?")
3732 "Regular expression to match a plain time or time range.
3733 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3734 groups carry important information:
3735 0 the full match
3736 1 the first time, range or not
3737 8 the second time, if it is a range.")
3739 (defconst org-plain-time-extension-regexp
3740 (concat
3741 "\\(\\<[012]?[0-9]"
3742 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3743 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3744 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3745 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3746 groups carry important information:
3747 0 the full match
3748 7 hours of duration
3749 9 minutes of duration")
3751 (defconst org-stamp-time-of-day-regexp
3752 (concat
3753 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3754 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3755 "\\(--?"
3756 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3757 "Regular expression to match a timestamp time or time range.
3758 After a match, the following groups carry important information:
3759 0 the full match
3760 1 date plus weekday, for back referencing to make sure both times are on the same day
3761 2 the first time, range or not
3762 4 the second time, if it is a range.")
3764 (defconst org-startup-options
3765 '(("fold" org-startup-folded t)
3766 ("overview" org-startup-folded t)
3767 ("nofold" org-startup-folded nil)
3768 ("showall" org-startup-folded nil)
3769 ("showeverything" org-startup-folded showeverything)
3770 ("content" org-startup-folded content)
3771 ("indent" org-startup-indented t)
3772 ("noindent" org-startup-indented nil)
3773 ("hidestars" org-hide-leading-stars t)
3774 ("showstars" org-hide-leading-stars nil)
3775 ("odd" org-odd-levels-only t)
3776 ("oddeven" org-odd-levels-only nil)
3777 ("align" org-startup-align-all-tables t)
3778 ("noalign" org-startup-align-all-tables nil)
3779 ("customtime" org-display-custom-times t)
3780 ("logdone" org-log-done time)
3781 ("lognotedone" org-log-done note)
3782 ("nologdone" org-log-done nil)
3783 ("lognoteclock-out" org-log-note-clock-out t)
3784 ("nolognoteclock-out" org-log-note-clock-out nil)
3785 ("logrepeat" org-log-repeat state)
3786 ("lognoterepeat" org-log-repeat note)
3787 ("nologrepeat" org-log-repeat nil)
3788 ("logreschedule" org-log-reschedule time)
3789 ("lognotereschedule" org-log-reschedule note)
3790 ("nologreschedule" org-log-reschedule nil)
3791 ("logredeadline" org-log-redeadline time)
3792 ("lognoteredeadline" org-log-redeadline note)
3793 ("nologredeadline" org-log-redeadline nil)
3794 ("fninline" org-footnote-define-inline t)
3795 ("nofninline" org-footnote-define-inline nil)
3796 ("fnlocal" org-footnote-section nil)
3797 ("fnauto" org-footnote-auto-label t)
3798 ("fnprompt" org-footnote-auto-label nil)
3799 ("fnconfirm" org-footnote-auto-label confirm)
3800 ("fnplain" org-footnote-auto-label plain)
3801 ("fnadjust" org-footnote-auto-adjust t)
3802 ("nofnadjust" org-footnote-auto-adjust nil)
3803 ("constcgs" constants-unit-system cgs)
3804 ("constSI" constants-unit-system SI)
3805 ("noptag" org-tag-persistent-alist nil)
3806 ("hideblocks" org-hide-block-startup t)
3807 ("nohideblocks" org-hide-block-startup nil)
3808 ("beamer" org-startup-with-beamer-mode t))
3809 "Variable associated with STARTUP options for org-mode.
3810 Each element is a list of three items: The startup options as written
3811 in the #+STARTUP line, the corresponding variable, and the value to
3812 set this variable to if the option is found. An optional forth element PUSH
3813 means to push this value onto the list in the variable.")
3815 (defun org-set-regexps-and-options ()
3816 "Precompute regular expressions for current buffer."
3817 (when (org-mode-p)
3818 (org-set-local 'org-todo-kwd-alist nil)
3819 (org-set-local 'org-todo-key-alist nil)
3820 (org-set-local 'org-todo-key-trigger nil)
3821 (org-set-local 'org-todo-keywords-1 nil)
3822 (org-set-local 'org-done-keywords nil)
3823 (org-set-local 'org-todo-heads nil)
3824 (org-set-local 'org-todo-sets nil)
3825 (org-set-local 'org-todo-log-states nil)
3826 (org-set-local 'org-file-properties nil)
3827 (org-set-local 'org-file-tags nil)
3828 (let ((re (org-make-options-regexp
3829 '("CATEGORY" "TODO" "COLUMNS"
3830 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3831 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3832 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3833 (splitre "[ \t]+")
3834 kwds kws0 kwsa key log value cat arch tags const links hw dws
3835 tail sep kws1 prio props ftags drawers beamer-p
3836 ext-setup-or-nil setup-contents (start 0))
3837 (save-excursion
3838 (save-restriction
3839 (widen)
3840 (goto-char (point-min))
3841 (while (or (and ext-setup-or-nil
3842 (string-match re ext-setup-or-nil start)
3843 (setq start (match-end 0)))
3844 (and (setq ext-setup-or-nil nil start 0)
3845 (re-search-forward re nil t)))
3846 (setq key (upcase (match-string 1 ext-setup-or-nil))
3847 value (org-match-string-no-properties 2 ext-setup-or-nil))
3848 (cond
3849 ((equal key "CATEGORY")
3850 (if (string-match "[ \t]+$" value)
3851 (setq value (replace-match "" t t value)))
3852 (setq cat value))
3853 ((member key '("SEQ_TODO" "TODO"))
3854 (push (cons 'sequence (org-split-string value splitre)) kwds))
3855 ((equal key "TYP_TODO")
3856 (push (cons 'type (org-split-string value splitre)) kwds))
3857 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3858 ;; general TODO-like setup
3859 (push (cons (intern (downcase (match-string 1 key)))
3860 (org-split-string value splitre)) kwds))
3861 ((equal key "TAGS")
3862 (setq tags (append tags (if tags '("\\n") nil)
3863 (org-split-string value splitre))))
3864 ((equal key "COLUMNS")
3865 (org-set-local 'org-columns-default-format value))
3866 ((equal key "LINK")
3867 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3868 (push (cons (match-string 1 value)
3869 (org-trim (match-string 2 value)))
3870 links)))
3871 ((equal key "PRIORITIES")
3872 (setq prio (org-split-string value " +")))
3873 ((equal key "PROPERTY")
3874 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3875 (push (cons (match-string 1 value) (match-string 2 value))
3876 props)))
3877 ((equal key "FILETAGS")
3878 (when (string-match "\\S-" value)
3879 (setq ftags
3880 (append
3881 ftags
3882 (apply 'append
3883 (mapcar (lambda (x) (org-split-string x ":"))
3884 (org-split-string value)))))))
3885 ((equal key "DRAWERS")
3886 (setq drawers (org-split-string value splitre)))
3887 ((equal key "CONSTANTS")
3888 (setq const (append const (org-split-string value splitre))))
3889 ((equal key "STARTUP")
3890 (let ((opts (org-split-string value splitre))
3891 l var val)
3892 (while (setq l (pop opts))
3893 (when (setq l (assoc l org-startup-options))
3894 (setq var (nth 1 l) val (nth 2 l))
3895 (if (not (nth 3 l))
3896 (set (make-local-variable var) val)
3897 (if (not (listp (symbol-value var)))
3898 (set (make-local-variable var) nil))
3899 (set (make-local-variable var) (symbol-value var))
3900 (add-to-list var val))))))
3901 ((equal key "ARCHIVE")
3902 (string-match " *$" value)
3903 (setq arch (replace-match "" t t value))
3904 (remove-text-properties 0 (length arch)
3905 '(face t fontified t) arch))
3906 ((equal key "LATEX_CLASS")
3907 (setq beamer-p (equal value "beamer")))
3908 ((equal key "SETUPFILE")
3909 (setq setup-contents (org-file-contents
3910 (expand-file-name
3911 (org-remove-double-quotes value))
3912 'noerror))
3913 (if (not ext-setup-or-nil)
3914 (setq ext-setup-or-nil setup-contents start 0)
3915 (setq ext-setup-or-nil
3916 (concat (substring ext-setup-or-nil 0 start)
3917 "\n" setup-contents "\n"
3918 (substring ext-setup-or-nil start)))))
3919 ))))
3920 (when cat
3921 (org-set-local 'org-category (intern cat))
3922 (push (cons "CATEGORY" cat) props))
3923 (when prio
3924 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3925 (setq prio (mapcar 'string-to-char prio))
3926 (org-set-local 'org-highest-priority (nth 0 prio))
3927 (org-set-local 'org-lowest-priority (nth 1 prio))
3928 (org-set-local 'org-default-priority (nth 2 prio)))
3929 (and props (org-set-local 'org-file-properties (nreverse props)))
3930 (and ftags (org-set-local 'org-file-tags
3931 (mapcar 'org-add-prop-inherited ftags)))
3932 (and drawers (org-set-local 'org-drawers drawers))
3933 (and arch (org-set-local 'org-archive-location arch))
3934 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3935 ;; Process the TODO keywords
3936 (unless kwds
3937 ;; Use the global values as if they had been given locally.
3938 (setq kwds (default-value 'org-todo-keywords))
3939 (if (stringp (car kwds))
3940 (setq kwds (list (cons org-todo-interpretation
3941 (default-value 'org-todo-keywords)))))
3942 (setq kwds (reverse kwds)))
3943 (setq kwds (nreverse kwds))
3944 (let (inter kws kw)
3945 (while (setq kws (pop kwds))
3946 (let ((kws (or
3947 (run-hook-with-args-until-success
3948 'org-todo-setup-filter-hook kws)
3949 kws)))
3950 (setq inter (pop kws) sep (member "|" kws)
3951 kws0 (delete "|" (copy-sequence kws))
3952 kwsa nil
3953 kws1 (mapcar
3954 (lambda (x)
3955 ;; 1 2
3956 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3957 (progn
3958 (setq kw (match-string 1 x)
3959 key (and (match-end 2) (match-string 2 x))
3960 log (org-extract-log-state-settings x))
3961 (push (cons kw (and key (string-to-char key))) kwsa)
3962 (and log (push log org-todo-log-states))
3964 (error "Invalid TODO keyword %s" x)))
3965 kws0)
3966 kwsa (if kwsa (append '((:startgroup))
3967 (nreverse kwsa)
3968 '((:endgroup))))
3969 hw (car kws1)
3970 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3971 tail (list inter hw (car dws) (org-last dws))))
3972 (add-to-list 'org-todo-heads hw 'append)
3973 (push kws1 org-todo-sets)
3974 (setq org-done-keywords (append org-done-keywords dws nil))
3975 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3976 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3977 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3978 (setq org-todo-sets (nreverse org-todo-sets)
3979 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3980 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3981 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3982 ;; Process the constants
3983 (when const
3984 (let (e cst)
3985 (while (setq e (pop const))
3986 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3987 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3988 (setq org-table-formula-constants-local cst)))
3990 ;; Process the tags.
3991 (when tags
3992 (let (e tgs)
3993 (while (setq e (pop tags))
3994 (cond
3995 ((equal e "{") (push '(:startgroup) tgs))
3996 ((equal e "}") (push '(:endgroup) tgs))
3997 ((equal e "\\n") (push '(:newline) tgs))
3998 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3999 (push (cons (match-string 1 e)
4000 (string-to-char (match-string 2 e)))
4001 tgs))
4002 (t (push (list e) tgs))))
4003 (org-set-local 'org-tag-alist nil)
4004 (while (setq e (pop tgs))
4005 (or (and (stringp (car e))
4006 (assoc (car e) org-tag-alist))
4007 (push e org-tag-alist)))))
4009 ;; Compute the regular expressions and other local variables
4010 (if (not org-done-keywords)
4011 (setq org-done-keywords (and org-todo-keywords-1
4012 (list (org-last org-todo-keywords-1)))))
4013 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4014 (length org-scheduled-string)
4015 (length org-clock-string)
4016 (length org-closed-string)))
4017 org-drawer-regexp
4018 (concat "^[ \t]*:\\("
4019 (mapconcat 'regexp-quote org-drawers "\\|")
4020 "\\):[ \t]*$")
4021 org-not-done-keywords
4022 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4023 org-todo-regexp
4024 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4025 "\\|") "\\)\\>")
4026 org-not-done-regexp
4027 (concat "\\<\\("
4028 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4029 "\\)\\>")
4030 org-not-done-heading-regexp
4031 (concat "^\\(\\*+\\)[ \t]+\\("
4032 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4033 "\\)\\>")
4034 org-todo-line-regexp
4035 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4036 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4037 "\\)\\>\\)?[ \t]*\\(.*\\)")
4038 org-complex-heading-regexp
4039 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4040 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4041 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4042 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4043 org-complex-heading-regexp-format
4044 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4045 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4046 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4047 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4048 org-nl-done-regexp
4049 (concat "\n\\*+[ \t]+"
4050 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4051 "\\)" "\\>")
4052 org-todo-line-tags-regexp
4053 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4054 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4055 (org-re
4056 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4057 org-looking-at-done-regexp
4058 (concat "^" "\\(?:"
4059 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4060 "\\>")
4061 org-deadline-regexp (concat "\\<" org-deadline-string)
4062 org-deadline-time-regexp
4063 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4064 org-deadline-line-regexp
4065 (concat "\\<\\(" org-deadline-string "\\).*")
4066 org-scheduled-regexp
4067 (concat "\\<" org-scheduled-string)
4068 org-scheduled-time-regexp
4069 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4070 org-closed-time-regexp
4071 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4072 org-keyword-time-regexp
4073 (concat "\\<\\(" org-scheduled-string
4074 "\\|" org-deadline-string
4075 "\\|" org-closed-string
4076 "\\|" org-clock-string "\\)"
4077 " *[[<]\\([^]>]+\\)[]>]")
4078 org-keyword-time-not-clock-regexp
4079 (concat "\\<\\(" org-scheduled-string
4080 "\\|" org-deadline-string
4081 "\\|" org-closed-string
4082 "\\)"
4083 " *[[<]\\([^]>]+\\)[]>]")
4084 org-maybe-keyword-time-regexp
4085 (concat "\\(\\<\\(" org-scheduled-string
4086 "\\|" org-deadline-string
4087 "\\|" org-closed-string
4088 "\\|" org-clock-string "\\)\\)?"
4089 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4090 org-planning-or-clock-line-re
4091 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4092 "\\|" org-deadline-string
4093 "\\|" org-closed-string "\\|" org-clock-string
4094 "\\)\\>\\)")
4095 org-all-time-keywords
4096 (mapcar (lambda (w) (substring w 0 -1))
4097 (list org-scheduled-string org-deadline-string
4098 org-clock-string org-closed-string))
4100 (org-compute-latex-and-specials-regexp)
4101 (org-set-font-lock-defaults))))
4103 (defun org-file-contents (file &optional noerror)
4104 "Return the contents of FILE, as a string."
4105 (if (or (not file)
4106 (not (file-readable-p file)))
4107 (if noerror
4108 (progn
4109 (message "Cannot read file %s" file)
4110 (ding) (sit-for 2)
4112 (error "Cannot read file %s" file))
4113 (with-temp-buffer
4114 (insert-file-contents file)
4115 (buffer-string))))
4117 (defun org-extract-log-state-settings (x)
4118 "Extract the log state setting from a TODO keyword string.
4119 This will extract info from a string like \"WAIT(w@/!)\"."
4120 (let (kw key log1 log2)
4121 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4122 (setq kw (match-string 1 x)
4123 key (and (match-end 2) (match-string 2 x))
4124 log1 (and (match-end 3) (match-string 3 x))
4125 log2 (and (match-end 4) (match-string 4 x)))
4126 (and (or log1 log2)
4127 (list kw
4128 (and log1 (if (equal log1 "!") 'time 'note))
4129 (and log2 (if (equal log2 "!") 'time 'note)))))))
4131 (defun org-remove-keyword-keys (list)
4132 "Remove a pair of parenthesis at the end of each string in LIST."
4133 (mapcar (lambda (x)
4134 (if (string-match "(.*)$" x)
4135 (substring x 0 (match-beginning 0))
4137 list))
4139 (defun org-assign-fast-keys (alist)
4140 "Assign fast keys to a keyword-key alist.
4141 Respect keys that are already there."
4142 (let (new e (alt ?0))
4143 (while (setq e (pop alist))
4144 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4145 (cdr e)) ;; Key already assigned.
4146 (push e new)
4147 (let ((clist (string-to-list (downcase (car e))))
4148 (used (append new alist)))
4149 (when (= (car clist) ?@)
4150 (pop clist))
4151 (while (and clist (rassoc (car clist) used))
4152 (pop clist))
4153 (unless clist
4154 (while (rassoc alt used)
4155 (incf alt)))
4156 (push (cons (car e) (or (car clist) alt)) new))))
4157 (nreverse new)))
4159 ;;; Some variables used in various places
4161 (defvar org-window-configuration nil
4162 "Used in various places to store a window configuration.")
4163 (defvar org-selected-window nil
4164 "Used in various places to store a window configuration.")
4165 (defvar org-finish-function nil
4166 "Function to be called when `C-c C-c' is used.
4167 This is for getting out of special buffers like remember.")
4170 ;; FIXME: Occasionally check by commenting these, to make sure
4171 ;; no other functions uses these, forgetting to let-bind them.
4172 (defvar entry)
4173 (defvar last-state)
4174 (defvar date)
4176 ;; Defined somewhere in this file, but used before definition.
4177 (defvar org-html-entities)
4178 (defvar org-struct-menu)
4179 (defvar org-org-menu)
4180 (defvar org-tbl-menu)
4182 ;;;; Define the Org-mode
4184 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4185 (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."))
4188 ;; We use a before-change function to check if a table might need
4189 ;; an update.
4190 (defvar org-table-may-need-update t
4191 "Indicates that a table might need an update.
4192 This variable is set by `org-before-change-function'.
4193 `org-table-align' sets it back to nil.")
4194 (defun org-before-change-function (beg end)
4195 "Every change indicates that a table might need an update."
4196 (setq org-table-may-need-update t))
4197 (defvar org-mode-map)
4198 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4199 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4200 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4201 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4202 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4203 (defvar org-table-buffer-is-an nil)
4204 (defconst org-outline-regexp "\\*+ ")
4206 ;;;###autoload
4207 (define-derived-mode org-mode outline-mode "Org"
4208 "Outline-based notes management and organizer, alias
4209 \"Carsten's outline-mode for keeping track of everything.\"
4211 Org-mode develops organizational tasks around a NOTES file which
4212 contains information about projects as plain text. Org-mode is
4213 implemented on top of outline-mode, which is ideal to keep the content
4214 of large files well structured. It supports ToDo items, deadlines and
4215 time stamps, which magically appear in the diary listing of the Emacs
4216 calendar. Tables are easily created with a built-in table editor.
4217 Plain text URL-like links connect to websites, emails (VM), Usenet
4218 messages (Gnus), BBDB entries, and any files related to the project.
4219 For printing and sharing of notes, an Org-mode file (or a part of it)
4220 can be exported as a structured ASCII or HTML file.
4222 The following commands are available:
4224 \\{org-mode-map}"
4226 ;; Get rid of Outline menus, they are not needed
4227 ;; Need to do this here because define-derived-mode sets up
4228 ;; the keymap so late. Still, it is a waste to call this each time
4229 ;; we switch another buffer into org-mode.
4230 (if (featurep 'xemacs)
4231 (when (boundp 'outline-mode-menu-heading)
4232 ;; Assume this is Greg's port, it used easymenu
4233 (easy-menu-remove outline-mode-menu-heading)
4234 (easy-menu-remove outline-mode-menu-show)
4235 (easy-menu-remove outline-mode-menu-hide))
4236 (define-key org-mode-map [menu-bar headings] 'undefined)
4237 (define-key org-mode-map [menu-bar hide] 'undefined)
4238 (define-key org-mode-map [menu-bar show] 'undefined))
4240 (org-load-modules-maybe)
4241 (easy-menu-add org-org-menu)
4242 (easy-menu-add org-tbl-menu)
4243 (org-install-agenda-files-menu)
4244 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4245 (org-add-to-invisibility-spec '(org-cwidth))
4246 (org-add-to-invisibility-spec '(org-hide-block . t))
4247 (when (featurep 'xemacs)
4248 (org-set-local 'line-move-ignore-invisible t))
4249 (org-set-local 'outline-regexp org-outline-regexp)
4250 (org-set-local 'outline-level 'org-outline-level)
4251 (when (and org-ellipsis
4252 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4253 (fboundp 'make-glyph-code))
4254 (unless org-display-table
4255 (setq org-display-table (make-display-table)))
4256 (set-display-table-slot
4257 org-display-table 4
4258 (vconcat (mapcar
4259 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4260 org-ellipsis)))
4261 (if (stringp org-ellipsis) org-ellipsis "..."))))
4262 (setq buffer-display-table org-display-table))
4263 (org-set-regexps-and-options)
4264 (when (and org-tag-faces (not org-tags-special-faces-re))
4265 ;; tag faces set outside customize.... force initialization.
4266 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4267 ;; Calc embedded
4268 (org-set-local 'calc-embedded-open-mode "# ")
4269 (modify-syntax-entry ?# "<")
4270 (modify-syntax-entry ?@ "w")
4271 (if org-startup-truncated (setq truncate-lines t))
4272 (org-set-local 'font-lock-unfontify-region-function
4273 'org-unfontify-region)
4274 ;; Activate before-change-function
4275 (org-set-local 'org-table-may-need-update t)
4276 (org-add-hook 'before-change-functions 'org-before-change-function nil
4277 'local)
4278 ;; Check for running clock before killing a buffer
4279 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4280 ;; Paragraphs and auto-filling
4281 (org-set-autofill-regexps)
4282 (setq indent-line-function 'org-indent-line-function)
4283 (org-update-radio-target-regexp)
4284 ;; Make sure dependence stuff works reliably, even for users who set it
4285 ;; too late :-(
4286 (if org-enforce-todo-dependencies
4287 (add-hook 'org-blocker-hook
4288 'org-block-todo-from-children-or-siblings-or-parent)
4289 (remove-hook 'org-blocker-hook
4290 'org-block-todo-from-children-or-siblings-or-parent))
4291 (if org-enforce-todo-checkbox-dependencies
4292 (add-hook 'org-blocker-hook
4293 'org-block-todo-from-checkboxes)
4294 (remove-hook 'org-blocker-hook
4295 'org-block-todo-from-checkboxes))
4297 ;; Comment characters
4298 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4299 (org-set-local 'comment-padding " ")
4301 ;; Align options lines
4302 (org-set-local
4303 'align-mode-rules-list
4304 '((org-in-buffer-settings
4305 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4306 (modes . '(org-mode)))))
4308 ;; Imenu
4309 (org-set-local 'imenu-create-index-function
4310 'org-imenu-get-tree)
4312 ;; Make isearch reveal context
4313 (if (or (featurep 'xemacs)
4314 (not (boundp 'outline-isearch-open-invisible-function)))
4315 ;; Emacs 21 and XEmacs make use of the hook
4316 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4317 ;; Emacs 22 deals with this through a special variable
4318 (org-set-local 'outline-isearch-open-invisible-function
4319 (lambda (&rest ignore) (org-show-context 'isearch))))
4321 ;; Turn on org-beamer-mode?
4322 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4324 ;; If empty file that did not turn on org-mode automatically, make it to.
4325 (if (and org-insert-mode-line-in-empty-file
4326 (interactive-p)
4327 (= (point-min) (point-max)))
4328 (insert "# -*- mode: org -*-\n\n"))
4329 (unless org-inhibit-startup
4330 (when org-startup-align-all-tables
4331 (let ((bmp (buffer-modified-p)))
4332 (org-table-map-tables 'org-table-align)
4333 (set-buffer-modified-p bmp)))
4334 (when org-startup-indented
4335 (require 'org-indent)
4336 (org-indent-mode 1))
4337 (unless org-inhibit-startup-visibility-stuff
4338 (org-set-startup-visibility))))
4340 (when (fboundp 'abbrev-table-put)
4341 (abbrev-table-put org-mode-abbrev-table
4342 :parents (list text-mode-abbrev-table)))
4344 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4346 (defun org-current-time ()
4347 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4348 (if (> (car org-time-stamp-rounding-minutes) 1)
4349 (let ((r (car org-time-stamp-rounding-minutes))
4350 (time (decode-time)))
4351 (apply 'encode-time
4352 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4353 (nthcdr 2 time))))
4354 (current-time)))
4356 ;;;; Font-Lock stuff, including the activators
4358 (defvar org-mouse-map (make-sparse-keymap))
4359 (org-defkey org-mouse-map
4360 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4361 (org-defkey org-mouse-map
4362 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4363 (when org-mouse-1-follows-link
4364 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4365 (when org-tab-follows-link
4366 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4367 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4369 (require 'font-lock)
4371 (defconst org-non-link-chars "]\t\n\r<>")
4372 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4373 "shell" "elisp"))
4374 (defvar org-link-types-re nil
4375 "Matches a link that has a url-like prefix like \"http:\"")
4376 (defvar org-link-re-with-space nil
4377 "Matches a link with spaces, optional angular brackets around it.")
4378 (defvar org-link-re-with-space2 nil
4379 "Matches a link with spaces, optional angular brackets around it.")
4380 (defvar org-link-re-with-space3 nil
4381 "Matches a link with spaces, only for internal part in bracket links.")
4382 (defvar org-angle-link-re nil
4383 "Matches link with angular brackets, spaces are allowed.")
4384 (defvar org-plain-link-re nil
4385 "Matches plain link, without spaces.")
4386 (defvar org-bracket-link-regexp nil
4387 "Matches a link in double brackets.")
4388 (defvar org-bracket-link-analytic-regexp nil
4389 "Regular expression used to analyze links.
4390 Here is what the match groups contain after a match:
4391 1: http:
4392 2: http
4393 3: path
4394 4: [desc]
4395 5: desc")
4396 (defvar org-bracket-link-analytic-regexp++ nil
4397 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4398 (defvar org-any-link-re nil
4399 "Regular expression matching any link.")
4401 (defun org-make-link-regexps ()
4402 "Update the link regular expressions.
4403 This should be called after the variable `org-link-types' has changed."
4404 (setq org-link-types-re
4405 (concat
4406 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4407 org-link-re-with-space
4408 (concat
4409 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4410 "\\([^" org-non-link-chars " ]"
4411 "[^" org-non-link-chars "]*"
4412 "[^" org-non-link-chars " ]\\)>?")
4413 org-link-re-with-space2
4414 (concat
4415 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4416 "\\([^" org-non-link-chars " ]"
4417 "[^\t\n\r]*"
4418 "[^" org-non-link-chars " ]\\)>?")
4419 org-link-re-with-space3
4420 (concat
4421 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4422 "\\([^" org-non-link-chars " ]"
4423 "[^\t\n\r]*\\)")
4424 org-angle-link-re
4425 (concat
4426 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4427 "\\([^" org-non-link-chars " ]"
4428 "[^" org-non-link-chars "]*"
4429 "\\)>")
4430 org-plain-link-re
4431 (concat
4432 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4433 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4434 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4435 org-bracket-link-regexp
4436 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4437 org-bracket-link-analytic-regexp
4438 (concat
4439 "\\[\\["
4440 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4441 "\\([^]]+\\)"
4442 "\\]"
4443 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4444 "\\]")
4445 org-bracket-link-analytic-regexp++
4446 (concat
4447 "\\[\\["
4448 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4449 "\\([^]]+\\)"
4450 "\\]"
4451 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4452 "\\]")
4453 org-any-link-re
4454 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4455 org-angle-link-re "\\)\\|\\("
4456 org-plain-link-re "\\)")))
4458 (org-make-link-regexps)
4460 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4461 "Regular expression for fast time stamp matching.")
4462 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4463 "Regular expression for fast time stamp matching.")
4464 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4465 "Regular expression matching time strings for analysis.
4466 This one does not require the space after the date, so it can be used
4467 on a string that terminates immediately after the date.")
4468 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4469 "Regular expression matching time strings for analysis.")
4470 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4471 "Regular expression matching time stamps, with groups.")
4472 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4473 "Regular expression matching time stamps (also [..]), with groups.")
4474 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4475 "Regular expression matching a time stamp range.")
4476 (defconst org-tr-regexp-both
4477 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4478 "Regular expression matching a time stamp range.")
4479 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4480 org-ts-regexp "\\)?")
4481 "Regular expression matching a time stamp or time stamp range.")
4482 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4483 org-ts-regexp-both "\\)?")
4484 "Regular expression matching a time stamp or time stamp range.
4485 The time stamps may be either active or inactive.")
4487 (defvar org-emph-face nil)
4489 (defun org-do-emphasis-faces (limit)
4490 "Run through the buffer and add overlays to links."
4491 (let (rtn a)
4492 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4493 (if (not (= (char-after (match-beginning 3))
4494 (char-after (match-beginning 4))))
4495 (progn
4496 (setq rtn t)
4497 (setq a (assoc (match-string 3) org-emphasis-alist))
4498 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4499 'face
4500 (nth 1 a))
4501 (and (nth 4 a)
4502 (org-remove-flyspell-overlays-in
4503 (match-beginning 0) (match-end 0)))
4504 (add-text-properties (match-beginning 2) (match-end 2)
4505 '(font-lock-multiline t))
4506 (when org-hide-emphasis-markers
4507 (add-text-properties (match-end 4) (match-beginning 5)
4508 '(invisible org-link))
4509 (add-text-properties (match-beginning 3) (match-end 3)
4510 '(invisible org-link)))))
4511 (backward-char 1))
4512 rtn))
4514 (defun org-emphasize (&optional char)
4515 "Insert or change an emphasis, i.e. a font like bold or italic.
4516 If there is an active region, change that region to a new emphasis.
4517 If there is no region, just insert the marker characters and position
4518 the cursor between them.
4519 CHAR should be either the marker character, or the first character of the
4520 HTML tag associated with that emphasis. If CHAR is a space, the means
4521 to remove the emphasis of the selected region.
4522 If char is not given (for example in an interactive call) it
4523 will be prompted for."
4524 (interactive)
4525 (let ((eal org-emphasis-alist) e det
4526 (erc org-emphasis-regexp-components)
4527 (prompt "")
4528 (string "") beg end move tag c s)
4529 (if (org-region-active-p)
4530 (setq beg (region-beginning) end (region-end)
4531 string (buffer-substring beg end))
4532 (setq move t))
4534 (while (setq e (pop eal))
4535 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4536 c (aref tag 0))
4537 (push (cons c (string-to-char (car e))) det)
4538 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4539 (substring tag 1)))))
4540 (setq det (nreverse det))
4541 (unless char
4542 (message "%s" (concat "Emphasis marker or tag:" prompt))
4543 (setq char (read-char-exclusive)))
4544 (setq char (or (cdr (assoc char det)) char))
4545 (if (equal char ?\ )
4546 (setq s "" move nil)
4547 (unless (assoc (char-to-string char) org-emphasis-alist)
4548 (error "No such emphasis marker: \"%c\"" char))
4549 (setq s (char-to-string char)))
4550 (while (and (> (length string) 1)
4551 (equal (substring string 0 1) (substring string -1))
4552 (assoc (substring string 0 1) org-emphasis-alist))
4553 (setq string (substring string 1 -1)))
4554 (setq string (concat s string s))
4555 (if beg (delete-region beg end))
4556 (unless (or (bolp)
4557 (string-match (concat "[" (nth 0 erc) "\n]")
4558 (char-to-string (char-before (point)))))
4559 (insert " "))
4560 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4561 (char-to-string (char-after (point))))
4562 (insert " ") (backward-char 1))
4563 (insert string)
4564 (and move (backward-char 1))))
4566 (defconst org-nonsticky-props
4567 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4569 (defsubst org-rear-nonsticky-at (pos)
4570 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4572 (defun org-activate-plain-links (limit)
4573 "Run through the buffer and add overlays to links."
4574 (catch 'exit
4575 (let (f)
4576 (if (re-search-forward org-plain-link-re limit t)
4577 (progn
4578 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4579 (setq f (get-text-property (match-beginning 0) 'face))
4580 (if (or (eq f 'org-tag)
4581 (and (listp f) (memq 'org-tag f)))
4583 (add-text-properties (match-beginning 0) (match-end 0)
4584 (list 'mouse-face 'highlight
4585 'face 'org-link
4586 'keymap org-mouse-map))
4587 (org-rear-nonsticky-at (match-end 0)))
4588 t)))))
4590 (defun org-activate-code (limit)
4591 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4592 (progn
4593 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4594 (remove-text-properties (match-beginning 0) (match-end 0)
4595 '(display t invisible t intangible t))
4596 t)))
4598 (defun org-fontify-meta-lines-and-blocks (limit)
4599 "Fontify #+ lines and blocks, in the correct ways."
4600 (let ((case-fold-search t))
4601 (if (re-search-forward
4602 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4603 limit t)
4604 (let ((beg (match-beginning 0))
4605 (beg1 (line-beginning-position 2))
4606 (dc1 (downcase (match-string 2)))
4607 (dc3 (downcase (match-string 3)))
4608 end end1 quoting block-type)
4609 (cond
4610 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4611 ;; a single line of backend-specific content
4612 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4613 (remove-text-properties (match-beginning 0) (match-end 0)
4614 '(display t invisible t intangible t))
4615 (add-text-properties (match-beginning 1) (match-end 3)
4616 '(font-lock-fontified t face org-meta-line))
4617 (add-text-properties (match-beginning 6) (match-end 6)
4618 '(font-lock-fontified t face org-block))
4620 ((and (match-end 4) (equal dc3 "begin"))
4621 ;; Truely a block
4622 (setq block-type (downcase (match-string 5))
4623 quoting (member block-type org-protecting-blocks))
4624 (when (re-search-forward
4625 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4626 nil t) ;; on purpose, we look further than LIMIT
4627 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4628 (when quoting
4629 (remove-text-properties beg end
4630 '(display t invisible t intangible t)))
4631 (add-text-properties
4632 beg end
4633 '(font-lock-fontified t font-lock-multiline t))
4634 (add-text-properties beg beg1 '(face org-meta-line))
4635 (add-text-properties end1 end '(face org-meta-line))
4636 (cond
4637 (quoting
4638 (add-text-properties beg1 end1 '(face org-block)))
4639 ((not org-fontify-quote-and-verse-blocks))
4640 ((string= block-type "quote")
4641 (add-text-properties beg1 end1 '(face org-quote)))
4642 ((string= block-type "verse")
4643 (add-text-properties beg1 end1 '(face org-verse))))
4645 ((not (member (char-after beg) '(?\ ?\t)))
4646 ;; just any other in-buffer setting, but not indented
4647 (add-text-properties
4648 beg (match-end 0)
4649 '(font-lock-fontified t face org-meta-line))
4651 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4652 "orgtbl:" "tblfm:" "tblname:"))
4653 (and (match-end 4) (equal dc3 "attr")))
4654 (add-text-properties
4655 beg (match-end 0)
4656 '(font-lock-fontified t face org-meta-line))
4658 ((member dc3 '(" " ""))
4659 (add-text-properties
4660 beg (match-end 0)
4661 '(font-lock-fontified t face font-lock-comment-face)))
4662 (t nil))))))
4664 (defun org-activate-angle-links (limit)
4665 "Run through the buffer and add overlays to links."
4666 (if (re-search-forward org-angle-link-re limit t)
4667 (progn
4668 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4669 (add-text-properties (match-beginning 0) (match-end 0)
4670 (list 'mouse-face 'highlight
4671 'keymap org-mouse-map))
4672 (org-rear-nonsticky-at (match-end 0))
4673 t)))
4675 (defun org-activate-footnote-links (limit)
4676 "Run through the buffer and add overlays to links."
4677 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4678 limit t)
4679 (progn
4680 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4681 (add-text-properties (match-beginning 2) (match-end 2)
4682 (list 'mouse-face 'highlight
4683 'keymap org-mouse-map
4684 'help-echo
4685 (if (= (point-at-bol) (match-beginning 2))
4686 "Footnote definition"
4687 "Footnote reference")
4689 (org-rear-nonsticky-at (match-end 2))
4690 t)))
4692 (defun org-activate-bracket-links (limit)
4693 "Run through the buffer and add overlays to bracketed links."
4694 (if (re-search-forward org-bracket-link-regexp limit t)
4695 (let* ((help (concat "LINK: "
4696 (org-match-string-no-properties 1)))
4697 ;; FIXME: above we should remove the escapes.
4698 ;; but that requires another match, protecting match data,
4699 ;; a lot of overhead for font-lock.
4700 (ip (org-maybe-intangible
4701 (list 'invisible 'org-link
4702 'keymap org-mouse-map 'mouse-face 'highlight
4703 'font-lock-multiline t 'help-echo help)))
4704 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4705 'font-lock-multiline t 'help-echo help)))
4706 ;; We need to remove the invisible property here. Table narrowing
4707 ;; may have made some of this invisible.
4708 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4709 (remove-text-properties (match-beginning 0) (match-end 0)
4710 '(invisible nil))
4711 (if (match-end 3)
4712 (progn
4713 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4714 (org-rear-nonsticky-at (match-beginning 3))
4715 (add-text-properties (match-beginning 3) (match-end 3) vp)
4716 (org-rear-nonsticky-at (match-end 3))
4717 (add-text-properties (match-end 3) (match-end 0) ip)
4718 (org-rear-nonsticky-at (match-end 0)))
4719 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4720 (org-rear-nonsticky-at (match-beginning 1))
4721 (add-text-properties (match-beginning 1) (match-end 1) vp)
4722 (org-rear-nonsticky-at (match-end 1))
4723 (add-text-properties (match-end 1) (match-end 0) ip)
4724 (org-rear-nonsticky-at (match-end 0)))
4725 t)))
4727 (defun org-activate-dates (limit)
4728 "Run through the buffer and add overlays to dates."
4729 (if (re-search-forward org-tsr-regexp-both limit t)
4730 (progn
4731 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4732 (add-text-properties (match-beginning 0) (match-end 0)
4733 (list 'mouse-face 'highlight
4734 'keymap org-mouse-map))
4735 (org-rear-nonsticky-at (match-end 0))
4736 (when org-display-custom-times
4737 (if (match-end 3)
4738 (org-display-custom-time (match-beginning 3) (match-end 3)))
4739 (org-display-custom-time (match-beginning 1) (match-end 1)))
4740 t)))
4742 (defvar org-target-link-regexp nil
4743 "Regular expression matching radio targets in plain text.")
4744 (make-variable-buffer-local 'org-target-link-regexp)
4745 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4746 "Regular expression matching a link target.")
4747 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4748 "Regular expression matching a radio target.")
4749 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4750 "Regular expression matching any target.")
4752 (defun org-activate-target-links (limit)
4753 "Run through the buffer and add overlays to target matches."
4754 (when org-target-link-regexp
4755 (let ((case-fold-search t))
4756 (if (re-search-forward org-target-link-regexp limit t)
4757 (progn
4758 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4759 (add-text-properties (match-beginning 0) (match-end 0)
4760 (list 'mouse-face 'highlight
4761 'keymap org-mouse-map
4762 'help-echo "Radio target link"
4763 'org-linked-text t))
4764 (org-rear-nonsticky-at (match-end 0))
4765 t)))))
4767 (defun org-update-radio-target-regexp ()
4768 "Find all radio targets in this file and update the regular expression."
4769 (interactive)
4770 (when (memq 'radio org-activate-links)
4771 (setq org-target-link-regexp
4772 (org-make-target-link-regexp (org-all-targets 'radio)))
4773 (org-restart-font-lock)))
4775 (defun org-hide-wide-columns (limit)
4776 (let (s e)
4777 (setq s (text-property-any (point) (or limit (point-max))
4778 'org-cwidth t))
4779 (when s
4780 (setq e (next-single-property-change s 'org-cwidth))
4781 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4782 (goto-char e)
4783 t)))
4785 (defvar org-latex-and-specials-regexp nil
4786 "Regular expression for highlighting export special stuff.")
4787 (defvar org-match-substring-regexp)
4788 (defvar org-match-substring-with-braces-regexp)
4790 ;; This should be with the exporter code, but we also use if for font-locking
4791 (defconst org-export-html-special-string-regexps
4792 '(("\\\\-" . "&shy;")
4793 ("---\\([^-]\\)" . "&mdash;\\1")
4794 ("--\\([^-]\\)" . "&ndash;\\1")
4795 ("\\.\\.\\." . "&hellip;"))
4796 "Regular expressions for special string conversion.")
4799 (defun org-compute-latex-and-specials-regexp ()
4800 "Compute regular expression for stuff treated specially by exporters."
4801 (if (not org-highlight-latex-fragments-and-specials)
4802 (org-set-local 'org-latex-and-specials-regexp nil)
4803 (require 'org-exp)
4804 (let*
4805 ((matchers (plist-get org-format-latex-options :matchers))
4806 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4807 org-latex-regexps)))
4808 (org-export-allow-BIND nil)
4809 (options (org-combine-plists (org-default-export-plist)
4810 (org-infile-export-plist)))
4811 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4812 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4813 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4814 (org-export-html-expand (plist-get options :expand-quoted-html))
4815 (org-export-with-special-strings (plist-get options :special-strings))
4816 (re-sub
4817 (cond
4818 ((equal org-export-with-sub-superscripts '{})
4819 (list org-match-substring-with-braces-regexp))
4820 (org-export-with-sub-superscripts
4821 (list org-match-substring-regexp))
4822 (t nil)))
4823 (re-latex
4824 (if org-export-with-LaTeX-fragments
4825 (mapcar (lambda (x) (nth 1 x)) latexs)))
4826 (re-macros
4827 (if org-export-with-TeX-macros
4828 (list (concat "\\\\"
4829 (regexp-opt
4830 (append (mapcar 'car org-html-entities)
4831 (if (boundp 'org-latex-entities)
4832 (mapcar (lambda (x)
4833 (or (car-safe x) x))
4834 org-latex-entities)
4835 nil))
4836 'words))) ; FIXME
4838 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4839 (re-special (if org-export-with-special-strings
4840 (mapcar (lambda (x) (car x))
4841 org-export-html-special-string-regexps)))
4842 (re-rest
4843 (delq nil
4844 (list
4845 (if org-export-html-expand "@<[^>\n]+>")
4846 ))))
4847 (org-set-local
4848 'org-latex-and-specials-regexp
4849 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4850 re-rest) "\\|")))))
4852 (defun org-do-latex-and-special-faces (limit)
4853 "Run through the buffer and add overlays to links."
4854 (when org-latex-and-specials-regexp
4855 (let (rtn d)
4856 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4857 limit t))
4858 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4859 'face))
4860 '(org-code org-verbatim underline)))
4861 (progn
4862 (setq rtn t
4863 d (cond ((member (char-after (1+ (match-beginning 0)))
4864 '(?_ ?^)) 1)
4865 (t 0)))
4866 (font-lock-prepend-text-property
4867 (+ d (match-beginning 0)) (match-end 0)
4868 'face 'org-latex-and-export-specials)
4869 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4870 '(font-lock-multiline t)))))
4871 rtn)))
4873 (defun org-restart-font-lock ()
4874 "Restart font-lock-mode, to force refontification."
4875 (when (and (boundp 'font-lock-mode) font-lock-mode)
4876 (font-lock-mode -1)
4877 (font-lock-mode 1)))
4879 (defun org-all-targets (&optional radio)
4880 "Return a list of all targets in this file.
4881 With optional argument RADIO, only find radio targets."
4882 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4883 rtn)
4884 (save-excursion
4885 (goto-char (point-min))
4886 (while (re-search-forward re nil t)
4887 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4888 rtn)))
4890 (defun org-make-target-link-regexp (targets)
4891 "Make regular expression matching all strings in TARGETS.
4892 The regular expression finds the targets also if there is a line break
4893 between words."
4894 (and targets
4895 (concat
4896 "\\<\\("
4897 (mapconcat
4898 (lambda (x)
4899 (while (string-match " +" x)
4900 (setq x (replace-match "\\s-+" t t x)))
4902 targets
4903 "\\|")
4904 "\\)\\>")))
4906 (defun org-activate-tags (limit)
4907 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4908 (progn
4909 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4910 (add-text-properties (match-beginning 1) (match-end 1)
4911 (list 'mouse-face 'highlight
4912 'keymap org-mouse-map))
4913 (org-rear-nonsticky-at (match-end 1))
4914 t)))
4916 (defun org-outline-level ()
4917 "Compute the outline level of the heading at point.
4918 This function assumes that the cursor is at the beginning of a line matched
4919 by outline-regexp. Otherwise it returns garbage.
4920 If this is called at a normal headline, the level is the number of stars.
4921 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4922 For plain list items, if they are matched by `outline-regexp', this returns
4923 1000 plus the line indentation."
4924 (save-excursion
4925 (looking-at outline-regexp)
4926 (if (match-beginning 1)
4927 (+ (org-get-string-indentation (match-string 1)) 1000)
4928 (1- (- (match-end 0) (match-beginning 0))))))
4930 (defvar org-font-lock-keywords nil)
4932 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4933 "Regular expression matching a property line.")
4935 (defvar org-font-lock-hook nil
4936 "Functions to be called for special font lock stuff.")
4938 (defun org-font-lock-hook (limit)
4939 (run-hook-with-args 'org-font-lock-hook limit))
4941 (defun org-set-font-lock-defaults ()
4942 (let* ((em org-fontify-emphasized-text)
4943 (lk org-activate-links)
4944 (org-font-lock-extra-keywords
4945 (list
4946 ;; Call the hook
4947 '(org-font-lock-hook)
4948 ;; Headlines
4949 `(,(if org-fontify-whole-heading-line
4950 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4951 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4952 (1 (org-get-level-face 1))
4953 (2 (org-get-level-face 2))
4954 (3 (org-get-level-face 3)))
4955 ;; Table lines
4956 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4957 (1 'org-table t))
4958 ;; Table internals
4959 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4960 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4961 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4962 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4963 ;; Drawers
4964 (list org-drawer-regexp '(0 'org-special-keyword t))
4965 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4966 ;; Properties
4967 (list org-property-re
4968 '(1 'org-special-keyword t)
4969 '(3 'org-property-value t))
4970 ;; Links
4971 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4972 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4973 (if (memq 'plain lk) '(org-activate-plain-links))
4974 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4975 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4976 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4977 (if (memq 'footnote lk) '(org-activate-footnote-links
4978 (2 'org-footnote t)))
4979 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4980 '(org-hide-wide-columns (0 nil append))
4981 ;; TODO lines
4982 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4983 '(1 (org-get-todo-face 1) t))
4984 ;; DONE
4985 (if org-fontify-done-headline
4986 (list (concat "^[*]+ +\\<\\("
4987 (mapconcat 'regexp-quote org-done-keywords "\\|")
4988 "\\)\\(.*\\)")
4989 '(2 'org-headline-done t))
4990 nil)
4991 ;; Priorities
4992 '(org-font-lock-add-priority-faces)
4993 ;; Tags
4994 '(org-font-lock-add-tag-faces)
4995 ;; Special keywords
4996 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4997 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4998 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4999 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5000 ;; Emphasis
5001 (if em
5002 (if (featurep 'xemacs)
5003 '(org-do-emphasis-faces (0 nil append))
5004 '(org-do-emphasis-faces)))
5005 ;; Checkboxes
5006 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5007 2 'org-checkbox prepend)
5008 (if org-provide-checkbox-statistics
5009 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5010 (0 (org-get-checkbox-statistics-face) t)))
5011 ;; Description list items
5012 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5013 2 'bold prepend)
5014 ;; ARCHIVEd headings
5015 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5016 '(1 'org-archived prepend))
5017 ;; Specials
5018 '(org-do-latex-and-special-faces)
5019 ;; Code
5020 '(org-activate-code (1 'org-code t))
5021 ;; COMMENT
5022 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5023 "\\|" org-quote-string "\\)\\>")
5024 '(1 'org-special-keyword t))
5025 '("^#.*" (0 'font-lock-comment-face t))
5026 ;; Blocks and meta lines
5027 '(org-fontify-meta-lines-and-blocks)
5029 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5030 ;; Now set the full font-lock-keywords
5031 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5032 (org-set-local 'font-lock-defaults
5033 '(org-font-lock-keywords t nil nil backward-paragraph))
5034 (kill-local-variable 'font-lock-keywords) nil))
5036 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5037 "Fontify string S like in Org-mode"
5038 (with-temp-buffer
5039 (insert s)
5040 (let ((org-odd-levels-only odd-levels))
5041 (org-mode)
5042 (font-lock-fontify-buffer)
5043 (buffer-string))))
5045 (defvar org-m nil)
5046 (defvar org-l nil)
5047 (defvar org-f nil)
5048 (defun org-get-level-face (n)
5049 "Get the right face for match N in font-lock matching of headlines."
5050 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5051 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5052 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5053 (cond
5054 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5055 ((eq n 2) org-f)
5056 (t (if org-level-color-stars-only nil org-f))))
5058 (defun org-get-todo-face (kwd)
5059 "Get the right face for a TODO keyword KWD.
5060 If KWD is a number, get the corresponding match group."
5061 (if (numberp kwd) (setq kwd (match-string kwd)))
5062 (or (cdr (assoc kwd org-todo-keyword-faces))
5063 (and (member kwd org-done-keywords) 'org-done)
5064 'org-todo))
5066 (defun org-font-lock-add-tag-faces (limit)
5067 "Add the special tag faces."
5068 (when (and org-tag-faces org-tags-special-faces-re)
5069 (while (re-search-forward org-tags-special-faces-re limit t)
5070 (add-text-properties (match-beginning 1) (match-end 1)
5071 (list 'face (org-get-tag-face 1)
5072 'font-lock-fontified t))
5073 (backward-char 1))))
5075 (defun org-font-lock-add-priority-faces (limit)
5076 "Add the special priority faces."
5077 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5078 (add-text-properties
5079 (match-beginning 0) (match-end 0)
5080 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5081 org-priority-faces))
5082 'org-special-keyword)
5083 'font-lock-fontified t))))
5085 (defun org-get-tag-face (kwd)
5086 "Get the right face for a TODO keyword KWD.
5087 If KWD is a number, get the corresponding match group."
5088 (if (numberp kwd) (setq kwd (match-string kwd)))
5089 (or (cdr (assoc kwd org-tag-faces))
5090 'org-tag))
5092 (defun org-unfontify-region (beg end &optional maybe_loudly)
5093 "Remove fontification and activation overlays from links."
5094 (font-lock-default-unfontify-region beg end)
5095 (let* ((buffer-undo-list t)
5096 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5097 (inhibit-modification-hooks t)
5098 deactivate-mark buffer-file-name buffer-file-truename)
5099 (remove-text-properties
5100 beg end
5101 (if org-indent-mode
5102 ;; also remove line-prefix and wrap-prefix properties
5103 '(mouse-face t keymap t org-linked-text t
5104 invisible t intangible t
5105 line-prefix t wrap-prefix t
5106 org-no-flyspell t)
5107 '(mouse-face t keymap t org-linked-text t
5108 invisible t intangible t
5109 org-no-flyspell t)))))
5111 ;;;; Visibility cycling, including org-goto and indirect buffer
5113 ;;; Cycling
5115 (defvar org-cycle-global-status nil)
5116 (make-variable-buffer-local 'org-cycle-global-status)
5117 (defvar org-cycle-subtree-status nil)
5118 (make-variable-buffer-local 'org-cycle-subtree-status)
5120 ;;;###autoload
5122 (defvar org-inlinetask-min-level)
5124 (defun org-cycle (&optional arg)
5125 "TAB-action and visibility cycling for Org-mode.
5127 This is the command invoked in Org-mode by the TAB key. Its main purpose
5128 is outline visibility cycling, but it also invokes other actions
5129 in special contexts.
5131 - When this function is called with a prefix argument, rotate the entire
5132 buffer through 3 states (global cycling)
5133 1. OVERVIEW: Show only top-level headlines.
5134 2. CONTENTS: Show all headlines of all levels, but no body text.
5135 3. SHOW ALL: Show everything.
5136 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5137 determined by the variable `org-startup-folded', and by any VISIBILITY
5138 properties in the buffer.
5139 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5140 including any drawers.
5142 - When inside a table, re-align the table and move to the next field.
5144 - When point is at the beginning of a headline, rotate the subtree started
5145 by this line through 3 different states (local cycling)
5146 1. FOLDED: Only the main headline is shown.
5147 2. CHILDREN: The main headline and the direct children are shown.
5148 From this state, you can move to one of the children
5149 and zoom in further.
5150 3. SUBTREE: Show the entire subtree, including body text.
5151 If there is no subtree, switch directly from CHILDREN to FOLDED.
5153 - When point is at the beginning of an empty headline and the variable
5154 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5155 of the headline by demoting and promoting it to likely levels. This
5156 speeds up creation document structure by presing TAB once or several
5157 times right after creating a new headline.
5159 - When there is a numeric prefix, go up to a heading with level ARG, do
5160 a `show-subtree' and return to the previous cursor position. If ARG
5161 is negative, go up that many levels.
5163 - When point is not at the beginning of a headline, execute the global
5164 binding for TAB, which is re-indenting the line. See the option
5165 `org-cycle-emulate-tab' for details.
5167 - Special case: if point is at the beginning of the buffer and there is
5168 no headline in line 1, this function will act as if called with prefix arg.
5169 But only if also the variable `org-cycle-global-at-bob' is t."
5170 (interactive "P")
5171 (org-load-modules-maybe)
5172 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5173 (and org-cycle-level-after-item/entry-creation
5174 (or (org-cycle-level)
5175 (org-cycle-item-indentation))))
5176 (let* ((limit-level
5177 (or org-cycle-max-level
5178 (and (boundp 'org-inlinetask-min-level)
5179 org-inlinetask-min-level
5180 (1- org-inlinetask-min-level))))
5181 (nstars (and limit-level
5182 (if org-odd-levels-only
5183 (and limit-level (1- (* limit-level 2)))
5184 limit-level)))
5185 (outline-regexp
5186 (cond
5187 ((not (org-mode-p)) outline-regexp)
5188 ((or (eq org-cycle-include-plain-lists 'integrate)
5189 (and org-cycle-include-plain-lists (org-at-item-p)))
5190 (concat "\\(?:\\*"
5191 (if nstars (format "\\{1,%d\\}" nstars) "+")
5192 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5193 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5194 (bob-special (and org-cycle-global-at-bob (bobp)
5195 (not (looking-at outline-regexp))))
5196 (org-cycle-hook
5197 (if bob-special
5198 (delq 'org-optimize-window-after-visibility-change
5199 (copy-sequence org-cycle-hook))
5200 org-cycle-hook))
5201 (pos (point)))
5203 (if (or bob-special (equal arg '(4)))
5204 ;; special case: use global cycling
5205 (setq arg t))
5207 (cond
5209 ((equal arg '(16))
5210 (org-set-startup-visibility)
5211 (message "Startup visibility, plus VISIBILITY properties"))
5213 ((equal arg '(64))
5214 (show-all)
5215 (message "Entire buffer visible, including drawers"))
5217 ((org-at-table-p 'any)
5218 ;; Enter the table or move to the next field in the table
5219 (or (org-table-recognize-table.el)
5220 (progn
5221 (if arg (org-table-edit-field t)
5222 (org-table-justify-field-maybe)
5223 (call-interactively 'org-table-next-field)))))
5225 ((run-hook-with-args-until-success
5226 'org-tab-after-check-for-table-hook))
5228 ((eq arg t) ;; Global cycling
5229 (org-cycle-internal-global))
5231 ((and org-drawers org-drawer-regexp
5232 (save-excursion
5233 (beginning-of-line 1)
5234 (looking-at org-drawer-regexp)))
5235 ;; Toggle block visibility
5236 (org-flag-drawer
5237 (not (get-char-property (match-end 0) 'invisible))))
5239 ((integerp arg)
5240 ;; Show-subtree, ARG levels up from here.
5241 (save-excursion
5242 (org-back-to-heading)
5243 (outline-up-heading (if (< arg 0) (- arg)
5244 (- (funcall outline-level) arg)))
5245 (org-show-subtree)))
5247 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5248 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5250 (org-cycle-internal-local))
5252 ;; TAB emulation and template completion
5253 (buffer-read-only (org-back-to-heading))
5255 ((run-hook-with-args-until-success
5256 'org-tab-after-check-for-cycling-hook))
5258 ((org-try-structure-completion))
5260 ((org-try-cdlatex-tab))
5262 ((run-hook-with-args-until-success
5263 'org-tab-before-tab-emulation-hook))
5265 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5266 (or (not (bolp))
5267 (not (looking-at outline-regexp))))
5268 (call-interactively (global-key-binding "\t")))
5270 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5271 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5272 (or (and (eq org-cycle-emulate-tab 'white)
5273 (= (match-end 0) (point-at-eol)))
5274 (and (eq org-cycle-emulate-tab 'whitestart)
5275 (>= (match-end 0) pos))))
5277 (eq org-cycle-emulate-tab t))
5278 (call-interactively (global-key-binding "\t")))
5280 (t (save-excursion
5281 (org-back-to-heading)
5282 (org-cycle)))))))
5284 (defun org-cycle-internal-global ()
5285 "Do the global cycling action."
5286 (cond
5287 ((and (eq last-command this-command)
5288 (eq org-cycle-global-status 'overview))
5289 ;; We just created the overview - now do table of contents
5290 ;; This can be slow in very large buffers, so indicate action
5291 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5292 (message "CONTENTS...")
5293 (org-content)
5294 (message "CONTENTS...done")
5295 (setq org-cycle-global-status 'contents)
5296 (run-hook-with-args 'org-cycle-hook 'contents))
5298 ((and (eq last-command this-command)
5299 (eq org-cycle-global-status 'contents))
5300 ;; We just showed the table of contents - now show everything
5301 (run-hook-with-args 'org-pre-cycle-hook 'all)
5302 (show-all)
5303 (message "SHOW ALL")
5304 (setq org-cycle-global-status 'all)
5305 (run-hook-with-args 'org-cycle-hook 'all))
5308 ;; Default action: go to overview
5309 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5310 (org-overview)
5311 (message "OVERVIEW")
5312 (setq org-cycle-global-status 'overview)
5313 (run-hook-with-args 'org-cycle-hook 'overview))))
5315 (defun org-cycle-internal-local ()
5316 "Do the local cycling action."
5317 (org-back-to-heading)
5318 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5319 ;; First, some boundaries
5320 (save-excursion
5321 (org-back-to-heading)
5322 (setq level (funcall outline-level))
5323 (save-excursion
5324 (beginning-of-line 2)
5325 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5326 ; XEmacs does not have `next-single-char-property-change'
5327 ; I'm not sure about Emacs 21.
5328 (while (and (not (eobp)) ;; this is like `next-line'
5329 (get-char-property (1- (point)) 'invisible))
5330 (beginning-of-line 2))
5331 (while (and (not (eobp)) ;; this is like `next-line'
5332 (get-char-property (1- (point)) 'invisible))
5333 (goto-char (next-single-char-property-change (point) 'invisible))
5334 ;;;??? (or (bolp) (beginning-of-line 2))))
5335 (and (eolp) (beginning-of-line 2))))
5336 (setq eol (point)))
5337 (outline-end-of-heading) (setq eoh (point))
5338 (save-excursion
5339 (outline-next-heading)
5340 (setq has-children (and (org-at-heading-p t)
5341 (> (funcall outline-level) level))))
5342 (org-end-of-subtree t)
5343 (unless (eobp)
5344 (skip-chars-forward " \t\n")
5345 (beginning-of-line 1) ; in case this is an item
5347 (setq eos (if (eobp) (point) (1- (point)))))
5348 ;; Find out what to do next and set `this-command'
5349 (cond
5350 ((= eos eoh)
5351 ;; Nothing is hidden behind this heading
5352 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5353 (message "EMPTY ENTRY")
5354 (setq org-cycle-subtree-status nil)
5355 (save-excursion
5356 (goto-char eos)
5357 (outline-next-heading)
5358 (if (org-invisible-p) (org-flag-heading nil))))
5359 ((and (or (>= eol eos)
5360 (not (string-match "\\S-" (buffer-substring eol eos))))
5361 (or has-children
5362 (not (setq children-skipped
5363 org-cycle-skip-children-state-if-no-children))))
5364 ;; Entire subtree is hidden in one line: children view
5365 (run-hook-with-args 'org-pre-cycle-hook 'children)
5366 (org-show-entry)
5367 (show-children)
5368 (message "CHILDREN")
5369 (save-excursion
5370 (goto-char eos)
5371 (outline-next-heading)
5372 (if (org-invisible-p) (org-flag-heading nil)))
5373 (setq org-cycle-subtree-status 'children)
5374 (run-hook-with-args 'org-cycle-hook 'children))
5375 ((or children-skipped
5376 (and (eq last-command this-command)
5377 (eq org-cycle-subtree-status 'children)))
5378 ;; We just showed the children, or no children are there,
5379 ;; now show everything.
5380 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5381 (org-show-subtree)
5382 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5383 (setq org-cycle-subtree-status 'subtree)
5384 (run-hook-with-args 'org-cycle-hook 'subtree))
5386 ;; Default action: hide the subtree.
5387 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5388 (hide-subtree)
5389 (message "FOLDED")
5390 (setq org-cycle-subtree-status 'folded)
5391 (run-hook-with-args 'org-cycle-hook 'folded)))))
5393 ;;;###autoload
5394 (defun org-global-cycle (&optional arg)
5395 "Cycle the global visibility. For details see `org-cycle'.
5396 With C-u prefix arg, switch to startup visibility.
5397 With a numeric prefix, show all headlines up to that level."
5398 (interactive "P")
5399 (let ((org-cycle-include-plain-lists
5400 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5401 (cond
5402 ((integerp arg)
5403 (show-all)
5404 (hide-sublevels arg)
5405 (setq org-cycle-global-status 'contents))
5406 ((equal arg '(4))
5407 (org-set-startup-visibility)
5408 (message "Startup visibility, plus VISIBILITY properties."))
5410 (org-cycle '(4))))))
5412 (defun org-set-startup-visibility ()
5413 "Set the visibility required by startup options and properties."
5414 (cond
5415 ((eq org-startup-folded t)
5416 (org-cycle '(4)))
5417 ((eq org-startup-folded 'content)
5418 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5419 (org-cycle '(4)) (org-cycle '(4)))))
5420 (unless (eq org-startup-folded 'showeverything)
5421 (if org-hide-block-startup (org-hide-block-all))
5422 (org-set-visibility-according-to-property 'no-cleanup)
5423 (org-cycle-hide-archived-subtrees 'all)
5424 (org-cycle-hide-drawers 'all)
5425 (org-cycle-show-empty-lines 'all)))
5427 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5428 "Switch subtree visibilities according to :VISIBILITY: property."
5429 (interactive)
5430 (let (org-show-entry-below state)
5431 (save-excursion
5432 (goto-char (point-min))
5433 (while (re-search-forward
5434 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5435 nil t)
5436 (setq state (match-string 1))
5437 (save-excursion
5438 (org-back-to-heading t)
5439 (hide-subtree)
5440 (org-reveal)
5441 (cond
5442 ((equal state '("fold" "folded"))
5443 (hide-subtree))
5444 ((equal state "children")
5445 (org-show-hidden-entry)
5446 (show-children))
5447 ((equal state "content")
5448 (save-excursion
5449 (save-restriction
5450 (org-narrow-to-subtree)
5451 (org-content))))
5452 ((member state '("all" "showall"))
5453 (show-subtree)))))
5454 (unless no-cleanup
5455 (org-cycle-hide-archived-subtrees 'all)
5456 (org-cycle-hide-drawers 'all)
5457 (org-cycle-show-empty-lines 'all)))))
5459 (defun org-overview ()
5460 "Switch to overview mode, showing only top-level headlines.
5461 Really, this shows all headlines with level equal or greater than the level
5462 of the first headline in the buffer. This is important, because if the
5463 first headline is not level one, then (hide-sublevels 1) gives confusing
5464 results."
5465 (interactive)
5466 (let ((level (save-excursion
5467 (goto-char (point-min))
5468 (if (re-search-forward (concat "^" outline-regexp) nil t)
5469 (progn
5470 (goto-char (match-beginning 0))
5471 (funcall outline-level))))))
5472 (and level (hide-sublevels level))))
5474 (defun org-content (&optional arg)
5475 "Show all headlines in the buffer, like a table of contents.
5476 With numerical argument N, show content up to level N."
5477 (interactive "P")
5478 (save-excursion
5479 ;; Visit all headings and show their offspring
5480 (and (integerp arg) (org-overview))
5481 (goto-char (point-max))
5482 (catch 'exit
5483 (while (and (progn (condition-case nil
5484 (outline-previous-visible-heading 1)
5485 (error (goto-char (point-min))))
5487 (looking-at outline-regexp))
5488 (if (integerp arg)
5489 (show-children (1- arg))
5490 (show-branches))
5491 (if (bobp) (throw 'exit nil))))))
5494 (defun org-optimize-window-after-visibility-change (state)
5495 "Adjust the window after a change in outline visibility.
5496 This function is the default value of the hook `org-cycle-hook'."
5497 (when (get-buffer-window (current-buffer))
5498 (cond
5499 ((eq state 'content) nil)
5500 ((eq state 'all) nil)
5501 ((eq state 'folded) nil)
5502 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5503 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5505 (defun org-remove-empty-overlays-at (pos)
5506 "Remove outline overlays that do not contain non-white stuff."
5507 (mapc
5508 (lambda (o)
5509 (and (eq 'outline (org-overlay-get o 'invisible))
5510 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5511 (org-overlay-end o))))
5512 (org-delete-overlay o)))
5513 (org-overlays-at pos)))
5515 (defun org-clean-visibility-after-subtree-move ()
5516 "Fix visibility issues after moving a subtree."
5517 ;; First, find a reasonable region to look at:
5518 ;; Start two siblings above, end three below
5519 (let* ((beg (save-excursion
5520 (and (org-get-last-sibling)
5521 (org-get-last-sibling))
5522 (point)))
5523 (end (save-excursion
5524 (and (org-get-next-sibling)
5525 (org-get-next-sibling)
5526 (org-get-next-sibling))
5527 (if (org-at-heading-p)
5528 (point-at-eol)
5529 (point))))
5530 (level (looking-at "\\*+"))
5531 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5532 (save-excursion
5533 (save-restriction
5534 (narrow-to-region beg end)
5535 (when re
5536 ;; Properly fold already folded siblings
5537 (goto-char (point-min))
5538 (while (re-search-forward re nil t)
5539 (if (and (not (org-invisible-p))
5540 (save-excursion
5541 (goto-char (point-at-eol)) (org-invisible-p)))
5542 (hide-entry))))
5543 (org-cycle-show-empty-lines 'overview)
5544 (org-cycle-hide-drawers 'overview)))))
5546 (defun org-cycle-show-empty-lines (state)
5547 "Show empty lines above all visible headlines.
5548 The region to be covered depends on STATE when called through
5549 `org-cycle-hook'. Lisp program can use t for STATE to get the
5550 entire buffer covered. Note that an empty line is only shown if there
5551 are at least `org-cycle-separator-lines' empty lines before the headline."
5552 (when (not (= org-cycle-separator-lines 0))
5553 (save-excursion
5554 (let* ((n (abs org-cycle-separator-lines))
5555 (re (cond
5556 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5557 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5558 (t (let ((ns (number-to-string (- n 2))))
5559 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5560 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5561 beg end b e)
5562 (cond
5563 ((memq state '(overview contents t))
5564 (setq beg (point-min) end (point-max)))
5565 ((memq state '(children folded))
5566 (setq beg (point) end (progn (org-end-of-subtree t t)
5567 (beginning-of-line 2)
5568 (point)))))
5569 (when beg
5570 (goto-char beg)
5571 (while (re-search-forward re end t)
5572 (unless (get-char-property (match-end 1) 'invisible)
5573 (setq e (match-end 1))
5574 (if (< org-cycle-separator-lines 0)
5575 (setq b (save-excursion
5576 (goto-char (match-beginning 0))
5577 (org-back-over-empty-lines)
5578 (if (save-excursion
5579 (goto-char (max (point-min) (1- (point))))
5580 (org-on-heading-p))
5581 (1- (point))
5582 (point))))
5583 (setq b (match-beginning 1)))
5584 (outline-flag-region b e nil)))))))
5585 ;; Never hide empty lines at the end of the file.
5586 (save-excursion
5587 (goto-char (point-max))
5588 (outline-previous-heading)
5589 (outline-end-of-heading)
5590 (if (and (looking-at "[ \t\n]+")
5591 (= (match-end 0) (point-max)))
5592 (outline-flag-region (point) (match-end 0) nil))))
5594 (defun org-show-empty-lines-in-parent ()
5595 "Move to the parent and re-show empty lines before visible headlines."
5596 (save-excursion
5597 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5598 (org-cycle-show-empty-lines context))))
5600 (defun org-files-list ()
5601 "Return `org-agenda-files' list, plus all open org-mode files.
5602 This is useful for operations that need to scan all of a user's
5603 open and agenda-wise Org files."
5604 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5605 (dolist (buf (buffer-list))
5606 (with-current-buffer buf
5607 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5608 (let ((file (expand-file-name (buffer-file-name))))
5609 (unless (member file files)
5610 (push file files))))))
5611 files))
5613 (defsubst org-entry-beginning-position ()
5614 "Return the beginning position of the current entry."
5615 (save-excursion (outline-back-to-heading t) (point)))
5617 (defsubst org-entry-end-position ()
5618 "Return the end position of the current entry."
5619 (save-excursion (outline-next-heading) (point)))
5621 (defun org-cycle-hide-drawers (state)
5622 "Re-hide all drawers after a visibility state change."
5623 (when (and (org-mode-p)
5624 (not (memq state '(overview folded contents))))
5625 (save-excursion
5626 (let* ((globalp (memq state '(contents all)))
5627 (beg (if globalp (point-min) (point)))
5628 (end (if globalp (point-max)
5629 (if (eq state 'children)
5630 (save-excursion (outline-next-heading) (point))
5631 (org-end-of-subtree t)))))
5632 (goto-char beg)
5633 (while (re-search-forward org-drawer-regexp end t)
5634 (org-flag-drawer t))))))
5636 (defun org-flag-drawer (flag)
5637 (save-excursion
5638 (beginning-of-line 1)
5639 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5640 (let ((b (match-end 0))
5641 (outline-regexp org-outline-regexp))
5642 (if (re-search-forward
5643 "^[ \t]*:END:"
5644 (save-excursion (outline-next-heading) (point)) t)
5645 (outline-flag-region b (point-at-eol) flag)
5646 (error ":END: line missing at position %s" b))))))
5648 (defun org-subtree-end-visible-p ()
5649 "Is the end of the current subtree visible?"
5650 (pos-visible-in-window-p
5651 (save-excursion (org-end-of-subtree t) (point))))
5653 (defun org-first-headline-recenter (&optional N)
5654 "Move cursor to the first headline and recenter the headline.
5655 Optional argument N means put the headline into the Nth line of the window."
5656 (goto-char (point-min))
5657 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5658 (beginning-of-line)
5659 (recenter (prefix-numeric-value N))))
5661 ;;; Saving and restoring visibility
5663 (defun org-outline-overlay-data (&optional use-markers)
5664 "Return a list of the locations of all outline overlays.
5665 The are overlays with the `invisible' property value `outline'.
5666 The return valus is a list of cons cells, with start and stop
5667 positions for each overlay.
5668 If USE-MARKERS is set, return the positions as markers."
5669 (let (beg end)
5670 (save-excursion
5671 (save-restriction
5672 (widen)
5673 (delq nil
5674 (mapcar (lambda (o)
5675 (when (eq (org-overlay-get o 'invisible) 'outline)
5676 (setq beg (org-overlay-start o)
5677 end (org-overlay-end o))
5678 (and beg end (> end beg)
5679 (if use-markers
5680 (cons (move-marker (make-marker) beg)
5681 (move-marker (make-marker) end))
5682 (cons beg end)))))
5683 (org-overlays-in (point-min) (point-max))))))))
5685 (defun org-set-outline-overlay-data (data)
5686 "Create visibility overlays for all positions in DATA.
5687 DATA should have been made by `org-outline-overlay-data'."
5688 (let (o)
5689 (save-excursion
5690 (save-restriction
5691 (widen)
5692 (show-all)
5693 (mapc (lambda (c)
5694 (setq o (org-make-overlay (car c) (cdr c)))
5695 (org-overlay-put o 'invisible 'outline))
5696 data)))))
5698 (defmacro org-save-outline-visibility (use-markers &rest body)
5699 "Save and restore outline visibility around BODY.
5700 If USE-MARKERS is non-nil, use markers for the positions.
5701 This means that the buffer may change while running BODY,
5702 but it also means that the buffer should stay alive
5703 during the operation, because otherwise all these markers will
5704 point nowhere."
5705 `(let ((data (org-outline-overlay-data ,use-markers)))
5706 (unwind-protect
5707 (progn
5708 ,@body
5709 (org-set-outline-overlay-data data))
5710 (when ,use-markers
5711 (mapc (lambda (c)
5712 (and (markerp (car c)) (move-marker (car c) nil))
5713 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5714 data)))))
5717 ;;; Folding of blocks
5719 (defconst org-block-regexp
5721 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5722 "Regular expression for hiding blocks.")
5724 (defvar org-hide-block-overlays nil
5725 "Overlays hiding blocks.")
5726 (make-variable-buffer-local 'org-hide-block-overlays)
5728 (defun org-block-map (function &optional start end)
5729 "Call func at the head of all source blocks in the current
5730 buffer. Optional arguments START and END can be used to limit
5731 the range."
5732 (let ((start (or start (point-min)))
5733 (end (or end (point-max))))
5734 (save-excursion
5735 (goto-char start)
5736 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5737 (save-excursion
5738 (save-match-data
5739 (goto-char (match-beginning 0))
5740 (funcall function)))))))
5742 (defun org-hide-block-toggle-all ()
5743 "Toggle the visibility of all blocks in the current buffer."
5744 (org-block-map #'org-hide-block-toggle))
5746 (defun org-hide-block-all ()
5747 "Fold all blocks in the current buffer."
5748 (interactive)
5749 (org-show-block-all)
5750 (org-block-map #'org-hide-block-toggle-maybe))
5752 (defun org-show-block-all ()
5753 "Unfold all blocks in the current buffer."
5754 (mapc 'org-delete-overlay org-hide-block-overlays)
5755 (setq org-hide-block-overlays nil))
5757 (defun org-hide-block-toggle-maybe ()
5758 "Toggle visibility of block at point."
5759 (interactive)
5760 (let ((case-fold-search t))
5761 (if (save-excursion
5762 (beginning-of-line 1)
5763 (looking-at org-block-regexp))
5764 (progn (org-hide-block-toggle)
5765 t) ;; to signal that we took action
5766 nil))) ;; to signal that we did not
5768 (defun org-hide-block-toggle (&optional force)
5769 "Toggle the visibility of the current block."
5770 (interactive)
5771 (save-excursion
5772 (beginning-of-line)
5773 (if (re-search-forward org-block-regexp nil t)
5774 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5775 (end (match-end 0)) ;; end of entire body
5777 (if (memq t (mapcar (lambda (overlay)
5778 (eq (org-overlay-get overlay 'invisible)
5779 'org-hide-block))
5780 (org-overlays-at start)))
5781 (if (or (not force) (eq force 'off))
5782 (mapc (lambda (ov)
5783 (when (member ov org-hide-block-overlays)
5784 (setq org-hide-block-overlays
5785 (delq ov org-hide-block-overlays)))
5786 (when (eq (org-overlay-get ov 'invisible)
5787 'org-hide-block)
5788 (org-delete-overlay ov)))
5789 (org-overlays-at start)))
5790 (setq ov (org-make-overlay start end))
5791 (org-overlay-put ov 'invisible 'org-hide-block)
5792 ;; make the block accessible to isearch
5793 (org-overlay-put
5794 ov 'isearch-open-invisible
5795 (lambda (ov)
5796 (when (member ov org-hide-block-overlays)
5797 (setq org-hide-block-overlays
5798 (delq ov org-hide-block-overlays)))
5799 (when (eq (org-overlay-get ov 'invisible)
5800 'org-hide-block)
5801 (org-delete-overlay ov))))
5802 (push ov org-hide-block-overlays)))
5803 (error "Not looking at a source block"))))
5805 ;; org-tab-after-check-for-cycling-hook
5806 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5807 ;; Remove overlays when changing major mode
5808 (add-hook 'org-mode-hook
5809 (lambda () (org-add-hook 'change-major-mode-hook
5810 'org-show-block-all 'append 'local)))
5812 ;;; Org-goto
5814 (defvar org-goto-window-configuration nil)
5815 (defvar org-goto-marker nil)
5816 (defvar org-goto-map
5817 (let ((map (make-sparse-keymap)))
5818 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5819 (while (setq cmd (pop cmds))
5820 (substitute-key-definition cmd cmd map global-map)))
5821 (suppress-keymap map)
5822 (org-defkey map "\C-m" 'org-goto-ret)
5823 (org-defkey map [(return)] 'org-goto-ret)
5824 (org-defkey map [(left)] 'org-goto-left)
5825 (org-defkey map [(right)] 'org-goto-right)
5826 (org-defkey map [(control ?g)] 'org-goto-quit)
5827 (org-defkey map "\C-i" 'org-cycle)
5828 (org-defkey map [(tab)] 'org-cycle)
5829 (org-defkey map [(down)] 'outline-next-visible-heading)
5830 (org-defkey map [(up)] 'outline-previous-visible-heading)
5831 (if org-goto-auto-isearch
5832 (if (fboundp 'define-key-after)
5833 (define-key-after map [t] 'org-goto-local-auto-isearch)
5834 nil)
5835 (org-defkey map "q" 'org-goto-quit)
5836 (org-defkey map "n" 'outline-next-visible-heading)
5837 (org-defkey map "p" 'outline-previous-visible-heading)
5838 (org-defkey map "f" 'outline-forward-same-level)
5839 (org-defkey map "b" 'outline-backward-same-level)
5840 (org-defkey map "u" 'outline-up-heading))
5841 (org-defkey map "/" 'org-occur)
5842 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5843 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5844 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5845 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5846 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5847 map))
5849 (defconst org-goto-help
5850 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5851 RET=jump to location [Q]uit and return to previous location
5852 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5854 (defvar org-goto-start-pos) ; dynamically scoped parameter
5856 ;; FIXME: Docstring does not mention both interfaces
5857 (defun org-goto (&optional alternative-interface)
5858 "Look up a different location in the current file, keeping current visibility.
5860 When you want look-up or go to a different location in a document, the
5861 fastest way is often to fold the entire buffer and then dive into the tree.
5862 This method has the disadvantage, that the previous location will be folded,
5863 which may not be what you want.
5865 This command works around this by showing a copy of the current buffer
5866 in an indirect buffer, in overview mode. You can dive into the tree in
5867 that copy, use org-occur and incremental search to find a location.
5868 When pressing RET or `Q', the command returns to the original buffer in
5869 which the visibility is still unchanged. After RET is will also jump to
5870 the location selected in the indirect buffer and expose the
5871 the headline hierarchy above."
5872 (interactive "P")
5873 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5874 (org-refile-use-outline-path t)
5875 (org-refile-target-verify-function nil)
5876 (interface
5877 (if (not alternative-interface)
5878 org-goto-interface
5879 (if (eq org-goto-interface 'outline)
5880 'outline-path-completion
5881 'outline)))
5882 (org-goto-start-pos (point))
5883 (selected-point
5884 (if (eq interface 'outline)
5885 (car (org-get-location (current-buffer) org-goto-help))
5886 (nth 3 (org-refile-get-location "Goto: ")))))
5887 (if selected-point
5888 (progn
5889 (org-mark-ring-push org-goto-start-pos)
5890 (goto-char selected-point)
5891 (if (or (org-invisible-p) (org-invisible-p2))
5892 (org-show-context 'org-goto)))
5893 (message "Quit"))))
5895 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5896 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5897 (defvar org-goto-local-auto-isearch-map) ; defined below
5899 (defun org-get-location (buf help)
5900 "Let the user select a location in the Org-mode buffer BUF.
5901 This function uses a recursive edit. It returns the selected position
5902 or nil."
5903 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5904 (isearch-hide-immediately nil)
5905 (isearch-search-fun-function
5906 (lambda () 'org-goto-local-search-headings))
5907 (org-goto-selected-point org-goto-exit-command)
5908 (pop-up-frames nil)
5909 (special-display-buffer-names nil)
5910 (special-display-regexps nil)
5911 (special-display-function nil))
5912 (save-excursion
5913 (save-window-excursion
5914 (delete-other-windows)
5915 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5916 (switch-to-buffer
5917 (condition-case nil
5918 (make-indirect-buffer (current-buffer) "*org-goto*")
5919 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5920 (with-output-to-temp-buffer "*Help*"
5921 (princ help))
5922 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5923 (setq buffer-read-only nil)
5924 (let ((org-startup-truncated t)
5925 (org-startup-folded nil)
5926 (org-startup-align-all-tables nil))
5927 (org-mode)
5928 (org-overview))
5929 (setq buffer-read-only t)
5930 (if (and (boundp 'org-goto-start-pos)
5931 (integer-or-marker-p org-goto-start-pos))
5932 (let ((org-show-hierarchy-above t)
5933 (org-show-siblings t)
5934 (org-show-following-heading t))
5935 (goto-char org-goto-start-pos)
5936 (and (org-invisible-p) (org-show-context)))
5937 (goto-char (point-min)))
5938 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5939 (message "Select location and press RET")
5940 (use-local-map org-goto-map)
5941 (recursive-edit)
5943 (kill-buffer "*org-goto*")
5944 (cons org-goto-selected-point org-goto-exit-command)))
5946 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5947 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5948 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5949 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5951 (defun org-goto-local-search-headings (string bound noerror)
5952 "Search and make sure that any matches are in headlines."
5953 (catch 'return
5954 (while (if isearch-forward
5955 (search-forward string bound noerror)
5956 (search-backward string bound noerror))
5957 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5958 (and (member :headline context)
5959 (not (member :tags context))))
5960 (throw 'return (point))))))
5962 (defun org-goto-local-auto-isearch ()
5963 "Start isearch."
5964 (interactive)
5965 (goto-char (point-min))
5966 (let ((keys (this-command-keys)))
5967 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5968 (isearch-mode t)
5969 (isearch-process-search-char (string-to-char keys)))))
5971 (defun org-goto-ret (&optional arg)
5972 "Finish `org-goto' by going to the new location."
5973 (interactive "P")
5974 (setq org-goto-selected-point (point)
5975 org-goto-exit-command 'return)
5976 (throw 'exit nil))
5978 (defun org-goto-left ()
5979 "Finish `org-goto' by going to the new location."
5980 (interactive)
5981 (if (org-on-heading-p)
5982 (progn
5983 (beginning-of-line 1)
5984 (setq org-goto-selected-point (point)
5985 org-goto-exit-command 'left)
5986 (throw 'exit nil))
5987 (error "Not on a heading")))
5989 (defun org-goto-right ()
5990 "Finish `org-goto' by going to the new location."
5991 (interactive)
5992 (if (org-on-heading-p)
5993 (progn
5994 (setq org-goto-selected-point (point)
5995 org-goto-exit-command 'right)
5996 (throw 'exit nil))
5997 (error "Not on a heading")))
5999 (defun org-goto-quit ()
6000 "Finish `org-goto' without cursor motion."
6001 (interactive)
6002 (setq org-goto-selected-point nil)
6003 (setq org-goto-exit-command 'quit)
6004 (throw 'exit nil))
6006 ;;; Indirect buffer display of subtrees
6008 (defvar org-indirect-dedicated-frame nil
6009 "This is the frame being used for indirect tree display.")
6010 (defvar org-last-indirect-buffer nil)
6012 (defun org-tree-to-indirect-buffer (&optional arg)
6013 "Create indirect buffer and narrow it to current subtree.
6014 With numerical prefix ARG, go up to this level and then take that tree.
6015 If ARG is negative, go up that many levels.
6016 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6017 indirect buffer previously made with this command, to avoid proliferation of
6018 indirect buffers. However, when you call the command with a `C-u' prefix, or
6019 when `org-indirect-buffer-display' is `new-frame', the last buffer
6020 is kept so that you can work with several indirect buffers at the same time.
6021 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6022 requests that a new frame be made for the new buffer, so that the dedicated
6023 frame is not changed."
6024 (interactive "P")
6025 (let ((cbuf (current-buffer))
6026 (cwin (selected-window))
6027 (pos (point))
6028 beg end level heading ibuf)
6029 (save-excursion
6030 (org-back-to-heading t)
6031 (when (numberp arg)
6032 (setq level (org-outline-level))
6033 (if (< arg 0) (setq arg (+ level arg)))
6034 (while (> (setq level (org-outline-level)) arg)
6035 (outline-up-heading 1 t)))
6036 (setq beg (point)
6037 heading (org-get-heading))
6038 (org-end-of-subtree t t)
6039 (if (org-on-heading-p) (backward-char 1))
6040 (setq end (point)))
6041 (if (and (buffer-live-p org-last-indirect-buffer)
6042 (not (eq org-indirect-buffer-display 'new-frame))
6043 (not arg))
6044 (kill-buffer org-last-indirect-buffer))
6045 (setq ibuf (org-get-indirect-buffer cbuf)
6046 org-last-indirect-buffer ibuf)
6047 (cond
6048 ((or (eq org-indirect-buffer-display 'new-frame)
6049 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6050 (select-frame (make-frame))
6051 (delete-other-windows)
6052 (switch-to-buffer ibuf)
6053 (org-set-frame-title heading))
6054 ((eq org-indirect-buffer-display 'dedicated-frame)
6055 (raise-frame
6056 (select-frame (or (and org-indirect-dedicated-frame
6057 (frame-live-p org-indirect-dedicated-frame)
6058 org-indirect-dedicated-frame)
6059 (setq org-indirect-dedicated-frame (make-frame)))))
6060 (delete-other-windows)
6061 (switch-to-buffer ibuf)
6062 (org-set-frame-title (concat "Indirect: " heading)))
6063 ((eq org-indirect-buffer-display 'current-window)
6064 (switch-to-buffer ibuf))
6065 ((eq org-indirect-buffer-display 'other-window)
6066 (pop-to-buffer ibuf))
6067 (t (error "Invalid value")))
6068 (if (featurep 'xemacs)
6069 (save-excursion (org-mode) (turn-on-font-lock)))
6070 (narrow-to-region beg end)
6071 (show-all)
6072 (goto-char pos)
6073 (and (window-live-p cwin) (select-window cwin))))
6075 (defun org-get-indirect-buffer (&optional buffer)
6076 (setq buffer (or buffer (current-buffer)))
6077 (let ((n 1) (base (buffer-name buffer)) bname)
6078 (while (buffer-live-p
6079 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6080 (setq n (1+ n)))
6081 (condition-case nil
6082 (make-indirect-buffer buffer bname 'clone)
6083 (error (make-indirect-buffer buffer bname)))))
6085 (defun org-set-frame-title (title)
6086 "Set the title of the current frame to the string TITLE."
6087 ;; FIXME: how to name a single frame in XEmacs???
6088 (unless (featurep 'xemacs)
6089 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6091 ;;;; Structure editing
6093 ;;; Inserting headlines
6095 (defun org-previous-line-empty-p ()
6096 (save-excursion
6097 (and (not (bobp))
6098 (or (beginning-of-line 0) t)
6099 (save-match-data
6100 (looking-at "[ \t]*$")))))
6102 (defun org-insert-heading (&optional force-heading invisible-ok)
6103 "Insert a new heading or item with same depth at point.
6104 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6105 If point is at the beginning of a headline, insert a sibling before the
6106 current headline. If point is not at the beginning, do not split the line,
6107 but create the new headline after the current line.
6108 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6109 This is important for non-interactive uses of the command."
6110 (interactive "P")
6111 (if (or (= (buffer-size) 0)
6112 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6113 (org-on-heading-p))))
6114 (not (org-in-item-p))))
6115 (insert "\n* ")
6116 (when (or force-heading (not (org-insert-item)))
6117 (let* ((empty-line-p nil)
6118 (head (save-excursion
6119 (condition-case nil
6120 (progn
6121 (org-back-to-heading invisible-ok)
6122 (setq empty-line-p (org-previous-line-empty-p))
6123 (match-string 0))
6124 (error "*"))))
6125 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6126 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6127 pos hide-previous previous-pos)
6128 (cond
6129 ((and (org-on-heading-p) (bolp)
6130 (or (bobp)
6131 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6132 ;; insert before the current line
6133 (open-line (if blank 2 1)))
6134 ((and (bolp)
6135 (not org-insert-heading-respect-content)
6136 (or (bobp)
6137 (save-excursion
6138 (backward-char 1) (not (org-invisible-p)))))
6139 ;; insert right here
6140 nil)
6142 ;; somewhere in the line
6143 (save-excursion
6144 (setq previous-pos (point-at-bol))
6145 (end-of-line)
6146 (setq hide-previous (org-invisible-p)))
6147 (and org-insert-heading-respect-content (org-show-subtree))
6148 (let ((split
6149 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6150 (save-excursion
6151 (let ((p (point)))
6152 (goto-char (point-at-bol))
6153 (and (looking-at org-complex-heading-regexp)
6154 (> p (match-beginning 4)))))))
6155 tags pos)
6156 (cond
6157 (org-insert-heading-respect-content
6158 (org-end-of-subtree nil t)
6159 (or (bolp) (newline))
6160 (or (org-previous-line-empty-p)
6161 (and blank (newline)))
6162 (open-line 1))
6163 ((org-on-heading-p)
6164 (when hide-previous
6165 (show-children)
6166 (org-show-entry))
6167 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6168 (setq tags (and (match-end 2) (match-string 2)))
6169 (and (match-end 1)
6170 (delete-region (match-beginning 1) (match-end 1)))
6171 (setq pos (point-at-bol))
6172 (or split (end-of-line 1))
6173 (delete-horizontal-space)
6174 (newline (if blank 2 1))
6175 (when tags
6176 (save-excursion
6177 (goto-char pos)
6178 (end-of-line 1)
6179 (insert " " tags)
6180 (org-set-tags nil 'align))))
6182 (or split (end-of-line 1))
6183 (newline (if blank 2 1)))))))
6184 (insert head) (just-one-space)
6185 (setq pos (point))
6186 (end-of-line 1)
6187 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6188 (when (and org-insert-heading-respect-content hide-previous)
6189 (save-excursion
6190 (goto-char previous-pos)
6191 (hide-subtree)))
6192 (run-hooks 'org-insert-heading-hook)))))
6194 (defun org-get-heading (&optional no-tags)
6195 "Return the heading of the current entry, without the stars."
6196 (save-excursion
6197 (org-back-to-heading t)
6198 (if (looking-at
6199 (if no-tags
6200 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6201 "\\*+[ \t]+\\([^\r\n]*\\)"))
6202 (match-string 1) "")))
6204 (defun org-heading-components ()
6205 "Return the components of the current heading.
6206 This is a list with the following elements:
6207 - the level as an integer
6208 - the reduced level, different if `org-odd-levels-only' is set.
6209 - the TODO keyword, or nil
6210 - the priority character, like ?A, or nil if no priority is given
6211 - the headline text itself, or the tags string if no headline text
6212 - the tags string, or nil."
6213 (save-excursion
6214 (org-back-to-heading t)
6215 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6216 (list (length (match-string 1))
6217 (org-reduced-level (length (match-string 1)))
6218 (org-match-string-no-properties 2)
6219 (and (match-end 3) (aref (match-string 3) 2))
6220 (org-match-string-no-properties 4)
6221 (org-match-string-no-properties 5)))))
6223 (defun org-get-entry ()
6224 "Get the entry text, after heading, entire subtree."
6225 (save-excursion
6226 (org-back-to-heading t)
6227 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6229 (defun org-insert-heading-after-current ()
6230 "Insert a new heading with same level as current, after current subtree."
6231 (interactive)
6232 (org-back-to-heading)
6233 (org-insert-heading)
6234 (org-move-subtree-down)
6235 (end-of-line 1))
6237 (defun org-insert-heading-respect-content ()
6238 (interactive)
6239 (let ((org-insert-heading-respect-content t))
6240 (org-insert-heading t)))
6242 (defun org-insert-todo-heading-respect-content (&optional force-state)
6243 (interactive "P")
6244 (let ((org-insert-heading-respect-content t))
6245 (org-insert-todo-heading force-state t)))
6247 (defun org-insert-todo-heading (arg &optional force-heading)
6248 "Insert a new heading with the same level and TODO state as current heading.
6249 If the heading has no TODO state, or if the state is DONE, use the first
6250 state (TODO by default). Also with prefix arg, force first state."
6251 (interactive "P")
6252 (when (or force-heading (not (org-insert-item 'checkbox)))
6253 (org-insert-heading force-heading)
6254 (save-excursion
6255 (org-back-to-heading)
6256 (outline-previous-heading)
6257 (looking-at org-todo-line-regexp))
6258 (let*
6259 ((new-mark-x
6260 (if (or arg
6261 (not (match-beginning 2))
6262 (member (match-string 2) org-done-keywords))
6263 (car org-todo-keywords-1)
6264 (match-string 2)))
6265 (new-mark
6267 (run-hook-with-args-until-success
6268 'org-todo-get-default-hook new-mark-x nil)
6269 new-mark-x)))
6270 (beginning-of-line 1)
6271 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6272 (if org-treat-insert-todo-heading-as-state-change
6273 (org-todo new-mark)
6274 (insert new-mark " "))))
6275 (when org-provide-todo-statistics
6276 (org-update-parent-todo-statistics))))
6278 (defun org-insert-subheading (arg)
6279 "Insert a new subheading and demote it.
6280 Works for outline headings and for plain lists alike."
6281 (interactive "P")
6282 (org-insert-heading arg)
6283 (cond
6284 ((org-on-heading-p) (org-do-demote))
6285 ((org-at-item-p) (org-indent-item 1))))
6287 (defun org-insert-todo-subheading (arg)
6288 "Insert a new subheading with TODO keyword or checkbox and demote it.
6289 Works for outline headings and for plain lists alike."
6290 (interactive "P")
6291 (org-insert-todo-heading arg)
6292 (cond
6293 ((org-on-heading-p) (org-do-demote))
6294 ((org-at-item-p) (org-indent-item 1))))
6296 ;;; Promotion and Demotion
6298 (defvar org-after-demote-entry-hook nil
6299 "Hook run after an entry has been demoted.
6300 The cursor will be at the beginning of the entry.
6301 When a subtree is being demoted, the hook will be called for each node.")
6303 (defvar org-after-promote-entry-hook nil
6304 "Hook run after an entry has been promoted.
6305 The cursor will be at the beginning of the entry.
6306 When a subtree is being promoted, the hook will be called for each node.")
6308 (defun org-promote-subtree ()
6309 "Promote the entire subtree.
6310 See also `org-promote'."
6311 (interactive)
6312 (save-excursion
6313 (org-map-tree 'org-promote))
6314 (org-fix-position-after-promote))
6316 (defun org-demote-subtree ()
6317 "Demote the entire subtree. See `org-demote'.
6318 See also `org-promote'."
6319 (interactive)
6320 (save-excursion
6321 (org-map-tree 'org-demote))
6322 (org-fix-position-after-promote))
6325 (defun org-do-promote ()
6326 "Promote the current heading higher up the tree.
6327 If the region is active in `transient-mark-mode', promote all headings
6328 in the region."
6329 (interactive)
6330 (save-excursion
6331 (if (org-region-active-p)
6332 (org-map-region 'org-promote (region-beginning) (region-end))
6333 (org-promote)))
6334 (org-fix-position-after-promote))
6336 (defun org-do-demote ()
6337 "Demote the current heading lower down the tree.
6338 If the region is active in `transient-mark-mode', demote all headings
6339 in the region."
6340 (interactive)
6341 (save-excursion
6342 (if (org-region-active-p)
6343 (org-map-region 'org-demote (region-beginning) (region-end))
6344 (org-demote)))
6345 (org-fix-position-after-promote))
6347 (defun org-fix-position-after-promote ()
6348 "Make sure that after pro/demotion cursor position is right."
6349 (let ((pos (point)))
6350 (when (save-excursion
6351 (beginning-of-line 1)
6352 (looking-at org-todo-line-regexp)
6353 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6354 (cond ((eobp) (insert " "))
6355 ((eolp) (insert " "))
6356 ((equal (char-after) ?\ ) (forward-char 1))))))
6358 (defun org-current-level ()
6359 "Return the level of the current entry, or nil if before the first headline.
6360 The level is the number of stars at the beginning of the headline."
6361 (save-excursion
6362 (condition-case nil
6363 (progn
6364 (org-back-to-heading t)
6365 (funcall outline-level))
6366 (error nil))))
6368 (defun org-reduced-level (l)
6369 "Compute the effective level of a heading.
6370 This takes into account the setting of `org-odd-levels-only'."
6371 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6373 (defun org-get-valid-level (level &optional change)
6374 "Rectify a level change under the influence of `org-odd-levels-only'
6375 LEVEL is a current level, CHANGE is by how much the level should be
6376 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6377 even level numbers will become the next higher odd number."
6378 (if org-odd-levels-only
6379 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6380 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6381 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6382 (max 1 (+ level (or change 0)))))
6384 (if (boundp 'define-obsolete-function-alias)
6385 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6386 (define-obsolete-function-alias 'org-get-legal-level
6387 'org-get-valid-level)
6388 (define-obsolete-function-alias 'org-get-legal-level
6389 'org-get-valid-level "23.1")))
6391 (defun org-promote ()
6392 "Promote the current heading higher up the tree.
6393 If the region is active in `transient-mark-mode', promote all headings
6394 in the region."
6395 (org-back-to-heading t)
6396 (let* ((level (save-match-data (funcall outline-level)))
6397 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6398 (diff (abs (- level (length up-head) -1))))
6399 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6400 (replace-match up-head nil t)
6401 ;; Fixup tag positioning
6402 (and org-auto-align-tags (org-set-tags nil t))
6403 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6404 (run-hooks 'org-after-promote-entry-hook)))
6406 (defun org-demote ()
6407 "Demote the current heading lower down the tree.
6408 If the region is active in `transient-mark-mode', demote all headings
6409 in the region."
6410 (org-back-to-heading t)
6411 (let* ((level (save-match-data (funcall outline-level)))
6412 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6413 (diff (abs (- level (length down-head) -1))))
6414 (replace-match down-head nil t)
6415 ;; Fixup tag positioning
6416 (and org-auto-align-tags (org-set-tags nil t))
6417 (if org-adapt-indentation (org-fixup-indentation diff))
6418 (run-hooks 'org-after-demote-entry-hook)))
6420 (defvar org-tab-ind-state nil)
6422 (defun org-cycle-level ()
6423 (let ((org-adapt-indentation nil))
6424 (when (and (looking-at "[ \t]*$")
6425 (org-looking-back
6426 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6427 (setq this-command 'org-cycle-level)
6428 (if (eq last-command 'org-cycle-level)
6429 (condition-case nil
6430 (progn (org-do-promote)
6431 (if (equal org-tab-ind-state (org-current-level))
6432 (org-do-promote)))
6433 (error
6434 (progn
6435 (save-excursion
6436 (beginning-of-line 1)
6437 (and (looking-at "\\*+")
6438 (replace-match
6439 (make-string org-tab-ind-state ?*))))
6440 (setq this-command 'org-cycle))))
6441 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6442 (org-do-demote))
6443 t)))
6445 (defun org-map-tree (fun)
6446 "Call FUN for every heading underneath the current one."
6447 (org-back-to-heading)
6448 (let ((level (funcall outline-level)))
6449 (save-excursion
6450 (funcall fun)
6451 (while (and (progn
6452 (outline-next-heading)
6453 (> (funcall outline-level) level))
6454 (not (eobp)))
6455 (funcall fun)))))
6457 (defun org-map-region (fun beg end)
6458 "Call FUN for every heading between BEG and END."
6459 (let ((org-ignore-region t))
6460 (save-excursion
6461 (setq end (copy-marker end))
6462 (goto-char beg)
6463 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6464 (< (point) end))
6465 (funcall fun))
6466 (while (and (progn
6467 (outline-next-heading)
6468 (< (point) end))
6469 (not (eobp)))
6470 (funcall fun)))))
6472 (defun org-fixup-indentation (diff)
6473 "Change the indentation in the current entry by DIFF
6474 However, if any line in the current entry has no indentation, or if it
6475 would end up with no indentation after the change, nothing at all is done."
6476 (save-excursion
6477 (let ((end (save-excursion (outline-next-heading)
6478 (point-marker)))
6479 (prohibit (if (> diff 0)
6480 "^\\S-"
6481 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6482 col)
6483 (unless (save-excursion (end-of-line 1)
6484 (re-search-forward prohibit end t))
6485 (while (and (< (point) end)
6486 (re-search-forward "^[ \t]+" end t))
6487 (goto-char (match-end 0))
6488 (setq col (current-column))
6489 (if (< diff 0) (replace-match ""))
6490 (org-indent-to-column (+ diff col))))
6491 (move-marker end nil))))
6493 (defun org-convert-to-odd-levels ()
6494 "Convert an org-mode file with all levels allowed to one with odd levels.
6495 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6496 level 5 etc."
6497 (interactive)
6498 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6499 (let ((outline-regexp org-outline-regexp)
6500 (outline-level 'org-outline-level)
6501 (org-odd-levels-only nil) n)
6502 (save-excursion
6503 (goto-char (point-min))
6504 (while (re-search-forward "^\\*\\*+ " nil t)
6505 (setq n (- (length (match-string 0)) 2))
6506 (while (>= (setq n (1- n)) 0)
6507 (org-demote))
6508 (end-of-line 1))))))
6510 (defun org-convert-to-oddeven-levels ()
6511 "Convert an org-mode file with only odd levels to one with odd and even levels.
6512 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6513 section with an even level, conversion would destroy the structure of the file. An error
6514 is signaled in this case."
6515 (interactive)
6516 (goto-char (point-min))
6517 ;; First check if there are no even levels
6518 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6519 (org-show-context t)
6520 (error "Not all levels are odd in this file. Conversion not possible"))
6521 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6522 (let ((outline-regexp org-outline-regexp)
6523 (outline-level 'org-outline-level)
6524 (org-odd-levels-only nil) n)
6525 (save-excursion
6526 (goto-char (point-min))
6527 (while (re-search-forward "^\\*\\*+ " nil t)
6528 (setq n (/ (1- (length (match-string 0))) 2))
6529 (while (>= (setq n (1- n)) 0)
6530 (org-promote))
6531 (end-of-line 1))))))
6533 (defun org-tr-level (n)
6534 "Make N odd if required."
6535 (if org-odd-levels-only (1+ (/ n 2)) n))
6537 ;;; Vertical tree motion, cutting and pasting of subtrees
6539 (defun org-move-subtree-up (&optional arg)
6540 "Move the current subtree up past ARG headlines of the same level."
6541 (interactive "p")
6542 (org-move-subtree-down (- (prefix-numeric-value arg))))
6544 (defun org-move-subtree-down (&optional arg)
6545 "Move the current subtree down past ARG headlines of the same level."
6546 (interactive "p")
6547 (setq arg (prefix-numeric-value arg))
6548 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6549 'org-get-last-sibling))
6550 (ins-point (make-marker))
6551 (cnt (abs arg))
6552 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6553 ;; Select the tree
6554 (org-back-to-heading)
6555 (setq beg0 (point))
6556 (save-excursion
6557 (setq ne-beg (org-back-over-empty-lines))
6558 (setq beg (point)))
6559 (save-match-data
6560 (save-excursion (outline-end-of-heading)
6561 (setq folded (org-invisible-p)))
6562 (outline-end-of-subtree))
6563 (outline-next-heading)
6564 (setq ne-end (org-back-over-empty-lines))
6565 (setq end (point))
6566 (goto-char beg0)
6567 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6568 ;; include less whitespace
6569 (save-excursion
6570 (goto-char beg)
6571 (forward-line (- ne-beg ne-end))
6572 (setq beg (point))))
6573 ;; Find insertion point, with error handling
6574 (while (> cnt 0)
6575 (or (and (funcall movfunc) (looking-at outline-regexp))
6576 (progn (goto-char beg0)
6577 (error "Cannot move past superior level or buffer limit")))
6578 (setq cnt (1- cnt)))
6579 (if (> arg 0)
6580 ;; Moving forward - still need to move over subtree
6581 (progn (org-end-of-subtree t t)
6582 (save-excursion
6583 (org-back-over-empty-lines)
6584 (or (bolp) (newline)))))
6585 (setq ne-ins (org-back-over-empty-lines))
6586 (move-marker ins-point (point))
6587 (setq txt (buffer-substring beg end))
6588 (org-save-markers-in-region beg end)
6589 (delete-region beg end)
6590 (org-remove-empty-overlays-at beg)
6591 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6592 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6593 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6594 (let ((bbb (point)))
6595 (insert-before-markers txt)
6596 (org-reinstall-markers-in-region bbb)
6597 (move-marker ins-point bbb))
6598 (or (bolp) (insert "\n"))
6599 (setq ins-end (point))
6600 (goto-char ins-point)
6601 (org-skip-whitespace)
6602 (when (and (< arg 0)
6603 (org-first-sibling-p)
6604 (> ne-ins ne-beg))
6605 ;; Move whitespace back to beginning
6606 (save-excursion
6607 (goto-char ins-end)
6608 (let ((kill-whole-line t))
6609 (kill-line (- ne-ins ne-beg)) (point)))
6610 (insert (make-string (- ne-ins ne-beg) ?\n)))
6611 (move-marker ins-point nil)
6612 (if folded
6613 (hide-subtree)
6614 (org-show-entry)
6615 (show-children)
6616 (org-cycle-hide-drawers 'children))
6617 (org-clean-visibility-after-subtree-move)))
6619 (defvar org-subtree-clip ""
6620 "Clipboard for cut and paste of subtrees.
6621 This is actually only a copy of the kill, because we use the normal kill
6622 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6624 (defvar org-subtree-clip-folded nil
6625 "Was the last copied subtree folded?
6626 This is used to fold the tree back after pasting.")
6628 (defun org-cut-subtree (&optional n)
6629 "Cut the current subtree into the clipboard.
6630 With prefix arg N, cut this many sequential subtrees.
6631 This is a short-hand for marking the subtree and then cutting it."
6632 (interactive "p")
6633 (org-copy-subtree n 'cut))
6635 (defun org-copy-subtree (&optional n cut force-store-markers)
6636 "Cut the current subtree into the clipboard.
6637 With prefix arg N, cut this many sequential subtrees.
6638 This is a short-hand for marking the subtree and then copying it.
6639 If CUT is non-nil, actually cut the subtree.
6640 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6641 of some markers in the region, even if CUT is non-nil. This is
6642 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6643 (interactive "p")
6644 (let (beg end folded (beg0 (point)))
6645 (if (interactive-p)
6646 (org-back-to-heading nil) ; take what looks like a subtree
6647 (org-back-to-heading t)) ; take what is really there
6648 (org-back-over-empty-lines)
6649 (setq beg (point))
6650 (skip-chars-forward " \t\r\n")
6651 (save-match-data
6652 (save-excursion (outline-end-of-heading)
6653 (setq folded (org-invisible-p)))
6654 (condition-case nil
6655 (org-forward-same-level (1- n) t)
6656 (error nil))
6657 (org-end-of-subtree t t))
6658 (org-back-over-empty-lines)
6659 (setq end (point))
6660 (goto-char beg0)
6661 (when (> end beg)
6662 (setq org-subtree-clip-folded folded)
6663 (when (or cut force-store-markers)
6664 (org-save-markers-in-region beg end))
6665 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6666 (setq org-subtree-clip (current-kill 0))
6667 (message "%s: Subtree(s) with %d characters"
6668 (if cut "Cut" "Copied")
6669 (length org-subtree-clip)))))
6671 (defun org-paste-subtree (&optional level tree for-yank)
6672 "Paste the clipboard as a subtree, with modification of headline level.
6673 The entire subtree is promoted or demoted in order to match a new headline
6674 level.
6676 If the cursor is at the beginning of a headline, the same level as
6677 that headline is used to paste the tree
6679 If not, the new level is derived from the *visible* headings
6680 before and after the insertion point, and taken to be the inferior headline
6681 level of the two. So if the previous visible heading is level 3 and the
6682 next is level 4 (or vice versa), level 4 will be used for insertion.
6683 This makes sure that the subtree remains an independent subtree and does
6684 not swallow low level entries.
6686 You can also force a different level, either by using a numeric prefix
6687 argument, or by inserting the heading marker by hand. For example, if the
6688 cursor is after \"*****\", then the tree will be shifted to level 5.
6690 If optional TREE is given, use this text instead of the kill ring.
6692 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6693 move back over whitespace before inserting, and move point to the end of
6694 the inserted text when done."
6695 (interactive "P")
6696 (setq tree (or tree (and kill-ring (current-kill 0))))
6697 (unless (org-kill-is-subtree-p tree)
6698 (error "%s"
6699 (substitute-command-keys
6700 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6701 (let* ((visp (not (org-invisible-p)))
6702 (txt tree)
6703 (^re (concat "^\\(" outline-regexp "\\)"))
6704 (re (concat "\\(" outline-regexp "\\)"))
6705 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6707 (old-level (if (string-match ^re txt)
6708 (- (match-end 0) (match-beginning 0) 1)
6709 -1))
6710 (force-level (cond (level (prefix-numeric-value level))
6711 ((and (looking-at "[ \t]*$")
6712 (string-match
6713 ^re_ (buffer-substring
6714 (point-at-bol) (point))))
6715 (- (match-end 1) (match-beginning 1)))
6716 ((and (bolp)
6717 (looking-at org-outline-regexp))
6718 (- (match-end 0) (point) 1))
6719 (t nil)))
6720 (previous-level (save-excursion
6721 (condition-case nil
6722 (progn
6723 (outline-previous-visible-heading 1)
6724 (if (looking-at re)
6725 (- (match-end 0) (match-beginning 0) 1)
6727 (error 1))))
6728 (next-level (save-excursion
6729 (condition-case nil
6730 (progn
6731 (or (looking-at outline-regexp)
6732 (outline-next-visible-heading 1))
6733 (if (looking-at re)
6734 (- (match-end 0) (match-beginning 0) 1)
6736 (error 1))))
6737 (new-level (or force-level (max previous-level next-level)))
6738 (shift (if (or (= old-level -1)
6739 (= new-level -1)
6740 (= old-level new-level))
6742 (- new-level old-level)))
6743 (delta (if (> shift 0) -1 1))
6744 (func (if (> shift 0) 'org-demote 'org-promote))
6745 (org-odd-levels-only nil)
6746 beg end newend)
6747 ;; Remove the forced level indicator
6748 (if force-level
6749 (delete-region (point-at-bol) (point)))
6750 ;; Paste
6751 (beginning-of-line 1)
6752 (unless for-yank (org-back-over-empty-lines))
6753 (setq beg (point))
6754 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6755 (insert-before-markers txt)
6756 (unless (string-match "\n\\'" txt) (insert "\n"))
6757 (setq newend (point))
6758 (org-reinstall-markers-in-region beg)
6759 (setq end (point))
6760 (goto-char beg)
6761 (skip-chars-forward " \t\n\r")
6762 (setq beg (point))
6763 (if (and (org-invisible-p) visp)
6764 (save-excursion (outline-show-heading)))
6765 ;; Shift if necessary
6766 (unless (= shift 0)
6767 (save-restriction
6768 (narrow-to-region beg end)
6769 (while (not (= shift 0))
6770 (org-map-region func (point-min) (point-max))
6771 (setq shift (+ delta shift)))
6772 (goto-char (point-min))
6773 (setq newend (point-max))))
6774 (when (or (interactive-p) for-yank)
6775 (message "Clipboard pasted as level %d subtree" new-level))
6776 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6777 kill-ring
6778 (eq org-subtree-clip (current-kill 0))
6779 org-subtree-clip-folded)
6780 ;; The tree was folded before it was killed/copied
6781 (hide-subtree))
6782 (and for-yank (goto-char newend))))
6784 (defun org-kill-is-subtree-p (&optional txt)
6785 "Check if the current kill is an outline subtree, or a set of trees.
6786 Returns nil if kill does not start with a headline, or if the first
6787 headline level is not the largest headline level in the tree.
6788 So this will actually accept several entries of equal levels as well,
6789 which is OK for `org-paste-subtree'.
6790 If optional TXT is given, check this string instead of the current kill."
6791 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6792 (start-level (and kill
6793 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6794 org-outline-regexp "\\)")
6795 kill)
6796 (- (match-end 2) (match-beginning 2) 1)))
6797 (re (concat "^" org-outline-regexp))
6798 (start (1+ (or (match-beginning 2) -1))))
6799 (if (not start-level)
6800 (progn
6801 nil) ;; does not even start with a heading
6802 (catch 'exit
6803 (while (setq start (string-match re kill (1+ start)))
6804 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6805 (throw 'exit nil)))
6806 t))))
6808 (defvar org-markers-to-move nil
6809 "Markers that should be moved with a cut-and-paste operation.
6810 Those markers are stored together with their positions relative to
6811 the start of the region.")
6813 (defun org-save-markers-in-region (beg end)
6814 "Check markers in region.
6815 If these markers are between BEG and END, record their position relative
6816 to BEG, so that after moving the block of text, we can put the markers back
6817 into place.
6818 This function gets called just before an entry or tree gets cut from the
6819 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6820 called immediately, to move the markers with the entries."
6821 (setq org-markers-to-move nil)
6822 (when (featurep 'org-clock)
6823 (org-clock-save-markers-for-cut-and-paste beg end))
6824 (when (featurep 'org-agenda)
6825 (org-agenda-save-markers-for-cut-and-paste beg end)))
6827 (defun org-check-and-save-marker (marker beg end)
6828 "Check if MARKER is between BEG and END.
6829 If yes, remember the marker and the distance to BEG."
6830 (when (and (marker-buffer marker)
6831 (equal (marker-buffer marker) (current-buffer)))
6832 (if (and (>= marker beg) (< marker end))
6833 (push (cons marker (- marker beg)) org-markers-to-move))))
6835 (defun org-reinstall-markers-in-region (beg)
6836 "Move all remembered markers to their position relative to BEG."
6837 (mapc (lambda (x)
6838 (move-marker (car x) (+ beg (cdr x))))
6839 org-markers-to-move)
6840 (setq org-markers-to-move nil))
6842 (defun org-narrow-to-subtree ()
6843 "Narrow buffer to the current subtree."
6844 (interactive)
6845 (save-excursion
6846 (save-match-data
6847 (narrow-to-region
6848 (progn (org-back-to-heading t) (point))
6849 (progn (org-end-of-subtree t t)
6850 (if (org-on-heading-p) (backward-char 1))
6851 (point))))))
6853 (defun org-clone-subtree-with-time-shift (n &optional shift)
6854 "Clone the task (subtree) at point N times.
6855 The clones will be inserted as siblings.
6857 In interactive use, the user will be prompted for the number of clones
6858 to be produced, and for a time SHIFT, which may be a repeater as used
6859 in time stamps, for example `+3d'.
6861 When a valid repeater is given and the entry contains any time stamps,
6862 the clones will become a sequence in time, with time stamps in the
6863 subtree shifted for each clone produced. If SHIFT is nil or the
6864 empty string, time stamps will be left alone.
6866 If the original subtree did contain time stamps with a repeater,
6867 the following will happen:
6868 - the repeater will be removed in each clone
6869 - an additional clone will be produced, with the current, unshifted
6870 date(s) in the entry.
6871 - the original entry will be placed *after* all the clones, with
6872 repeater intact.
6873 - the start days in the repeater in the original entry will be shifted
6874 to past the last clone.
6875 I this way you can spell out a number of instances of a repeating task,
6876 and still retain the repeater to cover future instances of the task."
6877 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6878 (let (beg end template task
6879 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6880 (if (not (and (integerp n) (> n 0)))
6881 (error "Invalid number of replications %s" n))
6882 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6883 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6884 shift)))
6885 (error "Invalid shift specification %s" shift))
6886 (when doshift
6887 (setq shift-n (string-to-number (match-string 1 shift))
6888 shift-what (cdr (assoc (match-string 2 shift)
6889 '(("d" . day) ("w" . week)
6890 ("m" . month) ("y" . year))))))
6891 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6892 (setq nmin 1 nmax n)
6893 (org-back-to-heading t)
6894 (setq beg (point))
6895 (org-end-of-subtree t t)
6896 (or (bolp) (insert "\n"))
6897 (setq end (point))
6898 (setq template (buffer-substring beg end))
6899 (when (and doshift
6900 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6901 (delete-region beg end)
6902 (setq end beg)
6903 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6904 (goto-char end)
6905 (loop for n from nmin to nmax do
6906 (if (not doshift)
6907 (setq task template)
6908 (with-temp-buffer
6909 (insert template)
6910 (org-mode)
6911 (goto-char (point-min))
6912 (while (re-search-forward org-ts-regexp-both nil t)
6913 (org-timestamp-change (* n shift-n) shift-what))
6914 (unless (= n n-no-remove)
6915 (goto-char (point-min))
6916 (while (re-search-forward org-ts-regexp nil t)
6917 (save-excursion
6918 (goto-char (match-beginning 0))
6919 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6920 (delete-region (match-beginning 1) (match-end 1))))))
6921 (setq task (buffer-string))))
6922 (insert task))
6923 (goto-char beg)))
6925 ;;; Outline Sorting
6927 (defun org-sort (with-case)
6928 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6929 Optional argument WITH-CASE means sort case-sensitively.
6930 With a double prefix argument, also remove duplicate entries."
6931 (interactive "P")
6932 (if (org-at-table-p)
6933 (org-call-with-arg 'org-table-sort-lines with-case)
6934 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6936 (defun org-sort-remove-invisible (s)
6937 (remove-text-properties 0 (length s) org-rm-props s)
6938 (while (string-match org-bracket-link-regexp s)
6939 (setq s (replace-match (if (match-end 2)
6940 (match-string 3 s)
6941 (match-string 1 s)) t t s)))
6944 (defvar org-priority-regexp) ; defined later in the file
6946 (defvar org-after-sorting-entries-or-items-hook nil
6947 "Hook that is run after a bunch of entries or items have been sorted.
6948 When children are sorted, the cursor is in the parent line when this
6949 hook gets called. When a region or a plain list is sorted, the cursor
6950 will be in the first entry of the sorted region/list.")
6952 (defun org-sort-entries-or-items
6953 (&optional with-case sorting-type getkey-func compare-func property)
6954 "Sort entries on a certain level of an outline tree, or plain list items.
6955 If there is an active region, the entries in the region are sorted.
6956 Else, if the cursor is before the first entry, sort the top-level items.
6957 Else, the children of the entry at point are sorted.
6958 If the cursor is at the first item in a plain list, the list items will be
6959 sorted.
6961 Sorting can be alphabetically, numerically, by date/time as given by
6962 a time stamp, by a property or by priority.
6964 The command prompts for the sorting type unless it has been given to the
6965 function through the SORTING-TYPE argument, which needs to a character,
6966 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6967 precise meaning of each character:
6969 n Numerically, by converting the beginning of the entry/item to a number.
6970 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6971 t By date/time, either the first active time stamp in the entry, or, if
6972 none exist, by the first inactive one.
6973 In items, only the first line will be checked.
6974 s By the scheduled date/time.
6975 d By deadline date/time.
6976 c By creation time, which is assumed to be the first inactive time stamp
6977 at the beginning of a line.
6978 p By priority according to the cookie.
6979 r By the value of a property.
6981 Capital letters will reverse the sort order.
6983 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6984 called with point at the beginning of the record. It must return either
6985 a string or a number that should serve as the sorting key for that record.
6987 Comparing entries ignores case by default. However, with an optional argument
6988 WITH-CASE, the sorting considers case as well."
6989 (interactive "P")
6990 (let ((case-func (if with-case 'identity 'downcase))
6991 start beg end stars re re2
6992 txt what tmp plain-list-p)
6993 ;; Find beginning and end of region to sort
6994 (cond
6995 ((org-region-active-p)
6996 ;; we will sort the region
6997 (setq end (region-end)
6998 what "region")
6999 (goto-char (region-beginning))
7000 (if (not (org-on-heading-p)) (outline-next-heading))
7001 (setq start (point)))
7002 ((org-at-item-p)
7003 ;; we will sort this plain list
7004 (org-beginning-of-item-list) (setq start (point))
7005 (org-end-of-item-list)
7006 (or (bolp) (insert "\n"))
7007 (setq end (point))
7008 (goto-char start)
7009 (setq plain-list-p t
7010 what "plain list"))
7011 ((or (org-on-heading-p)
7012 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7013 ;; we will sort the children of the current headline
7014 (org-back-to-heading)
7015 (setq start (point)
7016 end (progn (org-end-of-subtree t t)
7017 (or (bolp) (insert "\n"))
7018 (org-back-over-empty-lines)
7019 (point))
7020 what "children")
7021 (goto-char start)
7022 (show-subtree)
7023 (outline-next-heading))
7025 ;; we will sort the top-level entries in this file
7026 (goto-char (point-min))
7027 (or (org-on-heading-p) (outline-next-heading))
7028 (setq start (point))
7029 (goto-char (point-max))
7030 (beginning-of-line 1)
7031 (when (looking-at ".*?\\S-")
7032 ;; File ends in a non-white line
7033 (end-of-line 1)
7034 (insert "\n"))
7035 (setq end (point-max))
7036 (setq what "top-level")
7037 (goto-char start)
7038 (show-all)))
7040 (setq beg (point))
7041 (if (>= beg end) (error "Nothing to sort"))
7043 (unless plain-list-p
7044 (looking-at "\\(\\*+\\)")
7045 (setq stars (match-string 1)
7046 re (concat "^" (regexp-quote stars) " +")
7047 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7048 txt (buffer-substring beg end))
7049 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7050 (if (and (not (equal stars "*")) (string-match re2 txt))
7051 (error "Region to sort contains a level above the first entry")))
7053 (unless sorting-type
7054 (message
7055 (if plain-list-p
7056 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7057 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7058 [t]ime [s]cheduled [d]eadline [c]reated
7059 A/N/T/S/D/C/P/O/F means reversed:")
7060 what)
7061 (setq sorting-type (read-char-exclusive))
7063 (and (= (downcase sorting-type) ?f)
7064 (setq getkey-func
7065 (org-icompleting-read "Sort using function: "
7066 obarray 'fboundp t nil nil))
7067 (setq getkey-func (intern getkey-func)))
7069 (and (= (downcase sorting-type) ?r)
7070 (setq property
7071 (org-icompleting-read "Property: "
7072 (mapcar 'list (org-buffer-property-keys t))
7073 nil t))))
7075 (message "Sorting entries...")
7077 (save-restriction
7078 (narrow-to-region start end)
7080 (let ((dcst (downcase sorting-type))
7081 (case-fold-search nil)
7082 (now (current-time)))
7083 (sort-subr
7084 (/= dcst sorting-type)
7085 ;; This function moves to the beginning character of the "record" to
7086 ;; be sorted.
7087 (if plain-list-p
7088 (lambda nil
7089 (if (org-at-item-p) t (goto-char (point-max))))
7090 (lambda nil
7091 (if (re-search-forward re nil t)
7092 (goto-char (match-beginning 0))
7093 (goto-char (point-max)))))
7094 ;; This function moves to the last character of the "record" being
7095 ;; sorted.
7096 (if plain-list-p
7097 'org-end-of-item
7098 (lambda nil
7099 (save-match-data
7100 (condition-case nil
7101 (outline-forward-same-level 1)
7102 (error
7103 (goto-char (point-max)))))))
7105 ;; This function returns the value that gets sorted against.
7106 (if plain-list-p
7107 (lambda nil
7108 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7109 (cond
7110 ((= dcst ?n)
7111 (string-to-number (buffer-substring (match-end 0)
7112 (point-at-eol))))
7113 ((= dcst ?a)
7114 (buffer-substring (match-end 0) (point-at-eol)))
7115 ((= dcst ?t)
7116 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7117 (re-search-forward org-ts-regexp-both
7118 (point-at-eol) t))
7119 (org-time-string-to-seconds (match-string 0))
7120 (org-float-time now)))
7121 ((= dcst ?f)
7122 (if getkey-func
7123 (progn
7124 (setq tmp (funcall getkey-func))
7125 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7126 tmp)
7127 (error "Invalid key function `%s'" getkey-func)))
7128 (t (error "Invalid sorting type `%c'" sorting-type)))))
7129 (lambda nil
7130 (cond
7131 ((= dcst ?n)
7132 (if (looking-at org-complex-heading-regexp)
7133 (string-to-number (match-string 4))
7134 nil))
7135 ((= dcst ?a)
7136 (if (looking-at org-complex-heading-regexp)
7137 (funcall case-func (match-string 4))
7138 nil))
7139 ((= dcst ?t)
7140 (let ((end (save-excursion (outline-next-heading) (point))))
7141 (if (or (re-search-forward org-ts-regexp end t)
7142 (re-search-forward org-ts-regexp-both end t))
7143 (org-time-string-to-seconds (match-string 0))
7144 (org-float-time now))))
7145 ((= dcst ?c)
7146 (let ((end (save-excursion (outline-next-heading) (point))))
7147 (if (re-search-forward
7148 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7149 end t)
7150 (org-time-string-to-seconds (match-string 0))
7151 (org-float-time now))))
7152 ((= dcst ?s)
7153 (let ((end (save-excursion (outline-next-heading) (point))))
7154 (if (re-search-forward org-scheduled-time-regexp end t)
7155 (org-time-string-to-seconds (match-string 1))
7156 (org-float-time now))))
7157 ((= dcst ?d)
7158 (let ((end (save-excursion (outline-next-heading) (point))))
7159 (if (re-search-forward org-deadline-time-regexp end t)
7160 (org-time-string-to-seconds (match-string 1))
7161 (org-float-time now))))
7162 ((= dcst ?p)
7163 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7164 (string-to-char (match-string 2))
7165 org-default-priority))
7166 ((= dcst ?r)
7167 (or (org-entry-get nil property) ""))
7168 ((= dcst ?o)
7169 (if (looking-at org-complex-heading-regexp)
7170 (- 9999 (length (member (match-string 2)
7171 org-todo-keywords-1)))))
7172 ((= dcst ?f)
7173 (if getkey-func
7174 (progn
7175 (setq tmp (funcall getkey-func))
7176 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7177 tmp)
7178 (error "Invalid key function `%s'" getkey-func)))
7179 (t (error "Invalid sorting type `%c'" sorting-type)))))
7181 (cond
7182 ((= dcst ?a) 'string<)
7183 ((= dcst ?f) compare-func)
7184 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7185 (t nil)))))
7186 (run-hooks 'org-after-sorting-entries-or-items-hook)
7187 (message "Sorting entries...done")))
7189 (defun org-do-sort (table what &optional with-case sorting-type)
7190 "Sort TABLE of WHAT according to SORTING-TYPE.
7191 The user will be prompted for the SORTING-TYPE if the call to this
7192 function does not specify it. WHAT is only for the prompt, to indicate
7193 what is being sorted. The sorting key will be extracted from
7194 the car of the elements of the table.
7195 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7196 (unless sorting-type
7197 (message
7198 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7199 what)
7200 (setq sorting-type (read-char-exclusive)))
7201 (let ((dcst (downcase sorting-type))
7202 extractfun comparefun)
7203 ;; Define the appropriate functions
7204 (cond
7205 ((= dcst ?n)
7206 (setq extractfun 'string-to-number
7207 comparefun (if (= dcst sorting-type) '< '>)))
7208 ((= dcst ?a)
7209 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7210 (lambda(x) (downcase (org-sort-remove-invisible x))))
7211 comparefun (if (= dcst sorting-type)
7212 'string<
7213 (lambda (a b) (and (not (string< a b))
7214 (not (string= a b)))))))
7215 ((= dcst ?t)
7216 (setq extractfun
7217 (lambda (x)
7218 (if (or (string-match org-ts-regexp x)
7219 (string-match org-ts-regexp-both x))
7220 (org-float-time
7221 (org-time-string-to-time (match-string 0 x)))
7223 comparefun (if (= dcst sorting-type) '< '>)))
7224 (t (error "Invalid sorting type `%c'" sorting-type)))
7226 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7227 table)
7228 (lambda (a b) (funcall comparefun (car a) (car b))))))
7231 ;;; The orgstruct minor mode
7233 ;; Define a minor mode which can be used in other modes in order to
7234 ;; integrate the org-mode structure editing commands.
7236 ;; This is really a hack, because the org-mode structure commands use
7237 ;; keys which normally belong to the major mode. Here is how it
7238 ;; works: The minor mode defines all the keys necessary to operate the
7239 ;; structure commands, but wraps the commands into a function which
7240 ;; tests if the cursor is currently at a headline or a plain list
7241 ;; item. If that is the case, the structure command is used,
7242 ;; temporarily setting many Org-mode variables like regular
7243 ;; expressions for filling etc. However, when any of those keys is
7244 ;; used at a different location, function uses `key-binding' to look
7245 ;; up if the key has an associated command in another currently active
7246 ;; keymap (minor modes, major mode, global), and executes that
7247 ;; command. There might be problems if any of the keys is otherwise
7248 ;; used as a prefix key.
7250 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7251 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7252 ;; addresses this by checking explicitly for both bindings.
7254 (defvar orgstruct-mode-map (make-sparse-keymap)
7255 "Keymap for the minor `orgstruct-mode'.")
7257 (defvar org-local-vars nil
7258 "List of local variables, for use by `orgstruct-mode'")
7260 ;;;###autoload
7261 (define-minor-mode orgstruct-mode
7262 "Toggle the minor more `orgstruct-mode'.
7263 This mode is for using Org-mode structure commands in other modes.
7264 The following key behave as if Org-mode was active, if the cursor
7265 is on a headline, or on a plain list item (both in the definition
7266 of Org-mode).
7268 M-up Move entry/item up
7269 M-down Move entry/item down
7270 M-left Promote
7271 M-right Demote
7272 M-S-up Move entry/item up
7273 M-S-down Move entry/item down
7274 M-S-left Promote subtree
7275 M-S-right Demote subtree
7276 M-q Fill paragraph and items like in Org-mode
7277 C-c ^ Sort entries
7278 C-c - Cycle list bullet
7279 TAB Cycle item visibility
7280 M-RET Insert new heading/item
7281 S-M-RET Insert new TODO heading / Checkbox item
7282 C-c C-c Set tags / toggle checkbox"
7283 nil " OrgStruct" nil
7284 (org-load-modules-maybe)
7285 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7287 ;;;###autoload
7288 (defun turn-on-orgstruct ()
7289 "Unconditionally turn on `orgstruct-mode'."
7290 (orgstruct-mode 1))
7292 (defun orgstruct++-mode (&optional arg)
7293 "Toggle `orgstruct-mode', the enhanced version of it.
7294 In addition to setting orgstruct-mode, this also exports all indentation
7295 and autofilling variables from org-mode into the buffer. It will also
7296 recognize item context in multiline items.
7297 Note that turning off orgstruct-mode will *not* remove the
7298 indentation/paragraph settings. This can only be done by refreshing the
7299 major mode, for example with \\[normal-mode]."
7300 (interactive "P")
7301 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7302 (if (< arg 1)
7303 (orgstruct-mode -1)
7304 (orgstruct-mode 1)
7305 (let (var val)
7306 (mapc
7307 (lambda (x)
7308 (when (string-match
7309 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7310 (symbol-name (car x)))
7311 (setq var (car x) val (nth 1 x))
7312 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7313 org-local-vars)
7314 (org-set-local 'orgstruct-is-++ t))))
7316 (defvar orgstruct-is-++ nil
7317 "Is orgstruct-mode in ++ version in the current-buffer?")
7318 (make-variable-buffer-local 'orgstruct-is-++)
7320 ;;;###autoload
7321 (defun turn-on-orgstruct++ ()
7322 "Unconditionally turn on `orgstruct++-mode'."
7323 (orgstruct++-mode 1))
7325 (defun orgstruct-error ()
7326 "Error when there is no default binding for a structure key."
7327 (interactive)
7328 (error "This key has no function outside structure elements"))
7330 (defun orgstruct-setup ()
7331 "Setup orgstruct keymaps."
7332 (let ((nfunc 0)
7333 (bindings
7334 (list
7335 '([(meta up)] org-metaup)
7336 '([(meta down)] org-metadown)
7337 '([(meta left)] org-metaleft)
7338 '([(meta right)] org-metaright)
7339 '([(meta shift up)] org-shiftmetaup)
7340 '([(meta shift down)] org-shiftmetadown)
7341 '([(meta shift left)] org-shiftmetaleft)
7342 '([(meta shift right)] org-shiftmetaright)
7343 '([?\e (up)] org-metaup)
7344 '([?\e (down)] org-metadown)
7345 '([?\e (left)] org-metaleft)
7346 '([?\e (right)] org-metaright)
7347 '([?\e (shift up)] org-shiftmetaup)
7348 '([?\e (shift down)] org-shiftmetadown)
7349 '([?\e (shift left)] org-shiftmetaleft)
7350 '([?\e (shift right)] org-shiftmetaright)
7351 '([(shift up)] org-shiftup)
7352 '([(shift down)] org-shiftdown)
7353 '([(shift left)] org-shiftleft)
7354 '([(shift right)] org-shiftright)
7355 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7356 '("\M-q" fill-paragraph)
7357 '("\C-c^" org-sort)
7358 '("\C-c-" org-cycle-list-bullet)))
7359 elt key fun cmd)
7360 (while (setq elt (pop bindings))
7361 (setq nfunc (1+ nfunc))
7362 (setq key (org-key (car elt))
7363 fun (nth 1 elt)
7364 cmd (orgstruct-make-binding fun nfunc key))
7365 (org-defkey orgstruct-mode-map key cmd))
7367 ;; Special treatment needed for TAB and RET
7368 (org-defkey orgstruct-mode-map [(tab)]
7369 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7370 (org-defkey orgstruct-mode-map "\C-i"
7371 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7373 (org-defkey orgstruct-mode-map "\M-\C-m"
7374 (orgstruct-make-binding 'org-insert-heading 105
7375 "\M-\C-m" [(meta return)]))
7376 (org-defkey orgstruct-mode-map [(meta return)]
7377 (orgstruct-make-binding 'org-insert-heading 106
7378 [(meta return)] "\M-\C-m"))
7380 (org-defkey orgstruct-mode-map [(shift meta return)]
7381 (orgstruct-make-binding 'org-insert-todo-heading 107
7382 [(meta return)] "\M-\C-m"))
7384 (org-defkey orgstruct-mode-map "\e\C-m"
7385 (orgstruct-make-binding 'org-insert-heading 108
7386 "\e\C-m" [?\e (return)]))
7387 (org-defkey orgstruct-mode-map [?\e (return)]
7388 (orgstruct-make-binding 'org-insert-heading 109
7389 [?\e (return)] "\e\C-m"))
7390 (org-defkey orgstruct-mode-map [?\e (shift return)]
7391 (orgstruct-make-binding 'org-insert-todo-heading 110
7392 [?\e (return)] "\e\C-m"))
7394 (unless org-local-vars
7395 (setq org-local-vars (org-get-local-variables)))
7399 (defun orgstruct-make-binding (fun n &rest keys)
7400 "Create a function for binding in the structure minor mode.
7401 FUN is the command to call inside a table. N is used to create a unique
7402 command name. KEYS are keys that should be checked in for a command
7403 to execute outside of tables."
7404 (eval
7405 (list 'defun
7406 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7407 '(arg)
7408 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7409 "Outside of structure, run the binding of `"
7410 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7411 "'.")
7412 '(interactive "p")
7413 (list 'if
7414 `(org-context-p 'headline 'item
7415 (and orgstruct-is-++
7416 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7417 'item-body))
7418 (list 'org-run-like-in-org-mode (list 'quote fun))
7419 (list 'let '(orgstruct-mode)
7420 (list 'call-interactively
7421 (append '(or)
7422 (mapcar (lambda (k)
7423 (list 'key-binding k))
7424 keys)
7425 '('orgstruct-error))))))))
7427 (defun org-context-p (&rest contexts)
7428 "Check if local context is any of CONTEXTS.
7429 Possible values in the list of contexts are `table', `headline', and `item'."
7430 (let ((pos (point)))
7431 (goto-char (point-at-bol))
7432 (prog1 (or (and (memq 'table contexts)
7433 (looking-at "[ \t]*|"))
7434 (and (memq 'headline contexts)
7435 ;;????????? (looking-at "\\*+"))
7436 (looking-at outline-regexp))
7437 (and (memq 'item contexts)
7438 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7439 (and (memq 'item-body contexts)
7440 (org-in-item-p)))
7441 (goto-char pos))))
7443 (defun org-get-local-variables ()
7444 "Return a list of all local variables in an org-mode buffer."
7445 (let (varlist)
7446 (with-current-buffer (get-buffer-create "*Org tmp*")
7447 (erase-buffer)
7448 (org-mode)
7449 (setq varlist (buffer-local-variables)))
7450 (kill-buffer "*Org tmp*")
7451 (delq nil
7452 (mapcar
7453 (lambda (x)
7454 (setq x
7455 (if (symbolp x)
7456 (list x)
7457 (list (car x) (list 'quote (cdr x)))))
7458 (if (string-match
7459 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7460 (symbol-name (car x)))
7461 x nil))
7462 varlist))))
7464 ;;;###autoload
7465 (defun org-run-like-in-org-mode (cmd)
7466 "Run a command, pretending that the current buffer is in Org-mode.
7467 This will temporarily bind local variables that are typically bound in
7468 Org-mode to the values they have in Org-mode, and then interactively
7469 call CMD."
7470 (org-load-modules-maybe)
7471 (unless org-local-vars
7472 (setq org-local-vars (org-get-local-variables)))
7473 (eval (list 'let org-local-vars
7474 (list 'call-interactively (list 'quote cmd)))))
7476 ;;;; Archiving
7478 (defun org-get-category (&optional pos)
7479 "Get the category applying to position POS."
7480 (get-text-property (or pos (point)) 'org-category))
7482 (defun org-refresh-category-properties ()
7483 "Refresh category text properties in the buffer."
7484 (let ((def-cat (cond
7485 ((null org-category)
7486 (if buffer-file-name
7487 (file-name-sans-extension
7488 (file-name-nondirectory buffer-file-name))
7489 "???"))
7490 ((symbolp org-category) (symbol-name org-category))
7491 (t org-category)))
7492 beg end cat pos optionp)
7493 (org-unmodified
7494 (save-excursion
7495 (save-restriction
7496 (widen)
7497 (goto-char (point-min))
7498 (put-text-property (point) (point-max) 'org-category def-cat)
7499 (while (re-search-forward
7500 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7501 (setq pos (match-end 0)
7502 optionp (equal (char-after (match-beginning 0)) ?#)
7503 cat (org-trim (match-string 2)))
7504 (if optionp
7505 (setq beg (point-at-bol) end (point-max))
7506 (org-back-to-heading t)
7507 (setq beg (point) end (org-end-of-subtree t t)))
7508 (put-text-property beg end 'org-category cat)
7509 (goto-char pos)))))))
7512 ;;;; Link Stuff
7514 ;;; Link abbreviations
7516 (defun org-link-expand-abbrev (link)
7517 "Apply replacements as defined in `org-link-abbrev-alist."
7518 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7519 (let* ((key (match-string 1 link))
7520 (as (or (assoc key org-link-abbrev-alist-local)
7521 (assoc key org-link-abbrev-alist)))
7522 (tag (and (match-end 2) (match-string 3 link)))
7523 rpl)
7524 (if (not as)
7525 link
7526 (setq rpl (cdr as))
7527 (cond
7528 ((symbolp rpl) (funcall rpl tag))
7529 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7530 ((string-match "%h" rpl)
7531 (replace-match (url-hexify-string (or tag "")) t t rpl))
7532 (t (concat rpl tag)))))
7533 link))
7535 ;;; Storing and inserting links
7537 (defvar org-insert-link-history nil
7538 "Minibuffer history for links inserted with `org-insert-link'.")
7540 (defvar org-stored-links nil
7541 "Contains the links stored with `org-store-link'.")
7543 (defvar org-store-link-plist nil
7544 "Plist with info about the most recently link created with `org-store-link'.")
7546 (defvar org-link-protocols nil
7547 "Link protocols added to Org-mode using `org-add-link-type'.")
7549 (defvar org-store-link-functions nil
7550 "List of functions that are called to create and store a link.
7551 Each function will be called in turn until one returns a non-nil
7552 value. Each function should check if it is responsible for creating
7553 this link (for example by looking at the major mode).
7554 If not, it must exit and return nil.
7555 If yes, it should return a non-nil value after a calling
7556 `org-store-link-props' with a list of properties and values.
7557 Special properties are:
7559 :type The link prefix. like \"http\". This must be given.
7560 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7561 This is obligatory as well.
7562 :description Optional default description for the second pair
7563 of brackets in an Org-mode link. The user can still change
7564 this when inserting this link into an Org-mode buffer.
7566 In addition to these, any additional properties can be specified
7567 and then used in remember templates.")
7569 (defun org-add-link-type (type &optional follow export)
7570 "Add TYPE to the list of `org-link-types'.
7571 Re-compute all regular expressions depending on `org-link-types'
7573 FOLLOW and EXPORT are two functions.
7575 FOLLOW should take the link path as the single argument and do whatever
7576 is necessary to follow the link, for example find a file or display
7577 a mail message.
7579 EXPORT should format the link path for export to one of the export formats.
7580 It should be a function accepting three arguments:
7582 path the path of the link, the text after the prefix (like \"http:\")
7583 desc the description of the link, if any, nil if there was no description
7584 format the export format, a symbol like `html' or `latex'.
7586 The function may use the FORMAT information to return different values
7587 depending on the format. The return value will be put literally into
7588 the exported file.
7589 Org-mode has a built-in default for exporting links. If you are happy with
7590 this default, there is no need to define an export function for the link
7591 type. For a simple example of an export function, see `org-bbdb.el'."
7592 (add-to-list 'org-link-types type t)
7593 (org-make-link-regexps)
7594 (if (assoc type org-link-protocols)
7595 (setcdr (assoc type org-link-protocols) (list follow export))
7596 (push (list type follow export) org-link-protocols)))
7598 (defvar org-agenda-buffer-name)
7600 ;;;###autoload
7601 (defun org-store-link (arg)
7602 "\\<org-mode-map>Store an org-link to the current location.
7603 This link is added to `org-stored-links' and can later be inserted
7604 into an org-buffer with \\[org-insert-link].
7606 For some link types, a prefix arg is interpreted:
7607 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7608 For file links, arg negates `org-context-in-file-links'."
7609 (interactive "P")
7610 (org-load-modules-maybe)
7611 (setq org-store-link-plist nil) ; reset
7612 (let ((outline-regexp (org-get-limited-outline-regexp))
7613 link cpltxt desc description search txt custom-id)
7614 (cond
7616 ((run-hook-with-args-until-success 'org-store-link-functions)
7617 (setq link (plist-get org-store-link-plist :link)
7618 desc (or (plist-get org-store-link-plist :description) link)))
7620 ((equal (buffer-name) "*Org Edit Src Example*")
7621 (let (label gc)
7622 (while (or (not label)
7623 (save-excursion
7624 (save-restriction
7625 (widen)
7626 (goto-char (point-min))
7627 (re-search-forward
7628 (regexp-quote (format org-coderef-label-format label))
7629 nil t))))
7630 (when label (message "Label exists already") (sit-for 2))
7631 (setq label (read-string "Code line label: " label)))
7632 (end-of-line 1)
7633 (setq link (format org-coderef-label-format label))
7634 (setq gc (- 79 (length link)))
7635 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7636 (insert link)
7637 (setq link (concat "(" label ")") desc nil)))
7639 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7640 ;; We are in the agenda, link to referenced location
7641 (let ((m (or (get-text-property (point) 'org-hd-marker)
7642 (get-text-property (point) 'org-marker))))
7643 (when m
7644 (org-with-point-at m
7645 (call-interactively 'org-store-link)))))
7647 ((eq major-mode 'calendar-mode)
7648 (let ((cd (calendar-cursor-to-date)))
7649 (setq link
7650 (format-time-string
7651 (car org-time-stamp-formats)
7652 (apply 'encode-time
7653 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7654 nil nil nil))))
7655 (org-store-link-props :type "calendar" :date cd)))
7657 ((eq major-mode 'w3-mode)
7658 (setq cpltxt (if (and (buffer-name)
7659 (not (string-match "Untitled" (buffer-name))))
7660 (buffer-name)
7661 (url-view-url t))
7662 link (org-make-link (url-view-url t)))
7663 (org-store-link-props :type "w3" :url (url-view-url t)))
7665 ((eq major-mode 'w3m-mode)
7666 (setq cpltxt (or w3m-current-title w3m-current-url)
7667 link (org-make-link w3m-current-url))
7668 (org-store-link-props :type "w3m" :url (url-view-url t)))
7670 ((setq search (run-hook-with-args-until-success
7671 'org-create-file-search-functions))
7672 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7673 "::" search))
7674 (setq cpltxt (or description link)))
7676 ((eq major-mode 'image-mode)
7677 (setq cpltxt (concat "file:"
7678 (abbreviate-file-name buffer-file-name))
7679 link (org-make-link cpltxt))
7680 (org-store-link-props :type "image" :file buffer-file-name))
7682 ((eq major-mode 'dired-mode)
7683 ;; link to the file in the current line
7684 (let ((file (dired-get-filename nil t)))
7685 (setq file (if file
7686 (abbreviate-file-name
7687 (expand-file-name (dired-get-filename nil t)))
7688 ;; otherwise, no file so use current directory.
7689 default-directory))
7690 (setq cpltxt (concat "file:" file)
7691 link (org-make-link cpltxt))))
7693 ((and buffer-file-name (org-mode-p))
7694 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7695 (cond
7696 ((org-in-regexp "<<\\(.*?\\)>>")
7697 (setq cpltxt
7698 (concat "file:"
7699 (abbreviate-file-name buffer-file-name)
7700 "::" (match-string 1))
7701 link (org-make-link cpltxt)))
7702 ((and (featurep 'org-id)
7703 (or (eq org-link-to-org-use-id t)
7704 (and (eq org-link-to-org-use-id 'create-if-interactive)
7705 (interactive-p))
7706 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7707 (interactive-p)
7708 (not custom-id))
7709 (and org-link-to-org-use-id
7710 (condition-case nil
7711 (org-entry-get nil "ID")
7712 (error nil)))))
7713 ;; We can make a link using the ID.
7714 (setq link (condition-case nil
7715 (prog1 (org-id-store-link)
7716 (setq desc (plist-get org-store-link-plist
7717 :description)))
7718 (error
7719 ;; probably before first headline, link to file only
7720 (concat "file:"
7721 (abbreviate-file-name buffer-file-name))))))
7723 ;; Just link to current headline
7724 (setq cpltxt (concat "file:"
7725 (abbreviate-file-name buffer-file-name)))
7726 ;; Add a context search string
7727 (when (org-xor org-context-in-file-links arg)
7728 (setq txt (cond
7729 ((org-on-heading-p) nil)
7730 ((org-region-active-p)
7731 (buffer-substring (region-beginning) (region-end)))
7732 (t nil)))
7733 (when (or (null txt) (string-match "\\S-" txt))
7734 (setq cpltxt
7735 (concat cpltxt "::"
7736 (condition-case nil
7737 (org-make-org-heading-search-string txt)
7738 (error "")))
7739 desc (or (nth 4 (ignore-errors
7740 (org-heading-components))) "NONE"))))
7741 (if (string-match "::\\'" cpltxt)
7742 (setq cpltxt (substring cpltxt 0 -2)))
7743 (setq link (org-make-link cpltxt)))))
7745 ((buffer-file-name (buffer-base-buffer))
7746 ;; Just link to this file here.
7747 (setq cpltxt (concat "file:"
7748 (abbreviate-file-name
7749 (buffer-file-name (buffer-base-buffer)))))
7750 ;; Add a context string
7751 (when (org-xor org-context-in-file-links arg)
7752 (setq txt (if (org-region-active-p)
7753 (buffer-substring (region-beginning) (region-end))
7754 (buffer-substring (point-at-bol) (point-at-eol))))
7755 ;; Only use search option if there is some text.
7756 (when (string-match "\\S-" txt)
7757 (setq cpltxt
7758 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7759 desc "NONE")))
7760 (setq link (org-make-link cpltxt)))
7762 ((interactive-p)
7763 (error "Cannot link to a buffer which is not visiting a file"))
7765 (t (setq link nil)))
7767 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7768 (setq link (or link cpltxt)
7769 desc (or desc cpltxt))
7770 (if (equal desc "NONE") (setq desc nil))
7772 (if (and (or (interactive-p) executing-kbd-macro) link)
7773 (progn
7774 (setq org-stored-links
7775 (cons (list link desc) org-stored-links))
7776 (message "Stored: %s" (or desc link))
7777 (when custom-id
7778 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7779 "::#" custom-id))
7780 (setq org-stored-links
7781 (cons (list link desc) org-stored-links))))
7782 (and link (org-make-link-string link desc)))))
7784 (defun org-store-link-props (&rest plist)
7785 "Store link properties, extract names and addresses."
7786 (let (x adr)
7787 (when (setq x (plist-get plist :from))
7788 (setq adr (mail-extract-address-components x))
7789 (setq plist (plist-put plist :fromname (car adr)))
7790 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7791 (when (setq x (plist-get plist :to))
7792 (setq adr (mail-extract-address-components x))
7793 (setq plist (plist-put plist :toname (car adr)))
7794 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7795 (let ((from (plist-get plist :from))
7796 (to (plist-get plist :to)))
7797 (when (and from to org-from-is-user-regexp)
7798 (setq plist
7799 (plist-put plist :fromto
7800 (if (string-match org-from-is-user-regexp from)
7801 (concat "to %t")
7802 (concat "from %f"))))))
7803 (setq org-store-link-plist plist))
7805 (defun org-add-link-props (&rest plist)
7806 "Add these properties to the link property list."
7807 (let (key value)
7808 (while plist
7809 (setq key (pop plist) value (pop plist))
7810 (setq org-store-link-plist
7811 (plist-put org-store-link-plist key value)))))
7813 (defun org-email-link-description (&optional fmt)
7814 "Return the description part of an email link.
7815 This takes information from `org-store-link-plist' and formats it
7816 according to FMT (default from `org-email-link-description-format')."
7817 (setq fmt (or fmt org-email-link-description-format))
7818 (let* ((p org-store-link-plist)
7819 (to (plist-get p :toaddress))
7820 (from (plist-get p :fromaddress))
7821 (table
7822 (list
7823 (cons "%c" (plist-get p :fromto))
7824 (cons "%F" (plist-get p :from))
7825 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7826 (cons "%T" (plist-get p :to))
7827 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7828 (cons "%s" (plist-get p :subject))
7829 (cons "%m" (plist-get p :message-id)))))
7830 (when (string-match "%c" fmt)
7831 ;; Check if the user wrote this message
7832 (if (and org-from-is-user-regexp from to
7833 (save-match-data (string-match org-from-is-user-regexp from)))
7834 (setq fmt (replace-match "to %t" t t fmt))
7835 (setq fmt (replace-match "from %f" t t fmt))))
7836 (org-replace-escapes fmt table)))
7838 (defun org-make-org-heading-search-string (&optional string heading)
7839 "Make search string for STRING or current headline."
7840 (interactive)
7841 (let ((s (or string (org-get-heading))))
7842 (unless (and string (not heading))
7843 ;; We are using a headline, clean up garbage in there.
7844 (if (string-match org-todo-regexp s)
7845 (setq s (replace-match "" t t s)))
7846 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7847 (setq s (replace-match "" t t s)))
7848 (setq s (org-trim s))
7849 (if (string-match (concat "^\\(" org-quote-string "\\|"
7850 org-comment-string "\\)") s)
7851 (setq s (replace-match "" t t s)))
7852 (while (string-match org-ts-regexp s)
7853 (setq s (replace-match "" t t s))))
7854 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7855 (setq s (replace-match " " t t s)))
7856 (or string (setq s (concat "*" s))) ; Add * for headlines
7857 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7859 (defun org-make-link (&rest strings)
7860 "Concatenate STRINGS."
7861 (apply 'concat strings))
7863 (defun org-make-link-string (link &optional description)
7864 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7865 (unless (string-match "\\S-" link)
7866 (error "Empty link"))
7867 (when (and description
7868 (stringp description)
7869 (not (string-match "\\S-" description)))
7870 (setq description nil))
7871 (when (stringp description)
7872 ;; Remove brackets from the description, they are fatal.
7873 (while (string-match "\\[" description)
7874 (setq description (replace-match "{" t t description)))
7875 (while (string-match "\\]" description)
7876 (setq description (replace-match "}" t t description))))
7877 (when (equal (org-link-escape link) description)
7878 ;; No description needed, it is identical
7879 (setq description nil))
7880 (when (and (not description)
7881 (not (equal link (org-link-escape link))))
7882 (setq description (org-extract-attributes link)))
7883 (concat "[[" (org-link-escape link) "]"
7884 (if description (concat "[" description "]") "")
7885 "]"))
7887 (defconst org-link-escape-chars
7888 '((?\ . "%20")
7889 (?\[ . "%5B")
7890 (?\] . "%5D")
7891 (?\340 . "%E0") ; `a
7892 (?\342 . "%E2") ; ^a
7893 (?\347 . "%E7") ; ,c
7894 (?\350 . "%E8") ; `e
7895 (?\351 . "%E9") ; 'e
7896 (?\352 . "%EA") ; ^e
7897 (?\356 . "%EE") ; ^i
7898 (?\364 . "%F4") ; ^o
7899 (?\371 . "%F9") ; `u
7900 (?\373 . "%FB") ; ^u
7901 (?\; . "%3B")
7902 (?? . "%3F")
7903 (?= . "%3D")
7904 (?+ . "%2B")
7906 "Association list of escapes for some characters problematic in links.
7907 This is the list that is used for internal purposes.")
7909 (defvar org-url-encoding-use-url-hexify nil)
7911 (defconst org-link-escape-chars-browser
7912 '((?\ . "%20")) ; 32 for the SPC char
7913 "Association list of escapes for some characters problematic in links.
7914 This is the list that is used before handing over to the browser.")
7916 (defun org-link-escape (text &optional table)
7917 "Escape characters in TEXT that are problematic for links."
7918 (if (and org-url-encoding-use-url-hexify (not table))
7919 (url-hexify-string text)
7920 (setq table (or table org-link-escape-chars))
7921 (when text
7922 (let ((re (mapconcat (lambda (x) (regexp-quote
7923 (char-to-string (car x))))
7924 table "\\|")))
7925 (while (string-match re text)
7926 (setq text
7927 (replace-match
7928 (cdr (assoc (string-to-char (match-string 0 text))
7929 table))
7930 t t text)))
7931 text))))
7933 (defun org-link-unescape (text &optional table)
7934 "Reverse the action of `org-link-escape'."
7935 (if (and org-url-encoding-use-url-hexify (not table))
7936 (url-unhex-string text)
7937 (setq table (or table org-link-escape-chars))
7938 (when text
7939 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7940 table "\\|")))
7941 (while (string-match re text)
7942 (setq text
7943 (replace-match
7944 (char-to-string (car (rassoc (match-string 0 text) table)))
7945 t t text)))
7946 text))))
7948 (defun org-xor (a b)
7949 "Exclusive or."
7950 (if a (not b) b))
7952 (defun org-fixup-message-id-for-http (s)
7953 "Replace special characters in a message id, so it can be used in an http query."
7954 (while (string-match "<" s)
7955 (setq s (replace-match "%3C" t t s)))
7956 (while (string-match ">" s)
7957 (setq s (replace-match "%3E" t t s)))
7958 (while (string-match "@" s)
7959 (setq s (replace-match "%40" t t s)))
7962 ;;;###autoload
7963 (defun org-insert-link-global ()
7964 "Insert a link like Org-mode does.
7965 This command can be called in any mode to insert a link in Org-mode syntax."
7966 (interactive)
7967 (org-load-modules-maybe)
7968 (org-run-like-in-org-mode 'org-insert-link))
7970 (defun org-insert-link (&optional complete-file link-location)
7971 "Insert a link. At the prompt, enter the link.
7973 Completion can be used to insert any of the link protocol prefixes like
7974 http or ftp in use.
7976 The history can be used to select a link previously stored with
7977 `org-store-link'. When the empty string is entered (i.e. if you just
7978 press RET at the prompt), the link defaults to the most recently
7979 stored link. As SPC triggers completion in the minibuffer, you need to
7980 use M-SPC or C-q SPC to force the insertion of a space character.
7982 You will also be prompted for a description, and if one is given, it will
7983 be displayed in the buffer instead of the link.
7985 If there is already a link at point, this command will allow you to edit link
7986 and description parts.
7988 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7989 be selected using completion. The path to the file will be relative to the
7990 current directory if the file is in the current directory or a subdirectory.
7991 Otherwise, the link will be the absolute path as completed in the minibuffer
7992 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7993 option `org-link-file-path-type'.
7995 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7996 the current directory or below.
7998 With three \\[universal-argument] prefixes, negate the meaning of
7999 `org-keep-stored-link-after-insertion'.
8001 If `org-make-link-description-function' is non-nil, this function will be
8002 called with the link target, and the result will be the default
8003 link description.
8005 If the LINK-LOCATION parameter is non-nil, this value will be
8006 used as the link location instead of reading one interactively."
8007 (interactive "P")
8008 (let* ((wcf (current-window-configuration))
8009 (region (if (org-region-active-p)
8010 (buffer-substring (region-beginning) (region-end))))
8011 (remove (and region (list (region-beginning) (region-end))))
8012 (desc region)
8013 tmphist ; byte-compile incorrectly complains about this
8014 (link link-location)
8015 entry file all-prefixes)
8016 (cond
8017 (link-location) ; specified by arg, just use it.
8018 ((org-in-regexp org-bracket-link-regexp 1)
8019 ;; We do have a link at point, and we are going to edit it.
8020 (setq remove (list (match-beginning 0) (match-end 0)))
8021 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8022 (setq link (read-string "Link: "
8023 (org-link-unescape
8024 (org-match-string-no-properties 1)))))
8025 ((or (org-in-regexp org-angle-link-re)
8026 (org-in-regexp org-plain-link-re))
8027 ;; Convert to bracket link
8028 (setq remove (list (match-beginning 0) (match-end 0))
8029 link (read-string "Link: "
8030 (org-remove-angle-brackets (match-string 0)))))
8031 ((member complete-file '((4) (16)))
8032 ;; Completing read for file names.
8033 (setq link (org-file-complete-link complete-file)))
8035 ;; Read link, with completion for stored links.
8036 (with-output-to-temp-buffer "*Org Links*"
8037 (princ "Insert a link.
8038 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8039 (when org-stored-links
8040 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8041 (princ (mapconcat
8042 (lambda (x)
8043 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8044 (reverse org-stored-links) "\n"))))
8045 (let ((cw (selected-window)))
8046 (select-window (get-buffer-window "*Org Links*"))
8047 (setq truncate-lines t)
8048 (unless (pos-visible-in-window-p (point-max))
8049 (org-fit-window-to-buffer))
8050 (and (window-live-p cw) (select-window cw)))
8051 ;; Fake a link history, containing the stored links.
8052 (setq tmphist (append (mapcar 'car org-stored-links)
8053 org-insert-link-history))
8054 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8055 (mapcar 'car org-link-abbrev-alist)
8056 org-link-types))
8057 (unwind-protect
8058 (progn
8059 (setq link
8060 (let ((org-completion-use-ido nil)
8061 (org-completion-use-iswitchb nil))
8062 (org-completing-read
8063 "Link: "
8064 (append
8065 (mapcar (lambda (x) (list (concat x ":")))
8066 all-prefixes)
8067 (mapcar 'car org-stored-links))
8068 nil nil nil
8069 'tmphist
8070 (car (car org-stored-links)))))
8071 (if (not (string-match "\\S-" link))
8072 (error "No link selected"))
8073 (if (or (member link all-prefixes)
8074 (and (equal ":" (substring link -1))
8075 (member (substring link 0 -1) all-prefixes)
8076 (setq link (substring link 0 -1))))
8077 (setq link (org-link-try-special-completion link))))
8078 (set-window-configuration wcf)
8079 (kill-buffer "*Org Links*"))
8080 (setq entry (assoc link org-stored-links))
8081 (or entry (push link org-insert-link-history))
8082 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8083 (not org-keep-stored-link-after-insertion))
8084 (setq org-stored-links (delq (assoc link org-stored-links)
8085 org-stored-links)))
8086 (setq desc (or desc (nth 1 entry)))))
8088 (if (string-match org-plain-link-re link)
8089 ;; URL-like link, normalize the use of angular brackets.
8090 (setq link (org-make-link (org-remove-angle-brackets link))))
8092 ;; Check if we are linking to the current file with a search option
8093 ;; If yes, simplify the link by using only the search option.
8094 (when (and buffer-file-name
8095 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8096 (let* ((path (match-string 1 link))
8097 (case-fold-search nil)
8098 (search (match-string 2 link)))
8099 (save-match-data
8100 (if (equal (file-truename buffer-file-name) (file-truename path))
8101 ;; We are linking to this same file, with a search option
8102 (setq link search)))))
8104 ;; Check if we can/should use a relative path. If yes, simplify the link
8105 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8106 (let* ((type (match-string 1 link))
8107 (path (match-string 2 link))
8108 (origpath path)
8109 (case-fold-search nil))
8110 (cond
8111 ((or (eq org-link-file-path-type 'absolute)
8112 (equal complete-file '(16)))
8113 (setq path (abbreviate-file-name (expand-file-name path))))
8114 ((eq org-link-file-path-type 'noabbrev)
8115 (setq path (expand-file-name path)))
8116 ((eq org-link-file-path-type 'relative)
8117 (setq path (file-relative-name path)))
8119 (save-match-data
8120 (if (string-match (concat "^" (regexp-quote
8121 (file-name-as-directory
8122 (expand-file-name "."))))
8123 (expand-file-name path))
8124 ;; We are linking a file with relative path name.
8125 (setq path (substring (expand-file-name path)
8126 (match-end 0)))
8127 (setq path (abbreviate-file-name (expand-file-name path)))))))
8128 (setq link (concat type path))
8129 (if (equal desc origpath)
8130 (setq desc path))))
8132 (if org-make-link-description-function
8133 (setq desc (funcall org-make-link-description-function link desc)))
8135 (setq desc (read-string "Description: " desc))
8136 (unless (string-match "\\S-" desc) (setq desc nil))
8137 (if remove (apply 'delete-region remove))
8138 (insert (org-make-link-string link desc))))
8140 (defun org-link-try-special-completion (type)
8141 "If there is completion support for link type TYPE, offer it."
8142 (let ((fun (intern (concat "org-" type "-complete-link"))))
8143 (if (functionp fun)
8144 (funcall fun)
8145 (read-string "Link (no completion support): " (concat type ":")))))
8147 (defun org-file-complete-link (&optional arg)
8148 "Create a file link using completion."
8149 (let (file link)
8150 (setq file (read-file-name "File: "))
8151 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8152 (pwd1 (file-name-as-directory (abbreviate-file-name
8153 (expand-file-name ".")))))
8154 (cond
8155 ((equal arg '(16))
8156 (setq link (org-make-link
8157 "file:"
8158 (abbreviate-file-name (expand-file-name file)))))
8159 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8160 (setq link (org-make-link "file:" (match-string 1 file))))
8161 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8162 (expand-file-name file))
8163 (setq link (org-make-link
8164 "file:" (match-string 1 (expand-file-name file)))))
8165 (t (setq link (org-make-link "file:" file)))))
8166 link))
8168 (defun org-completing-read (&rest args)
8169 "Completing-read with SPACE being a normal character."
8170 (let ((minibuffer-local-completion-map
8171 (copy-keymap minibuffer-local-completion-map)))
8172 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8173 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8174 (apply 'org-icompleting-read args)))
8176 (defun org-completing-read-no-i (&rest args)
8177 (let (org-completion-use-ido org-completion-use-iswitchb)
8178 (apply 'org-completing-read args)))
8180 (defun org-iswitchb-completing-read (prompt choices &rest args)
8181 "Use iswitch as a completing-read replacement to choose from choices.
8182 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8183 from."
8184 (let* ((iswitchb-use-virtual-buffers nil)
8185 (iswitchb-make-buflist-hook
8186 (lambda ()
8187 (setq iswitchb-temp-buflist choices))))
8188 (iswitchb-read-buffer prompt)))
8190 (defun org-icompleting-read (&rest args)
8191 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8192 (org-without-partial-completion
8193 (if (and org-completion-use-ido
8194 (fboundp 'ido-completing-read)
8195 (boundp 'ido-mode) ido-mode
8196 (listp (second args)))
8197 (let ((ido-enter-matching-directory nil))
8198 (apply 'ido-completing-read (concat (car args))
8199 (if (consp (car (nth 1 args)))
8200 (mapcar (lambda (x) (car x)) (nth 1 args))
8201 (nth 1 args))
8202 (cddr args)))
8203 (if (and org-completion-use-iswitchb
8204 (boundp 'iswitchb-mode) iswitchb-mode
8205 (listp (second args)))
8206 (apply 'org-iswitchb-completing-read (concat (car args))
8207 (if (consp (car (nth 1 args)))
8208 (mapcar (lambda (x) (car x)) (nth 1 args))
8209 (nth 1 args))
8210 (cddr args))
8211 (apply 'completing-read args)))))
8213 (defun org-extract-attributes (s)
8214 "Extract the attributes cookie from a string and set as text property."
8215 (let (a attr (start 0) key value)
8216 (save-match-data
8217 (when (string-match "{{\\([^}]+\\)}}$" s)
8218 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8219 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8220 (setq key (match-string 1 a) value (match-string 2 a)
8221 start (match-end 0)
8222 attr (plist-put attr (intern key) value))))
8223 (org-add-props s nil 'org-attr attr))
8226 (defun org-extract-attributes-from-string (tag)
8227 (let (key value attr)
8228 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8229 (setq key (match-string 1 tag) value (match-string 2 tag)
8230 tag (replace-match "" t t tag)
8231 attr (plist-put attr (intern key) value)))
8232 (cons tag attr)))
8234 (defun org-attributes-to-string (plist)
8235 "Format a property list into an HTML attribute list."
8236 (let ((s "") key value)
8237 (while plist
8238 (setq key (pop plist) value (pop plist))
8239 (and value
8240 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8243 ;;; Opening/following a link
8245 (defvar org-link-search-failed nil)
8247 (defvar org-open-link-functions nil
8248 "Hook for functions finding a plain text link.
8249 These functions must take a single argument, the link content.
8250 They will be called for links that look like [[link text][description]]
8251 when LINK TEXT does not have a protocol like \"http:\" and does not look
8252 like a filename (e.g. \"./blue.png\").
8254 These functions will be called *before* Org attempts to resolve the
8255 link by doing text searches in the current buffer - so if you want a
8256 link \"[[target]]\" to still find \"<<target>>\", your function should
8257 handle this as a special case.
8259 When the function does handle the link, it must return a non-nil value.
8260 If it decides that it is not responsible for this link, it must return
8261 nil to indicate that that Org-mode can continue with other options
8262 like exact and fuzzy text search.")
8264 (defun org-next-link ()
8265 "Move forward to the next link.
8266 If the link is in hidden text, expose it."
8267 (interactive)
8268 (when (and org-link-search-failed (eq this-command last-command))
8269 (goto-char (point-min))
8270 (message "Link search wrapped back to beginning of buffer"))
8271 (setq org-link-search-failed nil)
8272 (let* ((pos (point))
8273 (ct (org-context))
8274 (a (assoc :link ct)))
8275 (if a (goto-char (nth 2 a)))
8276 (if (re-search-forward org-any-link-re nil t)
8277 (progn
8278 (goto-char (match-beginning 0))
8279 (if (org-invisible-p) (org-show-context)))
8280 (goto-char pos)
8281 (setq org-link-search-failed t)
8282 (error "No further link found"))))
8284 (defun org-previous-link ()
8285 "Move backward to the previous link.
8286 If the link is in hidden text, expose it."
8287 (interactive)
8288 (when (and org-link-search-failed (eq this-command last-command))
8289 (goto-char (point-max))
8290 (message "Link search wrapped back to end of buffer"))
8291 (setq org-link-search-failed nil)
8292 (let* ((pos (point))
8293 (ct (org-context))
8294 (a (assoc :link ct)))
8295 (if a (goto-char (nth 1 a)))
8296 (if (re-search-backward org-any-link-re nil t)
8297 (progn
8298 (goto-char (match-beginning 0))
8299 (if (org-invisible-p) (org-show-context)))
8300 (goto-char pos)
8301 (setq org-link-search-failed t)
8302 (error "No further link found"))))
8304 (defun org-translate-link (s)
8305 "Translate a link string if a translation function has been defined."
8306 (if (and org-link-translation-function
8307 (fboundp org-link-translation-function)
8308 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8309 (progn
8310 (setq s (funcall org-link-translation-function
8311 (match-string 1) (match-string 2)))
8312 (concat (car s) ":" (cdr s)))
8315 (defun org-translate-link-from-planner (type path)
8316 "Translate a link from Emacs Planner syntax so that Org can follow it.
8317 This is still an experimental function, your mileage may vary."
8318 (cond
8319 ((member type '("http" "https" "news" "ftp"))
8320 ;; standard Internet links are the same.
8321 nil)
8322 ((and (equal type "irc") (string-match "^//" path))
8323 ;; Planner has two / at the beginning of an irc link, we have 1.
8324 ;; We should have zero, actually....
8325 (setq path (substring path 1)))
8326 ((and (equal type "lisp") (string-match "^/" path))
8327 ;; Planner has a slash, we do not.
8328 (setq type "elisp" path (substring path 1)))
8329 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8330 ;; A typical message link. Planner has the id after the final slash,
8331 ;; we separate it with a hash mark
8332 (setq path (concat (match-string 1 path) "#"
8333 (org-remove-angle-brackets (match-string 2 path)))))
8335 (cons type path))
8337 (defun org-find-file-at-mouse (ev)
8338 "Open file link or URL at mouse."
8339 (interactive "e")
8340 (mouse-set-point ev)
8341 (org-open-at-point 'in-emacs))
8343 (defun org-open-at-mouse (ev)
8344 "Open file link or URL at mouse."
8345 (interactive "e")
8346 (mouse-set-point ev)
8347 (if (eq major-mode 'org-agenda-mode)
8348 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8349 (org-open-at-point))
8351 (defvar org-window-config-before-follow-link nil
8352 "The window configuration before following a link.
8353 This is saved in case the need arises to restore it.")
8355 (defvar org-open-link-marker (make-marker)
8356 "Marker pointing to the location where `org-open-at-point; was called.")
8358 ;;;###autoload
8359 (defun org-open-at-point-global ()
8360 "Follow a link like Org-mode does.
8361 This command can be called in any mode to follow a link that has
8362 Org-mode syntax."
8363 (interactive)
8364 (org-run-like-in-org-mode 'org-open-at-point))
8366 ;;;###autoload
8367 (defun org-open-link-from-string (s &optional arg reference-buffer)
8368 "Open a link in the string S, as if it was in Org-mode."
8369 (interactive "sLink: \nP")
8370 (let ((reference-buffer (or reference-buffer (current-buffer))))
8371 (with-temp-buffer
8372 (let ((org-inhibit-startup t))
8373 (org-mode)
8374 (insert s)
8375 (goto-char (point-min))
8376 (org-open-at-point arg reference-buffer)))))
8378 (defun org-open-at-point (&optional in-emacs reference-buffer)
8379 "Open link at or after point.
8380 If there is no link at point, this function will search forward up to
8381 the end of the current line.
8382 Normally, files will be opened by an appropriate application. If the
8383 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8384 With a double prefix argument, try to open outside of Emacs, in the
8385 application the system uses for this file type."
8386 (interactive "P")
8387 (org-load-modules-maybe)
8388 (move-marker org-open-link-marker (point))
8389 (setq org-window-config-before-follow-link (current-window-configuration))
8390 (org-remove-occur-highlights nil nil t)
8391 (cond
8392 ((and (org-on-heading-p)
8393 (not (org-in-regexp
8394 (concat org-plain-link-re "\\|"
8395 org-bracket-link-regexp "\\|"
8396 org-angle-link-re "\\|"
8397 "[ \t]:[^ \t\n]+:[ \t]*$")))
8398 (not (get-text-property (point) 'org-linked-text)))
8399 (or (org-offer-links-in-entry in-emacs)
8400 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8401 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8402 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8403 (org-footnote-action))
8405 (let (type path link line search (pos (point)))
8406 (catch 'match
8407 (save-excursion
8408 (skip-chars-forward "^]\n\r")
8409 (when (org-in-regexp org-bracket-link-regexp 1)
8410 (setq link (org-extract-attributes
8411 (org-link-unescape (org-match-string-no-properties 1))))
8412 (while (string-match " *\n *" link)
8413 (setq link (replace-match " " t t link)))
8414 (setq link (org-link-expand-abbrev link))
8415 (cond
8416 ((or (file-name-absolute-p link)
8417 (string-match "^\\.\\.?/" link))
8418 (setq type "file" path link))
8419 ((string-match org-link-re-with-space3 link)
8420 (setq type (match-string 1 link) path (match-string 2 link)))
8421 (t (setq type "thisfile" path link)))
8422 (throw 'match t)))
8424 (when (get-text-property (point) 'org-linked-text)
8425 (setq type "thisfile"
8426 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8427 (1+ (point)) (point))
8428 path (buffer-substring
8429 (previous-single-property-change pos 'org-linked-text)
8430 (next-single-property-change pos 'org-linked-text)))
8431 (throw 'match t))
8433 (save-excursion
8434 (when (or (org-in-regexp org-angle-link-re)
8435 (org-in-regexp org-plain-link-re))
8436 (setq type (match-string 1) path (match-string 2))
8437 (throw 'match t)))
8438 (save-excursion
8439 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8440 (setq type "tags"
8441 path (match-string 1))
8442 (while (string-match ":" path)
8443 (setq path (replace-match "+" t t path)))
8444 (throw 'match t)))
8445 (when (org-in-regexp "<\\([^><\n]+\\)>")
8446 (setq type "tree-match"
8447 path (match-string 1))
8448 (throw 'match t)))
8449 (unless path
8450 (error "No link found"))
8452 ;; switch back to reference buffer
8453 ;; needed when if called in a temporary buffer through
8454 ;; org-open-link-from-string
8455 (with-current-buffer (or reference-buffer (current-buffer))
8457 ;; Remove any trailing spaces in path
8458 (if (string-match " +\\'" path)
8459 (setq path (replace-match "" t t path)))
8460 (if (and org-link-translation-function
8461 (fboundp org-link-translation-function))
8462 ;; Check if we need to translate the link
8463 (let ((tmp (funcall org-link-translation-function type path)))
8464 (setq type (car tmp) path (cdr tmp))))
8466 (cond
8468 ((assoc type org-link-protocols)
8469 (funcall (nth 1 (assoc type org-link-protocols)) path))
8471 ((equal type "mailto")
8472 (let ((cmd (car org-link-mailto-program))
8473 (args (cdr org-link-mailto-program)) args1
8474 (address path) (subject "") a)
8475 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8476 (setq address (match-string 1 path)
8477 subject (org-link-escape (match-string 2 path))))
8478 (while args
8479 (cond
8480 ((not (stringp (car args))) (push (pop args) args1))
8481 (t (setq a (pop args))
8482 (if (string-match "%a" a)
8483 (setq a (replace-match address t t a)))
8484 (if (string-match "%s" a)
8485 (setq a (replace-match subject t t a)))
8486 (push a args1))))
8487 (apply cmd (nreverse args1))))
8489 ((member type '("http" "https" "ftp" "news"))
8490 (browse-url (concat type ":" (org-link-escape
8491 path org-link-escape-chars-browser))))
8493 ((member type '("message"))
8494 (browse-url (concat type ":" path)))
8496 ((string= type "tags")
8497 (org-tags-view in-emacs path))
8499 ((string= type "tree-match")
8500 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8502 ((string= type "file")
8503 (if (string-match "::\\([0-9]+\\)\\'" path)
8504 (setq line (string-to-number (match-string 1 path))
8505 path (substring path 0 (match-beginning 0)))
8506 (if (string-match "::\\(.+\\)\\'" path)
8507 (setq search (match-string 1 path)
8508 path (substring path 0 (match-beginning 0)))))
8509 (if (string-match "[*?{]" (file-name-nondirectory path))
8510 (dired path)
8511 (org-open-file path in-emacs line search)))
8513 ((string= type "news")
8514 (require 'org-gnus)
8515 (org-gnus-follow-link path))
8517 ((string= type "shell")
8518 (let ((cmd path))
8519 (if (or (not org-confirm-shell-link-function)
8520 (funcall org-confirm-shell-link-function
8521 (format "Execute \"%s\" in shell? "
8522 (org-add-props cmd nil
8523 'face 'org-warning))))
8524 (progn
8525 (message "Executing %s" cmd)
8526 (shell-command cmd))
8527 (error "Abort"))))
8529 ((string= type "elisp")
8530 (let ((cmd path))
8531 (if (or (not org-confirm-elisp-link-function)
8532 (funcall org-confirm-elisp-link-function
8533 (format "Execute \"%s\" as elisp? "
8534 (org-add-props cmd nil
8535 'face 'org-warning))))
8536 (message "%s => %s" cmd
8537 (if (equal (string-to-char cmd) ?\()
8538 (eval (read cmd))
8539 (call-interactively (read cmd))))
8540 (error "Abort"))))
8542 ((and (string= type "thisfile")
8543 (run-hook-with-args-until-success
8544 'org-open-link-functions path)))
8546 ((string= type "thisfile")
8547 (if in-emacs
8548 (switch-to-buffer-other-window
8549 (org-get-buffer-for-internal-link (current-buffer)))
8550 (org-mark-ring-push))
8551 (let ((cmd `(org-link-search
8552 ,path
8553 ,(cond ((equal in-emacs '(4)) 'occur)
8554 ((equal in-emacs '(16)) 'org-occur)
8555 (t nil))
8556 ,pos)))
8557 (condition-case nil (eval cmd)
8558 (error (progn (widen) (eval cmd))))))
8561 (browse-url-at-point)))))))
8562 (move-marker org-open-link-marker nil)
8563 (run-hook-with-args 'org-follow-link-hook))
8565 (defun org-offer-links-in-entry (&optional nth zero)
8566 "Offer links in the current entry and follow the selected link.
8567 If there is only one link, follow it immediately as well.
8568 If NTH is an integer, immediately pick the NTH link found.
8569 If ZERO is a string, check also this string for a link, and if
8570 there is one, offer it as link number zero."
8571 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8572 "\\(" org-angle-link-re "\\)\\|"
8573 "\\(" org-plain-link-re "\\)"))
8574 (cnt ?0)
8575 (in-emacs (if (integerp nth) nil nth))
8576 have-zero end links link c)
8577 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8578 (push (match-string 0 zero) links)
8579 (setq cnt (1- cnt) have-zero t))
8580 (save-excursion
8581 (org-back-to-heading t)
8582 (setq end (save-excursion (outline-next-heading) (point)))
8583 (while (re-search-forward re end t)
8584 (push (match-string 0) links))
8585 (setq links (org-uniquify (reverse links))))
8587 (cond
8588 ((null links)
8589 (message "No links"))
8590 ((equal (length links) 1)
8591 (setq link (list (car links))))
8592 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8593 (setq link (nth (if have-zero nth (1- nth)) links)))
8594 (t ; we have to select a link
8595 (save-excursion
8596 (save-window-excursion
8597 (delete-other-windows)
8598 (with-output-to-temp-buffer "*Select Link*"
8599 (mapc (lambda (l)
8600 (if (not (string-match org-bracket-link-regexp l))
8601 (princ (format "[%c] %s\n" (incf cnt)
8602 (org-remove-angle-brackets l)))
8603 (if (match-end 3)
8604 (princ (format "[%c] %s (%s)\n" (incf cnt)
8605 (match-string 3 l) (match-string 1 l)))
8606 (princ (format "[%c] %s\n" (incf cnt)
8607 (match-string 1 l))))))
8608 links))
8609 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8610 (message "Select link to open, RET to open all:")
8611 (setq c (read-char-exclusive))
8612 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8613 (when (equal c ?q) (error "Abort"))
8614 (if (equal c ?\C-m)
8615 (setq link links)
8616 (setq nth (- c ?0))
8617 (if have-zero (setq nth (1+ nth)))
8618 (unless (and (integerp nth) (>= (length links) nth))
8619 (error "Invalid link selection"))
8620 (setq link (list (nth (1- nth) links))))))
8621 (if link
8622 (let ((buf (current-buffer)))
8623 (dolist (l link)
8624 (org-open-link-from-string l in-emacs buf))
8626 nil)))
8628 ;; Add special file links that specify the way of opening
8630 (org-add-link-type "file+sys" 'org-open-file-with-system)
8631 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8632 (defun org-open-file-with-system (path)
8633 "Open file at PATH using the system way of opeing it."
8634 (org-open-file path 'system))
8635 (defun org-open-file-with-emacs (path)
8636 "Open file at PATH in emacs."
8637 (org-open-file path 'emacs))
8638 (defun org-remove-file-link-modifiers ()
8639 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8640 (goto-char (point-min))
8641 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8642 (org-if-unprotected
8643 (replace-match "file:" t t))))
8644 (eval-after-load "org-exp"
8645 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8646 'org-remove-file-link-modifiers))
8648 ;;;; Time estimates
8650 (defun org-get-effort (&optional pom)
8651 "Get the effort estimate for the current entry."
8652 (org-entry-get pom org-effort-property))
8654 ;;; File search
8656 (defvar org-create-file-search-functions nil
8657 "List of functions to construct the right search string for a file link.
8658 These functions are called in turn with point at the location to
8659 which the link should point.
8661 A function in the hook should first test if it would like to
8662 handle this file type, for example by checking the major-mode or
8663 the file extension. If it decides not to handle this file, it
8664 should just return nil to give other functions a chance. If it
8665 does handle the file, it must return the search string to be used
8666 when following the link. The search string will be part of the
8667 file link, given after a double colon, and `org-open-at-point'
8668 will automatically search for it. If special measures must be
8669 taken to make the search successful, another function should be
8670 added to the companion hook `org-execute-file-search-functions',
8671 which see.
8673 A function in this hook may also use `setq' to set the variable
8674 `description' to provide a suggestion for the descriptive text to
8675 be used for this link when it gets inserted into an Org-mode
8676 buffer with \\[org-insert-link].")
8678 (defvar org-execute-file-search-functions nil
8679 "List of functions to execute a file search triggered by a link.
8681 Functions added to this hook must accept a single argument, the
8682 search string that was part of the file link, the part after the
8683 double colon. The function must first check if it would like to
8684 handle this search, for example by checking the major-mode or the
8685 file extension. If it decides not to handle this search, it
8686 should just return nil to give other functions a chance. If it
8687 does handle the search, it must return a non-nil value to keep
8688 other functions from trying.
8690 Each function can access the current prefix argument through the
8691 variable `current-prefix-argument'. Note that a single prefix is
8692 used to force opening a link in Emacs, so it may be good to only
8693 use a numeric or double prefix to guide the search function.
8695 In case this is needed, a function in this hook can also restore
8696 the window configuration before `org-open-at-point' was called using:
8698 (set-window-configuration org-window-config-before-follow-link)")
8700 (defun org-link-search (s &optional type avoid-pos)
8701 "Search for a link search option.
8702 If S is surrounded by forward slashes, it is interpreted as a
8703 regular expression. In org-mode files, this will create an `org-occur'
8704 sparse tree. In ordinary files, `occur' will be used to list matches.
8705 If the current buffer is in `dired-mode', grep will be used to search
8706 in all files. If AVOID-POS is given, ignore matches near that position."
8707 (let ((case-fold-search t)
8708 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8709 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8710 (append '(("") (" ") ("\t") ("\n"))
8711 org-emphasis-alist)
8712 "\\|") "\\)"))
8713 (pos (point))
8714 (pre nil) (post nil)
8715 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8716 (cond
8717 ;; First check if there are any special
8718 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8719 ;; Now try the builtin stuff
8720 ((and (equal (string-to-char s0) ?#)
8721 (> (length s0) 1)
8722 (save-excursion
8723 (goto-char (point-min))
8724 (and
8725 (re-search-forward
8726 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8727 (setq type 'dedicated
8728 pos (match-beginning 0))))
8729 ;; There is an exact target for this
8730 (goto-char pos)
8731 (org-back-to-heading t)))
8732 ((save-excursion
8733 (goto-char (point-min))
8734 (and
8735 (re-search-forward
8736 (concat "<<" (regexp-quote s0) ">>") nil t)
8737 (setq type 'dedicated
8738 pos (match-beginning 0))))
8739 ;; There is an exact target for this
8740 (goto-char pos))
8741 ((and (string-match "^(\\(.*\\))$" s0)
8742 (save-excursion
8743 (goto-char (point-min))
8744 (and
8745 (re-search-forward
8746 (concat "[^[]" (regexp-quote
8747 (format org-coderef-label-format
8748 (match-string 1 s0))))
8749 nil t)
8750 (setq type 'dedicated
8751 pos (1+ (match-beginning 0))))))
8752 ;; There is a coderef target for this
8753 (goto-char pos))
8754 ((string-match "^/\\(.*\\)/$" s)
8755 ;; A regular expression
8756 (cond
8757 ((org-mode-p)
8758 (org-occur (match-string 1 s)))
8759 ;;((eq major-mode 'dired-mode)
8760 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8761 (t (org-do-occur (match-string 1 s)))))
8763 ;; A normal search strings
8764 (when (equal (string-to-char s) ?*)
8765 ;; Anchor on headlines, post may include tags.
8766 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8767 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8768 s (substring s 1)))
8769 (remove-text-properties
8770 0 (length s)
8771 '(face nil mouse-face nil keymap nil fontified nil) s)
8772 ;; Make a series of regular expressions to find a match
8773 (setq words (org-split-string s "[ \n\r\t]+")
8775 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8776 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8777 "\\)" markers)
8778 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8779 re2a (concat "[ \t\r\n]" re2a_)
8780 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8781 re4 (concat "[^a-zA-Z_]" re4_)
8783 re1 (concat pre re2 post)
8784 re3 (concat pre (if pre re4_ re4) post)
8785 re5 (concat pre ".*" re4)
8786 re2 (concat pre re2)
8787 re2a (concat pre (if pre re2a_ re2a))
8788 re4 (concat pre (if pre re4_ re4))
8789 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8790 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8791 re5 "\\)"
8793 (cond
8794 ((eq type 'org-occur) (org-occur reall))
8795 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8796 (t (goto-char (point-min))
8797 (setq type 'fuzzy)
8798 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8799 (org-search-not-self 1 re1 nil t)
8800 (org-search-not-self 1 re2 nil t)
8801 (org-search-not-self 1 re2a nil t)
8802 (org-search-not-self 1 re3 nil t)
8803 (org-search-not-self 1 re4 nil t)
8804 (org-search-not-self 1 re5 nil t)
8806 (goto-char (match-beginning 1))
8807 (goto-char pos)
8808 (error "No match")))))
8810 ;; Normal string-search
8811 (goto-char (point-min))
8812 (if (search-forward s nil t)
8813 (goto-char (match-beginning 0))
8814 (error "No match"))))
8815 (and (org-mode-p) (org-show-context 'link-search))
8816 type))
8818 (defun org-search-not-self (group &rest args)
8819 "Execute `re-search-forward', but only accept matches that do not
8820 enclose the position of `org-open-link-marker'."
8821 (let ((m org-open-link-marker))
8822 (catch 'exit
8823 (while (apply 're-search-forward args)
8824 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8825 (goto-char (match-end group))
8826 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8827 (> (match-beginning 0) (marker-position m))
8828 (< (match-end 0) (marker-position m)))
8829 (save-match-data
8830 (or (not (org-in-regexp
8831 org-bracket-link-analytic-regexp 1))
8832 (not (match-end 4)) ; no description
8833 (and (<= (match-beginning 4) (point))
8834 (>= (match-end 4) (point))))))
8835 (throw 'exit (point))))))))
8837 (defun org-get-buffer-for-internal-link (buffer)
8838 "Return a buffer to be used for displaying the link target of internal links."
8839 (cond
8840 ((not org-display-internal-link-with-indirect-buffer)
8841 buffer)
8842 ((string-match "(Clone)$" (buffer-name buffer))
8843 (message "Buffer is already a clone, not making another one")
8844 ;; we also do not modify visibility in this case
8845 buffer)
8846 (t ; make a new indirect buffer for displaying the link
8847 (let* ((bn (buffer-name buffer))
8848 (ibn (concat bn "(Clone)"))
8849 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8850 (with-current-buffer ib (org-overview))
8851 ib))))
8853 (defun org-do-occur (regexp &optional cleanup)
8854 "Call the Emacs command `occur'.
8855 If CLEANUP is non-nil, remove the printout of the regular expression
8856 in the *Occur* buffer. This is useful if the regex is long and not useful
8857 to read."
8858 (occur regexp)
8859 (when cleanup
8860 (let ((cwin (selected-window)) win beg end)
8861 (when (setq win (get-buffer-window "*Occur*"))
8862 (select-window win))
8863 (goto-char (point-min))
8864 (when (re-search-forward "match[a-z]+" nil t)
8865 (setq beg (match-end 0))
8866 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8867 (setq end (1- (match-beginning 0)))))
8868 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8869 (goto-char (point-min))
8870 (select-window cwin))))
8872 ;;; The mark ring for links jumps
8874 (defvar org-mark-ring nil
8875 "Mark ring for positions before jumps in Org-mode.")
8876 (defvar org-mark-ring-last-goto nil
8877 "Last position in the mark ring used to go back.")
8878 ;; Fill and close the ring
8879 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8880 (loop for i from 1 to org-mark-ring-length do
8881 (push (make-marker) org-mark-ring))
8882 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8883 org-mark-ring)
8885 (defun org-mark-ring-push (&optional pos buffer)
8886 "Put the current position or POS into the mark ring and rotate it."
8887 (interactive)
8888 (setq pos (or pos (point)))
8889 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8890 (move-marker (car org-mark-ring)
8891 (or pos (point))
8892 (or buffer (current-buffer)))
8893 (message "%s"
8894 (substitute-command-keys
8895 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8897 (defun org-mark-ring-goto (&optional n)
8898 "Jump to the previous position in the mark ring.
8899 With prefix arg N, jump back that many stored positions. When
8900 called several times in succession, walk through the entire ring.
8901 Org-mode commands jumping to a different position in the current file,
8902 or to another Org-mode file, automatically push the old position
8903 onto the ring."
8904 (interactive "p")
8905 (let (p m)
8906 (if (eq last-command this-command)
8907 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8908 (setq p org-mark-ring))
8909 (setq org-mark-ring-last-goto p)
8910 (setq m (car p))
8911 (switch-to-buffer (marker-buffer m))
8912 (goto-char m)
8913 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8915 (defun org-remove-angle-brackets (s)
8916 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8917 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8919 (defun org-add-angle-brackets (s)
8920 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8921 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8923 (defun org-remove-double-quotes (s)
8924 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8925 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8928 ;;; Following specific links
8930 (defun org-follow-timestamp-link ()
8931 (cond
8932 ((org-at-date-range-p t)
8933 (let ((org-agenda-start-on-weekday)
8934 (t1 (match-string 1))
8935 (t2 (match-string 2)))
8936 (setq t1 (time-to-days (org-time-string-to-time t1))
8937 t2 (time-to-days (org-time-string-to-time t2)))
8938 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8939 ((org-at-timestamp-p t)
8940 (org-agenda-list nil (time-to-days (org-time-string-to-time
8941 (substring (match-string 1) 0 10)))
8943 (t (error "This should not happen"))))
8946 ;;; Following file links
8947 (defvar org-wait nil)
8948 (defun org-open-file (path &optional in-emacs line search)
8949 "Open the file at PATH.
8950 First, this expands any special file name abbreviations. Then the
8951 configuration variable `org-file-apps' is checked if it contains an
8952 entry for this file type, and if yes, the corresponding command is launched.
8954 If no application is found, Emacs simply visits the file.
8956 With optional prefix argument IN-EMACS, Emacs will visit the file.
8957 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8958 and to use an external application to visit the file.
8960 Optional LINE specifies a line to go to, optional SEARCH a string to
8961 search for. If LINE or SEARCH is given, the file will always be
8962 opened in Emacs.
8963 If the file does not exist, an error is thrown."
8964 (setq in-emacs (or in-emacs line search))
8965 (let* ((file (if (equal path "")
8966 buffer-file-name
8967 (substitute-in-file-name (expand-file-name path))))
8968 (apps (append org-file-apps (org-default-apps)))
8969 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8970 (dirp (if remp nil (file-directory-p file)))
8971 (file (if (and dirp org-open-directory-means-index-dot-org)
8972 (concat (file-name-as-directory file) "index.org")
8973 file))
8974 (a-m-a-p (assq 'auto-mode apps))
8975 (dfile (downcase file))
8976 (old-buffer (current-buffer))
8977 (old-pos (point))
8978 (old-mode major-mode)
8979 ext cmd)
8980 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8981 (setq ext (match-string 1 dfile))
8982 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8983 (setq ext (match-string 1 dfile))))
8984 (cond
8985 ((member in-emacs '((16) system))
8986 (setq cmd (cdr (assoc 'system apps))))
8987 (in-emacs (setq cmd 'emacs))
8989 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8990 (and dirp (cdr (assoc 'directory apps)))
8991 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8992 'string-match)
8993 (cdr (assoc ext apps))
8994 (cdr (assoc t apps))))))
8995 (when (eq cmd 'system)
8996 (setq cmd (cdr (assoc 'system apps))))
8997 (when (eq cmd 'default)
8998 (setq cmd (cdr (assoc t apps))))
8999 (when (eq cmd 'mailcap)
9000 (require 'mailcap)
9001 (mailcap-parse-mailcaps)
9002 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9003 (command (mailcap-mime-info mime-type)))
9004 (if (stringp command)
9005 (setq cmd command)
9006 (setq cmd 'emacs))))
9007 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9008 (not (file-exists-p file))
9009 (not org-open-non-existing-files))
9010 (error "No such file: %s" file))
9011 (cond
9012 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9013 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9014 (while (string-match "['\"]%s['\"]" cmd)
9015 (setq cmd (replace-match "%s" t t cmd)))
9016 (while (string-match "%s" cmd)
9017 (setq cmd (replace-match
9018 (save-match-data
9019 (shell-quote-argument
9020 (convert-standard-filename file)))
9021 t t cmd)))
9022 (save-window-excursion
9023 (start-process-shell-command cmd nil cmd)
9024 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9026 ((or (stringp cmd)
9027 (eq cmd 'emacs))
9028 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9029 (widen)
9030 (if line (org-goto-line line)
9031 (if search (org-link-search search))))
9032 ((consp cmd)
9033 (let ((file (convert-standard-filename file)))
9034 (eval cmd)))
9035 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9036 (and (org-mode-p) (eq old-mode 'org-mode)
9037 (or (not (equal old-buffer (current-buffer)))
9038 (not (equal old-pos (point))))
9039 (org-mark-ring-push old-pos old-buffer))))
9041 (defun org-default-apps ()
9042 "Return the default applications for this operating system."
9043 (cond
9044 ((eq system-type 'darwin)
9045 org-file-apps-defaults-macosx)
9046 ((eq system-type 'windows-nt)
9047 org-file-apps-defaults-windowsnt)
9048 (t org-file-apps-defaults-gnu)))
9050 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9051 "Convert extensions to regular expressions in the cars of LIST.
9052 Also, weed out any non-string entries, because the return value is used
9053 only for regexp matching.
9054 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9055 point to the symbol `emacs', indicating that the file should
9056 be opened in Emacs."
9057 (append
9058 (delq nil
9059 (mapcar (lambda (x)
9060 (if (not (stringp (car x)))
9062 (if (string-match "\\W" (car x))
9064 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9065 list))
9066 (if add-auto-mode
9067 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9069 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9070 (defun org-file-remote-p (file)
9071 "Test whether FILE specifies a location on a remote system.
9072 Return non-nil if the location is indeed remote.
9074 For example, the filename \"/user@host:/foo\" specifies a location
9075 on the system \"/user@host:\"."
9076 (cond ((fboundp 'file-remote-p)
9077 (file-remote-p file))
9078 ((fboundp 'tramp-handle-file-remote-p)
9079 (tramp-handle-file-remote-p file))
9080 ((and (boundp 'ange-ftp-name-format)
9081 (string-match (car ange-ftp-name-format) file))
9083 (t nil)))
9086 ;;;; Refiling
9088 (defun org-get-org-file ()
9089 "Read a filename, with default directory `org-directory'."
9090 (let ((default (or org-default-notes-file remember-data-file)))
9091 (read-file-name (format "File name [%s]: " default)
9092 (file-name-as-directory org-directory)
9093 default)))
9095 (defun org-notes-order-reversed-p ()
9096 "Check if the current file should receive notes in reversed order."
9097 (cond
9098 ((not org-reverse-note-order) nil)
9099 ((eq t org-reverse-note-order) t)
9100 ((not (listp org-reverse-note-order)) nil)
9101 (t (catch 'exit
9102 (let ((all org-reverse-note-order)
9103 entry)
9104 (while (setq entry (pop all))
9105 (if (string-match (car entry) buffer-file-name)
9106 (throw 'exit (cdr entry))))
9107 nil)))))
9109 (defvar org-refile-target-table nil
9110 "The list of refile targets, created by `org-refile'.")
9112 (defvar org-agenda-new-buffers nil
9113 "Buffers created to visit agenda files.")
9115 (defun org-get-refile-targets (&optional default-buffer)
9116 "Produce a table with refile targets."
9117 (let ((case-fold-search nil)
9118 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9119 (entries (or org-refile-targets '((nil . (:level . 1)))))
9120 targets txt re files f desc descre fast-path-p level pos0)
9121 (message "Getting targets...")
9122 (with-current-buffer (or default-buffer (current-buffer))
9123 (while (setq entry (pop entries))
9124 (setq files (car entry) desc (cdr entry))
9125 (setq fast-path-p nil)
9126 (cond
9127 ((null files) (setq files (list (current-buffer))))
9128 ((eq files 'org-agenda-files)
9129 (setq files (org-agenda-files 'unrestricted)))
9130 ((and (symbolp files) (fboundp files))
9131 (setq files (funcall files)))
9132 ((and (symbolp files) (boundp files))
9133 (setq files (symbol-value files))))
9134 (if (stringp files) (setq files (list files)))
9135 (cond
9136 ((eq (car desc) :tag)
9137 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9138 ((eq (car desc) :todo)
9139 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9140 ((eq (car desc) :regexp)
9141 (setq descre (cdr desc)))
9142 ((eq (car desc) :level)
9143 (setq descre (concat "^\\*\\{" (number-to-string
9144 (if org-odd-levels-only
9145 (1- (* 2 (cdr desc)))
9146 (cdr desc)))
9147 "\\}[ \t]")))
9148 ((eq (car desc) :maxlevel)
9149 (setq fast-path-p t)
9150 (setq descre (concat "^\\*\\{1," (number-to-string
9151 (if org-odd-levels-only
9152 (1- (* 2 (cdr desc)))
9153 (cdr desc)))
9154 "\\}[ \t]")))
9155 (t (error "Bad refiling target description %s" desc)))
9156 (while (setq f (pop files))
9157 (with-current-buffer
9158 (if (bufferp f) f (org-get-agenda-file-buffer f))
9159 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9160 (setq f (and f (expand-file-name f)))
9161 (if (eq org-refile-use-outline-path 'file)
9162 (push (list (file-name-nondirectory f) f nil nil) targets))
9163 (save-excursion
9164 (save-restriction
9165 (widen)
9166 (goto-char (point-min))
9167 (while (re-search-forward descre nil t)
9168 (goto-char (setq pos0 (point-at-bol)))
9169 (catch 'next
9170 (when org-refile-target-verify-function
9171 (save-match-data
9172 (or (funcall org-refile-target-verify-function)
9173 (throw 'next t))))
9174 (when (looking-at org-complex-heading-regexp)
9175 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9176 txt (org-link-display-format (match-string 4))
9177 re (concat "^" (regexp-quote
9178 (buffer-substring (match-beginning 1)
9179 (match-end 4)))))
9180 (if (match-end 5) (setq re (concat re "[ \t]+"
9181 (regexp-quote
9182 (match-string 5)))))
9183 (setq re (concat re "[ \t]*$"))
9184 (when org-refile-use-outline-path
9185 (setq txt (mapconcat 'org-protect-slash
9186 (append
9187 (if (eq org-refile-use-outline-path 'file)
9188 (list (file-name-nondirectory
9189 (buffer-file-name (buffer-base-buffer))))
9190 (if (eq org-refile-use-outline-path 'full-file-path)
9191 (list (buffer-file-name (buffer-base-buffer)))))
9192 (org-get-outline-path fast-path-p level txt)
9193 (list txt))
9194 "/")))
9195 (push (list txt f re (point)) targets)))
9196 (when (= (point) pos0)
9197 ;; verification function has not moved point
9198 (goto-char (point-at-eol))))))))))
9199 (message "Getting targets...done")
9200 (nreverse targets)))
9202 (defun org-protect-slash (s)
9203 (while (string-match "/" s)
9204 (setq s (replace-match "\\" t t s)))
9207 (defvar org-olpa (make-vector 20 nil))
9209 (defun org-get-outline-path (&optional fastp level heading)
9210 "Return the outline path to the current entry, as a list.
9211 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9212 routine which makes outline path derivations for an entire file,
9213 avoiding backtracing."
9214 (if fastp
9215 (progn
9216 (if (> level 19)
9217 (error "Outline path failure, more than 19 levels."))
9218 (loop for i from level upto 19 do
9219 (aset org-olpa i nil))
9220 (prog1
9221 (delq nil (append org-olpa nil))
9222 (aset org-olpa level heading)))
9223 (let (rtn case-fold-search)
9224 (save-excursion
9225 (save-restriction
9226 (widen)
9227 (while (org-up-heading-safe)
9228 (when (looking-at org-complex-heading-regexp)
9229 (push (org-match-string-no-properties 4) rtn)))
9230 rtn)))))
9232 (defun org-format-outline-path (path &optional width prefix)
9233 "Format the outlie path PATH for display.
9234 Width is the maximum number of characters that is available.
9235 Prefix is a prefix to be included in the returned string,
9236 such as the file name."
9237 (setq width (or width 79))
9238 (if prefix (setq width (- width (length prefix))))
9239 (if (not path)
9240 (or prefix "")
9241 (let* ((nsteps (length path))
9242 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9243 (maxwidth (if (<= total-width width)
9244 10000 ;; everything fits
9245 ;; we need to shorten the level headings
9246 (/ (- width nsteps) nsteps)))
9247 (org-odd-levels-only nil)
9248 (n 0)
9249 (total (1+ (length prefix))))
9250 (setq maxwidth (max maxwidth 10))
9251 (concat prefix
9252 (mapconcat
9253 (lambda (h)
9254 (setq n (1+ n))
9255 (if (and (= n nsteps) (< maxwidth 10000))
9256 (setq maxwidth (- total-width total)))
9257 (if (< (length h) maxwidth)
9258 (progn (setq total (+ total (length h) 1)) h)
9259 (setq h (substring h 0 (- maxwidth 2))
9260 total (+ total maxwidth 1))
9261 (if (string-match "[ \t]+\\'" h)
9262 (setq h (substring h 0 (match-beginning 0))))
9263 (setq h (concat h "..")))
9264 (org-add-props h nil 'face
9265 (nth (% (1- n) org-n-level-faces)
9266 org-level-faces))
9268 path "/")))))
9270 (defun org-display-outline-path (&optional file current)
9271 "Display the current outline path in the echo area."
9272 (interactive "P")
9273 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9274 (case-fold-search nil)
9275 (path (and (org-mode-p) (org-get-outline-path))))
9276 (if current (setq path (append path
9277 (save-excursion
9278 (org-back-to-heading t)
9279 (if (looking-at org-complex-heading-regexp)
9280 (list (match-string 4)))))))
9281 (message "%s"
9282 (org-format-outline-path
9283 path
9284 (1- (frame-width))
9285 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9287 (defvar org-refile-history nil
9288 "History for refiling operations.")
9290 (defvar org-after-refile-insert-hook nil
9291 "Hook run after `org-refile' has inserted its stuff at the new location.
9292 Note that this is still *before* the stuff will be removed from
9293 the *old* location.")
9295 (defun org-refile (&optional goto default-buffer rfloc)
9296 "Move the entry at point to another heading.
9297 The list of target headings is compiled using the information in
9298 `org-refile-targets', which see. This list is created before each use
9299 and will therefore always be up-to-date.
9301 At the target location, the entry is filed as a subitem of the target heading.
9302 Depending on `org-reverse-note-order', the new subitem will either be the
9303 first or the last subitem.
9305 If there is an active region, all entries in that region will be moved.
9306 However, the region must fulfil the requirement that the first heading
9307 is the first one sets the top-level of the moved text - at most siblings
9308 below it are allowed.
9310 With prefix arg GOTO, the command will only visit the target location,
9311 not actually move anything.
9312 With a double prefix `C-u C-u', go to the location where the last refiling
9313 operation has put the subtree.
9314 With a prefix argument of `2', refile to the running clock.
9316 RFLOC can be a refile location obtained in a different way.
9318 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9319 (interactive "P")
9320 (let* ((cbuf (current-buffer))
9321 (regionp (org-region-active-p))
9322 (region-start (and regionp (region-beginning)))
9323 (region-end (and regionp (region-end)))
9324 (region-length (and regionp (- region-end region-start)))
9325 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9326 pos it nbuf file re level reversed)
9327 (setq last-command nil)
9328 (when regionp
9329 (goto-char region-start)
9330 (or (bolp) (goto-char (point-at-bol)))
9331 (setq region-start (point))
9332 (unless (org-kill-is-subtree-p
9333 (buffer-substring region-start region-end))
9334 (error "The region is not a (sequence of) subtree(s)")))
9335 (if (equal goto '(16))
9336 (org-refile-goto-last-stored)
9337 (when (or
9338 (and (equal goto 2)
9339 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9340 (prog1
9341 (setq it (list (or org-clock-heading "running clock")
9342 (buffer-file-name
9343 (marker-buffer org-clock-hd-marker))
9345 (marker-position org-clock-hd-marker)))
9346 (setq goto nil)))
9347 (setq it (or rfloc
9348 (save-excursion
9349 (org-refile-get-location
9350 (if goto "Goto: " "Refile to: ") default-buffer
9351 org-refile-allow-creating-parent-nodes)))))
9352 (setq file (nth 1 it)
9353 re (nth 2 it)
9354 pos (nth 3 it))
9355 (if (and (not goto)
9357 (equal (buffer-file-name) file)
9358 (if regionp
9359 (and (>= pos region-start)
9360 (<= pos region-end))
9361 (and (>= pos (point))
9362 (< pos (save-excursion
9363 (org-end-of-subtree t t))))))
9364 (error "Cannot refile to position inside the tree or region"))
9366 (setq nbuf (or (find-buffer-visiting file)
9367 (find-file-noselect file)))
9368 (if goto
9369 (progn
9370 (switch-to-buffer nbuf)
9371 (goto-char pos)
9372 (org-show-context 'org-goto))
9373 (if regionp
9374 (progn
9375 (org-kill-new (buffer-substring region-start region-end))
9376 (org-save-markers-in-region region-start region-end))
9377 (org-copy-subtree 1 nil t))
9378 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9379 (find-file-noselect file)))
9380 (setq reversed (org-notes-order-reversed-p))
9381 (save-excursion
9382 (save-restriction
9383 (widen)
9384 (if pos
9385 (progn
9386 (goto-char pos)
9387 (looking-at outline-regexp)
9388 (setq level (org-get-valid-level (funcall outline-level) 1))
9389 (goto-char
9390 (if reversed
9391 (or (outline-next-heading) (point-max))
9392 (or (save-excursion (org-get-next-sibling))
9393 (org-end-of-subtree t t)
9394 (point-max)))))
9395 (setq level 1)
9396 (if (not reversed)
9397 (goto-char (point-max))
9398 (goto-char (point-min))
9399 (or (outline-next-heading) (goto-char (point-max)))))
9400 (if (not (bolp)) (newline))
9401 (bookmark-set "org-refile-last-stored")
9402 (org-paste-subtree level)
9403 (if (fboundp 'deactivate-mark) (deactivate-mark))
9404 (run-hooks 'org-after-refile-insert-hook))))
9405 (if regionp
9406 (delete-region (point) (+ (point) region-length))
9407 (org-cut-subtree))
9408 (when (featurep 'org-inlinetask)
9409 (org-inlinetask-remove-END-maybe))
9410 (setq org-markers-to-move nil)
9411 (message "Refiled to \"%s\"" (car it))))))
9412 (org-reveal))
9414 (defun org-refile-goto-last-stored ()
9415 "Go to the location where the last refile was stored."
9416 (interactive)
9417 (bookmark-jump "org-refile-last-stored")
9418 (message "This is the location of the last refile"))
9420 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9421 "Prompt the user for a refile location, using PROMPT."
9422 (let ((org-refile-targets org-refile-targets)
9423 (org-refile-use-outline-path org-refile-use-outline-path))
9424 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9425 (unless org-refile-target-table
9426 (error "No refile targets"))
9427 (let* ((cbuf (current-buffer))
9428 (partial-completion-mode nil)
9429 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9430 (cfunc (if (and org-refile-use-outline-path
9431 org-outline-path-complete-in-steps)
9432 'org-olpath-completing-read
9433 'org-icompleting-read))
9434 (extra (if org-refile-use-outline-path "/" ""))
9435 (filename (and cfn (expand-file-name cfn)))
9436 (tbl (mapcar
9437 (lambda (x)
9438 (if (and (not (member org-refile-use-outline-path
9439 '(file full-file-path)))
9440 (not (equal filename (nth 1 x))))
9441 (cons (concat (car x) extra " ("
9442 (file-name-nondirectory (nth 1 x)) ")")
9443 (cdr x))
9444 (cons (concat (car x) extra) (cdr x))))
9445 org-refile-target-table))
9446 (completion-ignore-case t)
9447 pa answ parent-target child parent old-hist)
9448 (setq old-hist org-refile-history)
9449 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9450 nil 'org-refile-history))
9451 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9452 (if pa
9453 (progn
9454 (when (or (not org-refile-history)
9455 (not (eq old-hist org-refile-history))
9456 (not (equal (car pa) (car org-refile-history))))
9457 (setq org-refile-history
9458 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9459 org-refile-history
9460 (cdr org-refile-history))))
9461 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9462 (pop org-refile-history)))
9464 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9465 (setq parent (match-string 1 answ)
9466 child (match-string 2 answ))
9467 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9468 (when (and parent-target
9469 (or (eq new-nodes t)
9470 (and (eq new-nodes 'confirm)
9471 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9472 (org-refile-new-child parent-target child))))))
9474 (defun org-refile-new-child (parent-target child)
9475 "Use refile target PARENT-TARGET to add new CHILD below it."
9476 (unless parent-target
9477 (error "Cannot find parent for new node"))
9478 (let ((file (nth 1 parent-target))
9479 (pos (nth 3 parent-target))
9480 level)
9481 (with-current-buffer (or (find-buffer-visiting file)
9482 (find-file-noselect file))
9483 (save-excursion
9484 (save-restriction
9485 (widen)
9486 (if pos
9487 (goto-char pos)
9488 (goto-char (point-max))
9489 (if (not (bolp)) (newline)))
9490 (when (looking-at outline-regexp)
9491 (setq level (funcall outline-level))
9492 (org-end-of-subtree t t))
9493 (org-back-over-empty-lines)
9494 (insert "\n" (make-string
9495 (if pos (org-get-valid-level level 1) 1) ?*)
9496 " " child "\n")
9497 (beginning-of-line 0)
9498 (list (concat (car parent-target) "/" child) file "" (point)))))))
9500 (defun org-olpath-completing-read (prompt collection &rest args)
9501 "Read an outline path like a file name."
9502 (let ((thetable collection)
9503 (org-completion-use-ido nil) ; does not work with ido.
9504 (org-completion-use-iswitchb nil)) ; or iswitchb
9505 (apply
9506 'org-icompleting-read prompt
9507 (lambda (string predicate &optional flag)
9508 (let (rtn r f (l (length string)))
9509 (cond
9510 ((eq flag nil)
9511 ;; try completion
9512 (try-completion string thetable))
9513 ((eq flag t)
9514 ;; all-completions
9515 (setq rtn (all-completions string thetable predicate))
9516 (mapcar
9517 (lambda (x)
9518 (setq r (substring x l))
9519 (if (string-match " ([^)]*)$" x)
9520 (setq f (match-string 0 x))
9521 (setq f ""))
9522 (if (string-match "/" r)
9523 (concat string (substring r 0 (match-end 0)) f)
9525 rtn))
9526 ((eq flag 'lambda)
9527 ;; exact match?
9528 (assoc string thetable)))
9530 args)))
9532 ;;;; Dynamic blocks
9534 (defun org-find-dblock (name)
9535 "Find the first dynamic block with name NAME in the buffer.
9536 If not found, stay at current position and return nil."
9537 (let (pos)
9538 (save-excursion
9539 (goto-char (point-min))
9540 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9541 nil t)
9542 (match-beginning 0))))
9543 (if pos (goto-char pos))
9544 pos))
9546 (defconst org-dblock-start-re
9547 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9548 "Matches the start line of a dynamic block, with parameters.")
9550 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9551 "Matches the end of a dynamic block.")
9553 (defun org-create-dblock (plist)
9554 "Create a dynamic block section, with parameters taken from PLIST.
9555 PLIST must contain a :name entry which is used as name of the block."
9556 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9557 (end-of-line 1)
9558 (newline))
9559 (let ((col (current-column))
9560 (name (plist-get plist :name)))
9561 (insert "#+BEGIN: " name)
9562 (while plist
9563 (if (eq (car plist) :name)
9564 (setq plist (cddr plist))
9565 (insert " " (prin1-to-string (pop plist)))))
9566 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9567 (beginning-of-line -2)))
9569 (defun org-prepare-dblock ()
9570 "Prepare dynamic block for refresh.
9571 This empties the block, puts the cursor at the insert position and returns
9572 the property list including an extra property :name with the block name."
9573 (unless (looking-at org-dblock-start-re)
9574 (error "Not at a dynamic block"))
9575 (let* ((begdel (1+ (match-end 0)))
9576 (name (org-no-properties (match-string 1)))
9577 (params (append (list :name name)
9578 (read (concat "(" (match-string 3) ")")))))
9579 (save-excursion
9580 (beginning-of-line 1)
9581 (skip-chars-forward " \t")
9582 (setq params (plist-put params :indentation-column (current-column))))
9583 (unless (re-search-forward org-dblock-end-re nil t)
9584 (error "Dynamic block not terminated"))
9585 (setq params
9586 (append params
9587 (list :content (buffer-substring
9588 begdel (match-beginning 0)))))
9589 (delete-region begdel (match-beginning 0))
9590 (goto-char begdel)
9591 (open-line 1)
9592 params))
9594 (defun org-map-dblocks (&optional command)
9595 "Apply COMMAND to all dynamic blocks in the current buffer.
9596 If COMMAND is not given, use `org-update-dblock'."
9597 (let ((cmd (or command 'org-update-dblock))
9598 pos)
9599 (save-excursion
9600 (goto-char (point-min))
9601 (while (re-search-forward org-dblock-start-re nil t)
9602 (goto-char (setq pos (match-beginning 0)))
9603 (condition-case nil
9604 (funcall cmd)
9605 (error (message "Error during update of dynamic block")))
9606 (goto-char pos)
9607 (unless (re-search-forward org-dblock-end-re nil t)
9608 (error "Dynamic block not terminated"))))))
9610 (defun org-dblock-update (&optional arg)
9611 "User command for updating dynamic blocks.
9612 Update the dynamic block at point. With prefix ARG, update all dynamic
9613 blocks in the buffer."
9614 (interactive "P")
9615 (if arg
9616 (org-update-all-dblocks)
9617 (or (looking-at org-dblock-start-re)
9618 (org-beginning-of-dblock))
9619 (org-update-dblock)))
9621 (defun org-update-dblock ()
9622 "Update the dynamic block at point
9623 This means to empty the block, parse for parameters and then call
9624 the correct writing function."
9625 (save-window-excursion
9626 (let* ((pos (point))
9627 (line (org-current-line))
9628 (params (org-prepare-dblock))
9629 (name (plist-get params :name))
9630 (indent (plist-get params :indentation-column))
9631 (cmd (intern (concat "org-dblock-write:" name))))
9632 (message "Updating dynamic block `%s' at line %d..." name line)
9633 (funcall cmd params)
9634 (message "Updating dynamic block `%s' at line %d...done" name line)
9635 (goto-char pos)
9636 (when (and indent (> indent 0))
9637 (setq indent (make-string indent ?\ ))
9638 (save-excursion
9639 (org-beginning-of-dblock)
9640 (forward-line 1)
9641 (while (not (looking-at org-dblock-end-re))
9642 (insert indent)
9643 (beginning-of-line 2))
9644 (when (looking-at org-dblock-end-re)
9645 (and (looking-at "[ \t]+")
9646 (replace-match ""))
9647 (insert indent)))))))
9649 (defun org-beginning-of-dblock ()
9650 "Find the beginning of the dynamic block at point.
9651 Error if there is no such block at point."
9652 (let ((pos (point))
9653 beg)
9654 (end-of-line 1)
9655 (if (and (re-search-backward org-dblock-start-re nil t)
9656 (setq beg (match-beginning 0))
9657 (re-search-forward org-dblock-end-re nil t)
9658 (> (match-end 0) pos))
9659 (goto-char beg)
9660 (goto-char pos)
9661 (error "Not in a dynamic block"))))
9663 (defun org-update-all-dblocks ()
9664 "Update all dynamic blocks in the buffer.
9665 This function can be used in a hook."
9666 (when (org-mode-p)
9667 (org-map-dblocks 'org-update-dblock)))
9670 ;;;; Completion
9672 (defconst org-additional-option-like-keywords
9673 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9674 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9675 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9676 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9677 "BEGIN:" "END:"
9678 "ORGTBL" "TBLFM:" "TBLNAME:"
9679 "BEGIN_EXAMPLE" "END_EXAMPLE"
9680 "BEGIN_QUOTE" "END_QUOTE"
9681 "BEGIN_VERSE" "END_VERSE"
9682 "BEGIN_CENTER" "END_CENTER"
9683 "BEGIN_SRC" "END_SRC"
9684 "CATEGORY" "COLUMNS"
9685 "CAPTION" "LABEL"
9686 "SETUPFILE"
9687 "BIND"
9688 "MACRO"))
9690 (defcustom org-structure-template-alist
9692 ("s" "#+begin_src ?\n\n#+end_src"
9693 "<src lang=\"?\">\n\n</src>")
9694 ("e" "#+begin_example\n?\n#+end_example"
9695 "<example>\n?\n</example>")
9696 ("q" "#+begin_quote\n?\n#+end_quote"
9697 "<quote>\n?\n</quote>")
9698 ("v" "#+begin_verse\n?\n#+end_verse"
9699 "<verse>\n?\n/verse>")
9700 ("c" "#+begin_center\n?\n#+end_center"
9701 "<center>\n?\n/center>")
9702 ("l" "#+begin_latex\n?\n#+end_latex"
9703 "<literal style=\"latex\">\n?\n</literal>")
9704 ("L" "#+latex: "
9705 "<literal style=\"latex\">?</literal>")
9706 ("h" "#+begin_html\n?\n#+end_html"
9707 "<literal style=\"html\">\n?\n</literal>")
9708 ("H" "#+html: "
9709 "<literal style=\"html\">?</literal>")
9710 ("a" "#+begin_ascii\n?\n#+end_ascii")
9711 ("A" "#+ascii: ")
9712 ("i" "#+include %file ?"
9713 "<include file=%file markup=\"?\">")
9715 "Structure completion elements.
9716 This is a list of abbreviation keys and values. The value gets inserted
9717 it you type @samp{.} followed by the key and then the completion key,
9718 usually `M-TAB'. %file will be replaced by a file name after prompting
9719 for the file using completion.
9720 There are two templates for each key, the first uses the original Org syntax,
9721 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9722 the default when the /org-mtags.el/ module has been loaded. See also the
9723 variable `org-mtags-prefer-muse-templates'.
9724 This is an experimental feature, it is undecided if it is going to stay in."
9725 :group 'org-completion
9726 :type '(repeat
9727 (string :tag "Key")
9728 (string :tag "Template")
9729 (string :tag "Muse Template")))
9731 (defun org-try-structure-completion ()
9732 "Try to complete a structure template before point.
9733 This looks for strings like \"<e\" on an otherwise empty line and
9734 expands them."
9735 (let ((l (buffer-substring (point-at-bol) (point)))
9737 (when (and (looking-at "[ \t]*$")
9738 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9739 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9740 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9741 (match-beginning 1)) a)
9742 t)))
9744 (defun org-complete-expand-structure-template (start cell)
9745 "Expand a structure template."
9746 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9747 (rpl (nth (if musep 2 1) cell))
9748 (ind ""))
9749 (delete-region start (point))
9750 (when (string-match "\\`#\\+" rpl)
9751 (cond
9752 ((bolp))
9753 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9754 (setq ind (buffer-substring (point-at-bol) (point))))
9755 (t (newline))))
9756 (setq start (point))
9757 (if (string-match "%file" rpl)
9758 (setq rpl (replace-match
9759 (concat
9760 "\""
9761 (save-match-data
9762 (abbreviate-file-name (read-file-name "Include file: ")))
9763 "\"")
9764 t t rpl)))
9765 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9766 (concat "\n" ind)))
9767 (insert rpl)
9768 (if (re-search-backward "\\?" start t) (delete-char 1))))
9771 (defun org-complete (&optional arg)
9772 "Perform completion on word at point.
9773 At the beginning of a headline, this completes TODO keywords as given in
9774 `org-todo-keywords'.
9775 If the current word is preceded by a backslash, completes the TeX symbols
9776 that are supported for HTML support.
9777 If the current word is preceded by \"#+\", completes special words for
9778 setting file options.
9779 In the line after \"#+STARTUP:, complete valid keywords.\"
9780 At all other locations, this simply calls the value of
9781 `org-completion-fallback-command'."
9782 (interactive "P")
9783 (org-without-partial-completion
9784 (catch 'exit
9785 (let* ((a nil)
9786 (end (point))
9787 (beg1 (save-excursion
9788 (skip-chars-backward (org-re "[:alnum:]_@"))
9789 (point)))
9790 (beg (save-excursion
9791 (skip-chars-backward "a-zA-Z0-9_:$")
9792 (point)))
9793 (confirm (lambda (x) (stringp (car x))))
9794 (searchhead (equal (char-before beg) ?*))
9795 (struct
9796 (when (and (member (char-before beg1) '(?. ?<))
9797 (setq a (assoc (buffer-substring beg1 (point))
9798 org-structure-template-alist)))
9799 (org-complete-expand-structure-template (1- beg1) a)
9800 (throw 'exit t)))
9801 (tag (and (equal (char-before beg1) ?:)
9802 (equal (char-after (point-at-bol)) ?*)))
9803 (prop (and (equal (char-before beg1) ?:)
9804 (not (equal (char-after (point-at-bol)) ?*))))
9805 (texp (equal (char-before beg) ?\\))
9806 (link (equal (char-before beg) ?\[))
9807 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9808 beg)
9809 "#+"))
9810 (startup (string-match "^#\\+STARTUP:.*"
9811 (buffer-substring (point-at-bol) (point))))
9812 (completion-ignore-case opt)
9813 (type nil)
9814 (tbl nil)
9815 (table (cond
9816 (opt
9817 (setq type :opt)
9818 (require 'org-exp)
9819 (append
9820 (delq nil
9821 (mapcar
9822 (lambda (x)
9823 (if (string-match
9824 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9825 (cons (match-string 2 x)
9826 (match-string 1 x))))
9827 (org-split-string (org-get-current-options) "\n")))
9828 (mapcar 'list org-additional-option-like-keywords)))
9829 (startup
9830 (setq type :startup)
9831 org-startup-options)
9832 (link (append org-link-abbrev-alist-local
9833 org-link-abbrev-alist))
9834 (texp
9835 (setq type :tex)
9836 org-html-entities)
9837 ((string-match "\\`\\*+[ \t]+\\'"
9838 (buffer-substring (point-at-bol) beg))
9839 (setq type :todo)
9840 (mapcar 'list org-todo-keywords-1))
9841 (searchhead
9842 (setq type :searchhead)
9843 (save-excursion
9844 (goto-char (point-min))
9845 (while (re-search-forward org-todo-line-regexp nil t)
9846 (push (list
9847 (org-make-org-heading-search-string
9848 (match-string 3) t))
9849 tbl)))
9850 tbl)
9851 (tag (setq type :tag beg beg1)
9852 (or org-tag-alist (org-get-buffer-tags)))
9853 (prop (setq type :prop beg beg1)
9854 (mapcar 'list (org-buffer-property-keys nil t t)))
9855 (t (progn
9856 (call-interactively org-completion-fallback-command)
9857 (throw 'exit nil)))))
9858 (pattern (buffer-substring-no-properties beg end))
9859 (completion (try-completion pattern table confirm)))
9860 (cond ((eq completion t)
9861 (if (not (assoc (upcase pattern) table))
9862 (message "Already complete")
9863 (if (and (equal type :opt)
9864 (not (member (car (assoc (upcase pattern) table))
9865 org-additional-option-like-keywords)))
9866 (insert (substring (cdr (assoc (upcase pattern) table))
9867 (length pattern)))
9868 (if (memq type '(:tag :prop)) (insert ":")))))
9869 ((null completion)
9870 (message "Can't find completion for \"%s\"" pattern)
9871 (ding))
9872 ((not (string= pattern completion))
9873 (delete-region beg end)
9874 (if (string-match " +$" completion)
9875 (setq completion (replace-match "" t t completion)))
9876 (insert completion)
9877 (if (get-buffer-window "*Completions*")
9878 (delete-window (get-buffer-window "*Completions*")))
9879 (if (assoc completion table)
9880 (if (eq type :todo) (insert " ")
9881 (if (memq type '(:tag :prop)) (insert ":"))))
9882 (if (and (equal type :opt) (assoc completion table))
9883 (message "%s" (substitute-command-keys
9884 "Press \\[org-complete] again to insert example settings"))))
9886 (message "Making completion list...")
9887 (let ((list (sort (all-completions pattern table confirm)
9888 'string<)))
9889 (with-output-to-temp-buffer "*Completions*"
9890 (condition-case nil
9891 ;; Protection needed for XEmacs and emacs 21
9892 (display-completion-list list pattern)
9893 (error (display-completion-list list)))))
9894 (message "Making completion list...%s" "done")))))))
9896 ;;;; TODO, DEADLINE, Comments
9898 (defun org-toggle-comment ()
9899 "Change the COMMENT state of an entry."
9900 (interactive)
9901 (save-excursion
9902 (org-back-to-heading)
9903 (let (case-fold-search)
9904 (if (looking-at (concat outline-regexp
9905 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9906 (replace-match "" t t nil 1)
9907 (if (looking-at outline-regexp)
9908 (progn
9909 (goto-char (match-end 0))
9910 (insert org-comment-string " ")))))))
9912 (defvar org-last-todo-state-is-todo nil
9913 "This is non-nil when the last TODO state change led to a TODO state.
9914 If the last change removed the TODO tag or switched to DONE, then
9915 this is nil.")
9917 (defvar org-setting-tags nil) ; dynamically skipped
9919 (defun org-parse-local-options (string var)
9920 "Parse STRING for startup setting relevant for variable VAR."
9921 (let ((rtn (symbol-value var))
9922 e opts)
9923 (save-match-data
9924 (if (or (not string) (not (string-match "\\S-" string)))
9926 (setq opts (delq nil (mapcar (lambda (x)
9927 (setq e (assoc x org-startup-options))
9928 (if (eq (nth 1 e) var) e nil))
9929 (org-split-string string "[ \t]+"))))
9930 (if (not opts)
9932 (setq rtn nil)
9933 (while (setq e (pop opts))
9934 (if (not (nth 3 e))
9935 (setq rtn (nth 2 e))
9936 (if (not (listp rtn)) (setq rtn nil))
9937 (push (nth 2 e) rtn)))
9938 rtn)))))
9940 (defvar org-todo-setup-filter-hook nil
9941 "Hook for functions that pre-filter todo specs.
9943 Each function takes a todo spec and returns either `nil' or the spec
9944 transformed into canonical form." )
9946 (defvar org-todo-get-default-hook nil
9947 "Hook for functions that get a default item for todo.
9949 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9950 `nil' or a string to be used for the todo mark." )
9952 (defvar org-agenda-headline-snapshot-before-repeat)
9954 (defun org-todo (&optional arg)
9955 "Change the TODO state of an item.
9956 The state of an item is given by a keyword at the start of the heading,
9957 like
9958 *** TODO Write paper
9959 *** DONE Call mom
9961 The different keywords are specified in the variable `org-todo-keywords'.
9962 By default the available states are \"TODO\" and \"DONE\".
9963 So for this example: when the item starts with TODO, it is changed to DONE.
9964 When it starts with DONE, the DONE is removed. And when neither TODO nor
9965 DONE are present, add TODO at the beginning of the heading.
9967 With C-u prefix arg, use completion to determine the new state.
9968 With numeric prefix arg, switch to that state.
9969 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9970 With a triple C-u prefix, circumvent any state blocking.
9972 For calling through lisp, arg is also interpreted in the following way:
9973 'none -> empty state
9974 \"\"(empty string) -> switch to empty state
9975 'done -> switch to DONE
9976 'nextset -> switch to the next set of keywords
9977 'previousset -> switch to the previous set of keywords
9978 \"WAITING\" -> switch to the specified keyword, but only if it
9979 really is a member of `org-todo-keywords'."
9980 (interactive "P")
9981 (if (equal arg '(16)) (setq arg 'nextset))
9982 (let ((org-blocker-hook org-blocker-hook)
9983 (case-fold-search nil))
9984 (when (equal arg '(64))
9985 (setq arg nil org-blocker-hook nil))
9986 (when (and org-blocker-hook
9987 (or org-inhibit-blocking
9988 (org-entry-get nil "NOBLOCKING")))
9989 (setq org-blocker-hook nil))
9990 (save-excursion
9991 (catch 'exit
9992 (org-back-to-heading t)
9993 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9994 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9995 (looking-at " *"))
9996 (let* ((match-data (match-data))
9997 (startpos (point-at-bol))
9998 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9999 (org-log-done org-log-done)
10000 (org-log-repeat org-log-repeat)
10001 (org-todo-log-states org-todo-log-states)
10002 (this (match-string 1))
10003 (hl-pos (match-beginning 0))
10004 (head (org-get-todo-sequence-head this))
10005 (ass (assoc head org-todo-kwd-alist))
10006 (interpret (nth 1 ass))
10007 (done-word (nth 3 ass))
10008 (final-done-word (nth 4 ass))
10009 (last-state (or this ""))
10010 (completion-ignore-case t)
10011 (member (member this org-todo-keywords-1))
10012 (tail (cdr member))
10013 (state (cond
10014 ((and org-todo-key-trigger
10015 (or (and (equal arg '(4))
10016 (eq org-use-fast-todo-selection 'prefix))
10017 (and (not arg) org-use-fast-todo-selection
10018 (not (eq org-use-fast-todo-selection
10019 'prefix)))))
10020 ;; Use fast selection
10021 (org-fast-todo-selection))
10022 ((and (equal arg '(4))
10023 (or (not org-use-fast-todo-selection)
10024 (not org-todo-key-trigger)))
10025 ;; Read a state with completion
10026 (org-icompleting-read
10027 "State: " (mapcar (lambda(x) (list x))
10028 org-todo-keywords-1)
10029 nil t))
10030 ((eq arg 'right)
10031 (if this
10032 (if tail (car tail) nil)
10033 (car org-todo-keywords-1)))
10034 ((eq arg 'left)
10035 (if (equal member org-todo-keywords-1)
10037 (if this
10038 (nth (- (length org-todo-keywords-1)
10039 (length tail) 2)
10040 org-todo-keywords-1)
10041 (org-last org-todo-keywords-1))))
10042 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10043 (setq arg nil))) ; hack to fall back to cycling
10044 (arg
10045 ;; user or caller requests a specific state
10046 (cond
10047 ((equal arg "") nil)
10048 ((eq arg 'none) nil)
10049 ((eq arg 'done) (or done-word (car org-done-keywords)))
10050 ((eq arg 'nextset)
10051 (or (car (cdr (member head org-todo-heads)))
10052 (car org-todo-heads)))
10053 ((eq arg 'previousset)
10054 (let ((org-todo-heads (reverse org-todo-heads)))
10055 (or (car (cdr (member head org-todo-heads)))
10056 (car org-todo-heads))))
10057 ((car (member arg org-todo-keywords-1)))
10058 ((stringp arg)
10059 (error "State `%s' not valid in this file" arg))
10060 ((nth (1- (prefix-numeric-value arg))
10061 org-todo-keywords-1))))
10062 ((null member) (or head (car org-todo-keywords-1)))
10063 ((equal this final-done-word) nil) ;; -> make empty
10064 ((null tail) nil) ;; -> first entry
10065 ((memq interpret '(type priority))
10066 (if (eq this-command last-command)
10067 (car tail)
10068 (if (> (length tail) 0)
10069 (or done-word (car org-done-keywords))
10070 nil)))
10072 (car tail))))
10073 (state (or
10074 (run-hook-with-args-until-success
10075 'org-todo-get-default-hook state last-state)
10076 state))
10077 (next (if state (concat " " state " ") " "))
10078 (change-plist (list :type 'todo-state-change :from this :to state
10079 :position startpos))
10080 dolog now-done-p)
10081 (when org-blocker-hook
10082 (setq org-last-todo-state-is-todo
10083 (not (member this org-done-keywords)))
10084 (unless (save-excursion
10085 (save-match-data
10086 (run-hook-with-args-until-failure
10087 'org-blocker-hook change-plist)))
10088 (if (interactive-p)
10089 (error "TODO state change from %s to %s blocked" this state)
10090 ;; fail silently
10091 (message "TODO state change from %s to %s blocked" this state)
10092 (throw 'exit nil))))
10093 (store-match-data match-data)
10094 (replace-match next t t)
10095 (unless (pos-visible-in-window-p hl-pos)
10096 (message "TODO state changed to %s" (org-trim next)))
10097 (unless head
10098 (setq head (org-get-todo-sequence-head state)
10099 ass (assoc head org-todo-kwd-alist)
10100 interpret (nth 1 ass)
10101 done-word (nth 3 ass)
10102 final-done-word (nth 4 ass)))
10103 (when (memq arg '(nextset previousset))
10104 (message "Keyword-Set %d/%d: %s"
10105 (- (length org-todo-sets) -1
10106 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10107 (length org-todo-sets)
10108 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10109 (setq org-last-todo-state-is-todo
10110 (not (member state org-done-keywords)))
10111 (setq now-done-p (and (member state org-done-keywords)
10112 (not (member this org-done-keywords))))
10113 (and logging (org-local-logging logging))
10114 (when (and (or org-todo-log-states org-log-done)
10115 (not (eq org-inhibit-logging t))
10116 (not (memq arg '(nextset previousset))))
10117 ;; we need to look at recording a time and note
10118 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10119 (nth 2 (assoc this org-todo-log-states))))
10120 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10121 (setq dolog 'time))
10122 (when (and state
10123 (member state org-not-done-keywords)
10124 (not (member this org-not-done-keywords)))
10125 ;; This is now a todo state and was not one before
10126 ;; If there was a CLOSED time stamp, get rid of it.
10127 (org-add-planning-info nil nil 'closed))
10128 (when (and now-done-p org-log-done)
10129 ;; It is now done, and it was not done before
10130 (org-add-planning-info 'closed (org-current-time))
10131 (if (and (not dolog) (eq 'note org-log-done))
10132 (org-add-log-setup 'done state this 'findpos 'note)))
10133 (when (and state dolog)
10134 ;; This is a non-nil state, and we need to log it
10135 (org-add-log-setup 'state state this 'findpos dolog)))
10136 ;; Fixup tag positioning
10137 (org-todo-trigger-tag-changes state)
10138 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10139 (when org-provide-todo-statistics
10140 (org-update-parent-todo-statistics))
10141 (run-hooks 'org-after-todo-state-change-hook)
10142 (if (and arg (not (member state org-done-keywords)))
10143 (setq head (org-get-todo-sequence-head state)))
10144 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10145 ;; Do we need to trigger a repeat?
10146 (when now-done-p
10147 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10148 ;; This is for the agenda, take a snapshot of the headline.
10149 (save-match-data
10150 (setq org-agenda-headline-snapshot-before-repeat
10151 (org-get-heading))))
10152 (org-auto-repeat-maybe state))
10153 ;; Fixup cursor location if close to the keyword
10154 (if (and (outline-on-heading-p)
10155 (not (bolp))
10156 (save-excursion (beginning-of-line 1)
10157 (looking-at org-todo-line-regexp))
10158 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10159 (progn
10160 (goto-char (or (match-end 2) (match-end 1)))
10161 (and (looking-at " ") (just-one-space))))
10162 (when org-trigger-hook
10163 (save-excursion
10164 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10166 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10167 "Block turning an entry into a TODO, using the hierarchy.
10168 This checks whether the current task should be blocked from state
10169 changes. Such blocking occurs when:
10171 1. The task has children which are not all in a completed state.
10173 2. A task has a parent with the property :ORDERED:, and there
10174 are siblings prior to the current task with incomplete
10175 status.
10177 3. The parent of the task is blocked because it has siblings that should
10178 be done first, or is child of a block grandparent TODO entry."
10180 (if (not org-enforce-todo-dependencies)
10181 t ; if locally turned off don't block
10182 (catch 'dont-block
10183 ;; If this is not a todo state change, or if this entry is already DONE,
10184 ;; do not block
10185 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10186 (member (plist-get change-plist :from)
10187 (cons 'done org-done-keywords))
10188 (member (plist-get change-plist :to)
10189 (cons 'todo org-not-done-keywords))
10190 (not (plist-get change-plist :to)))
10191 (throw 'dont-block t))
10192 ;; If this task has children, and any are undone, it's blocked
10193 (save-excursion
10194 (org-back-to-heading t)
10195 (let ((this-level (funcall outline-level)))
10196 (outline-next-heading)
10197 (let ((child-level (funcall outline-level)))
10198 (while (and (not (eobp))
10199 (> child-level this-level))
10200 ;; this todo has children, check whether they are all
10201 ;; completed
10202 (if (and (not (org-entry-is-done-p))
10203 (org-entry-is-todo-p))
10204 (throw 'dont-block nil))
10205 (outline-next-heading)
10206 (setq child-level (funcall outline-level))))))
10207 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10208 ;; any previous siblings are undone, it's blocked
10209 (save-excursion
10210 (org-back-to-heading t)
10211 (let* ((pos (point))
10212 (parent-pos (and (org-up-heading-safe) (point))))
10213 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10214 (when (and (org-entry-get (point) "ORDERED")
10215 (forward-line 1)
10216 (re-search-forward org-not-done-heading-regexp pos t))
10217 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10218 ;; Search further up the hierarchy, to see if an anchestor is blocked
10219 (while t
10220 (goto-char parent-pos)
10221 (if (not (looking-at org-not-done-heading-regexp))
10222 (throw 'dont-block t)) ; do not block, parent is not a TODO
10223 (setq pos (point))
10224 (setq parent-pos (and (org-up-heading-safe) (point)))
10225 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10226 (when (and (org-entry-get (point) "ORDERED")
10227 (forward-line 1)
10228 (re-search-forward org-not-done-heading-regexp pos t))
10229 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10231 (defcustom org-track-ordered-property-with-tag nil
10232 "Should the ORDERED property also be shown as a tag?
10233 The ORDERED property decides if an entry should require subtasks to be
10234 completed in sequence. Since a property is not very visible, setting
10235 this option means that toggling the ORDERED property with the command
10236 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10237 not relevant for the behavior, but it makes things more visible.
10239 Note that toggling the tag with tags commands will not change the property
10240 and therefore not influence behavior!
10242 This can be t, meaning the tag ORDERED should be used, It can also be a
10243 string to select a different tag for this task."
10244 :group 'org-todo
10245 :type '(choice
10246 (const :tag "No tracking" nil)
10247 (const :tag "Track with ORDERED tag" t)
10248 (string :tag "Use other tag")))
10250 (defun org-toggle-ordered-property ()
10251 "Toggle the ORDERED property of the current entry.
10252 For better visibility, you can track the value of this property with a tag.
10253 See variable `org-track-ordered-property-with-tag'."
10254 (interactive)
10255 (let* ((t1 org-track-ordered-property-with-tag)
10256 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10257 (save-excursion
10258 (org-back-to-heading)
10259 (if (org-entry-get nil "ORDERED")
10260 (progn
10261 (org-delete-property "ORDERED")
10262 (and tag (org-toggle-tag tag 'off))
10263 (message "Subtasks can be completed in arbitrary order"))
10264 (org-entry-put nil "ORDERED" "t")
10265 (and tag (org-toggle-tag tag 'on))
10266 (message "Subtasks must be completed in sequence")))))
10268 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10269 (defun org-block-todo-from-checkboxes (change-plist)
10270 "Block turning an entry into a TODO, using checkboxes.
10271 This checks whether the current task should be blocked from state
10272 changes because there are unchecked boxes in this entry."
10273 (if (not org-enforce-todo-checkbox-dependencies)
10274 t ; if locally turned off don't block
10275 (catch 'dont-block
10276 ;; If this is not a todo state change, or if this entry is already DONE,
10277 ;; do not block
10278 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10279 (member (plist-get change-plist :from)
10280 (cons 'done org-done-keywords))
10281 (member (plist-get change-plist :to)
10282 (cons 'todo org-not-done-keywords))
10283 (not (plist-get change-plist :to)))
10284 (throw 'dont-block t))
10285 ;; If this task has checkboxes that are not checked, it's blocked
10286 (save-excursion
10287 (org-back-to-heading t)
10288 (let ((beg (point)) end)
10289 (outline-next-heading)
10290 (setq end (point))
10291 (goto-char beg)
10292 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10293 end t)
10294 (progn
10295 (if (boundp 'org-blocked-by-checkboxes)
10296 (setq org-blocked-by-checkboxes t))
10297 (throw 'dont-block nil)))))
10298 t))) ; do not block
10300 (defun org-entry-blocked-p ()
10301 "Is the current entry blocked?"
10302 (if (org-entry-get nil "NOBLOCKING")
10303 nil ;; Never block this entry
10304 (not
10305 (run-hook-with-args-until-failure
10306 'org-blocker-hook
10307 (list :type 'todo-state-change
10308 :position (point)
10309 :from 'todo
10310 :to 'done)))))
10312 (defun org-update-statistics-cookies (all)
10313 "Update the statistics cookie, either from TODO or from checkboxes.
10314 This should be called with the cursor in a line with a statistics cookie."
10315 (interactive "P")
10316 (if all
10317 (progn
10318 (org-update-checkbox-count 'all)
10319 (org-map-entries 'org-update-parent-todo-statistics))
10320 (if (not (org-on-heading-p))
10321 (org-update-checkbox-count)
10322 (let ((pos (move-marker (make-marker) (point)))
10323 end l1 l2)
10324 (ignore-errors (org-back-to-heading t))
10325 (if (not (org-on-heading-p))
10326 (org-update-checkbox-count)
10327 (setq l1 (org-outline-level))
10328 (setq end (save-excursion
10329 (outline-next-heading)
10330 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10331 (point)))
10332 (if (and (save-excursion
10333 (re-search-forward
10334 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10335 (not (save-excursion (re-search-forward
10336 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10337 (org-update-checkbox-count)
10338 (if (and l2 (> l2 l1))
10339 (progn
10340 (goto-char end)
10341 (org-update-parent-todo-statistics))
10342 (goto-char pos)
10343 (beginning-of-line 1)
10344 (while (re-search-forward
10345 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10346 (point-at-eol) t)
10347 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10348 (goto-char pos)
10349 (move-marker pos nil)))))
10351 (defvar org-entry-property-inherited-from) ;; defined below
10352 (defun org-update-parent-todo-statistics ()
10353 "Update any statistics cookie in the parent of the current headline.
10354 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10355 the entire subtree and this will travel up the hierarchy and update
10356 statistics everywhere."
10357 (interactive)
10358 (let* ((lim 0) prop
10359 (recursive (or (not org-hierarchical-todo-statistics)
10360 (string-match
10361 "\\<recursive\\>"
10362 (or (setq prop (org-entry-get
10363 nil "COOKIE_DATA" 'inherit)) ""))))
10364 (lim (or (and prop (marker-position
10365 org-entry-property-inherited-from))
10366 lim))
10367 (first t)
10368 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10369 level ltoggle l1 new ndel
10370 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10371 (catch 'exit
10372 (save-excursion
10373 (beginning-of-line 1)
10374 (if (org-at-heading-p)
10375 (setq ltoggle (funcall outline-level))
10376 (error "This should not happen"))
10377 (while (and (setq level (org-up-heading-safe))
10378 (or recursive first)
10379 (>= (point) lim))
10380 (setq first nil cookie-present nil)
10381 (unless (and level
10382 (not (string-match
10383 "\\<checkbox\\>"
10384 (downcase
10385 (or (org-entry-get
10386 nil "COOKIE_DATA")
10387 "")))))
10388 (throw 'exit nil))
10389 (while (re-search-forward box-re (point-at-eol) t)
10390 (setq cnt-all 0 cnt-done 0 cookie-present t)
10391 (setq is-percent (match-end 2))
10392 (save-match-data
10393 (unless (outline-next-heading) (throw 'exit nil))
10394 (while (and (looking-at org-complex-heading-regexp)
10395 (> (setq l1 (length (match-string 1))) level))
10396 (setq kwd (and (or recursive (= l1 ltoggle))
10397 (match-string 2)))
10398 (if (or (eq org-provide-todo-statistics 'all-headlines)
10399 (and (listp org-provide-todo-statistics)
10400 (or (member kwd org-provide-todo-statistics)
10401 (member kwd org-done-keywords))))
10402 (setq cnt-all (1+ cnt-all))
10403 (if (eq org-provide-todo-statistics t)
10404 (and kwd (setq cnt-all (1+ cnt-all)))))
10405 (and (member kwd org-done-keywords)
10406 (setq cnt-done (1+ cnt-done)))
10407 (outline-next-heading)))
10408 (setq new
10409 (if is-percent
10410 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10411 (format "[%d/%d]" cnt-done cnt-all))
10412 ndel (- (match-end 0) (match-beginning 0)))
10413 (goto-char (match-beginning 0))
10414 (insert new)
10415 (delete-region (point) (+ (point) ndel)))
10416 (when cookie-present
10417 (run-hook-with-args 'org-after-todo-statistics-hook
10418 cnt-done (- cnt-all cnt-done))))))
10419 (run-hooks 'org-todo-statistics-hook)))
10421 (defvar org-after-todo-statistics-hook nil
10422 "Hook that is called after a TODO statistics cookie has been updated.
10423 Each function is called with two arguments: the number of not-done entries
10424 and the number of done entries.
10426 For example, the following function, when added to this hook, will switch
10427 an entry to DONE when all children are done, and back to TODO when new
10428 entries are set to a TODO status. Note that this hook is only called
10429 when there is a statistics cookie in the headline!
10431 (defun org-summary-todo (n-done n-not-done)
10432 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10433 (let (org-log-done org-log-states) ; turn off logging
10434 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10437 (defvar org-todo-statistics-hook nil
10438 "Hook that is run whenever Org thinks TODO statistics should be updated.
10439 This hook runs even if there is no statistics cookie present, in which case
10440 `org-after-todo-statistics-hook' would not run.")
10442 (defun org-todo-trigger-tag-changes (state)
10443 "Apply the changes defined in `org-todo-state-tags-triggers'."
10444 (let ((l org-todo-state-tags-triggers)
10445 changes)
10446 (when (or (not state) (equal state ""))
10447 (setq changes (append changes (cdr (assoc "" l)))))
10448 (when (and (stringp state) (> (length state) 0))
10449 (setq changes (append changes (cdr (assoc state l)))))
10450 (when (member state org-not-done-keywords)
10451 (setq changes (append changes (cdr (assoc 'todo l)))))
10452 (when (member state org-done-keywords)
10453 (setq changes (append changes (cdr (assoc 'done l)))))
10454 (dolist (c changes)
10455 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10457 (defun org-local-logging (value)
10458 "Get logging settings from a property VALUE."
10459 (let* (words w a)
10460 ;; directly set the variables, they are already local.
10461 (setq org-log-done nil
10462 org-log-repeat nil
10463 org-todo-log-states nil)
10464 (setq words (org-split-string value))
10465 (while (setq w (pop words))
10466 (cond
10467 ((setq a (assoc w org-startup-options))
10468 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10469 (set (nth 1 a) (nth 2 a))))
10470 ((setq a (org-extract-log-state-settings w))
10471 (and (member (car a) org-todo-keywords-1)
10472 (push a org-todo-log-states)))))))
10474 (defun org-get-todo-sequence-head (kwd)
10475 "Return the head of the TODO sequence to which KWD belongs.
10476 If KWD is not set, check if there is a text property remembering the
10477 right sequence."
10478 (let (p)
10479 (cond
10480 ((not kwd)
10481 (or (get-text-property (point-at-bol) 'org-todo-head)
10482 (progn
10483 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10484 nil (point-at-eol)))
10485 (get-text-property p 'org-todo-head))))
10486 ((not (member kwd org-todo-keywords-1))
10487 (car org-todo-keywords-1))
10488 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10490 (defun org-fast-todo-selection ()
10491 "Fast TODO keyword selection with single keys.
10492 Returns the new TODO keyword, or nil if no state change should occur."
10493 (let* ((fulltable org-todo-key-alist)
10494 (done-keywords org-done-keywords) ;; needed for the faces.
10495 (maxlen (apply 'max (mapcar
10496 (lambda (x)
10497 (if (stringp (car x)) (string-width (car x)) 0))
10498 fulltable)))
10499 (expert nil)
10500 (fwidth (+ maxlen 3 1 3))
10501 (ncol (/ (- (window-width) 4) fwidth))
10502 tg cnt e c tbl
10503 groups ingroup)
10504 (save-excursion
10505 (save-window-excursion
10506 (if expert
10507 (set-buffer (get-buffer-create " *Org todo*"))
10508 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10509 (erase-buffer)
10510 (org-set-local 'org-done-keywords done-keywords)
10511 (setq tbl fulltable cnt 0)
10512 (while (setq e (pop tbl))
10513 (cond
10514 ((equal e '(:startgroup))
10515 (push '() groups) (setq ingroup t)
10516 (when (not (= cnt 0))
10517 (setq cnt 0)
10518 (insert "\n"))
10519 (insert "{ "))
10520 ((equal e '(:endgroup))
10521 (setq ingroup nil cnt 0)
10522 (insert "}\n"))
10523 ((equal e '(:newline))
10524 (when (not (= cnt 0))
10525 (setq cnt 0)
10526 (insert "\n")
10527 (setq e (car tbl))
10528 (while (equal (car tbl) '(:newline))
10529 (insert "\n")
10530 (setq tbl (cdr tbl)))))
10532 (setq tg (car e) c (cdr e))
10533 (if ingroup (push tg (car groups)))
10534 (setq tg (org-add-props tg nil 'face
10535 (org-get-todo-face tg)))
10536 (if (and (= cnt 0) (not ingroup)) (insert " "))
10537 (insert "[" c "] " tg (make-string
10538 (- fwidth 4 (length tg)) ?\ ))
10539 (when (= (setq cnt (1+ cnt)) ncol)
10540 (insert "\n")
10541 (if ingroup (insert " "))
10542 (setq cnt 0)))))
10543 (insert "\n")
10544 (goto-char (point-min))
10545 (if (not expert) (org-fit-window-to-buffer))
10546 (message "[a-z..]:Set [SPC]:clear")
10547 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10548 (cond
10549 ((or (= c ?\C-g)
10550 (and (= c ?q) (not (rassoc c fulltable))))
10551 (setq quit-flag t))
10552 ((= c ?\ ) nil)
10553 ((setq e (rassoc c fulltable) tg (car e))
10555 (t (setq quit-flag t)))))))
10557 (defun org-entry-is-todo-p ()
10558 (member (org-get-todo-state) org-not-done-keywords))
10560 (defun org-entry-is-done-p ()
10561 (member (org-get-todo-state) org-done-keywords))
10563 (defun org-get-todo-state ()
10564 (save-excursion
10565 (org-back-to-heading t)
10566 (and (looking-at org-todo-line-regexp)
10567 (match-end 2)
10568 (match-string 2))))
10570 (defun org-at-date-range-p (&optional inactive-ok)
10571 "Is the cursor inside a date range?"
10572 (interactive)
10573 (save-excursion
10574 (catch 'exit
10575 (let ((pos (point)))
10576 (skip-chars-backward "^[<\r\n")
10577 (skip-chars-backward "<[")
10578 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10579 (>= (match-end 0) pos)
10580 (throw 'exit t))
10581 (skip-chars-backward "^<[\r\n")
10582 (skip-chars-backward "<[")
10583 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10584 (>= (match-end 0) pos)
10585 (throw 'exit t)))
10586 nil)))
10588 (defun org-get-repeat (&optional tagline)
10589 "Check if there is a deadline/schedule with repeater in this entry."
10590 (save-match-data
10591 (save-excursion
10592 (org-back-to-heading t)
10593 (and (re-search-forward (if tagline
10594 (concat tagline "\\s-*" org-repeat-re)
10595 org-repeat-re)
10596 (org-entry-end-position) t)
10597 (match-string-no-properties 1)))))
10599 (defvar org-last-changed-timestamp)
10600 (defvar org-last-inserted-timestamp)
10601 (defvar org-log-post-message)
10602 (defvar org-log-note-purpose)
10603 (defvar org-log-note-how)
10604 (defvar org-log-note-extra)
10605 (defun org-auto-repeat-maybe (done-word)
10606 "Check if the current headline contains a repeated deadline/schedule.
10607 If yes, set TODO state back to what it was and change the base date
10608 of repeating deadline/scheduled time stamps to new date.
10609 This function is run automatically after each state change to a DONE state."
10610 ;; last-state is dynamically scoped into this function
10611 (let* ((repeat (org-get-repeat))
10612 (aa (assoc last-state org-todo-kwd-alist))
10613 (interpret (nth 1 aa))
10614 (head (nth 2 aa))
10615 (whata '(("d" . day) ("m" . month) ("y" . year)))
10616 (msg "Entry repeats: ")
10617 (org-log-done nil)
10618 (org-todo-log-states nil)
10619 (nshiftmax 10) (nshift 0)
10620 re type n what ts time)
10621 (when repeat
10622 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10623 (org-todo (if (eq interpret 'type) last-state head))
10624 (org-entry-put nil "LAST_REPEAT" (format-time-string
10625 (org-time-stamp-format t t)))
10626 (when org-log-repeat
10627 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10628 (memq 'org-add-log-note post-command-hook))
10629 ;; OK, we are already setup for some record
10630 (if (eq org-log-repeat 'note)
10631 ;; make sure we take a note, not only a time stamp
10632 (setq org-log-note-how 'note))
10633 ;; Set up for taking a record
10634 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10635 last-state
10636 'findpos org-log-repeat)))
10637 (org-back-to-heading t)
10638 (org-add-planning-info nil nil 'closed)
10639 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10640 org-deadline-time-regexp "\\)\\|\\("
10641 org-ts-regexp "\\)"))
10642 (while (re-search-forward
10643 re (save-excursion (outline-next-heading) (point)) t)
10644 (setq type (if (match-end 1) org-scheduled-string
10645 (if (match-end 3) org-deadline-string "Plain:"))
10646 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10647 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10648 (setq n (string-to-number (match-string 2 ts))
10649 what (match-string 3 ts))
10650 (if (equal what "w") (setq n (* n 7) what "d"))
10651 ;; Preparation, see if we need to modify the start date for the change
10652 (when (match-end 1)
10653 (setq time (save-match-data (org-time-string-to-time ts)))
10654 (cond
10655 ((equal (match-string 1 ts) ".")
10656 ;; Shift starting date to today
10657 (org-timestamp-change
10658 (- (time-to-days (current-time)) (time-to-days time))
10659 'day))
10660 ((equal (match-string 1 ts) "+")
10661 (while (or (= nshift 0)
10662 (<= (time-to-days time) (time-to-days (current-time))))
10663 (when (= (incf nshift) nshiftmax)
10664 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10665 (error "Abort")))
10666 (org-timestamp-change n (cdr (assoc what whata)))
10667 (org-at-timestamp-p t)
10668 (setq ts (match-string 1))
10669 (setq time (save-match-data (org-time-string-to-time ts))))
10670 (org-timestamp-change (- n) (cdr (assoc what whata)))
10671 ;; rematch, so that we have everything in place for the real shift
10672 (org-at-timestamp-p t)
10673 (setq ts (match-string 1))
10674 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10675 (org-timestamp-change n (cdr (assoc what whata)))
10676 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10677 (setq org-log-post-message msg)
10678 (message "%s" msg))))
10680 (defun org-show-todo-tree (arg)
10681 "Make a compact tree which shows all headlines marked with TODO.
10682 The tree will show the lines where the regexp matches, and all higher
10683 headlines above the match.
10684 With a \\[universal-argument] prefix, prompt for a regexp to match.
10685 With a numeric prefix N, construct a sparse tree for the Nth element
10686 of `org-todo-keywords-1'."
10687 (interactive "P")
10688 (let ((case-fold-search nil)
10689 (kwd-re
10690 (cond ((null arg) org-not-done-regexp)
10691 ((equal arg '(4))
10692 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10693 (mapcar 'list org-todo-keywords-1))))
10694 (concat "\\("
10695 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10696 "\\)\\>")))
10697 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10698 (regexp-quote (nth (1- (prefix-numeric-value arg))
10699 org-todo-keywords-1)))
10700 (t (error "Invalid prefix argument: %s" arg)))))
10701 (message "%d TODO entries found"
10702 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10704 (defun org-deadline (&optional remove time)
10705 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10706 With argument REMOVE, remove any deadline from the item.
10707 When TIME is set, it should be an internal time specification, and the
10708 scheduling will use the corresponding date."
10709 (interactive "P")
10710 (let ((old-date (org-entry-get nil "DEADLINE")))
10711 (if remove
10712 (progn
10713 (when (and old-date org-log-redeadline)
10714 (org-add-log-setup 'deldeadline nil old-date 'findpos
10715 org-log-redeadline))
10716 (org-remove-timestamp-with-keyword org-deadline-string)
10717 (message "Item no longer has a deadline."))
10718 (if (org-get-repeat org-deadline-string)
10719 (error "Cannot change deadline on task with repeater, please do that by hand")
10720 (org-add-planning-info 'deadline time 'closed)
10721 (when (and old-date org-log-redeadline
10722 (not (equal old-date
10723 (substring org-last-inserted-timestamp 1 -1))))
10724 (org-add-log-setup 'redeadline nil old-date 'findpos
10725 org-log-redeadline))
10726 (message "Deadline on %s" org-last-inserted-timestamp)))))
10728 (defun org-schedule (&optional remove time)
10729 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10730 With argument REMOVE, remove any scheduling date from the item.
10731 When TIME is set, it should be an internal time specification, and the
10732 scheduling will use the corresponding date."
10733 (interactive "P")
10734 (let ((old-date (org-entry-get nil "SCHEDULED")))
10735 (if remove
10736 (progn
10737 (when (and old-date org-log-reschedule)
10738 (org-add-log-setup 'delschedule nil old-date 'findpos
10739 org-log-reschedule))
10740 (org-remove-timestamp-with-keyword org-scheduled-string)
10741 (message "Item is no longer scheduled."))
10742 (if (org-get-repeat org-scheduled-string)
10743 (error "Cannot reschedule task with repeater, please do that by hand")
10744 (org-add-planning-info 'scheduled time 'closed)
10745 (when (and old-date org-log-reschedule
10746 (not (equal old-date
10747 (substring org-last-inserted-timestamp 1 -1))))
10748 (org-add-log-setup 'reschedule nil old-date 'findpos
10749 org-log-reschedule))
10750 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10752 (defun org-get-scheduled-time (pom &optional inherit)
10753 "Get the scheduled time as a time tuple, of a format suitable
10754 for calling org-schedule with, or if there is no scheduling,
10755 returns nil."
10756 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10757 (when time
10758 (apply 'encode-time (org-parse-time-string time)))))
10760 (defun org-get-deadline-time (pom &optional inherit)
10761 "Get the deadine as a time tuple, of a format suitable for
10762 calling org-deadline with, or if there is no scheduling, returns
10763 nil."
10764 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10765 (when time
10766 (apply 'encode-time (org-parse-time-string time)))))
10768 (defun org-remove-timestamp-with-keyword (keyword)
10769 "Remove all time stamps with KEYWORD in the current entry."
10770 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10771 beg)
10772 (save-excursion
10773 (org-back-to-heading t)
10774 (setq beg (point))
10775 (outline-next-heading)
10776 (while (re-search-backward re beg t)
10777 (replace-match "")
10778 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10779 (equal (char-before) ?\ ))
10780 (backward-delete-char 1)
10781 (if (string-match "^[ \t]*$" (buffer-substring
10782 (point-at-bol) (point-at-eol)))
10783 (delete-region (point-at-bol)
10784 (min (point-max) (1+ (point-at-eol))))))))))
10786 (defun org-add-planning-info (what &optional time &rest remove)
10787 "Insert new timestamp with keyword in the line directly after the headline.
10788 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10789 If non is given, the user is prompted for a date.
10790 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10791 be removed."
10792 (interactive)
10793 (let (org-time-was-given org-end-time-was-given ts
10794 end default-time default-input)
10796 (catch 'exit
10797 (when (and (not time) (memq what '(scheduled deadline)))
10798 ;; Try to get a default date/time from existing timestamp
10799 (save-excursion
10800 (org-back-to-heading t)
10801 (setq end (save-excursion (outline-next-heading) (point)))
10802 (when (re-search-forward (if (eq what 'scheduled)
10803 org-scheduled-time-regexp
10804 org-deadline-time-regexp)
10805 end t)
10806 (setq ts (match-string 1)
10807 default-time
10808 (apply 'encode-time (org-parse-time-string ts))
10809 default-input (and ts (org-get-compact-tod ts))))))
10810 (when what
10811 ;; If necessary, get the time from the user
10812 (setq time (or time (org-read-date nil 'to-time nil nil
10813 default-time default-input))))
10815 (when (and org-insert-labeled-timestamps-at-point
10816 (member what '(scheduled deadline)))
10817 (insert
10818 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10819 (org-insert-time-stamp time org-time-was-given
10820 nil nil nil (list org-end-time-was-given))
10821 (setq what nil))
10822 (save-excursion
10823 (save-restriction
10824 (let (col list elt ts buffer-invisibility-spec)
10825 (org-back-to-heading t)
10826 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10827 (goto-char (match-end 1))
10828 (setq col (current-column))
10829 (goto-char (match-end 0))
10830 (if (eobp) (insert "\n") (forward-char 1))
10831 (when (and (not what)
10832 (not (looking-at
10833 (concat "[ \t]*"
10834 org-keyword-time-not-clock-regexp))))
10835 ;; Nothing to add, nothing to remove...... :-)
10836 (throw 'exit nil))
10837 (if (and (not (looking-at outline-regexp))
10838 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10839 "[^\r\n]*"))
10840 (not (equal (match-string 1) org-clock-string)))
10841 (narrow-to-region (match-beginning 0) (match-end 0))
10842 (insert-before-markers "\n")
10843 (backward-char 1)
10844 (narrow-to-region (point) (point))
10845 (and org-adapt-indentation (org-indent-to-column col)))
10846 ;; Check if we have to remove something.
10847 (setq list (cons what remove))
10848 (while list
10849 (setq elt (pop list))
10850 (goto-char (point-min))
10851 (when (or (and (eq elt 'scheduled)
10852 (re-search-forward org-scheduled-time-regexp nil t))
10853 (and (eq elt 'deadline)
10854 (re-search-forward org-deadline-time-regexp nil t))
10855 (and (eq elt 'closed)
10856 (re-search-forward org-closed-time-regexp nil t)))
10857 (replace-match "")
10858 (if (looking-at "--+<[^>]+>") (replace-match ""))
10859 (skip-chars-backward " ")
10860 (if (looking-at " +") (replace-match ""))))
10861 (goto-char (point-max))
10862 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10863 (when what
10864 (insert
10865 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10866 (cond ((eq what 'scheduled) org-scheduled-string)
10867 ((eq what 'deadline) org-deadline-string)
10868 ((eq what 'closed) org-closed-string))
10869 " ")
10870 (setq ts (org-insert-time-stamp
10871 time
10872 (or org-time-was-given
10873 (and (eq what 'closed) org-log-done-with-time))
10874 (eq what 'closed)
10875 nil nil (list org-end-time-was-given)))
10876 (end-of-line 1))
10877 (goto-char (point-min))
10878 (widen)
10879 (if (and (looking-at "[ \t]+\n")
10880 (equal (char-before) ?\n))
10881 (delete-region (1- (point)) (point-at-eol)))
10882 ts))))))
10884 (defvar org-log-note-marker (make-marker))
10885 (defvar org-log-note-purpose nil)
10886 (defvar org-log-note-state nil)
10887 (defvar org-log-note-previous-state nil)
10888 (defvar org-log-note-how nil)
10889 (defvar org-log-note-extra nil)
10890 (defvar org-log-note-window-configuration nil)
10891 (defvar org-log-note-return-to (make-marker))
10892 (defvar org-log-post-message nil
10893 "Message to be displayed after a log note has been stored.
10894 The auto-repeater uses this.")
10896 (defun org-add-note ()
10897 "Add a note to the current entry.
10898 This is done in the same way as adding a state change note."
10899 (interactive)
10900 (org-add-log-setup 'note nil nil 'findpos nil))
10902 (defvar org-property-end-re)
10903 (defun org-add-log-setup (&optional purpose state prev-state
10904 findpos how &optional extra)
10905 "Set up the post command hook to take a note.
10906 If this is about to TODO state change, the new state is expected in STATE.
10907 When FINDPOS is non-nil, find the correct position for the note in
10908 the current entry. If not, assume that it can be inserted at point.
10909 HOW is an indicator what kind of note should be created.
10910 EXTRA is additional text that will be inserted into the notes buffer."
10911 (let* ((org-log-into-drawer (org-log-into-drawer))
10912 (drawer (cond ((stringp org-log-into-drawer)
10913 org-log-into-drawer)
10914 (org-log-into-drawer "LOGBOOK")
10915 (t nil))))
10916 (save-restriction
10917 (save-excursion
10918 (when findpos
10919 (org-back-to-heading t)
10920 (narrow-to-region (point) (save-excursion
10921 (outline-next-heading) (point)))
10922 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10923 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10924 "[^\r\n]*\\)?"))
10925 (goto-char (match-end 0))
10926 (cond
10927 (drawer
10928 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10929 nil t)
10930 (progn
10931 (goto-char (match-end 0))
10932 (or org-log-states-order-reversed
10933 (and (re-search-forward org-property-end-re nil t)
10934 (goto-char (1- (match-beginning 0))))))
10935 (insert "\n:" drawer ":\n:END:")
10936 (beginning-of-line 0)
10937 (org-indent-line-function)
10938 (beginning-of-line 2)
10939 (org-indent-line-function)
10940 (end-of-line 0)))
10941 ((and org-log-state-notes-insert-after-drawers
10942 (save-excursion
10943 (forward-line) (looking-at org-drawer-regexp)))
10944 (forward-line)
10945 (while (looking-at org-drawer-regexp)
10946 (goto-char (match-end 0))
10947 (re-search-forward org-property-end-re (point-max) t)
10948 (forward-line))
10949 (forward-line -1)))
10950 (unless org-log-states-order-reversed
10951 (and (= (char-after) ?\n) (forward-char 1))
10952 (org-skip-over-state-notes)
10953 (skip-chars-backward " \t\n\r")))
10954 (move-marker org-log-note-marker (point))
10955 (setq org-log-note-purpose purpose
10956 org-log-note-state state
10957 org-log-note-previous-state prev-state
10958 org-log-note-how how
10959 org-log-note-extra extra)
10960 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10962 (defun org-skip-over-state-notes ()
10963 "Skip past the list of State notes in an entry."
10964 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10965 (while (looking-at "[ \t]*- State")
10966 (condition-case nil
10967 (org-next-item)
10968 (error (org-end-of-item)))))
10970 (defun org-add-log-note (&optional purpose)
10971 "Pop up a window for taking a note, and add this note later at point."
10972 (remove-hook 'post-command-hook 'org-add-log-note)
10973 (setq org-log-note-window-configuration (current-window-configuration))
10974 (delete-other-windows)
10975 (move-marker org-log-note-return-to (point))
10976 (switch-to-buffer (marker-buffer org-log-note-marker))
10977 (goto-char org-log-note-marker)
10978 (org-switch-to-buffer-other-window "*Org Note*")
10979 (erase-buffer)
10980 (if (memq org-log-note-how '(time state))
10981 (let (current-prefix-arg) (org-store-log-note))
10982 (let ((org-inhibit-startup t)) (org-mode))
10983 (insert (format "# Insert note for %s.
10984 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10985 (cond
10986 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10987 ((eq org-log-note-purpose 'done) "closed todo item")
10988 ((eq org-log-note-purpose 'state)
10989 (format "state change from \"%s\" to \"%s\""
10990 (or org-log-note-previous-state "")
10991 (or org-log-note-state "")))
10992 ((eq org-log-note-purpose 'reschedule)
10993 "rescheduling")
10994 ((eq org-log-note-purpose 'delschedule)
10995 "no longer scheduled")
10996 ((eq org-log-note-purpose 'redeadline)
10997 "changing deadline")
10998 ((eq org-log-note-purpose 'deldeadline)
10999 "removing deadline")
11000 ((eq org-log-note-purpose 'note)
11001 "this entry")
11002 (t (error "This should not happen")))))
11003 (if org-log-note-extra (insert org-log-note-extra))
11004 (org-set-local 'org-finish-function 'org-store-log-note)))
11006 (defvar org-note-abort nil) ; dynamically scoped
11007 (defun org-store-log-note ()
11008 "Finish taking a log note, and insert it to where it belongs."
11009 (let ((txt (buffer-string))
11010 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11011 lines ind)
11012 (kill-buffer (current-buffer))
11013 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11014 (setq txt (replace-match "" t t txt)))
11015 (if (string-match "\\s-+\\'" txt)
11016 (setq txt (replace-match "" t t txt)))
11017 (setq lines (org-split-string txt "\n"))
11018 (when (and note (string-match "\\S-" note))
11019 (setq note
11020 (org-replace-escapes
11021 note
11022 (list (cons "%u" (user-login-name))
11023 (cons "%U" user-full-name)
11024 (cons "%t" (format-time-string
11025 (org-time-stamp-format 'long 'inactive)
11026 (current-time)))
11027 (cons "%s" (if org-log-note-state
11028 (concat "\"" org-log-note-state "\"")
11029 ""))
11030 (cons "%S" (if org-log-note-previous-state
11031 (concat "\"" org-log-note-previous-state "\"")
11032 "\"\"")))))
11033 (if lines (setq note (concat note " \\\\")))
11034 (push note lines))
11035 (when (or current-prefix-arg org-note-abort)
11036 (when org-log-into-drawer
11037 (org-remove-empty-drawer-at
11038 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11039 org-log-note-marker))
11040 (setq lines nil))
11041 (when lines
11042 (with-current-buffer (marker-buffer org-log-note-marker)
11043 (save-excursion
11044 (goto-char org-log-note-marker)
11045 (move-marker org-log-note-marker nil)
11046 (end-of-line 1)
11047 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11048 (insert "- " (pop lines))
11049 (org-indent-line-function)
11050 (beginning-of-line 1)
11051 (looking-at "[ \t]*")
11052 (setq ind (concat (match-string 0) " "))
11053 (end-of-line 1)
11054 (while lines (insert "\n" ind (pop lines)))
11055 (message "Note stored")
11056 (org-back-to-heading t)
11057 (org-cycle-hide-drawers 'children)))))
11058 (set-window-configuration org-log-note-window-configuration)
11059 (with-current-buffer (marker-buffer org-log-note-return-to)
11060 (goto-char org-log-note-return-to))
11061 (move-marker org-log-note-return-to nil)
11062 (and org-log-post-message (message "%s" org-log-post-message)))
11064 (defun org-remove-empty-drawer-at (drawer pos)
11065 "Remove an empty drawer DRAWER at position POS.
11066 POS may also be a marker."
11067 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11068 (save-excursion
11069 (save-restriction
11070 (widen)
11071 (goto-char pos)
11072 (if (org-in-regexp
11073 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11074 (replace-match ""))))))
11076 (defun org-sparse-tree (&optional arg)
11077 "Create a sparse tree, prompt for the details.
11078 This command can create sparse trees. You first need to select the type
11079 of match used to create the tree:
11081 t Show entries with a specific TODO keyword.
11082 m Show entries selected by a tags/property match.
11083 p Enter a property name and its value (both with completion on existing
11084 names/values) and show entries with that property.
11085 / Show entries matching a regular expression (`r' can be used as well)
11086 d Show deadlines due within `org-deadline-warning-days'.
11087 b Show deadlines and scheduled items before a date.
11088 a Show deadlines and scheduled items after a date."
11089 (interactive "P")
11090 (let (ans kwd value)
11091 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11092 (setq ans (read-char-exclusive))
11093 (cond
11094 ((equal ans ?d)
11095 (call-interactively 'org-check-deadlines))
11096 ((equal ans ?b)
11097 (call-interactively 'org-check-before-date))
11098 ((equal ans ?a)
11099 (call-interactively 'org-check-after-date))
11100 ((equal ans ?t)
11101 (org-show-todo-tree '(4)))
11102 ((member ans '(?T ?m))
11103 (call-interactively 'org-match-sparse-tree))
11104 ((member ans '(?p ?P))
11105 (setq kwd (org-icompleting-read "Property: "
11106 (mapcar 'list (org-buffer-property-keys))))
11107 (setq value (org-icompleting-read "Value: "
11108 (mapcar 'list (org-property-values kwd))))
11109 (unless (string-match "\\`{.*}\\'" value)
11110 (setq value (concat "\"" value "\"")))
11111 (org-match-sparse-tree arg (concat kwd "=" value)))
11112 ((member ans '(?r ?R ?/))
11113 (call-interactively 'org-occur))
11114 (t (error "No such sparse tree command \"%c\"" ans)))))
11116 (defvar org-occur-highlights nil
11117 "List of overlays used for occur matches.")
11118 (make-variable-buffer-local 'org-occur-highlights)
11119 (defvar org-occur-parameters nil
11120 "Parameters of the active org-occur calls.
11121 This is a list, each call to org-occur pushes as cons cell,
11122 containing the regular expression and the callback, onto the list.
11123 The list can contain several entries if `org-occur' has been called
11124 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11125 will only contain one set of parameters. When the highlights are
11126 removed (for example with `C-c C-c', or with the next edit (depending
11127 on `org-remove-highlights-with-change'), this variable is emptied
11128 as well.")
11129 (make-variable-buffer-local 'org-occur-parameters)
11131 (defun org-occur (regexp &optional keep-previous callback)
11132 "Make a compact tree which shows all matches of REGEXP.
11133 The tree will show the lines where the regexp matches, and all higher
11134 headlines above the match. It will also show the heading after the match,
11135 to make sure editing the matching entry is easy.
11136 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11137 call to `org-occur' will be kept, to allow stacking of calls to this
11138 command.
11139 If CALLBACK is non-nil, it is a function which is called to confirm
11140 that the match should indeed be shown."
11141 (interactive "sRegexp: \nP")
11142 (when (equal regexp "")
11143 (error "Regexp cannot be empty"))
11144 (unless keep-previous
11145 (org-remove-occur-highlights nil nil t))
11146 (push (cons regexp callback) org-occur-parameters)
11147 (let ((cnt 0))
11148 (save-excursion
11149 (goto-char (point-min))
11150 (if (or (not keep-previous) ; do not want to keep
11151 (not org-occur-highlights)) ; no previous matches
11152 ;; hide everything
11153 (org-overview))
11154 (while (re-search-forward regexp nil t)
11155 (when (or (not callback)
11156 (save-match-data (funcall callback)))
11157 (setq cnt (1+ cnt))
11158 (when org-highlight-sparse-tree-matches
11159 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11160 (org-show-context 'occur-tree))))
11161 (when org-remove-highlights-with-change
11162 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11163 nil 'local))
11164 (unless org-sparse-tree-open-archived-trees
11165 (org-hide-archived-subtrees (point-min) (point-max)))
11166 (run-hooks 'org-occur-hook)
11167 (if (interactive-p)
11168 (message "%d match(es) for regexp %s" cnt regexp))
11169 cnt))
11171 (defun org-show-context (&optional key)
11172 "Make sure point and context and visible.
11173 How much context is shown depends upon the variables
11174 `org-show-hierarchy-above', `org-show-following-heading'. and
11175 `org-show-siblings'."
11176 (let ((heading-p (org-on-heading-p t))
11177 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11178 (following-p (org-get-alist-option org-show-following-heading key))
11179 (entry-p (org-get-alist-option org-show-entry-below key))
11180 (siblings-p (org-get-alist-option org-show-siblings key)))
11181 (catch 'exit
11182 ;; Show heading or entry text
11183 (if (and heading-p (not entry-p))
11184 (org-flag-heading nil) ; only show the heading
11185 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11186 (org-show-hidden-entry))) ; show entire entry
11187 (when following-p
11188 ;; Show next sibling, or heading below text
11189 (save-excursion
11190 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11191 (org-flag-heading nil))))
11192 (when siblings-p (org-show-siblings))
11193 (when hierarchy-p
11194 ;; show all higher headings, possibly with siblings
11195 (save-excursion
11196 (while (and (condition-case nil
11197 (progn (org-up-heading-all 1) t)
11198 (error nil))
11199 (not (bobp)))
11200 (org-flag-heading nil)
11201 (when siblings-p (org-show-siblings))))))))
11203 (defun org-reveal (&optional siblings)
11204 "Show current entry, hierarchy above it, and the following headline.
11205 This can be used to show a consistent set of context around locations
11206 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11207 not t for the search context.
11209 With optional argument SIBLINGS, on each level of the hierarchy all
11210 siblings are shown. This repairs the tree structure to what it would
11211 look like when opened with hierarchical calls to `org-cycle'."
11212 (interactive "P")
11213 (let ((org-show-hierarchy-above t)
11214 (org-show-following-heading t)
11215 (org-show-siblings (if siblings t org-show-siblings)))
11216 (org-show-context nil)))
11218 (defun org-highlight-new-match (beg end)
11219 "Highlight from BEG to END and mark the highlight is an occur headline."
11220 (let ((ov (org-make-overlay beg end)))
11221 (org-overlay-put ov 'face 'secondary-selection)
11222 (push ov org-occur-highlights)))
11224 (defun org-remove-occur-highlights (&optional beg end noremove)
11225 "Remove the occur highlights from the buffer.
11226 BEG and END are ignored. If NOREMOVE is nil, remove this function
11227 from the `before-change-functions' in the current buffer."
11228 (interactive)
11229 (unless org-inhibit-highlight-removal
11230 (mapc 'org-delete-overlay org-occur-highlights)
11231 (setq org-occur-highlights nil)
11232 (setq org-occur-parameters nil)
11233 (unless noremove
11234 (remove-hook 'before-change-functions
11235 'org-remove-occur-highlights 'local))))
11237 ;;;; Priorities
11239 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11240 "Regular expression matching the priority indicator.")
11242 (defvar org-remove-priority-next-time nil)
11244 (defun org-priority-up ()
11245 "Increase the priority of the current item."
11246 (interactive)
11247 (org-priority 'up))
11249 (defun org-priority-down ()
11250 "Decrease the priority of the current item."
11251 (interactive)
11252 (org-priority 'down))
11254 (defun org-priority (&optional action)
11255 "Change the priority of an item by ARG.
11256 ACTION can be `set', `up', `down', or a character."
11257 (interactive)
11258 (unless org-enable-priority-commands
11259 (error "Priority commands are disabled"))
11260 (setq action (or action 'set))
11261 (let (current new news have remove)
11262 (save-excursion
11263 (org-back-to-heading t)
11264 (if (looking-at org-priority-regexp)
11265 (setq current (string-to-char (match-string 2))
11266 have t)
11267 (setq current org-default-priority))
11268 (cond
11269 ((eq action 'remove)
11270 (setq remove t new ?\ ))
11271 ((or (eq action 'set)
11272 (if (featurep 'xemacs) (characterp action) (integerp action)))
11273 (if (not (eq action 'set))
11274 (setq new action)
11275 (message "Priority %c-%c, SPC to remove: "
11276 org-highest-priority org-lowest-priority)
11277 (setq new (read-char-exclusive)))
11278 (if (and (= (upcase org-highest-priority) org-highest-priority)
11279 (= (upcase org-lowest-priority) org-lowest-priority))
11280 (setq new (upcase new)))
11281 (cond ((equal new ?\ ) (setq remove t))
11282 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11283 (error "Priority must be between `%c' and `%c'"
11284 org-highest-priority org-lowest-priority))))
11285 ((eq action 'up)
11286 (if (and (not have) (eq last-command this-command))
11287 (setq new org-lowest-priority)
11288 (setq new (if (and org-priority-start-cycle-with-default (not have))
11289 org-default-priority (1- current)))))
11290 ((eq action 'down)
11291 (if (and (not have) (eq last-command this-command))
11292 (setq new org-highest-priority)
11293 (setq new (if (and org-priority-start-cycle-with-default (not have))
11294 org-default-priority (1+ current)))))
11295 (t (error "Invalid action")))
11296 (if (or (< (upcase new) org-highest-priority)
11297 (> (upcase new) org-lowest-priority))
11298 (setq remove t))
11299 (setq news (format "%c" new))
11300 (if have
11301 (if remove
11302 (replace-match "" t t nil 1)
11303 (replace-match news t t nil 2))
11304 (if remove
11305 (error "No priority cookie found in line")
11306 (let ((case-fold-search nil))
11307 (looking-at org-todo-line-regexp))
11308 (if (match-end 2)
11309 (progn
11310 (goto-char (match-end 2))
11311 (insert " [#" news "]"))
11312 (goto-char (match-beginning 3))
11313 (insert "[#" news "] "))))
11314 (org-preserve-lc (org-set-tags nil 'align)))
11315 (if remove
11316 (message "Priority removed")
11317 (message "Priority of current item set to %s" news))))
11319 (defun org-get-priority (s)
11320 "Find priority cookie and return priority."
11321 (save-match-data
11322 (if (not (string-match org-priority-regexp s))
11323 (* 1000 (- org-lowest-priority org-default-priority))
11324 (* 1000 (- org-lowest-priority
11325 (string-to-char (match-string 2 s)))))))
11327 ;;;; Tags
11329 (defvar org-agenda-archives-mode)
11330 (defvar org-map-continue-from nil
11331 "Position from where mapping should continue.
11332 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11334 (defvar org-scanner-tags nil
11335 "The current tag list while the tags scanner is running.")
11336 (defvar org-trust-scanner-tags nil
11337 "Should `org-get-tags-at' use the tags fro the scanner.
11338 This is for internal dynamical scoping only.
11339 When this is non-nil, the function `org-get-tags-at' will return the value
11340 of `org-scanner-tags' instead of building the list by itself. This
11341 can lead to large speed-ups when the tags scanner is used in a file with
11342 many entries, and when the list of tags is retrieved, for example to
11343 obtain a list of properties. Building the tags list for each entry in such
11344 a file becomes an N^2 operation - but with this variable set, it scales
11345 as N.")
11347 (defun org-scan-tags (action matcher &optional todo-only)
11348 "Scan headline tags with inheritance and produce output ACTION.
11350 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11351 or `agenda' to produce an entry list for an agenda view. It can also be
11352 a Lisp form or a function that should be called at each matched headline, in
11353 this case the return value is a list of all return values from these calls.
11355 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11356 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11357 only lines with a TODO keyword are included in the output."
11358 (require 'org-agenda)
11359 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11360 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11361 (org-re
11362 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11363 (props (list 'face 'default
11364 'done-face 'org-agenda-done
11365 'undone-face 'default
11366 'mouse-face 'highlight
11367 'org-not-done-regexp org-not-done-regexp
11368 'org-todo-regexp org-todo-regexp
11369 'help-echo
11370 (format "mouse-2 or RET jump to org file %s"
11371 (abbreviate-file-name
11372 (or (buffer-file-name (buffer-base-buffer))
11373 (buffer-name (buffer-base-buffer)))))))
11374 (case-fold-search nil)
11375 (org-map-continue-from nil)
11376 lspos tags tags-list
11377 (tags-alist (list (cons 0 org-file-tags)))
11378 (llast 0) rtn rtn1 level category i txt
11379 todo marker entry priority)
11380 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11381 (setq action (list 'lambda nil action)))
11382 (save-excursion
11383 (goto-char (point-min))
11384 (when (eq action 'sparse-tree)
11385 (org-overview)
11386 (org-remove-occur-highlights))
11387 (while (re-search-forward re nil t)
11388 (catch :skip
11389 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11390 tags (if (match-end 4) (org-match-string-no-properties 4)))
11391 (goto-char (setq lspos (match-beginning 0)))
11392 (setq level (org-reduced-level (funcall outline-level))
11393 category (org-get-category))
11394 (setq i llast llast level)
11395 ;; remove tag lists from same and sublevels
11396 (while (>= i level)
11397 (when (setq entry (assoc i tags-alist))
11398 (setq tags-alist (delete entry tags-alist)))
11399 (setq i (1- i)))
11400 ;; add the next tags
11401 (when tags
11402 (setq tags (org-split-string tags ":")
11403 tags-alist
11404 (cons (cons level tags) tags-alist)))
11405 ;; compile tags for current headline
11406 (setq tags-list
11407 (if org-use-tag-inheritance
11408 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11409 tags)
11410 org-scanner-tags tags-list)
11411 (when org-use-tag-inheritance
11412 (setcdr (car tags-alist)
11413 (mapcar (lambda (x)
11414 (setq x (copy-sequence x))
11415 (org-add-prop-inherited x))
11416 (cdar tags-alist))))
11417 (when (and tags org-use-tag-inheritance
11418 (or (not (eq t org-use-tag-inheritance))
11419 org-tags-exclude-from-inheritance))
11420 ;; selective inheritance, remove uninherited ones
11421 (setcdr (car tags-alist)
11422 (org-remove-uniherited-tags (cdar tags-alist))))
11423 (when (and (or (not todo-only)
11424 (and (member todo org-not-done-keywords)
11425 (or (not org-agenda-tags-todo-honor-ignore-options)
11426 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11427 (let ((case-fold-search t)) (eval matcher))
11429 (not (member org-archive-tag tags-list))
11430 ;; we have an archive tag, should we use this anyway?
11431 (or (not org-agenda-skip-archived-trees)
11432 (and (eq action 'agenda) org-agenda-archives-mode))))
11433 (unless (eq action 'sparse-tree) (org-agenda-skip))
11435 ;; select this headline
11437 (cond
11438 ((eq action 'sparse-tree)
11439 (and org-highlight-sparse-tree-matches
11440 (org-get-heading) (match-end 0)
11441 (org-highlight-new-match
11442 (match-beginning 0) (match-beginning 1)))
11443 (org-show-context 'tags-tree))
11444 ((eq action 'agenda)
11445 (setq txt (org-format-agenda-item
11447 (concat
11448 (if (eq org-tags-match-list-sublevels 'indented)
11449 (make-string (1- level) ?.) "")
11450 (org-get-heading))
11451 category
11452 tags-list
11454 priority (org-get-priority txt))
11455 (goto-char lspos)
11456 (setq marker (org-agenda-new-marker))
11457 (org-add-props txt props
11458 'org-marker marker 'org-hd-marker marker 'org-category category
11459 'todo-state todo
11460 'priority priority 'type "tagsmatch")
11461 (push txt rtn))
11462 ((functionp action)
11463 (setq org-map-continue-from nil)
11464 (save-excursion
11465 (setq rtn1 (funcall action))
11466 (push rtn1 rtn)))
11467 (t (error "Invalid action")))
11469 ;; if we are to skip sublevels, jump to end of subtree
11470 (unless org-tags-match-list-sublevels
11471 (org-end-of-subtree t)
11472 (backward-char 1))))
11473 ;; Get the correct position from where to continue
11474 (if org-map-continue-from
11475 (goto-char org-map-continue-from)
11476 (and (= (point) lspos) (end-of-line 1)))))
11477 (when (and (eq action 'sparse-tree)
11478 (not org-sparse-tree-open-archived-trees))
11479 (org-hide-archived-subtrees (point-min) (point-max)))
11480 (nreverse rtn)))
11482 (defun org-remove-uniherited-tags (tags)
11483 "Remove all tags that are not inherited from the list TAGS."
11484 (cond
11485 ((eq org-use-tag-inheritance t)
11486 (if org-tags-exclude-from-inheritance
11487 (org-delete-all org-tags-exclude-from-inheritance tags)
11488 tags))
11489 ((not org-use-tag-inheritance) nil)
11490 ((stringp org-use-tag-inheritance)
11491 (delq nil (mapcar
11492 (lambda (x)
11493 (if (and (string-match org-use-tag-inheritance x)
11494 (not (member x org-tags-exclude-from-inheritance)))
11495 x nil))
11496 tags)))
11497 ((listp org-use-tag-inheritance)
11498 (delq nil (mapcar
11499 (lambda (x)
11500 (if (member x org-use-tag-inheritance) x nil))
11501 tags)))))
11503 (defvar todo-only) ;; dynamically scoped
11505 (defun org-match-sparse-tree (&optional todo-only match)
11506 "Create a sparse tree according to tags string MATCH.
11507 MATCH can contain positive and negative selection of tags, like
11508 \"+WORK+URGENT-WITHBOSS\".
11509 If optional argument TODO-ONLY is non-nil, only select lines that are
11510 also TODO lines."
11511 (interactive "P")
11512 (org-prepare-agenda-buffers (list (current-buffer)))
11513 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11515 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11517 (defvar org-cached-props nil)
11518 (defun org-cached-entry-get (pom property)
11519 (if (or (eq t org-use-property-inheritance)
11520 (and (stringp org-use-property-inheritance)
11521 (string-match org-use-property-inheritance property))
11522 (and (listp org-use-property-inheritance)
11523 (member property org-use-property-inheritance)))
11524 ;; Caching is not possible, check it directly
11525 (org-entry-get pom property 'inherit)
11526 ;; Get all properties, so that we can do complicated checks easily
11527 (cdr (assoc property (or org-cached-props
11528 (setq org-cached-props
11529 (org-entry-properties pom)))))))
11531 (defun org-global-tags-completion-table (&optional files)
11532 "Return the list of all tags in all agenda buffer/files."
11533 (save-excursion
11534 (org-uniquify
11535 (delq nil
11536 (apply 'append
11537 (mapcar
11538 (lambda (file)
11539 (set-buffer (find-file-noselect file))
11540 (append (org-get-buffer-tags)
11541 (mapcar (lambda (x) (if (stringp (car-safe x))
11542 (list (car-safe x)) nil))
11543 org-tag-alist)))
11544 (if (and files (car files))
11545 files
11546 (org-agenda-files))))))))
11548 (defun org-make-tags-matcher (match)
11549 "Create the TAGS//TODO matcher form for the selection string MATCH."
11550 ;; todo-only is scoped dynamically into this function, and the function
11551 ;; may change it if the matcher asks for it.
11552 (unless match
11553 ;; Get a new match request, with completion
11554 (let ((org-last-tags-completion-table
11555 (org-global-tags-completion-table)))
11556 (setq match (org-completing-read-no-i
11557 "Match: " 'org-tags-completion-function nil nil nil
11558 'org-tags-history))))
11560 ;; Parse the string and create a lisp form
11561 (let ((match0 match)
11562 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11563 minus tag mm
11564 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11565 orterms term orlist re-p str-p level-p level-op time-p
11566 prop-p pn pv po cat-p gv rest)
11567 (if (string-match "/+" match)
11568 ;; match contains also a todo-matching request
11569 (progn
11570 (setq tagsmatch (substring match 0 (match-beginning 0))
11571 todomatch (substring match (match-end 0)))
11572 (if (string-match "^!" todomatch)
11573 (setq todo-only t todomatch (substring todomatch 1)))
11574 (if (string-match "^\\s-*$" todomatch)
11575 (setq todomatch nil)))
11576 ;; only matching tags
11577 (setq tagsmatch match todomatch nil))
11579 ;; Make the tags matcher
11580 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11581 (setq tagsmatcher t)
11582 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11583 (while (setq term (pop orterms))
11584 (while (and (equal (substring term -1) "\\") orterms)
11585 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11586 (while (string-match re term)
11587 (setq rest (substring term (match-end 0))
11588 minus (and (match-end 1)
11589 (equal (match-string 1 term) "-"))
11590 tag (match-string 2 term)
11591 re-p (equal (string-to-char tag) ?{)
11592 level-p (match-end 4)
11593 prop-p (match-end 5)
11594 mm (cond
11595 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11596 (level-p
11597 (setq level-op (org-op-to-function (match-string 3 term)))
11598 `(,level-op level ,(string-to-number
11599 (match-string 4 term))))
11600 (prop-p
11601 (setq pn (match-string 5 term)
11602 po (match-string 6 term)
11603 pv (match-string 7 term)
11604 cat-p (equal pn "CATEGORY")
11605 re-p (equal (string-to-char pv) ?{)
11606 str-p (equal (string-to-char pv) ?\")
11607 time-p (save-match-data
11608 (string-match "^\"[[<].*[]>]\"$" pv))
11609 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11610 (if time-p (setq pv (org-matcher-time pv)))
11611 (setq po (org-op-to-function po (if time-p 'time str-p)))
11612 (cond
11613 ((equal pn "CATEGORY")
11614 (setq gv '(get-text-property (point) 'org-category)))
11615 ((equal pn "TODO")
11616 (setq gv 'todo))
11618 (setq gv `(org-cached-entry-get nil ,pn))))
11619 (if re-p
11620 (if (eq po 'org<>)
11621 `(not (string-match ,pv (or ,gv "")))
11622 `(string-match ,pv (or ,gv "")))
11623 (if str-p
11624 `(,po (or ,gv "") ,pv)
11625 `(,po (string-to-number (or ,gv ""))
11626 ,(string-to-number pv) ))))
11627 (t `(member ,tag tags-list)))
11628 mm (if minus (list 'not mm) mm)
11629 term rest)
11630 (push mm tagsmatcher))
11631 (push (if (> (length tagsmatcher) 1)
11632 (cons 'and tagsmatcher)
11633 (car tagsmatcher))
11634 orlist)
11635 (setq tagsmatcher nil))
11636 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11637 (setq tagsmatcher
11638 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11639 ;; Make the todo matcher
11640 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11641 (setq todomatcher t)
11642 (setq orterms (org-split-string todomatch "|") orlist nil)
11643 (while (setq term (pop orterms))
11644 (while (string-match re term)
11645 (setq minus (and (match-end 1)
11646 (equal (match-string 1 term) "-"))
11647 kwd (match-string 2 term)
11648 re-p (equal (string-to-char kwd) ?{)
11649 term (substring term (match-end 0))
11650 mm (if re-p
11651 `(string-match ,(substring kwd 1 -1) todo)
11652 (list 'equal 'todo kwd))
11653 mm (if minus (list 'not mm) mm))
11654 (push mm todomatcher))
11655 (push (if (> (length todomatcher) 1)
11656 (cons 'and todomatcher)
11657 (car todomatcher))
11658 orlist)
11659 (setq todomatcher nil))
11660 (setq todomatcher (if (> (length orlist) 1)
11661 (cons 'or orlist) (car orlist))))
11663 ;; Return the string and lisp forms of the matcher
11664 (setq matcher (if todomatcher
11665 (list 'and tagsmatcher todomatcher)
11666 tagsmatcher))
11667 (cons match0 matcher)))
11669 (defun org-op-to-function (op &optional stringp)
11670 "Turn an operator into the appropriate function."
11671 (setq op
11672 (cond
11673 ((equal op "<" ) '(< string< org-time<))
11674 ((equal op ">" ) '(> org-string> org-time>))
11675 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11676 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11677 ((member op '("=" "==")) '(= string= org-time=))
11678 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11679 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11681 (defun org<> (a b) (not (= a b)))
11682 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11683 (defun org-string>= (a b) (not (string< a b)))
11684 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11685 (defun org-string<> (a b) (not (string= a b)))
11686 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11687 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11688 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11689 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11690 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11691 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11692 (defun org-2ft (s)
11693 "Convert S to a floating point time.
11694 If S is already a number, just return it. If it is a string, parse
11695 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11696 (cond
11697 ((numberp s) s)
11698 ((stringp s)
11699 (condition-case nil
11700 (float-time (apply 'encode-time (org-parse-time-string s)))
11701 (error 0.)))
11702 (t 0.)))
11704 (defun org-time-today ()
11705 "Time in seconds today at 0:00.
11706 Returns the float number of seconds since the beginning of the
11707 epoch to the beginning of today (00:00)."
11708 (float-time (apply 'encode-time
11709 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11711 (defun org-matcher-time (s)
11712 "Interpret a time comparison value."
11713 (save-match-data
11714 (cond
11715 ((string= s "<now>") (float-time))
11716 ((string= s "<today>") (org-time-today))
11717 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11718 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11719 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11720 (+ (org-time-today)
11721 (* (string-to-number (match-string 1 s))
11722 (cdr (assoc (match-string 2 s)
11723 '(("d" . 86400.0) ("w" . 604800.0)
11724 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11725 (t (org-2ft s)))))
11727 (defun org-match-any-p (re list)
11728 "Does re match any element of list?"
11729 (setq list (mapcar (lambda (x) (string-match re x)) list))
11730 (delq nil list))
11732 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11733 (defvar org-tags-overlay (org-make-overlay 1 1))
11734 (org-detach-overlay org-tags-overlay)
11736 (defun org-get-local-tags-at (&optional pos)
11737 "Get a list of tags defined in the current headline."
11738 (org-get-tags-at pos 'local))
11740 (defun org-get-local-tags ()
11741 "Get a list of tags defined in the current headline."
11742 (org-get-tags-at nil 'local))
11744 (defun org-get-tags-at (&optional pos local)
11745 "Get a list of all headline tags applicable at POS.
11746 POS defaults to point. If tags are inherited, the list contains
11747 the targets in the same sequence as the headlines appear, i.e.
11748 the tags of the current headline come last.
11749 When LOCAL is non-nil, only return tags from the current headline,
11750 ignore inherited ones."
11751 (interactive)
11752 (if (and org-trust-scanner-tags
11753 (or (not pos) (equal pos (point)))
11754 (not local))
11755 org-scanner-tags
11756 (let (tags ltags lastpos parent)
11757 (save-excursion
11758 (save-restriction
11759 (widen)
11760 (goto-char (or pos (point)))
11761 (save-match-data
11762 (catch 'done
11763 (condition-case nil
11764 (progn
11765 (org-back-to-heading t)
11766 (while (not (equal lastpos (point)))
11767 (setq lastpos (point))
11768 (when (looking-at
11769 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11770 (setq ltags (org-split-string
11771 (org-match-string-no-properties 1) ":"))
11772 (when parent
11773 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11774 (setq tags (append
11775 (if parent
11776 (org-remove-uniherited-tags ltags)
11777 ltags)
11778 tags)))
11779 (or org-use-tag-inheritance (throw 'done t))
11780 (if local (throw 'done t))
11781 (or (org-up-heading-safe) (error nil))
11782 (setq parent t)))
11783 (error nil)))))
11784 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11786 (defun org-add-prop-inherited (s)
11787 (add-text-properties 0 (length s) '(inherited t) s)
11790 (defun org-toggle-tag (tag &optional onoff)
11791 "Toggle the tag TAG for the current line.
11792 If ONOFF is `on' or `off', don't toggle but set to this state."
11793 (let (res current)
11794 (save-excursion
11795 (org-back-to-heading t)
11796 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11797 (point-at-eol) t)
11798 (progn
11799 (setq current (match-string 1))
11800 (replace-match ""))
11801 (setq current ""))
11802 (setq current (nreverse (org-split-string current ":")))
11803 (cond
11804 ((eq onoff 'on)
11805 (setq res t)
11806 (or (member tag current) (push tag current)))
11807 ((eq onoff 'off)
11808 (or (not (member tag current)) (setq current (delete tag current))))
11809 (t (if (member tag current)
11810 (setq current (delete tag current))
11811 (setq res t)
11812 (push tag current))))
11813 (end-of-line 1)
11814 (if current
11815 (progn
11816 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11817 (org-set-tags nil t))
11818 (delete-horizontal-space))
11819 (run-hooks 'org-after-tags-change-hook))
11820 res))
11822 (defun org-align-tags-here (to-col)
11823 ;; Assumes that this is a headline
11824 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11825 (beginning-of-line 1)
11826 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11827 (< pos (match-beginning 2)))
11828 (progn
11829 (setq tags-l (- (match-end 2) (match-beginning 2)))
11830 (goto-char (match-beginning 1))
11831 (insert " ")
11832 (delete-region (point) (1+ (match-beginning 2)))
11833 (setq ncol (max (1+ (current-column))
11834 (1+ col)
11835 (if (> to-col 0)
11836 to-col
11837 (- (abs to-col) tags-l))))
11838 (setq p (point))
11839 (insert (make-string (- ncol (current-column)) ?\ ))
11840 (setq ncol (current-column))
11841 (when indent-tabs-mode (tabify p (point-at-eol)))
11842 (org-move-to-column (min ncol col) t))
11843 (goto-char pos))))
11845 (defun org-set-tags-command (&optional arg just-align)
11846 "Call the set-tags command for the current entry."
11847 (interactive "P")
11848 (if (org-on-heading-p)
11849 (org-set-tags arg just-align)
11850 (save-excursion
11851 (org-back-to-heading t)
11852 (org-set-tags arg just-align))))
11854 (defun org-set-tags-to (data)
11855 "Set the tags of the current entry to DATA, replacing the current tags.
11856 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11857 If DATA is nil or the empty string, any tags will be removed."
11858 (interactive "sTags: ")
11859 (setq data
11860 (cond
11861 ((eq data nil) "")
11862 ((equal data "") "")
11863 ((stringp data)
11864 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11865 ":"))
11866 ((listp data)
11867 (concat ":" (mapconcat 'identity data ":") ":"))
11868 (t nil)))
11869 (when data
11870 (save-excursion
11871 (org-back-to-heading t)
11872 (when (looking-at org-complex-heading-regexp)
11873 (if (match-end 5)
11874 (progn
11875 (goto-char (match-beginning 5))
11876 (insert data)
11877 (delete-region (point) (point-at-eol))
11878 (org-set-tags nil 'align))
11879 (goto-char (point-at-eol))
11880 (insert " " data)
11881 (org-set-tags nil 'align)))
11882 (beginning-of-line 1)
11883 (if (looking-at ".*?\\([ \t]+\\)$")
11884 (delete-region (match-beginning 1) (match-end 1))))))
11886 (defun org-set-tags (&optional arg just-align)
11887 "Set the tags for the current headline.
11888 With prefix ARG, realign all tags in headings in the current buffer."
11889 (interactive "P")
11890 (let* ((re (concat "^" outline-regexp))
11891 (current (org-get-tags-string))
11892 (col (current-column))
11893 (org-setting-tags t)
11894 table current-tags inherited-tags ; computed below when needed
11895 tags p0 c0 c1 rpl)
11896 (if arg
11897 (save-excursion
11898 (goto-char (point-min))
11899 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11900 (while (re-search-forward re nil t)
11901 (org-set-tags nil t)
11902 (end-of-line 1)))
11903 (message "All tags realigned to column %d" org-tags-column))
11904 (if just-align
11905 (setq tags current)
11906 ;; Get a new set of tags from the user
11907 (save-excursion
11908 (setq table (append org-tag-persistent-alist
11909 (or org-tag-alist (org-get-buffer-tags))
11910 (and org-complete-tags-always-offer-all-agenda-tags
11911 (org-global-tags-completion-table (org-agenda-files))))
11912 org-last-tags-completion-table table
11913 current-tags (org-split-string current ":")
11914 inherited-tags (nreverse
11915 (nthcdr (length current-tags)
11916 (nreverse (org-get-tags-at))))
11917 tags
11918 (if (or (eq t org-use-fast-tag-selection)
11919 (and org-use-fast-tag-selection
11920 (delq nil (mapcar 'cdr table))))
11921 (org-fast-tag-selection
11922 current-tags inherited-tags table
11923 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11924 (let ((org-add-colon-after-tag-completion t))
11925 (org-trim
11926 (org-without-partial-completion
11927 (org-icompleting-read "Tags: " 'org-tags-completion-function
11928 nil nil current 'org-tags-history)))))))
11929 (while (string-match "[-+&]+" tags)
11930 ;; No boolean logic, just a list
11931 (setq tags (replace-match ":" t t tags))))
11933 (if org-tags-sort-function
11934 (setq tags (mapconcat 'identity
11935 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11936 org-tags-sort-function) ":")))
11938 (if (string-match "\\`[\t ]*\\'" tags)
11939 (setq tags "")
11940 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11941 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11943 ;; Insert new tags at the correct column
11944 (beginning-of-line 1)
11945 (cond
11946 ((and (equal current "") (equal tags "")))
11947 ((re-search-forward
11948 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11949 (point-at-eol) t)
11950 (if (equal tags "")
11951 (setq rpl "")
11952 (goto-char (match-beginning 0))
11953 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11954 (1+ (point)) (point))
11955 c1 (max (1+ c0) (if (> org-tags-column 0)
11956 org-tags-column
11957 (- (- org-tags-column) (length tags))))
11958 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11959 (replace-match rpl t t)
11960 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11961 tags)
11962 (t (error "Tags alignment failed")))
11963 (org-move-to-column col)
11964 (unless just-align
11965 (run-hooks 'org-after-tags-change-hook)))))
11967 (defun org-change-tag-in-region (beg end tag off)
11968 "Add or remove TAG for each entry in the region.
11969 This works in the agenda, and also in an org-mode buffer."
11970 (interactive
11971 (list (region-beginning) (region-end)
11972 (let ((org-last-tags-completion-table
11973 (if (org-mode-p)
11974 (org-get-buffer-tags)
11975 (org-global-tags-completion-table))))
11976 (org-icompleting-read
11977 "Tag: " 'org-tags-completion-function nil nil nil
11978 'org-tags-history))
11979 (progn
11980 (message "[s]et or [r]emove? ")
11981 (equal (read-char-exclusive) ?r))))
11982 (if (fboundp 'deactivate-mark) (deactivate-mark))
11983 (let ((agendap (equal major-mode 'org-agenda-mode))
11984 l1 l2 m buf pos newhead (cnt 0))
11985 (goto-char end)
11986 (setq l2 (1- (org-current-line)))
11987 (goto-char beg)
11988 (setq l1 (org-current-line))
11989 (loop for l from l1 to l2 do
11990 (org-goto-line l)
11991 (setq m (get-text-property (point) 'org-hd-marker))
11992 (when (or (and (org-mode-p) (org-on-heading-p))
11993 (and agendap m))
11994 (setq buf (if agendap (marker-buffer m) (current-buffer))
11995 pos (if agendap m (point)))
11996 (with-current-buffer buf
11997 (save-excursion
11998 (save-restriction
11999 (goto-char pos)
12000 (setq cnt (1+ cnt))
12001 (org-toggle-tag tag (if off 'off 'on))
12002 (setq newhead (org-get-heading)))))
12003 (and agendap (org-agenda-change-all-lines newhead m))))
12004 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12006 (defun org-tags-completion-function (string predicate &optional flag)
12007 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12008 (confirm (lambda (x) (stringp (car x)))))
12009 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12010 (setq s1 (match-string 1 string)
12011 s2 (match-string 2 string))
12012 (setq s1 "" s2 string))
12013 (cond
12014 ((eq flag nil)
12015 ;; try completion
12016 (setq rtn (try-completion s2 ctable confirm))
12017 (if (stringp rtn)
12018 (setq rtn
12019 (concat s1 s2 (substring rtn (length s2))
12020 (if (and org-add-colon-after-tag-completion
12021 (assoc rtn ctable))
12022 ":" ""))))
12023 rtn)
12024 ((eq flag t)
12025 ;; all-completions
12026 (all-completions s2 ctable confirm)
12028 ((eq flag 'lambda)
12029 ;; exact match?
12030 (assoc s2 ctable)))
12033 (defun org-fast-tag-insert (kwd tags face &optional end)
12034 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12035 (insert (format "%-12s" (concat kwd ":"))
12036 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12037 (or end "")))
12039 (defun org-fast-tag-show-exit (flag)
12040 (save-excursion
12041 (org-goto-line 3)
12042 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12043 (replace-match ""))
12044 (when flag
12045 (end-of-line 1)
12046 (org-move-to-column (- (window-width) 19) t)
12047 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12049 (defun org-set-current-tags-overlay (current prefix)
12050 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12051 (if (featurep 'xemacs)
12052 (org-overlay-display org-tags-overlay (concat prefix s)
12053 'secondary-selection)
12054 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12055 (org-overlay-display org-tags-overlay (concat prefix s)))))
12057 (defvar org-last-tag-selection-key nil)
12058 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12059 "Fast tag selection with single keys.
12060 CURRENT is the current list of tags in the headline, INHERITED is the
12061 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12062 possibly with grouping information. TODO-TABLE is a similar table with
12063 TODO keywords, should these have keys assigned to them.
12064 If the keys are nil, a-z are automatically assigned.
12065 Returns the new tags string, or nil to not change the current settings."
12066 (let* ((fulltable (append table todo-table))
12067 (maxlen (apply 'max (mapcar
12068 (lambda (x)
12069 (if (stringp (car x)) (string-width (car x)) 0))
12070 fulltable)))
12071 (buf (current-buffer))
12072 (expert (eq org-fast-tag-selection-single-key 'expert))
12073 (buffer-tags nil)
12074 (fwidth (+ maxlen 3 1 3))
12075 (ncol (/ (- (window-width) 4) fwidth))
12076 (i-face 'org-done)
12077 (c-face 'org-todo)
12078 tg cnt e c char c1 c2 ntable tbl rtn
12079 ov-start ov-end ov-prefix
12080 (exit-after-next org-fast-tag-selection-single-key)
12081 (done-keywords org-done-keywords)
12082 groups ingroup)
12083 (save-excursion
12084 (beginning-of-line 1)
12085 (if (looking-at
12086 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12087 (setq ov-start (match-beginning 1)
12088 ov-end (match-end 1)
12089 ov-prefix "")
12090 (setq ov-start (1- (point-at-eol))
12091 ov-end (1+ ov-start))
12092 (skip-chars-forward "^\n\r")
12093 (setq ov-prefix
12094 (concat
12095 (buffer-substring (1- (point)) (point))
12096 (if (> (current-column) org-tags-column)
12098 (make-string (- org-tags-column (current-column)) ?\ ))))))
12099 (org-move-overlay org-tags-overlay ov-start ov-end)
12100 (save-window-excursion
12101 (if expert
12102 (set-buffer (get-buffer-create " *Org tags*"))
12103 (delete-other-windows)
12104 (split-window-vertically)
12105 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12106 (erase-buffer)
12107 (org-set-local 'org-done-keywords done-keywords)
12108 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12109 (org-fast-tag-insert "Current" current c-face "\n\n")
12110 (org-fast-tag-show-exit exit-after-next)
12111 (org-set-current-tags-overlay current ov-prefix)
12112 (setq tbl fulltable char ?a cnt 0)
12113 (while (setq e (pop tbl))
12114 (cond
12115 ((equal (car e) :startgroup)
12116 (push '() groups) (setq ingroup t)
12117 (when (not (= cnt 0))
12118 (setq cnt 0)
12119 (insert "\n"))
12120 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12121 ((equal (car e) :endgroup)
12122 (setq ingroup nil cnt 0)
12123 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12124 ((equal e '(:newline))
12125 (when (not (= cnt 0))
12126 (setq cnt 0)
12127 (insert "\n")
12128 (setq e (car tbl))
12129 (while (equal (car tbl) '(:newline))
12130 (insert "\n")
12131 (setq tbl (cdr tbl)))))
12133 (setq tg (copy-sequence (car e)) c2 nil)
12134 (if (cdr e)
12135 (setq c (cdr e))
12136 ;; automatically assign a character.
12137 (setq c1 (string-to-char
12138 (downcase (substring
12139 tg (if (= (string-to-char tg) ?@) 1 0)))))
12140 (if (or (rassoc c1 ntable) (rassoc c1 table))
12141 (while (or (rassoc char ntable) (rassoc char table))
12142 (setq char (1+ char)))
12143 (setq c2 c1))
12144 (setq c (or c2 char)))
12145 (if ingroup (push tg (car groups)))
12146 (setq tg (org-add-props tg nil 'face
12147 (cond
12148 ((not (assoc tg table))
12149 (org-get-todo-face tg))
12150 ((member tg current) c-face)
12151 ((member tg inherited) i-face)
12152 (t nil))))
12153 (if (and (= cnt 0) (not ingroup)) (insert " "))
12154 (insert "[" c "] " tg (make-string
12155 (- fwidth 4 (length tg)) ?\ ))
12156 (push (cons tg c) ntable)
12157 (when (= (setq cnt (1+ cnt)) ncol)
12158 (insert "\n")
12159 (if ingroup (insert " "))
12160 (setq cnt 0)))))
12161 (setq ntable (nreverse ntable))
12162 (insert "\n")
12163 (goto-char (point-min))
12164 (if (not expert) (org-fit-window-to-buffer))
12165 (setq rtn
12166 (catch 'exit
12167 (while t
12168 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12169 (if (not groups) "no " "")
12170 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12171 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12172 (setq org-last-tag-selection-key c)
12173 (cond
12174 ((= c ?\r) (throw 'exit t))
12175 ((= c ?!)
12176 (setq groups (not groups))
12177 (goto-char (point-min))
12178 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12179 ((= c ?\C-c)
12180 (if (not expert)
12181 (org-fast-tag-show-exit
12182 (setq exit-after-next (not exit-after-next)))
12183 (setq expert nil)
12184 (delete-other-windows)
12185 (split-window-vertically)
12186 (org-switch-to-buffer-other-window " *Org tags*")
12187 (org-fit-window-to-buffer)))
12188 ((or (= c ?\C-g)
12189 (and (= c ?q) (not (rassoc c ntable))))
12190 (org-detach-overlay org-tags-overlay)
12191 (setq quit-flag t))
12192 ((= c ?\ )
12193 (setq current nil)
12194 (if exit-after-next (setq exit-after-next 'now)))
12195 ((= c ?\t)
12196 (condition-case nil
12197 (setq tg (org-icompleting-read
12198 "Tag: "
12199 (or buffer-tags
12200 (with-current-buffer buf
12201 (org-get-buffer-tags)))))
12202 (quit (setq tg "")))
12203 (when (string-match "\\S-" tg)
12204 (add-to-list 'buffer-tags (list tg))
12205 (if (member tg current)
12206 (setq current (delete tg current))
12207 (push tg current)))
12208 (if exit-after-next (setq exit-after-next 'now)))
12209 ((setq e (rassoc c todo-table) tg (car e))
12210 (with-current-buffer buf
12211 (save-excursion (org-todo tg)))
12212 (if exit-after-next (setq exit-after-next 'now)))
12213 ((setq e (rassoc c ntable) tg (car e))
12214 (if (member tg current)
12215 (setq current (delete tg current))
12216 (loop for g in groups do
12217 (if (member tg g)
12218 (mapc (lambda (x)
12219 (setq current (delete x current)))
12220 g)))
12221 (push tg current))
12222 (if exit-after-next (setq exit-after-next 'now))))
12224 ;; Create a sorted list
12225 (setq current
12226 (sort current
12227 (lambda (a b)
12228 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12229 (if (eq exit-after-next 'now) (throw 'exit t))
12230 (goto-char (point-min))
12231 (beginning-of-line 2)
12232 (delete-region (point) (point-at-eol))
12233 (org-fast-tag-insert "Current" current c-face)
12234 (org-set-current-tags-overlay current ov-prefix)
12235 (while (re-search-forward
12236 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12237 (setq tg (match-string 1))
12238 (add-text-properties
12239 (match-beginning 1) (match-end 1)
12240 (list 'face
12241 (cond
12242 ((member tg current) c-face)
12243 ((member tg inherited) i-face)
12244 (t (get-text-property (match-beginning 1) 'face))))))
12245 (goto-char (point-min)))))
12246 (org-detach-overlay org-tags-overlay)
12247 (if rtn
12248 (mapconcat 'identity current ":")
12249 nil))))
12251 (defun org-get-tags-string ()
12252 "Get the TAGS string in the current headline."
12253 (unless (org-on-heading-p t)
12254 (error "Not on a heading"))
12255 (save-excursion
12256 (beginning-of-line 1)
12257 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12258 (org-match-string-no-properties 1)
12259 "")))
12261 (defun org-get-tags ()
12262 "Get the list of tags specified in the current headline."
12263 (org-split-string (org-get-tags-string) ":"))
12265 (defun org-get-buffer-tags ()
12266 "Get a table of all tags used in the buffer, for completion."
12267 (let (tags)
12268 (save-excursion
12269 (goto-char (point-min))
12270 (while (re-search-forward
12271 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12272 (when (equal (char-after (point-at-bol 0)) ?*)
12273 (mapc (lambda (x) (add-to-list 'tags x))
12274 (org-split-string (org-match-string-no-properties 1) ":")))))
12275 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12276 (mapcar 'list tags)))
12278 ;;;; The mapping API
12280 ;;;###autoload
12281 (defun org-map-entries (func &optional match scope &rest skip)
12282 "Call FUNC at each headline selected by MATCH in SCOPE.
12284 FUNC is a function or a lisp form. The function will be called without
12285 arguments, with the cursor positioned at the beginning of the headline.
12286 The return values of all calls to the function will be collected and
12287 returned as a list.
12289 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12290 does not need to preserve point. After evaluation, the cursor will be
12291 moved to the end of the line (presumably of the headline of the
12292 processed entry) and search continues from there. Under some
12293 circumstances, this may not produce the wanted results. For example,
12294 if you have removed (e.g. archived) the current (sub)tree it could
12295 mean that the next entry will be skipped entirely. In such cases, you
12296 can specify the position from where search should continue by making
12297 FUNC set the variable `org-map-continue-from' to the desired buffer
12298 position.
12300 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12301 Only headlines that are matched by this query will be considered during
12302 the iteration. When MATCH is nil or t, all headlines will be
12303 visited by the iteration.
12305 SCOPE determines the scope of this command. It can be any of:
12307 nil The current buffer, respecting the restriction if any
12308 tree The subtree started with the entry at point
12309 file The current buffer, without restriction
12310 file-with-archives
12311 The current buffer, and any archives associated with it
12312 agenda All agenda files
12313 agenda-with-archives
12314 All agenda files with any archive files associated with them
12315 \(file1 file2 ...)
12316 If this is a list, all files in the list will be scanned
12318 The remaining args are treated as settings for the skipping facilities of
12319 the scanner. The following items can be given here:
12321 archive skip trees with the archive tag.
12322 comment skip trees with the COMMENT keyword
12323 function or Emacs Lisp form:
12324 will be used as value for `org-agenda-skip-function', so whenever
12325 the function returns t, FUNC will not be called for that
12326 entry and search will continue from the point where the
12327 function leaves it.
12329 If your function needs to retrieve the tags including inherited tags
12330 at the *current* entry, you can use the value of the variable
12331 `org-scanner-tags' which will be much faster than getting the value
12332 with `org-get-tags-at'. If your function gets properties with
12333 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12334 to t around the call to `org-entry-properties' to get the same speedup.
12335 Note that if your function moves around to retrieve tags and properties at
12336 a *different* entry, you cannot use these techniques."
12337 (let* ((org-agenda-archives-mode nil) ; just to make sure
12338 (org-agenda-skip-archived-trees (memq 'archive skip))
12339 (org-agenda-skip-comment-trees (memq 'comment skip))
12340 (org-agenda-skip-function
12341 (car (org-delete-all '(comment archive) skip)))
12342 (org-tags-match-list-sublevels t)
12343 matcher file res
12344 org-todo-keywords-for-agenda
12345 org-done-keywords-for-agenda
12346 org-todo-keyword-alist-for-agenda
12347 org-drawers-for-agenda
12348 org-tag-alist-for-agenda)
12350 (cond
12351 ((eq match t) (setq matcher t))
12352 ((eq match nil) (setq matcher t))
12353 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12355 (save-excursion
12356 (save-restriction
12357 (when (eq scope 'tree)
12358 (org-back-to-heading t)
12359 (org-narrow-to-subtree)
12360 (setq scope nil))
12362 (if (not scope)
12363 (progn
12364 (org-prepare-agenda-buffers
12365 (list (buffer-file-name (current-buffer))))
12366 (setq res (org-scan-tags func matcher)))
12367 ;; Get the right scope
12368 (cond
12369 ((and scope (listp scope) (symbolp (car scope)))
12370 (setq scope (eval scope)))
12371 ((eq scope 'agenda)
12372 (setq scope (org-agenda-files t)))
12373 ((eq scope 'agenda-with-archives)
12374 (setq scope (org-agenda-files t))
12375 (setq scope (org-add-archive-files scope)))
12376 ((eq scope 'file)
12377 (setq scope (list (buffer-file-name))))
12378 ((eq scope 'file-with-archives)
12379 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12380 (org-prepare-agenda-buffers scope)
12381 (while (setq file (pop scope))
12382 (with-current-buffer (org-find-base-buffer-visiting file)
12383 (save-excursion
12384 (save-restriction
12385 (widen)
12386 (goto-char (point-min))
12387 (setq res (append res (org-scan-tags func matcher))))))))))
12388 res))
12390 ;;;; Properties
12392 ;;; Setting and retrieving properties
12394 (defconst org-special-properties
12395 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12396 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12397 "The special properties valid in Org-mode.
12399 These are properties that are not defined in the property drawer,
12400 but in some other way.")
12402 (defconst org-default-properties
12403 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12404 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12405 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12406 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12407 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12408 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12409 "Some properties that are used by Org-mode for various purposes.
12410 Being in this list makes sure that they are offered for completion.")
12412 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12413 "Regular expression matching the first line of a property drawer.")
12415 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12416 "Regular expression matching the first line of a property drawer.")
12418 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12419 "Regular expression matching the first line of a property drawer.")
12421 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12422 "Regular expression matching the first line of a property drawer.")
12424 (defconst org-property-drawer-re
12425 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12426 org-property-end-re "\\)\n?")
12427 "Matches an entire property drawer.")
12429 (defconst org-clock-drawer-re
12430 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12431 org-property-end-re "\\)\n?")
12432 "Matches an entire clock drawer.")
12434 (defun org-property-action ()
12435 "Do an action on properties."
12436 (interactive)
12437 (let (c)
12438 (org-at-property-p)
12439 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12440 (setq c (read-char-exclusive))
12441 (cond
12442 ((equal c ?s)
12443 (call-interactively 'org-set-property))
12444 ((equal c ?d)
12445 (call-interactively 'org-delete-property))
12446 ((equal c ?D)
12447 (call-interactively 'org-delete-property-globally))
12448 ((equal c ?c)
12449 (call-interactively 'org-compute-property-at-point))
12450 (t (error "No such property action %c" c)))))
12452 (defun org-set-effort (&optional value)
12453 "Set the effort property of the current entry.
12454 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12455 allowed value."
12456 (interactive "P")
12457 (if (equal value 0) (setq value 10))
12458 (let* ((completion-ignore-case t)
12459 (prop org-effort-property)
12460 (cur (org-entry-get nil prop))
12461 (allowed (org-property-get-allowed-values nil prop 'table))
12462 (existing (mapcar 'list (org-property-values prop)))
12464 (val (cond
12465 ((stringp value) value)
12466 ((and allowed (integerp value))
12467 (or (car (nth (1- value) allowed))
12468 (car (org-last allowed))))
12469 (allowed
12470 (message "Select 1-9,0, [RET%s]: %s"
12471 (if cur (concat "=" cur) "")
12472 (mapconcat 'car allowed " "))
12473 (setq rpl (read-char-exclusive))
12474 (if (equal rpl ?\r)
12476 (setq rpl (- rpl ?0))
12477 (if (equal rpl 0) (setq rpl 10))
12478 (if (and (> rpl 0) (<= rpl (length allowed)))
12479 (car (nth (1- rpl) allowed))
12480 (org-completing-read "Effort: " allowed nil))))
12482 (let (org-completion-use-ido org-completion-use-iswitchb)
12483 (org-completing-read
12484 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12485 (concat "[" cur "]") "")
12486 ": ")
12487 existing nil nil "" nil cur))))))
12488 (unless (equal (org-entry-get nil prop) val)
12489 (org-entry-put nil prop val))
12490 (message "%s is now %s" prop val)))
12492 (defun org-at-property-p ()
12493 "Is the cursor in a property line?"
12494 ;; FIXME: Does not check if we are actually in the drawer.
12495 ;; FIXME: also returns true on any drawers.....
12496 ;; This is used by C-c C-c for property action.
12497 (save-excursion
12498 (beginning-of-line 1)
12499 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12501 (defun org-get-property-block (&optional beg end force)
12502 "Return the (beg . end) range of the body of the property drawer.
12503 BEG and END can be beginning and end of subtree, if not given
12504 they will be found.
12505 If the drawer does not exist and FORCE is non-nil, create the drawer."
12506 (catch 'exit
12507 (save-excursion
12508 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12509 (end (or end (progn (outline-next-heading) (point)))))
12510 (goto-char beg)
12511 (if (re-search-forward org-property-start-re end t)
12512 (setq beg (1+ (match-end 0)))
12513 (if force
12514 (save-excursion
12515 (org-insert-property-drawer)
12516 (setq end (progn (outline-next-heading) (point))))
12517 (throw 'exit nil))
12518 (goto-char beg)
12519 (if (re-search-forward org-property-start-re end t)
12520 (setq beg (1+ (match-end 0)))))
12521 (if (re-search-forward org-property-end-re end t)
12522 (setq end (match-beginning 0))
12523 (or force (throw 'exit nil))
12524 (goto-char beg)
12525 (setq end beg)
12526 (org-indent-line-function)
12527 (insert ":END:\n"))
12528 (cons beg end)))))
12530 (defun org-entry-properties (&optional pom which specific)
12531 "Get all properties of the entry at point-or-marker POM.
12532 This includes the TODO keyword, the tags, time strings for deadline,
12533 scheduled, and clocking, and any additional properties defined in the
12534 entry. The return value is an alist, keys may occur multiple times
12535 if the property key was used several times.
12536 POM may also be nil, in which case the current entry is used.
12537 If WHICH is nil or `all', get all properties. If WHICH is
12538 `special' or `standard', only get that subclass. If WHICH
12539 is a string only get exactly this property. Specific can be a string, the
12540 specific property we are interested in. Specifying it can speed
12541 things up because then unnecessary parsing is avoided."
12542 (setq which (or which 'all))
12543 (org-with-point-at pom
12544 (let ((clockstr (substring org-clock-string 0 -1))
12545 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12546 (case-fold-search nil)
12547 beg end range props sum-props key value string clocksum)
12548 (save-excursion
12549 (when (condition-case nil
12550 (and (org-mode-p) (org-back-to-heading t))
12551 (error nil))
12552 (setq beg (point))
12553 (setq sum-props (get-text-property (point) 'org-summaries))
12554 (setq clocksum (get-text-property (point) :org-clock-minutes))
12555 (outline-next-heading)
12556 (setq end (point))
12557 (when (memq which '(all special))
12558 ;; Get the special properties, like TODO and tags
12559 (goto-char beg)
12560 (when (and (or (not specific) (string= specific "TODO"))
12561 (looking-at org-todo-line-regexp) (match-end 2))
12562 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12563 (when (and (or (not specific) (string= specific "PRIORITY"))
12564 (looking-at org-priority-regexp))
12565 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12566 (when (and (or (not specific) (string= specific "TAGS"))
12567 (setq value (org-get-tags-string))
12568 (string-match "\\S-" value))
12569 (push (cons "TAGS" value) props))
12570 (when (and (or (not specific) (string= specific "ALLTAGS"))
12571 (setq value (org-get-tags-at)))
12572 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12573 ":"))
12574 props))
12575 (when (or (not specific) (string= specific "BLOCKED"))
12576 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12577 (when (or (not specific)
12578 (member specific org-all-time-keywords)
12579 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12580 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12581 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12582 string (if (equal key clockstr)
12583 (org-no-properties
12584 (org-trim
12585 (buffer-substring
12586 (match-beginning 3) (goto-char (point-at-eol)))))
12587 (substring (org-match-string-no-properties 3) 1 -1)))
12588 (unless key
12589 (if (= (char-after (match-beginning 3)) ?\[)
12590 (setq key "TIMESTAMP_IA")
12591 (setq key "TIMESTAMP")))
12592 (when (or (equal key clockstr) (not (assoc key props)))
12593 (push (cons key string) props))))
12597 (when (memq which '(all standard))
12598 ;; Get the standard properties, like :PROP: ...
12599 (setq range (org-get-property-block beg end))
12600 (when range
12601 (goto-char (car range))
12602 (while (re-search-forward
12603 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12604 (cdr range) t)
12605 (setq key (org-match-string-no-properties 1)
12606 value (org-trim (or (org-match-string-no-properties 2) "")))
12607 (unless (member key excluded)
12608 (push (cons key (or value "")) props)))))
12609 (if clocksum
12610 (push (cons "CLOCKSUM"
12611 (org-columns-number-to-string (/ (float clocksum) 60.)
12612 'add_times))
12613 props))
12614 (unless (assoc "CATEGORY" props)
12615 (setq value (or (org-get-category)
12616 (progn (org-refresh-category-properties)
12617 (org-get-category))))
12618 (push (cons "CATEGORY" value) props))
12619 (append sum-props (nreverse props)))))))
12621 (defun org-entry-get (pom property &optional inherit)
12622 "Get value of PROPERTY for entry at point-or-marker POM.
12623 If INHERIT is non-nil and the entry does not have the property,
12624 then also check higher levels of the hierarchy.
12625 If INHERIT is the symbol `selective', use inheritance only if the setting
12626 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12627 If the property is present but empty, the return value is the empty string.
12628 If the property is not present at all, nil is returned."
12629 (org-with-point-at pom
12630 (if (and inherit (if (eq inherit 'selective)
12631 (org-property-inherit-p property)
12633 (org-entry-get-with-inheritance property)
12634 (if (member property org-special-properties)
12635 ;; We need a special property. Use `org-entry-properties' to
12636 ;; retrieve it, but specify the wanted property
12637 (cdr (assoc property (org-entry-properties nil 'special property)))
12638 (let ((range (org-get-property-block)))
12639 (if (and range
12640 (goto-char (car range))
12641 (re-search-forward
12642 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12643 (cdr range) t))
12644 ;; Found the property, return it.
12645 (if (match-end 1)
12646 (org-match-string-no-properties 1)
12647 "")))))))
12649 (defun org-property-or-variable-value (var &optional inherit)
12650 "Check if there is a property fixing the value of VAR.
12651 If yes, return this value. If not, return the current value of the variable."
12652 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12653 (if (and prop (stringp prop) (string-match "\\S-" prop))
12654 (read prop)
12655 (symbol-value var))))
12657 (defun org-entry-delete (pom property)
12658 "Delete the property PROPERTY from entry at point-or-marker POM."
12659 (org-with-point-at pom
12660 (if (member property org-special-properties)
12661 nil ; cannot delete these properties.
12662 (let ((range (org-get-property-block)))
12663 (if (and range
12664 (goto-char (car range))
12665 (re-search-forward
12666 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12667 (cdr range) t))
12668 (progn
12669 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12671 nil)))))
12673 ;; Multi-values properties are properties that contain multiple values
12674 ;; These values are assumed to be single words, separated by whitespace.
12675 (defun org-entry-add-to-multivalued-property (pom property value)
12676 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12677 (let* ((old (org-entry-get pom property))
12678 (values (and old (org-split-string old "[ \t]"))))
12679 (setq value (org-entry-protect-space value))
12680 (unless (member value values)
12681 (setq values (cons value values))
12682 (org-entry-put pom property
12683 (mapconcat 'identity values " ")))))
12685 (defun org-entry-remove-from-multivalued-property (pom property value)
12686 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12687 (let* ((old (org-entry-get pom property))
12688 (values (and old (org-split-string old "[ \t]"))))
12689 (setq value (org-entry-protect-space value))
12690 (when (member value values)
12691 (setq values (delete value values))
12692 (org-entry-put pom property
12693 (mapconcat 'identity values " ")))))
12695 (defun org-entry-member-in-multivalued-property (pom property value)
12696 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12697 (let* ((old (org-entry-get pom property))
12698 (values (and old (org-split-string old "[ \t]"))))
12699 (setq value (org-entry-protect-space value))
12700 (member value values)))
12702 (defun org-entry-get-multivalued-property (pom property)
12703 "Return a list of values in a multivalued property."
12704 (let* ((value (org-entry-get pom property))
12705 (values (and value (org-split-string value "[ \t]"))))
12706 (mapcar 'org-entry-restore-space values)))
12708 (defun org-entry-put-multivalued-property (pom property &rest values)
12709 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12710 VALUES should be a list of strings. Spaces will be protected."
12711 (org-entry-put pom property
12712 (mapconcat 'org-entry-protect-space values " "))
12713 (let* ((value (org-entry-get pom property))
12714 (values (and value (org-split-string value "[ \t]"))))
12715 (mapcar 'org-entry-restore-space values)))
12717 (defun org-entry-protect-space (s)
12718 "Protect spaces and newline in string S."
12719 (while (string-match " " s)
12720 (setq s (replace-match "%20" t t s)))
12721 (while (string-match "\n" s)
12722 (setq s (replace-match "%0A" t t s)))
12725 (defun org-entry-restore-space (s)
12726 "Restore spaces and newline in string S."
12727 (while (string-match "%20" s)
12728 (setq s (replace-match " " t t s)))
12729 (while (string-match "%0A" s)
12730 (setq s (replace-match "\n" t t s)))
12733 (defvar org-entry-property-inherited-from (make-marker)
12734 "Marker pointing to the entry from where a property was inherited.
12735 Each call to `org-entry-get-with-inheritance' will set this marker to the
12736 location of the entry where the inheritance search matched. If there was
12737 no match, the marker will point nowhere.
12738 Note that also `org-entry-get' calls this function, if the INHERIT flag
12739 is set.")
12741 (defun org-entry-get-with-inheritance (property)
12742 "Get entry property, and search higher levels if not present."
12743 (move-marker org-entry-property-inherited-from nil)
12744 (let (tmp)
12745 (save-excursion
12746 (save-restriction
12747 (widen)
12748 (catch 'ex
12749 (while t
12750 (when (setq tmp (org-entry-get nil property))
12751 (org-back-to-heading t)
12752 (move-marker org-entry-property-inherited-from (point))
12753 (throw 'ex tmp))
12754 (or (org-up-heading-safe) (throw 'ex nil)))))
12755 (or tmp
12756 (cdr (assoc property org-file-properties))
12757 (cdr (assoc property org-global-properties))
12758 (cdr (assoc property org-global-properties-fixed))))))
12760 (defvar org-property-changed-functions nil
12761 "Hook called when the value of a property has changed.
12762 Each hook function should accept two arguments, the name of the property
12763 and the new value.")
12765 (defun org-entry-put (pom property value)
12766 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12767 (org-with-point-at pom
12768 (org-back-to-heading t)
12769 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12770 range)
12771 (cond
12772 ((equal property "TODO")
12773 (when (and (stringp value) (string-match "\\S-" value)
12774 (not (member value org-todo-keywords-1)))
12775 (error "\"%s\" is not a valid TODO state" value))
12776 (if (or (not value)
12777 (not (string-match "\\S-" value)))
12778 (setq value 'none))
12779 (org-todo value)
12780 (org-set-tags nil 'align))
12781 ((equal property "PRIORITY")
12782 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12783 (string-to-char value) ?\ ))
12784 (org-set-tags nil 'align))
12785 ((equal property "SCHEDULED")
12786 (if (re-search-forward org-scheduled-time-regexp end t)
12787 (cond
12788 ((eq value 'earlier) (org-timestamp-change -1 'day))
12789 ((eq value 'later) (org-timestamp-change 1 'day))
12790 (t (call-interactively 'org-schedule)))
12791 (call-interactively 'org-schedule)))
12792 ((equal property "DEADLINE")
12793 (if (re-search-forward org-deadline-time-regexp end t)
12794 (cond
12795 ((eq value 'earlier) (org-timestamp-change -1 'day))
12796 ((eq value 'later) (org-timestamp-change 1 'day))
12797 (t (call-interactively 'org-deadline)))
12798 (call-interactively 'org-deadline)))
12799 ((member property org-special-properties)
12800 (error "The %s property can not yet be set with `org-entry-put'"
12801 property))
12802 (t ; a non-special property
12803 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12804 (setq range (org-get-property-block beg end 'force))
12805 (goto-char (car range))
12806 (if (re-search-forward
12807 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12808 (progn
12809 (delete-region (match-beginning 1) (match-end 1))
12810 (goto-char (match-beginning 1)))
12811 (goto-char (cdr range))
12812 (insert "\n")
12813 (backward-char 1)
12814 (org-indent-line-function)
12815 (insert ":" property ":"))
12816 (and value (insert " " value))
12817 (org-indent-line-function)))))
12818 (run-hook-with-args 'org-property-changed-functions property value)))
12820 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12821 "Get all property keys in the current buffer.
12822 With INCLUDE-SPECIALS, also list the special properties that reflect things
12823 like tags and TODO state.
12824 With INCLUDE-DEFAULTS, also include properties that has special meaning
12825 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12826 With INCLUDE-COLUMNS, also include property names given in COLUMN
12827 formats in the current buffer."
12828 (let (rtn range cfmt s p)
12829 (save-excursion
12830 (save-restriction
12831 (widen)
12832 (goto-char (point-min))
12833 (while (re-search-forward org-property-start-re nil t)
12834 (setq range (org-get-property-block))
12835 (goto-char (car range))
12836 (while (re-search-forward
12837 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12838 (cdr range) t)
12839 (add-to-list 'rtn (org-match-string-no-properties 1)))
12840 (outline-next-heading))))
12842 (when include-specials
12843 (setq rtn (append org-special-properties rtn)))
12845 (when include-defaults
12846 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12847 (add-to-list 'rtn org-effort-property))
12849 (when include-columns
12850 (save-excursion
12851 (save-restriction
12852 (widen)
12853 (goto-char (point-min))
12854 (while (re-search-forward
12855 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12856 nil t)
12857 (setq cfmt (match-string 2) s 0)
12858 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12859 cfmt s)
12860 (setq s (match-end 0)
12861 p (match-string 1 cfmt))
12862 (unless (or (equal p "ITEM")
12863 (member p org-special-properties))
12864 (add-to-list 'rtn (match-string 1 cfmt))))))))
12866 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12868 (defun org-property-values (key)
12869 "Return a list of all values of property KEY."
12870 (save-excursion
12871 (save-restriction
12872 (widen)
12873 (goto-char (point-min))
12874 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12875 values)
12876 (while (re-search-forward re nil t)
12877 (add-to-list 'values (org-trim (match-string 1))))
12878 (delete "" values)))))
12880 (defun org-insert-property-drawer ()
12881 "Insert a property drawer into the current entry."
12882 (interactive)
12883 (org-back-to-heading t)
12884 (looking-at outline-regexp)
12885 (let ((indent (if org-adapt-indentation
12886 (- (match-end 0)(match-beginning 0))
12888 (beg (point))
12889 (re (concat "^[ \t]*" org-keyword-time-regexp))
12890 end hiddenp)
12891 (outline-next-heading)
12892 (setq end (point))
12893 (goto-char beg)
12894 (while (re-search-forward re end t))
12895 (setq hiddenp (org-invisible-p))
12896 (end-of-line 1)
12897 (and (equal (char-after) ?\n) (forward-char 1))
12898 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12899 (if (member (match-string 1) '("CLOCK:" ":END:"))
12900 ;; just skip this line
12901 (beginning-of-line 2)
12902 ;; Drawer start, find the end
12903 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12904 (beginning-of-line 1)))
12905 (org-skip-over-state-notes)
12906 (skip-chars-backward " \t\n\r")
12907 (if (eq (char-before) ?*) (forward-char 1))
12908 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12909 (beginning-of-line 0)
12910 (org-indent-to-column indent)
12911 (beginning-of-line 2)
12912 (org-indent-to-column indent)
12913 (beginning-of-line 0)
12914 (if hiddenp
12915 (save-excursion
12916 (org-back-to-heading t)
12917 (hide-entry))
12918 (org-flag-drawer t))))
12920 (defun org-set-property (property value)
12921 "In the current entry, set PROPERTY to VALUE.
12922 When called interactively, this will prompt for a property name, offering
12923 completion on existing and default properties. And then it will prompt
12924 for a value, offering completion either on allowed values (via an inherited
12925 xxx_ALL property) or on existing values in other instances of this property
12926 in the current file."
12927 (interactive
12928 (let* ((completion-ignore-case t)
12929 (keys (org-buffer-property-keys nil t t))
12930 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12931 (prop (if (member prop0 keys)
12932 prop0
12933 (or (cdr (assoc (downcase prop0)
12934 (mapcar (lambda (x) (cons (downcase x) x))
12935 keys)))
12936 prop0)))
12937 (cur (org-entry-get nil prop))
12938 (allowed (org-property-get-allowed-values nil prop 'table))
12939 (existing (mapcar 'list (org-property-values prop)))
12940 (val (if allowed
12941 (org-completing-read "Value: " allowed nil
12942 (not (get-text-property 0 'org-unrestricted
12943 (caar allowed))))
12944 (let (org-completion-use-ido org-completion-use-iswitchb)
12945 (org-completing-read
12946 (concat "Value " (if (and cur (string-match "\\S-" cur))
12947 (concat "[" cur "]") "")
12948 ": ")
12949 existing nil nil "" nil cur)))))
12950 (list prop (if (equal val "") cur val))))
12951 (unless (equal (org-entry-get nil property) value)
12952 (org-entry-put nil property value)))
12954 (defun org-delete-property (property)
12955 "In the current entry, delete PROPERTY."
12956 (interactive
12957 (let* ((completion-ignore-case t)
12958 (prop (org-icompleting-read
12959 "Property: " (org-entry-properties nil 'standard))))
12960 (list prop)))
12961 (message "Property %s %s" property
12962 (if (org-entry-delete nil property)
12963 "deleted"
12964 "was not present in the entry")))
12966 (defun org-delete-property-globally (property)
12967 "Remove PROPERTY globally, from all entries."
12968 (interactive
12969 (let* ((completion-ignore-case t)
12970 (prop (org-icompleting-read
12971 "Globally remove property: "
12972 (mapcar 'list (org-buffer-property-keys)))))
12973 (list prop)))
12974 (save-excursion
12975 (save-restriction
12976 (widen)
12977 (goto-char (point-min))
12978 (let ((cnt 0))
12979 (while (re-search-forward
12980 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12981 nil t)
12982 (setq cnt (1+ cnt))
12983 (replace-match ""))
12984 (message "Property \"%s\" removed from %d entries" property cnt)))))
12986 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12988 (defun org-compute-property-at-point ()
12989 "Compute the property at point.
12990 This looks for an enclosing column format, extracts the operator and
12991 then applies it to the property in the column format's scope."
12992 (interactive)
12993 (unless (org-at-property-p)
12994 (error "Not at a property"))
12995 (let ((prop (org-match-string-no-properties 2)))
12996 (org-columns-get-format-and-top-level)
12997 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12998 (error "No operator defined for property %s" prop))
12999 (org-columns-compute prop)))
13001 (defvar org-property-allowed-value-functions nil
13002 "Hook for functions supplying allowed values for a specific property.
13003 The functions must take a single argument, the name of the property, and
13004 return a flat list of allowed values. If \":ETC\" is one of
13005 the values, this means that these values are intended as defaults for
13006 completion, but that other values should be allowed too.
13007 The functions must return nil if they are not responsible for this
13008 property.")
13010 (defun org-property-get-allowed-values (pom property &optional table)
13011 "Get allowed values for the property PROPERTY.
13012 When TABLE is non-nil, return an alist that can directly be used for
13013 completion."
13014 (let (vals)
13015 (cond
13016 ((equal property "TODO")
13017 (setq vals (org-with-point-at pom
13018 (append org-todo-keywords-1 '("")))))
13019 ((equal property "PRIORITY")
13020 (let ((n org-lowest-priority))
13021 (while (>= n org-highest-priority)
13022 (push (char-to-string n) vals)
13023 (setq n (1- n)))))
13024 ((member property org-special-properties))
13025 ((setq vals (run-hook-with-args-until-success
13026 'org-property-allowed-value-functions property)))
13028 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13029 (when (and vals (string-match "\\S-" vals))
13030 (setq vals (car (read-from-string (concat "(" vals ")"))))
13031 (setq vals (mapcar (lambda (x)
13032 (cond ((stringp x) x)
13033 ((numberp x) (number-to-string x))
13034 ((symbolp x) (symbol-name x))
13035 (t "???")))
13036 vals)))))
13037 (when (member ":ETC" vals)
13038 (setq vals (remove ":ETC" vals))
13039 (org-add-props (car vals) '(org-unrestricted t)))
13040 (if table (mapcar 'list vals) vals)))
13042 (defun org-property-previous-allowed-value (&optional previous)
13043 "Switch to the next allowed value for this property."
13044 (interactive)
13045 (org-property-next-allowed-value t))
13047 (defun org-property-next-allowed-value (&optional previous)
13048 "Switch to the next allowed value for this property."
13049 (interactive)
13050 (unless (org-at-property-p)
13051 (error "Not at a property"))
13052 (let* ((key (match-string 2))
13053 (value (match-string 3))
13054 (allowed (or (org-property-get-allowed-values (point) key)
13055 (and (member value '("[ ]" "[-]" "[X]"))
13056 '("[ ]" "[X]"))))
13057 nval)
13058 (unless allowed
13059 (error "Allowed values for this property have not been defined"))
13060 (if previous (setq allowed (reverse allowed)))
13061 (if (member value allowed)
13062 (setq nval (car (cdr (member value allowed)))))
13063 (setq nval (or nval (car allowed)))
13064 (if (equal nval value)
13065 (error "Only one allowed value for this property"))
13066 (org-at-property-p)
13067 (replace-match (concat " :" key ": " nval) t t)
13068 (org-indent-line-function)
13069 (beginning-of-line 1)
13070 (skip-chars-forward " \t")
13071 (run-hook-with-args 'org-property-changed-functions key nval)))
13073 (defun org-find-entry-with-id (ident)
13074 "Locate the entry that contains the ID property with exact value IDENT.
13075 IDENT can be a string, a symbol or a number, this function will search for
13076 the string representation of it.
13077 Return the position where this entry starts, or nil if there is no such entry."
13078 (interactive "sID: ")
13079 (let ((id (cond
13080 ((stringp ident) ident)
13081 ((symbol-name ident) (symbol-name ident))
13082 ((numberp ident) (number-to-string ident))
13083 (t (error "IDENT %s must be a string, symbol or number" ident))))
13084 (case-fold-search nil))
13085 (save-excursion
13086 (save-restriction
13087 (widen)
13088 (goto-char (point-min))
13089 (when (re-search-forward
13090 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13091 nil t)
13092 (org-back-to-heading t)
13093 (point))))))
13095 ;;;; Timestamps
13097 (defvar org-last-changed-timestamp nil)
13098 (defvar org-last-inserted-timestamp nil
13099 "The last time stamp inserted with `org-insert-time-stamp'.")
13100 (defvar org-time-was-given) ; dynamically scoped parameter
13101 (defvar org-end-time-was-given) ; dynamically scoped parameter
13102 (defvar org-ts-what) ; dynamically scoped parameter
13104 (defun org-time-stamp (arg &optional inactive)
13105 "Prompt for a date/time and insert a time stamp.
13106 If the user specifies a time like HH:MM, or if this command is called
13107 with a prefix argument, the time stamp will contain date and time.
13108 Otherwise, only the date will be included. All parts of a date not
13109 specified by the user will be filled in from the current date/time.
13110 So if you press just return without typing anything, the time stamp
13111 will represent the current date/time. If there is already a timestamp
13112 at the cursor, it will be modified."
13113 (interactive "P")
13114 (let* ((ts nil)
13115 (default-time
13116 ;; Default time is either today, or, when entering a range,
13117 ;; the range start.
13118 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13119 (save-excursion
13120 (re-search-backward
13121 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13122 (- (point) 20) t)))
13123 (apply 'encode-time (org-parse-time-string (match-string 1)))
13124 (current-time)))
13125 (default-input (and ts (org-get-compact-tod ts)))
13126 org-time-was-given org-end-time-was-given time)
13127 (cond
13128 ((and (org-at-timestamp-p t)
13129 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13130 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13131 (insert "--")
13132 (setq time (let ((this-command this-command))
13133 (org-read-date arg 'totime nil nil
13134 default-time default-input)))
13135 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13136 ((org-at-timestamp-p t)
13137 (setq time (let ((this-command this-command))
13138 (org-read-date arg 'totime nil nil default-time default-input)))
13139 (when (org-at-timestamp-p t) ; just to get the match data
13140 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13141 (replace-match "")
13142 (setq org-last-changed-timestamp
13143 (org-insert-time-stamp
13144 time (or org-time-was-given arg)
13145 inactive nil nil (list org-end-time-was-given))))
13146 (message "Timestamp updated"))
13148 (setq time (let ((this-command this-command))
13149 (org-read-date arg 'totime nil nil default-time default-input)))
13150 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13151 nil nil (list org-end-time-was-given))))))
13153 ;; FIXME: can we use this for something else, like computing time differences?
13154 (defun org-get-compact-tod (s)
13155 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13156 (let* ((t1 (match-string 1 s))
13157 (h1 (string-to-number (match-string 2 s)))
13158 (m1 (string-to-number (match-string 3 s)))
13159 (t2 (and (match-end 4) (match-string 5 s)))
13160 (h2 (and t2 (string-to-number (match-string 6 s))))
13161 (m2 (and t2 (string-to-number (match-string 7 s))))
13162 dh dm)
13163 (if (not t2)
13165 (setq dh (- h2 h1) dm (- m2 m1))
13166 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13167 (concat t1 "+" (number-to-string dh)
13168 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13170 (defun org-time-stamp-inactive (&optional arg)
13171 "Insert an inactive time stamp.
13172 An inactive time stamp is enclosed in square brackets instead of angle
13173 brackets. It is inactive in the sense that it does not trigger agenda entries,
13174 does not link to the calendar and cannot be changed with the S-cursor keys.
13175 So these are more for recording a certain time/date."
13176 (interactive "P")
13177 (org-time-stamp arg 'inactive))
13179 (defvar org-date-ovl (org-make-overlay 1 1))
13180 (org-overlay-put org-date-ovl 'face 'org-warning)
13181 (org-detach-overlay org-date-ovl)
13183 (defvar org-ans1) ; dynamically scoped parameter
13184 (defvar org-ans2) ; dynamically scoped parameter
13186 (defvar org-plain-time-of-day-regexp) ; defined below
13188 (defvar org-overriding-default-time nil) ; dynamically scoped
13189 (defvar org-read-date-overlay nil)
13190 (defvar org-dcst nil) ; dynamically scoped
13191 (defvar org-read-date-history nil)
13192 (defvar org-read-date-final-answer nil)
13194 (defun org-read-date (&optional with-time to-time from-string prompt
13195 default-time default-input)
13196 "Read a date, possibly a time, and make things smooth for the user.
13197 The prompt will suggest to enter an ISO date, but you can also enter anything
13198 which will at least partially be understood by `parse-time-string'.
13199 Unrecognized parts of the date will default to the current day, month, year,
13200 hour and minute. If this command is called to replace a timestamp at point,
13201 of to enter the second timestamp of a range, the default time is taken from the
13202 existing stamp. For example,
13203 3-2-5 --> 2003-02-05
13204 feb 15 --> currentyear-02-15
13205 sep 12 9 --> 2009-09-12
13206 12:45 --> today 12:45
13207 22 sept 0:34 --> currentyear-09-22 0:34
13208 12 --> currentyear-currentmonth-12
13209 Fri --> nearest Friday (today or later)
13210 etc.
13212 Furthermore you can specify a relative date by giving, as the *first* thing
13213 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13214 change in days weeks, months, years.
13215 With a single plus or minus, the date is relative to today. With a double
13216 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13217 +4d --> four days from today
13218 +4 --> same as above
13219 +2w --> two weeks from today
13220 ++5 --> five days from default date
13222 The function understands only English month and weekday abbreviations,
13223 but this can be configured with the variables `parse-time-months' and
13224 `parse-time-weekdays'.
13226 While prompting, a calendar is popped up - you can also select the
13227 date with the mouse (button 1). The calendar shows a period of three
13228 months. To scroll it to other months, use the keys `>' and `<'.
13229 If you don't like the calendar, turn it off with
13230 \(setq org-read-date-popup-calendar nil)
13232 With optional argument TO-TIME, the date will immediately be converted
13233 to an internal time.
13234 With an optional argument WITH-TIME, the prompt will suggest to also
13235 insert a time. Note that when WITH-TIME is not set, you can still
13236 enter a time, and this function will inform the calling routine about
13237 this change. The calling routine may then choose to change the format
13238 used to insert the time stamp into the buffer to include the time.
13239 With optional argument FROM-STRING, read from this string instead from
13240 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13241 the time/date that is used for everything that is not specified by the
13242 user."
13243 (require 'parse-time)
13244 (let* ((org-time-stamp-rounding-minutes
13245 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13246 (org-dcst org-display-custom-times)
13247 (ct (org-current-time))
13248 (def (or org-overriding-default-time default-time ct))
13249 (defdecode (decode-time def))
13250 (dummy (progn
13251 (when (< (nth 2 defdecode) org-extend-today-until)
13252 (setcar (nthcdr 2 defdecode) -1)
13253 (setcar (nthcdr 1 defdecode) 59)
13254 (setq def (apply 'encode-time defdecode)
13255 defdecode (decode-time def)))))
13256 (calendar-frame-setup nil)
13257 (calendar-move-hook nil)
13258 (calendar-view-diary-initially-flag nil)
13259 (view-diary-entries-initially nil)
13260 (calendar-view-holidays-initially-flag nil)
13261 (view-calendar-holidays-initially nil)
13262 (timestr (format-time-string
13263 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13264 (prompt (concat (if prompt (concat prompt " ") "")
13265 (format "Date+time [%s]: " timestr)))
13266 ans (org-ans0 "") org-ans1 org-ans2 final)
13268 (cond
13269 (from-string (setq ans from-string))
13270 (org-read-date-popup-calendar
13271 (save-excursion
13272 (save-window-excursion
13273 (calendar)
13274 (calendar-forward-day (- (time-to-days def)
13275 (calendar-absolute-from-gregorian
13276 (calendar-current-date))))
13277 (org-eval-in-calendar nil t)
13278 (let* ((old-map (current-local-map))
13279 (map (copy-keymap calendar-mode-map))
13280 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13281 (org-defkey map (kbd "RET") 'org-calendar-select)
13282 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13283 'org-calendar-select-mouse)
13284 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13285 'org-calendar-select-mouse)
13286 (org-defkey minibuffer-local-map [(meta shift left)]
13287 (lambda () (interactive)
13288 (org-eval-in-calendar '(calendar-backward-month 1))))
13289 (org-defkey minibuffer-local-map [(meta shift right)]
13290 (lambda () (interactive)
13291 (org-eval-in-calendar '(calendar-forward-month 1))))
13292 (org-defkey minibuffer-local-map [(meta shift up)]
13293 (lambda () (interactive)
13294 (org-eval-in-calendar '(calendar-backward-year 1))))
13295 (org-defkey minibuffer-local-map [(meta shift down)]
13296 (lambda () (interactive)
13297 (org-eval-in-calendar '(calendar-forward-year 1))))
13298 (org-defkey minibuffer-local-map [?\e (shift left)]
13299 (lambda () (interactive)
13300 (org-eval-in-calendar '(calendar-backward-month 1))))
13301 (org-defkey minibuffer-local-map [?\e (shift right)]
13302 (lambda () (interactive)
13303 (org-eval-in-calendar '(calendar-forward-month 1))))
13304 (org-defkey minibuffer-local-map [?\e (shift up)]
13305 (lambda () (interactive)
13306 (org-eval-in-calendar '(calendar-backward-year 1))))
13307 (org-defkey minibuffer-local-map [?\e (shift down)]
13308 (lambda () (interactive)
13309 (org-eval-in-calendar '(calendar-forward-year 1))))
13310 (org-defkey minibuffer-local-map [(shift up)]
13311 (lambda () (interactive)
13312 (org-eval-in-calendar '(calendar-backward-week 1))))
13313 (org-defkey minibuffer-local-map [(shift down)]
13314 (lambda () (interactive)
13315 (org-eval-in-calendar '(calendar-forward-week 1))))
13316 (org-defkey minibuffer-local-map [(shift left)]
13317 (lambda () (interactive)
13318 (org-eval-in-calendar '(calendar-backward-day 1))))
13319 (org-defkey minibuffer-local-map [(shift right)]
13320 (lambda () (interactive)
13321 (org-eval-in-calendar '(calendar-forward-day 1))))
13322 (org-defkey minibuffer-local-map ">"
13323 (lambda () (interactive)
13324 (org-eval-in-calendar '(scroll-calendar-left 1))))
13325 (org-defkey minibuffer-local-map "<"
13326 (lambda () (interactive)
13327 (org-eval-in-calendar '(scroll-calendar-right 1))))
13328 (run-hooks 'org-read-date-minibuffer-setup-hook)
13329 (unwind-protect
13330 (progn
13331 (use-local-map map)
13332 (add-hook 'post-command-hook 'org-read-date-display)
13333 (setq org-ans0 (read-string prompt default-input
13334 'org-read-date-history nil))
13335 ;; org-ans0: from prompt
13336 ;; org-ans1: from mouse click
13337 ;; org-ans2: from calendar motion
13338 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13339 (remove-hook 'post-command-hook 'org-read-date-display)
13340 (use-local-map old-map)
13341 (when org-read-date-overlay
13342 (org-delete-overlay org-read-date-overlay)
13343 (setq org-read-date-overlay nil)))))))
13345 (t ; Naked prompt only
13346 (unwind-protect
13347 (setq ans (read-string prompt default-input
13348 'org-read-date-history timestr))
13349 (when org-read-date-overlay
13350 (org-delete-overlay org-read-date-overlay)
13351 (setq org-read-date-overlay nil)))))
13353 (setq final (org-read-date-analyze ans def defdecode))
13354 (setq org-read-date-final-answer ans)
13356 (if to-time
13357 (apply 'encode-time final)
13358 (if (and (boundp 'org-time-was-given) org-time-was-given)
13359 (format "%04d-%02d-%02d %02d:%02d"
13360 (nth 5 final) (nth 4 final) (nth 3 final)
13361 (nth 2 final) (nth 1 final))
13362 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13364 (defvar def)
13365 (defvar defdecode)
13366 (defvar with-time)
13367 (defvar org-read-date-analyze-futurep nil)
13368 (defun org-read-date-display ()
13369 "Display the current date prompt interpretation in the minibuffer."
13370 (when org-read-date-display-live
13371 (when org-read-date-overlay
13372 (org-delete-overlay org-read-date-overlay))
13373 (let ((p (point)))
13374 (end-of-line 1)
13375 (while (not (equal (buffer-substring
13376 (max (point-min) (- (point) 4)) (point))
13377 " "))
13378 (insert " "))
13379 (goto-char p))
13380 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13381 " " (or org-ans1 org-ans2)))
13382 (org-end-time-was-given nil)
13383 (f (org-read-date-analyze ans def defdecode))
13384 (fmts (if org-dcst
13385 org-time-stamp-custom-formats
13386 org-time-stamp-formats))
13387 (fmt (if (or with-time
13388 (and (boundp 'org-time-was-given) org-time-was-given))
13389 (cdr fmts)
13390 (car fmts)))
13391 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13392 (when (and org-end-time-was-given
13393 (string-match org-plain-time-of-day-regexp txt))
13394 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13395 org-end-time-was-given
13396 (substring txt (match-end 0)))))
13397 (when org-read-date-analyze-futurep
13398 (setq txt (concat txt " (=>F)")))
13399 (setq org-read-date-overlay
13400 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13401 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13403 (defun org-read-date-analyze (ans def defdecode)
13404 "Analyse the combined answer of the date prompt."
13405 ;; FIXME: cleanup and comment
13406 (let ((nowdecode (decode-time (current-time)))
13407 delta deltan deltaw deltadef year month day
13408 hour minute second wday pm h2 m2 tl wday1
13409 iso-year iso-weekday iso-week iso-year iso-date futurep)
13410 (setq org-read-date-analyze-futurep nil)
13411 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13412 (setq ans "+0"))
13414 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13415 (setq ans (replace-match "" t t ans)
13416 deltan (car delta)
13417 deltaw (nth 1 delta)
13418 deltadef (nth 2 delta)))
13420 ;; Check if there is an iso week date in there
13421 ;; If yes, store the info and postpone interpreting it until the rest
13422 ;; of the parsing is done
13423 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13424 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13425 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13426 iso-week (string-to-number (match-string 2 ans)))
13427 (setq ans (replace-match "" t t ans)))
13429 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13430 (when (string-match
13431 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13432 (setq year (if (match-end 2)
13433 (string-to-number (match-string 2 ans))
13434 (string-to-number (format-time-string "%Y")))
13435 month (string-to-number (match-string 3 ans))
13436 day (string-to-number (match-string 4 ans)))
13437 (if (< year 100) (setq year (+ 2000 year)))
13438 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13439 t nil ans)))
13440 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13441 ;; If there is a time with am/pm, and *no* time without it, we convert
13442 ;; so that matching will be successful.
13443 (loop for i from 1 to 2 do ; twice, for end time as well
13444 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13445 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13446 (setq hour (string-to-number (match-string 1 ans))
13447 minute (if (match-end 3)
13448 (string-to-number (match-string 3 ans))
13450 pm (equal ?p
13451 (string-to-char (downcase (match-string 4 ans)))))
13452 (if (and (= hour 12) (not pm))
13453 (setq hour 0)
13454 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13455 (setq ans (replace-match (format "%02d:%02d" hour minute)
13456 t t ans))))
13458 ;; Check if a time range is given as a duration
13459 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13460 (setq hour (string-to-number (match-string 1 ans))
13461 h2 (+ hour (string-to-number (match-string 3 ans)))
13462 minute (string-to-number (match-string 2 ans))
13463 m2 (+ minute (if (match-end 5) (string-to-number
13464 (match-string 5 ans))0)))
13465 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13466 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13467 t t ans)))
13469 ;; Check if there is a time range
13470 (when (boundp 'org-end-time-was-given)
13471 (setq org-time-was-given nil)
13472 (when (and (string-match org-plain-time-of-day-regexp ans)
13473 (match-end 8))
13474 (setq org-end-time-was-given (match-string 8 ans))
13475 (setq ans (concat (substring ans 0 (match-beginning 7))
13476 (substring ans (match-end 7))))))
13478 (setq tl (parse-time-string ans)
13479 day (or (nth 3 tl) (nth 3 defdecode))
13480 month (or (nth 4 tl)
13481 (if (and org-read-date-prefer-future
13482 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13483 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13484 (nth 4 defdecode)))
13485 year (or (nth 5 tl)
13486 (if (and org-read-date-prefer-future
13487 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13488 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13489 (nth 5 defdecode)))
13490 hour (or (nth 2 tl) (nth 2 defdecode))
13491 minute (or (nth 1 tl) (nth 1 defdecode))
13492 second (or (nth 0 tl) 0)
13493 wday (nth 6 tl))
13495 (when (and (eq org-read-date-prefer-future 'time)
13496 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13497 (equal day (nth 3 nowdecode))
13498 (equal month (nth 4 nowdecode))
13499 (equal year (nth 5 nowdecode))
13500 (nth 2 tl)
13501 (or (< (nth 2 tl) (nth 2 nowdecode))
13502 (and (= (nth 2 tl) (nth 2 nowdecode))
13503 (nth 1 tl)
13504 (< (nth 1 tl) (nth 1 nowdecode)))))
13505 (setq day (1+ day)
13506 futurep t))
13508 ;; Special date definitions below
13509 (cond
13510 (iso-week
13511 ;; There was an iso week
13512 (setq futurep nil)
13513 (setq year (or iso-year year)
13514 day (or iso-weekday wday 1)
13515 wday nil ; to make sure that the trigger below does not match
13516 iso-date (calendar-gregorian-from-absolute
13517 (calendar-absolute-from-iso
13518 (list iso-week day year))))
13519 ; FIXME: Should we also push ISO weeks into the future?
13520 ; (when (and org-read-date-prefer-future
13521 ; (not iso-year)
13522 ; (< (calendar-absolute-from-gregorian iso-date)
13523 ; (time-to-days (current-time))))
13524 ; (setq year (1+ year)
13525 ; iso-date (calendar-gregorian-from-absolute
13526 ; (calendar-absolute-from-iso
13527 ; (list iso-week day year)))))
13528 (setq month (car iso-date)
13529 year (nth 2 iso-date)
13530 day (nth 1 iso-date)))
13531 (deltan
13532 (setq futurep nil)
13533 (unless deltadef
13534 (let ((now (decode-time (current-time))))
13535 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13536 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13537 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13538 ((equal deltaw "m") (setq month (+ month deltan)))
13539 ((equal deltaw "y") (setq year (+ year deltan)))))
13540 ((and wday (not (nth 3 tl)))
13541 (setq futurep nil)
13542 ;; Weekday was given, but no day, so pick that day in the week
13543 ;; on or after the derived date.
13544 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13545 (unless (equal wday wday1)
13546 (setq day (+ day (% (- wday wday1 -7) 7))))))
13547 (if (and (boundp 'org-time-was-given)
13548 (nth 2 tl))
13549 (setq org-time-was-given t))
13550 (if (< year 100) (setq year (+ 2000 year)))
13551 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13552 (setq org-read-date-analyze-futurep futurep)
13553 (list second minute hour day month year)))
13555 (defvar parse-time-weekdays)
13557 (defun org-read-date-get-relative (s today default)
13558 "Check string S for special relative date string.
13559 TODAY and DEFAULT are internal times, for today and for a default.
13560 Return shift list (N what def-flag)
13561 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13562 N is the number of WHATs to shift.
13563 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13564 the DEFAULT date rather than TODAY."
13565 (when (and
13566 (string-match
13567 (concat
13568 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13569 "\\([0-9]+\\)?"
13570 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13571 "\\([ \t]\\|$\\)") s)
13572 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13573 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13574 (string-to-char (substring (match-string 1 s) -1))
13575 ?+))
13576 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13577 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13578 (what (if (match-end 3) (match-string 3 s) "d"))
13579 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13580 (date (if rel default today))
13581 (wday (nth 6 (decode-time date)))
13582 delta)
13583 (if wday1
13584 (progn
13585 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13586 (if (= dir ?-) (setq delta (- delta 7)))
13587 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13588 (list delta "d" rel))
13589 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13591 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13592 "Turn a user-specified date into the internal representation.
13593 The internal representation needed by the calendar is (month day year).
13594 This is a wrapper to handle the brain-dead convention in calendar that
13595 user function argument order change dependent on argument order."
13596 (if (boundp 'calendar-date-style)
13597 (cond
13598 ((eq calendar-date-style 'american)
13599 (list arg1 arg2 arg3))
13600 ((eq calendar-date-style 'european)
13601 (list arg2 arg1 arg3))
13602 ((eq calendar-date-style 'iso)
13603 (list arg2 arg3 arg1)))
13604 (if (org-bound-and-true-p european-calendar-style)
13605 (list arg2 arg1 arg3)
13606 (list arg1 arg2 arg3))))
13608 (defun org-eval-in-calendar (form &optional keepdate)
13609 "Eval FORM in the calendar window and return to current window.
13610 Also, store the cursor date in variable org-ans2."
13611 (let ((sf (selected-frame))
13612 (sw (selected-window)))
13613 (select-window (get-buffer-window "*Calendar*" t))
13614 (eval form)
13615 (when (and (not keepdate) (calendar-cursor-to-date))
13616 (let* ((date (calendar-cursor-to-date))
13617 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13618 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13619 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13620 (select-window sw)
13621 (org-select-frame-set-input-focus sf)))
13623 (defun org-calendar-select ()
13624 "Return to `org-read-date' with the date currently selected.
13625 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13626 (interactive)
13627 (when (calendar-cursor-to-date)
13628 (let* ((date (calendar-cursor-to-date))
13629 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13630 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13631 (if (active-minibuffer-window) (exit-minibuffer))))
13633 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13634 "Insert a date stamp for the date given by the internal TIME.
13635 WITH-HM means use the stamp format that includes the time of the day.
13636 INACTIVE means use square brackets instead of angular ones, so that the
13637 stamp will not contribute to the agenda.
13638 PRE and POST are optional strings to be inserted before and after the
13639 stamp.
13640 The command returns the inserted time stamp."
13641 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13642 stamp)
13643 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13644 (insert-before-markers (or pre ""))
13645 (insert-before-markers (setq stamp (format-time-string fmt time)))
13646 (when (listp extra)
13647 (setq extra (car extra))
13648 (if (and (stringp extra)
13649 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13650 (setq extra (format "-%02d:%02d"
13651 (string-to-number (match-string 1 extra))
13652 (string-to-number (match-string 2 extra))))
13653 (setq extra nil)))
13654 (when extra
13655 (backward-char 1)
13656 (insert-before-markers extra)
13657 (forward-char 1))
13658 (insert-before-markers (or post ""))
13659 (setq org-last-inserted-timestamp stamp)))
13661 (defun org-toggle-time-stamp-overlays ()
13662 "Toggle the use of custom time stamp formats."
13663 (interactive)
13664 (setq org-display-custom-times (not org-display-custom-times))
13665 (unless org-display-custom-times
13666 (let ((p (point-min)) (bmp (buffer-modified-p)))
13667 (while (setq p (next-single-property-change p 'display))
13668 (if (and (get-text-property p 'display)
13669 (eq (get-text-property p 'face) 'org-date))
13670 (remove-text-properties
13671 p (setq p (next-single-property-change p 'display))
13672 '(display t))))
13673 (set-buffer-modified-p bmp)))
13674 (if (featurep 'xemacs)
13675 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13676 (org-restart-font-lock)
13677 (setq org-table-may-need-update t)
13678 (if org-display-custom-times
13679 (message "Time stamps are overlayed with custom format")
13680 (message "Time stamp overlays removed")))
13682 (defun org-display-custom-time (beg end)
13683 "Overlay modified time stamp format over timestamp between BEG and END."
13684 (let* ((ts (buffer-substring beg end))
13685 t1 w1 with-hm tf time str w2 (off 0))
13686 (save-match-data
13687 (setq t1 (org-parse-time-string ts t))
13688 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13689 (setq off (- (match-end 0) (match-beginning 0)))))
13690 (setq end (- end off))
13691 (setq w1 (- end beg)
13692 with-hm (and (nth 1 t1) (nth 2 t1))
13693 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13694 time (org-fix-decoded-time t1)
13695 str (org-add-props
13696 (format-time-string
13697 (substring tf 1 -1) (apply 'encode-time time))
13698 nil 'mouse-face 'highlight)
13699 w2 (length str))
13700 (if (not (= w2 w1))
13701 (add-text-properties (1+ beg) (+ 2 beg)
13702 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13703 (if (featurep 'xemacs)
13704 (progn
13705 (put-text-property beg end 'invisible t)
13706 (put-text-property beg end 'end-glyph (make-glyph str)))
13707 (put-text-property beg end 'display str))))
13709 (defun org-translate-time (string)
13710 "Translate all timestamps in STRING to custom format.
13711 But do this only if the variable `org-display-custom-times' is set."
13712 (when org-display-custom-times
13713 (save-match-data
13714 (let* ((start 0)
13715 (re org-ts-regexp-both)
13716 t1 with-hm inactive tf time str beg end)
13717 (while (setq start (string-match re string start))
13718 (setq beg (match-beginning 0)
13719 end (match-end 0)
13720 t1 (save-match-data
13721 (org-parse-time-string (substring string beg end) t))
13722 with-hm (and (nth 1 t1) (nth 2 t1))
13723 inactive (equal (substring string beg (1+ beg)) "[")
13724 tf (funcall (if with-hm 'cdr 'car)
13725 org-time-stamp-custom-formats)
13726 time (org-fix-decoded-time t1)
13727 str (format-time-string
13728 (concat
13729 (if inactive "[" "<") (substring tf 1 -1)
13730 (if inactive "]" ">"))
13731 (apply 'encode-time time))
13732 string (replace-match str t t string)
13733 start (+ start (length str)))))))
13734 string)
13736 (defun org-fix-decoded-time (time)
13737 "Set 0 instead of nil for the first 6 elements of time.
13738 Don't touch the rest."
13739 (let ((n 0))
13740 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13742 (defun org-days-to-time (timestamp-string)
13743 "Difference between TIMESTAMP-STRING and now in days."
13744 (- (time-to-days (org-time-string-to-time timestamp-string))
13745 (time-to-days (current-time))))
13747 (defun org-deadline-close (timestamp-string &optional ndays)
13748 "Is the time in TIMESTAMP-STRING close to the current date?"
13749 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13750 (and (< (org-days-to-time timestamp-string) ndays)
13751 (not (org-entry-is-done-p))))
13753 (defun org-get-wdays (ts)
13754 "Get the deadline lead time appropriate for timestring TS."
13755 (cond
13756 ((<= org-deadline-warning-days 0)
13757 ;; 0 or negative, enforce this value no matter what
13758 (- org-deadline-warning-days))
13759 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13760 ;; lead time is specified.
13761 (floor (* (string-to-number (match-string 1 ts))
13762 (cdr (assoc (match-string 2 ts)
13763 '(("d" . 1) ("w" . 7)
13764 ("m" . 30.4) ("y" . 365.25)))))))
13765 ;; go for the default.
13766 (t org-deadline-warning-days)))
13768 (defun org-calendar-select-mouse (ev)
13769 "Return to `org-read-date' with the date currently selected.
13770 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13771 (interactive "e")
13772 (mouse-set-point ev)
13773 (when (calendar-cursor-to-date)
13774 (let* ((date (calendar-cursor-to-date))
13775 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13776 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13777 (if (active-minibuffer-window) (exit-minibuffer))))
13779 (defun org-check-deadlines (ndays)
13780 "Check if there are any deadlines due or past due.
13781 A deadline is considered due if it happens within `org-deadline-warning-days'
13782 days from today's date. If the deadline appears in an entry marked DONE,
13783 it is not shown. The prefix arg NDAYS can be used to test that many
13784 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13785 (interactive "P")
13786 (let* ((org-warn-days
13787 (cond
13788 ((equal ndays '(4)) 100000)
13789 (ndays (prefix-numeric-value ndays))
13790 (t (abs org-deadline-warning-days))))
13791 (case-fold-search nil)
13792 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13793 (callback
13794 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13796 (message "%d deadlines past-due or due within %d days"
13797 (org-occur regexp nil callback)
13798 org-warn-days)))
13800 (defun org-check-before-date (date)
13801 "Check if there are deadlines or scheduled entries before DATE."
13802 (interactive (list (org-read-date)))
13803 (let ((case-fold-search nil)
13804 (regexp (concat "\\<\\(" org-deadline-string
13805 "\\|" org-scheduled-string
13806 "\\) *<\\([^>]+\\)>"))
13807 (callback
13808 (lambda () (time-less-p
13809 (org-time-string-to-time (match-string 2))
13810 (org-time-string-to-time date)))))
13811 (message "%d entries before %s"
13812 (org-occur regexp nil callback) date)))
13814 (defun org-check-after-date (date)
13815 "Check if there are deadlines or scheduled entries after DATE."
13816 (interactive (list (org-read-date)))
13817 (let ((case-fold-search nil)
13818 (regexp (concat "\\<\\(" org-deadline-string
13819 "\\|" org-scheduled-string
13820 "\\) *<\\([^>]+\\)>"))
13821 (callback
13822 (lambda () (not
13823 (time-less-p
13824 (org-time-string-to-time (match-string 2))
13825 (org-time-string-to-time date))))))
13826 (message "%d entries after %s"
13827 (org-occur regexp nil callback) date)))
13829 (defun org-evaluate-time-range (&optional to-buffer)
13830 "Evaluate a time range by computing the difference between start and end.
13831 Normally the result is just printed in the echo area, but with prefix arg
13832 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13833 If the time range is actually in a table, the result is inserted into the
13834 next column.
13835 For time difference computation, a year is assumed to be exactly 365
13836 days in order to avoid rounding problems."
13837 (interactive "P")
13839 (org-clock-update-time-maybe)
13840 (save-excursion
13841 (unless (org-at-date-range-p t)
13842 (goto-char (point-at-bol))
13843 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13844 (if (not (org-at-date-range-p t))
13845 (error "Not at a time-stamp range, and none found in current line")))
13846 (let* ((ts1 (match-string 1))
13847 (ts2 (match-string 2))
13848 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13849 (match-end (match-end 0))
13850 (time1 (org-time-string-to-time ts1))
13851 (time2 (org-time-string-to-time ts2))
13852 (t1 (org-float-time time1))
13853 (t2 (org-float-time time2))
13854 (diff (abs (- t2 t1)))
13855 (negative (< (- t2 t1) 0))
13856 ;; (ys (floor (* 365 24 60 60)))
13857 (ds (* 24 60 60))
13858 (hs (* 60 60))
13859 (fy "%dy %dd %02d:%02d")
13860 (fy1 "%dy %dd")
13861 (fd "%dd %02d:%02d")
13862 (fd1 "%dd")
13863 (fh "%02d:%02d")
13864 y d h m align)
13865 (if havetime
13866 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13868 d (floor (/ diff ds)) diff (mod diff ds)
13869 h (floor (/ diff hs)) diff (mod diff hs)
13870 m (floor (/ diff 60)))
13871 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13873 d (floor (+ (/ diff ds) 0.5))
13874 h 0 m 0))
13875 (if (not to-buffer)
13876 (message "%s" (org-make-tdiff-string y d h m))
13877 (if (org-at-table-p)
13878 (progn
13879 (goto-char match-end)
13880 (setq align t)
13881 (and (looking-at " *|") (goto-char (match-end 0))))
13882 (goto-char match-end))
13883 (if (looking-at
13884 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13885 (replace-match ""))
13886 (if negative (insert " -"))
13887 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13888 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13889 (insert " " (format fh h m))))
13890 (if align (org-table-align))
13891 (message "Time difference inserted")))))
13893 (defun org-make-tdiff-string (y d h m)
13894 (let ((fmt "")
13895 (l nil))
13896 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13897 l (push y l)))
13898 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13899 l (push d l)))
13900 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13901 l (push h l)))
13902 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13903 l (push m l)))
13904 (apply 'format fmt (nreverse l))))
13906 (defun org-time-string-to-time (s)
13907 (apply 'encode-time (org-parse-time-string s)))
13908 (defun org-time-string-to-seconds (s)
13909 (org-float-time (org-time-string-to-time s)))
13911 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13912 "Convert a time stamp to an absolute day number.
13913 If there is a specifyer for a cyclic time stamp, get the closest date to
13914 DAYNR.
13915 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13916 the variable date is bound by the calendar when this is called."
13917 (cond
13918 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13919 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13920 daynr
13921 (+ daynr 1000)))
13922 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13923 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13924 (time-to-days (current-time))) (match-string 0 s)
13925 prefer show-all))
13926 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13928 (defun org-days-to-iso-week (days)
13929 "Return the iso week number."
13930 (require 'cal-iso)
13931 (car (calendar-iso-from-absolute days)))
13933 (defun org-small-year-to-year (year)
13934 "Convert 2-digit years into 4-digit years.
13935 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13936 The year 2000 cannot be abbreviated. Any year larger than 99
13937 is returned unchanged."
13938 (if (< year 38)
13939 (setq year (+ 2000 year))
13940 (if (< year 100)
13941 (setq year (+ 1900 year))))
13942 year)
13944 (defun org-time-from-absolute (d)
13945 "Return the time corresponding to date D.
13946 D may be an absolute day number, or a calendar-type list (month day year)."
13947 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13948 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13950 (defun org-calendar-holiday ()
13951 "List of holidays, for Diary display in Org-mode."
13952 (require 'holidays)
13953 (let ((hl (funcall
13954 (if (fboundp 'calendar-check-holidays)
13955 'calendar-check-holidays 'check-calendar-holidays) date)))
13956 (if hl (mapconcat 'identity hl "; "))))
13958 (defun org-diary-sexp-entry (sexp entry date)
13959 "Process a SEXP diary ENTRY for DATE."
13960 (require 'diary-lib)
13961 (let ((result (if calendar-debug-sexp
13962 (let ((stack-trace-on-error t))
13963 (eval (car (read-from-string sexp))))
13964 (condition-case nil
13965 (eval (car (read-from-string sexp)))
13966 (error
13967 (beep)
13968 (message "Bad sexp at line %d in %s: %s"
13969 (org-current-line)
13970 (buffer-file-name) sexp)
13971 (sleep-for 2))))))
13972 (cond ((stringp result) result)
13973 ((and (consp result)
13974 (stringp (cdr result))) (cdr result))
13975 (result entry)
13976 (t nil))))
13978 (defun org-diary-to-ical-string (frombuf)
13979 "Get iCalendar entries from diary entries in buffer FROMBUF.
13980 This uses the icalendar.el library."
13981 (let* ((tmpdir (if (featurep 'xemacs)
13982 (temp-directory)
13983 temporary-file-directory))
13984 (tmpfile (make-temp-name
13985 (expand-file-name "orgics" tmpdir)))
13986 buf rtn b e)
13987 (with-current-buffer frombuf
13988 (icalendar-export-region (point-min) (point-max) tmpfile)
13989 (setq buf (find-buffer-visiting tmpfile))
13990 (set-buffer buf)
13991 (goto-char (point-min))
13992 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13993 (setq b (match-beginning 0)))
13994 (goto-char (point-max))
13995 (if (re-search-backward "^END:VEVENT" nil t)
13996 (setq e (match-end 0)))
13997 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13998 (kill-buffer buf)
13999 (delete-file tmpfile)
14000 rtn))
14002 (defun org-closest-date (start current change prefer show-all)
14003 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14004 When PREFER is `past' return a date that is either CURRENT or past.
14005 When PREFER is `future', return a date that is either CURRENT or future.
14006 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14007 ;; Make the proper lists from the dates
14008 (catch 'exit
14009 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14010 dn dw sday cday n1 n2 n0
14011 d m y y1 y2 date1 date2 nmonths nm ny m2)
14013 (setq start (org-date-to-gregorian start)
14014 current (org-date-to-gregorian
14015 (if show-all
14016 current
14017 (time-to-days (current-time))))
14018 sday (calendar-absolute-from-gregorian start)
14019 cday (calendar-absolute-from-gregorian current))
14021 (if (<= cday sday) (throw 'exit sday))
14023 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14024 (setq dn (string-to-number (match-string 1 change))
14025 dw (cdr (assoc (match-string 2 change) a1)))
14026 (error "Invalid change specifyer: %s" change))
14027 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14028 (cond
14029 ((eq dw 'day)
14030 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14031 n2 (+ n1 dn)))
14032 ((eq dw 'year)
14033 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14034 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14035 (setq date1 (list m d y1)
14036 n1 (calendar-absolute-from-gregorian date1)
14037 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14038 n2 (calendar-absolute-from-gregorian date2)))
14039 ((eq dw 'month)
14040 ;; approx number of month between the two dates
14041 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14042 ;; How often does dn fit in there?
14043 (setq d (nth 1 start) m (car start) y (nth 2 start)
14044 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14045 m (+ m nm)
14046 ny (floor (/ m 12))
14047 y (+ y ny)
14048 m (- m (* ny 12)))
14049 (while (> m 12) (setq m (- m 12) y (1+ y)))
14050 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14051 (setq m2 (+ m dn) y2 y)
14052 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14053 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14054 (while (<= n2 cday)
14055 (setq n1 n2 m m2 y y2)
14056 (setq m2 (+ m dn) y2 y)
14057 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14058 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14059 ;; Make sure n1 is the earlier date
14060 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14061 (if show-all
14062 (cond
14063 ((eq prefer 'past) (if (= cday n2) n2 n1))
14064 ((eq prefer 'future) (if (= cday n1) n1 n2))
14065 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14066 (cond
14067 ((eq prefer 'past) (if (= cday n2) n2 n1))
14068 ((eq prefer 'future) (if (= cday n1) n1 n2))
14069 (t (if (= cday n1) n1 n2)))))))
14071 (defun org-date-to-gregorian (date)
14072 "Turn any specification of DATE into a gregorian date for the calendar."
14073 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14074 ((and (listp date) (= (length date) 3)) date)
14075 ((stringp date)
14076 (setq date (org-parse-time-string date))
14077 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14078 ((listp date)
14079 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14081 (defun org-parse-time-string (s &optional nodefault)
14082 "Parse the standard Org-mode time string.
14083 This should be a lot faster than the normal `parse-time-string'.
14084 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14085 hour and minute fields will be nil if not given."
14086 (if (string-match org-ts-regexp0 s)
14087 (list 0
14088 (if (or (match-beginning 8) (not nodefault))
14089 (string-to-number (or (match-string 8 s) "0")))
14090 (if (or (match-beginning 7) (not nodefault))
14091 (string-to-number (or (match-string 7 s) "0")))
14092 (string-to-number (match-string 4 s))
14093 (string-to-number (match-string 3 s))
14094 (string-to-number (match-string 2 s))
14095 nil nil nil)
14096 (error "Not a standard Org-mode time string: %s" s)))
14098 (defun org-timestamp-up (&optional arg)
14099 "Increase the date item at the cursor by one.
14100 If the cursor is on the year, change the year. If it is on the month or
14101 the day, change that.
14102 With prefix ARG, change by that many units."
14103 (interactive "p")
14104 (org-timestamp-change (prefix-numeric-value arg)))
14106 (defun org-timestamp-down (&optional arg)
14107 "Decrease the date item at the cursor by one.
14108 If the cursor is on the year, change the year. If it is on the month or
14109 the day, change that.
14110 With prefix ARG, change by that many units."
14111 (interactive "p")
14112 (org-timestamp-change (- (prefix-numeric-value arg))))
14114 (defun org-timestamp-up-day (&optional arg)
14115 "Increase the date in the time stamp by one day.
14116 With prefix ARG, change that many days."
14117 (interactive "p")
14118 (if (and (not (org-at-timestamp-p t))
14119 (org-on-heading-p))
14120 (org-todo 'up)
14121 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14123 (defun org-timestamp-down-day (&optional arg)
14124 "Decrease the date in the time stamp by one day.
14125 With prefix ARG, change that many days."
14126 (interactive "p")
14127 (if (and (not (org-at-timestamp-p t))
14128 (org-on-heading-p))
14129 (org-todo 'down)
14130 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14132 (defun org-at-timestamp-p (&optional inactive-ok)
14133 "Determine if the cursor is in or at a timestamp."
14134 (interactive)
14135 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14136 (pos (point))
14137 (ans (or (looking-at tsr)
14138 (save-excursion
14139 (skip-chars-backward "^[<\n\r\t")
14140 (if (> (point) (point-min)) (backward-char 1))
14141 (and (looking-at tsr)
14142 (> (- (match-end 0) pos) -1))))))
14143 (and ans
14144 (boundp 'org-ts-what)
14145 (setq org-ts-what
14146 (cond
14147 ((= pos (match-beginning 0)) 'bracket)
14148 ((= pos (1- (match-end 0))) 'bracket)
14149 ((org-pos-in-match-range pos 2) 'year)
14150 ((org-pos-in-match-range pos 3) 'month)
14151 ((org-pos-in-match-range pos 7) 'hour)
14152 ((org-pos-in-match-range pos 8) 'minute)
14153 ((or (org-pos-in-match-range pos 4)
14154 (org-pos-in-match-range pos 5)) 'day)
14155 ((and (> pos (or (match-end 8) (match-end 5)))
14156 (< pos (match-end 0)))
14157 (- pos (or (match-end 8) (match-end 5))))
14158 (t 'day))))
14159 ans))
14161 (defun org-toggle-timestamp-type ()
14162 "Toggle the type (<active> or [inactive]) of a time stamp."
14163 (interactive)
14164 (when (org-at-timestamp-p t)
14165 (let ((beg (match-beginning 0)) (end (match-end 0))
14166 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14167 (save-excursion
14168 (goto-char beg)
14169 (while (re-search-forward "[][<>]" end t)
14170 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14171 t t)))
14172 (message "Timestamp is now %sactive"
14173 (if (equal (char-after beg) ?<) "" "in")))))
14175 (defun org-timestamp-change (n &optional what)
14176 "Change the date in the time stamp at point.
14177 The date will be changed by N times WHAT. WHAT can be `day', `month',
14178 `year', `minute', `second'. If WHAT is not given, the cursor position
14179 in the timestamp determines what will be changed."
14180 (let ((pos (point))
14181 with-hm inactive
14182 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14183 org-ts-what
14184 extra rem
14185 ts time time0)
14186 (if (not (org-at-timestamp-p t))
14187 (error "Not at a timestamp"))
14188 (if (and (not what) (eq org-ts-what 'bracket))
14189 (org-toggle-timestamp-type)
14190 (if (and (not what) (not (eq org-ts-what 'day))
14191 org-display-custom-times
14192 (get-text-property (point) 'display)
14193 (not (get-text-property (1- (point)) 'display)))
14194 (setq org-ts-what 'day))
14195 (setq org-ts-what (or what org-ts-what)
14196 inactive (= (char-after (match-beginning 0)) ?\[)
14197 ts (match-string 0))
14198 (replace-match "")
14199 (if (string-match
14200 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14202 (setq extra (match-string 1 ts)))
14203 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14204 (setq with-hm t))
14205 (setq time0 (org-parse-time-string ts))
14206 (when (and (eq org-ts-what 'minute)
14207 (eq current-prefix-arg nil))
14208 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14209 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14210 (setcar (cdr time0) (+ (nth 1 time0)
14211 (if (> n 0) (- rem) (- dm rem))))))
14212 (setq time
14213 (encode-time (or (car time0) 0)
14214 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14215 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14216 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14217 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14218 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14219 (nthcdr 6 time0)))
14220 (when (and (member org-ts-what '(hour minute))
14221 extra
14222 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14223 (setq extra (org-modify-ts-extra
14224 extra
14225 (if (eq org-ts-what 'hour) 2 5)
14226 n dm)))
14227 (when (integerp org-ts-what)
14228 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14229 (if (eq what 'calendar)
14230 (let ((cal-date (org-get-date-from-calendar)))
14231 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14232 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14233 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14234 (setcar time0 (or (car time0) 0))
14235 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14236 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14237 (setq time (apply 'encode-time time0))))
14238 (setq org-last-changed-timestamp
14239 (org-insert-time-stamp time with-hm inactive nil nil extra))
14240 (org-clock-update-time-maybe)
14241 (goto-char pos)
14242 ;; Try to recenter the calendar window, if any
14243 (if (and org-calendar-follow-timestamp-change
14244 (get-buffer-window "*Calendar*" t)
14245 (memq org-ts-what '(day month year)))
14246 (org-recenter-calendar (time-to-days time))))))
14248 (defun org-modify-ts-extra (s pos n dm)
14249 "Change the different parts of the lead-time and repeat fields in timestamp."
14250 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14251 ng h m new rem)
14252 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14253 (cond
14254 ((or (org-pos-in-match-range pos 2)
14255 (org-pos-in-match-range pos 3))
14256 (setq m (string-to-number (match-string 3 s))
14257 h (string-to-number (match-string 2 s)))
14258 (if (org-pos-in-match-range pos 2)
14259 (setq h (+ h n))
14260 (setq n (* dm (org-no-warnings (signum n))))
14261 (when (not (= 0 (setq rem (% m dm))))
14262 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14263 (setq m (+ m n)))
14264 (if (< m 0) (setq m (+ m 60) h (1- h)))
14265 (if (> m 59) (setq m (- m 60) h (1+ h)))
14266 (setq h (min 24 (max 0 h)))
14267 (setq ng 1 new (format "-%02d:%02d" h m)))
14268 ((org-pos-in-match-range pos 6)
14269 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14270 ((org-pos-in-match-range pos 5)
14271 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14273 ((org-pos-in-match-range pos 9)
14274 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14275 ((org-pos-in-match-range pos 8)
14276 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14278 (when ng
14279 (setq s (concat
14280 (substring s 0 (match-beginning ng))
14282 (substring s (match-end ng))))))
14285 (defun org-recenter-calendar (date)
14286 "If the calendar is visible, recenter it to DATE."
14287 (let* ((win (selected-window))
14288 (cwin (get-buffer-window "*Calendar*" t))
14289 (calendar-move-hook nil))
14290 (when cwin
14291 (select-window cwin)
14292 (calendar-goto-date (if (listp date) date
14293 (calendar-gregorian-from-absolute date)))
14294 (select-window win))))
14296 (defun org-goto-calendar (&optional arg)
14297 "Go to the Emacs calendar at the current date.
14298 If there is a time stamp in the current line, go to that date.
14299 A prefix ARG can be used to force the current date."
14300 (interactive "P")
14301 (let ((tsr org-ts-regexp) diff
14302 (calendar-move-hook nil)
14303 (calendar-view-holidays-initially-flag nil)
14304 (view-calendar-holidays-initially nil)
14305 (calendar-view-diary-initially-flag nil)
14306 (view-diary-entries-initially nil))
14307 (if (or (org-at-timestamp-p)
14308 (save-excursion
14309 (beginning-of-line 1)
14310 (looking-at (concat ".*" tsr))))
14311 (let ((d1 (time-to-days (current-time)))
14312 (d2 (time-to-days
14313 (org-time-string-to-time (match-string 1)))))
14314 (setq diff (- d2 d1))))
14315 (calendar)
14316 (calendar-goto-today)
14317 (if (and diff (not arg)) (calendar-forward-day diff))))
14319 (defun org-get-date-from-calendar ()
14320 "Return a list (month day year) of date at point in calendar."
14321 (with-current-buffer "*Calendar*"
14322 (save-match-data
14323 (calendar-cursor-to-date))))
14325 (defun org-date-from-calendar ()
14326 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14327 If there is already a time stamp at the cursor position, update it."
14328 (interactive)
14329 (if (org-at-timestamp-p t)
14330 (org-timestamp-change 0 'calendar)
14331 (let ((cal-date (org-get-date-from-calendar)))
14332 (org-insert-time-stamp
14333 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14335 (defun org-minutes-to-hh:mm-string (m)
14336 "Compute H:MM from a number of minutes."
14337 (let ((h (/ m 60)))
14338 (setq m (- m (* 60 h)))
14339 (format org-time-clocksum-format h m)))
14341 (defun org-hh:mm-string-to-minutes (s)
14342 "Convert a string H:MM to a number of minutes.
14343 If the string is just a number, interpret it as minutes.
14344 In fact, the first hh:mm or number in the string will be taken,
14345 there can be extra stuff in the string.
14346 If no number is found, the return value is 0."
14347 (cond
14348 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14349 (+ (* (string-to-number (match-string 1 s)) 60)
14350 (string-to-number (match-string 2 s))))
14351 ((string-match "\\([0-9]+\\)" s)
14352 (string-to-number (match-string 1 s)))
14353 (t 0)))
14355 ;;;; Files
14357 (defun org-save-all-org-buffers ()
14358 "Save all Org-mode buffers without user confirmation."
14359 (interactive)
14360 (message "Saving all Org-mode buffers...")
14361 (save-some-buffers t 'org-mode-p)
14362 (when (featurep 'org-id) (org-id-locations-save))
14363 (message "Saving all Org-mode buffers... done"))
14365 (defun org-revert-all-org-buffers ()
14366 "Revert all Org-mode buffers.
14367 Prompt for confirmation when there are unsaved changes.
14368 Be sure you know what you are doing before letting this function
14369 overwrite your changes.
14371 This function is useful in a setup where one tracks org files
14372 with a version control system, to revert on one machine after pulling
14373 changes from another. I believe the procedure must be like this:
14375 1. M-x org-save-all-org-buffers
14376 2. Pull changes from the other machine, resolve conflicts
14377 3. M-x org-revert-all-org-buffers"
14378 (interactive)
14379 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14380 (error "Abort"))
14381 (save-excursion
14382 (save-window-excursion
14383 (mapc
14384 (lambda (b)
14385 (when (and (with-current-buffer b (org-mode-p))
14386 (with-current-buffer b buffer-file-name))
14387 (switch-to-buffer b)
14388 (revert-buffer t 'no-confirm)))
14389 (buffer-list))
14390 (when (and (featurep 'org-id) org-id-track-globally)
14391 (org-id-locations-load)))))
14393 ;;;; Agenda files
14395 ;;;###autoload
14396 (defun org-iswitchb (&optional arg)
14397 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14398 With a prefix argument, restrict available to files.
14399 With two prefix arguments, restrict available buffers to agenda files."
14400 (interactive "P")
14401 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14402 ((equal arg '(16)) (org-buffer-list 'agenda))
14403 (t (org-buffer-list)))))
14404 (switch-to-buffer
14405 (org-icompleting-read "Org buffer: "
14406 (mapcar 'list (mapcar 'buffer-name blist))
14407 nil t))))
14409 ;;;###autoload
14410 (defalias 'org-ido-switchb 'org-iswitchb)
14412 (defun org-buffer-list (&optional predicate exclude-tmp)
14413 "Return a list of Org buffers.
14414 PREDICATE can be `export', `files' or `agenda'.
14416 export restrict the list to Export buffers.
14417 files restrict the list to buffers visiting Org files.
14418 agenda restrict the list to buffers visiting agenda files.
14420 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14421 (let* ((bfn nil)
14422 (agenda-files (and (eq predicate 'agenda)
14423 (mapcar 'file-truename (org-agenda-files t))))
14424 (filter
14425 (cond
14426 ((eq predicate 'files)
14427 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14428 ((eq predicate 'export)
14429 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14430 ((eq predicate 'agenda)
14431 (lambda (b)
14432 (with-current-buffer b
14433 (and (eq major-mode 'org-mode)
14434 (setq bfn (buffer-file-name b))
14435 (member (file-truename bfn) agenda-files)))))
14436 (t (lambda (b) (with-current-buffer b
14437 (or (eq major-mode 'org-mode)
14438 (string-match "\*Org .*Export"
14439 (buffer-name b)))))))))
14440 (delq nil
14441 (mapcar
14442 (lambda(b)
14443 (if (and (funcall filter b)
14444 (or (not exclude-tmp)
14445 (not (string-match "tmp" (buffer-name b)))))
14447 nil))
14448 (buffer-list)))))
14450 (defun org-agenda-files (&optional unrestricted archives)
14451 "Get the list of agenda files.
14452 Optional UNRESTRICTED means return the full list even if a restriction
14453 is currently in place.
14454 When ARCHIVES is t, include all archive files hat are really being
14455 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14456 `org-agenda-archives-mode' is t."
14457 (let ((files
14458 (cond
14459 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14460 ((stringp org-agenda-files) (org-read-agenda-file-list))
14461 ((listp org-agenda-files) org-agenda-files)
14462 (t (error "Invalid value of `org-agenda-files'")))))
14463 (setq files (apply 'append
14464 (mapcar (lambda (f)
14465 (if (file-directory-p f)
14466 (directory-files
14467 f t org-agenda-file-regexp)
14468 (list f)))
14469 files)))
14470 (when org-agenda-skip-unavailable-files
14471 (setq files (delq nil
14472 (mapcar (function
14473 (lambda (file)
14474 (and (file-readable-p file) file)))
14475 files))))
14476 (when (or (eq archives t)
14477 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14478 (setq files (org-add-archive-files files)))
14479 files))
14481 (defun org-edit-agenda-file-list ()
14482 "Edit the list of agenda files.
14483 Depending on setup, this either uses customize to edit the variable
14484 `org-agenda-files', or it visits the file that is holding the list. In the
14485 latter case, the buffer is set up in a way that saving it automatically kills
14486 the buffer and restores the previous window configuration."
14487 (interactive)
14488 (if (stringp org-agenda-files)
14489 (let ((cw (current-window-configuration)))
14490 (find-file org-agenda-files)
14491 (org-set-local 'org-window-configuration cw)
14492 (org-add-hook 'after-save-hook
14493 (lambda ()
14494 (set-window-configuration
14495 (prog1 org-window-configuration
14496 (kill-buffer (current-buffer))))
14497 (org-install-agenda-files-menu)
14498 (message "New agenda file list installed"))
14499 nil 'local)
14500 (message "%s" (substitute-command-keys
14501 "Edit list and finish with \\[save-buffer]")))
14502 (customize-variable 'org-agenda-files)))
14504 (defun org-store-new-agenda-file-list (list)
14505 "Set new value for the agenda file list and save it correctly."
14506 (if (stringp org-agenda-files)
14507 (let ((f org-agenda-files) b)
14508 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14509 (with-temp-file f
14510 (insert (mapconcat 'identity list "\n") "\n")))
14511 (let ((org-mode-hook nil) (org-inhibit-startup t)
14512 (org-insert-mode-line-in-empty-file nil))
14513 (setq org-agenda-files list)
14514 (customize-save-variable 'org-agenda-files org-agenda-files))))
14516 (defun org-read-agenda-file-list ()
14517 "Read the list of agenda files from a file."
14518 (when (file-directory-p org-agenda-files)
14519 (error "`org-agenda-files' cannot be a single directory"))
14520 (when (stringp org-agenda-files)
14521 (with-temp-buffer
14522 (insert-file-contents org-agenda-files)
14523 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14526 ;;;###autoload
14527 (defun org-cycle-agenda-files ()
14528 "Cycle through the files in `org-agenda-files'.
14529 If the current buffer visits an agenda file, find the next one in the list.
14530 If the current buffer does not, find the first agenda file."
14531 (interactive)
14532 (let* ((fs (org-agenda-files t))
14533 (files (append fs (list (car fs))))
14534 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14535 file)
14536 (unless files (error "No agenda files"))
14537 (catch 'exit
14538 (while (setq file (pop files))
14539 (if (equal (file-truename file) tcf)
14540 (when (car files)
14541 (find-file (car files))
14542 (throw 'exit t))))
14543 (find-file (car fs)))
14544 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14546 (defun org-agenda-file-to-front (&optional to-end)
14547 "Move/add the current file to the top of the agenda file list.
14548 If the file is not present in the list, it is added to the front. If it is
14549 present, it is moved there. With optional argument TO-END, add/move to the
14550 end of the list."
14551 (interactive "P")
14552 (let ((org-agenda-skip-unavailable-files nil)
14553 (file-alist (mapcar (lambda (x)
14554 (cons (file-truename x) x))
14555 (org-agenda-files t)))
14556 (ctf (file-truename buffer-file-name))
14557 x had)
14558 (setq x (assoc ctf file-alist) had x)
14560 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14561 (if to-end
14562 (setq file-alist (append (delq x file-alist) (list x)))
14563 (setq file-alist (cons x (delq x file-alist))))
14564 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14565 (org-install-agenda-files-menu)
14566 (message "File %s to %s of agenda file list"
14567 (if had "moved" "added") (if to-end "end" "front"))))
14569 (defun org-remove-file (&optional file)
14570 "Remove current file from the list of files in variable `org-agenda-files'.
14571 These are the files which are being checked for agenda entries.
14572 Optional argument FILE means use this file instead of the current."
14573 (interactive)
14574 (let* ((org-agenda-skip-unavailable-files nil)
14575 (file (or file buffer-file-name))
14576 (true-file (file-truename file))
14577 (afile (abbreviate-file-name file))
14578 (files (delq nil (mapcar
14579 (lambda (x)
14580 (if (equal true-file
14581 (file-truename x))
14582 nil x))
14583 (org-agenda-files t)))))
14584 (if (not (= (length files) (length (org-agenda-files t))))
14585 (progn
14586 (org-store-new-agenda-file-list files)
14587 (org-install-agenda-files-menu)
14588 (message "Removed file: %s" afile))
14589 (message "File was not in list: %s (not removed)" afile))))
14591 (defun org-file-menu-entry (file)
14592 (vector file (list 'find-file file) t))
14594 (defun org-check-agenda-file (file)
14595 "Make sure FILE exists. If not, ask user what to do."
14596 (when (not (file-exists-p file))
14597 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14598 (abbreviate-file-name file))
14599 (let ((r (downcase (read-char-exclusive))))
14600 (cond
14601 ((equal r ?r)
14602 (org-remove-file file)
14603 (throw 'nextfile t))
14604 (t (error "Abort"))))))
14606 (defun org-get-agenda-file-buffer (file)
14607 "Get a buffer visiting FILE. If the buffer needs to be created, add
14608 it to the list of buffers which might be released later."
14609 (let ((buf (org-find-base-buffer-visiting file)))
14610 (if buf
14611 buf ; just return it
14612 ;; Make a new buffer and remember it
14613 (setq buf (find-file-noselect file))
14614 (if buf (push buf org-agenda-new-buffers))
14615 buf)))
14617 (defun org-release-buffers (blist)
14618 "Release all buffers in list, asking the user for confirmation when needed.
14619 When a buffer is unmodified, it is just killed. When modified, it is saved
14620 \(if the user agrees) and then killed."
14621 (let (buf file)
14622 (while (setq buf (pop blist))
14623 (setq file (buffer-file-name buf))
14624 (when (and (buffer-modified-p buf)
14625 file
14626 (y-or-n-p (format "Save file %s? " file)))
14627 (with-current-buffer buf (save-buffer)))
14628 (kill-buffer buf))))
14630 (defun org-prepare-agenda-buffers (files)
14631 "Create buffers for all agenda files, protect archived trees and comments."
14632 (interactive)
14633 (let ((pa '(:org-archived t))
14634 (pc '(:org-comment t))
14635 (pall '(:org-archived t :org-comment t))
14636 (inhibit-read-only t)
14637 (rea (concat ":" org-archive-tag ":"))
14638 bmp file re)
14639 (save-excursion
14640 (save-restriction
14641 (while (setq file (pop files))
14642 (catch 'nextfile
14643 (if (bufferp file)
14644 (set-buffer file)
14645 (org-check-agenda-file file)
14646 (set-buffer (org-get-agenda-file-buffer file)))
14647 (widen)
14648 (setq bmp (buffer-modified-p))
14649 (org-refresh-category-properties)
14650 (setq org-todo-keywords-for-agenda
14651 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14652 (setq org-done-keywords-for-agenda
14653 (append org-done-keywords-for-agenda org-done-keywords))
14654 (setq org-todo-keyword-alist-for-agenda
14655 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14656 (setq org-drawers-for-agenda
14657 (append org-drawers-for-agenda org-drawers))
14658 (setq org-tag-alist-for-agenda
14659 (append org-tag-alist-for-agenda org-tag-alist))
14661 (save-excursion
14662 (remove-text-properties (point-min) (point-max) pall)
14663 (when org-agenda-skip-archived-trees
14664 (goto-char (point-min))
14665 (while (re-search-forward rea nil t)
14666 (if (org-on-heading-p t)
14667 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14668 (goto-char (point-min))
14669 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14670 (while (re-search-forward re nil t)
14671 (add-text-properties
14672 (match-beginning 0) (org-end-of-subtree t) pc)))
14673 (set-buffer-modified-p bmp)))))
14674 (setq org-todo-keyword-alist-for-agenda
14675 (org-uniquify org-todo-keyword-alist-for-agenda)
14676 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14678 ;;;; Embedded LaTeX
14680 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14681 "Keymap for the minor `org-cdlatex-mode'.")
14683 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14684 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14685 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14686 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14687 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14689 (defvar org-cdlatex-texmathp-advice-is-done nil
14690 "Flag remembering if we have applied the advice to texmathp already.")
14692 (define-minor-mode org-cdlatex-mode
14693 "Toggle the minor `org-cdlatex-mode'.
14694 This mode supports entering LaTeX environment and math in LaTeX fragments
14695 in Org-mode.
14696 \\{org-cdlatex-mode-map}"
14697 nil " OCDL" nil
14698 (when org-cdlatex-mode (require 'cdlatex))
14699 (unless org-cdlatex-texmathp-advice-is-done
14700 (setq org-cdlatex-texmathp-advice-is-done t)
14701 (defadvice texmathp (around org-math-always-on activate)
14702 "Always return t in org-mode buffers.
14703 This is because we want to insert math symbols without dollars even outside
14704 the LaTeX math segments. If Orgmode thinks that point is actually inside
14705 an embedded LaTeX fragment, let texmathp do its job.
14706 \\[org-cdlatex-mode-map]"
14707 (interactive)
14708 (let (p)
14709 (cond
14710 ((not (org-mode-p)) ad-do-it)
14711 ((eq this-command 'cdlatex-math-symbol)
14712 (setq ad-return-value t
14713 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14715 (let ((p (org-inside-LaTeX-fragment-p)))
14716 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14717 (setq ad-return-value t
14718 texmathp-why '("Org-mode embedded math" . 0))
14719 (if p ad-do-it)))))))))
14721 (defun turn-on-org-cdlatex ()
14722 "Unconditionally turn on `org-cdlatex-mode'."
14723 (org-cdlatex-mode 1))
14725 (defun org-inside-LaTeX-fragment-p ()
14726 "Test if point is inside a LaTeX fragment.
14727 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14728 sequence appearing also before point.
14729 Even though the matchers for math are configurable, this function assumes
14730 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14731 delimiters are skipped when they have been removed by customization.
14732 The return value is nil, or a cons cell with the delimiter and
14733 and the position of this delimiter.
14735 This function does a reasonably good job, but can locally be fooled by
14736 for example currency specifications. For example it will assume being in
14737 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14738 fragments that are properly closed, but during editing, we have to live
14739 with the uncertainty caused by missing closing delimiters. This function
14740 looks only before point, not after."
14741 (catch 'exit
14742 (let ((pos (point))
14743 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14744 (lim (progn
14745 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14746 (point)))
14747 dd-on str (start 0) m re)
14748 (goto-char pos)
14749 (when dodollar
14750 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14751 re (nth 1 (assoc "$" org-latex-regexps)))
14752 (while (string-match re str start)
14753 (cond
14754 ((= (match-end 0) (length str))
14755 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14756 ((= (match-end 0) (- (length str) 5))
14757 (throw 'exit nil))
14758 (t (setq start (match-end 0))))))
14759 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14760 (goto-char pos)
14761 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14762 (and (match-beginning 2) (throw 'exit nil))
14763 ;; count $$
14764 (while (re-search-backward "\\$\\$" lim t)
14765 (setq dd-on (not dd-on)))
14766 (goto-char pos)
14767 (if dd-on (cons "$$" m))))))
14769 (defun org-inside-latex-macro-p ()
14770 "Is point inside a LaTeX macro or its arguments?"
14771 (save-match-data
14772 (org-in-regexp
14773 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14775 (defun org-try-cdlatex-tab ()
14776 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14777 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14778 - inside a LaTeX fragment, or
14779 - after the first word in a line, where an abbreviation expansion could
14780 insert a LaTeX environment."
14781 (when org-cdlatex-mode
14782 (cond
14783 ((save-excursion
14784 (skip-chars-backward "a-zA-Z0-9*")
14785 (skip-chars-backward " \t")
14786 (bolp))
14787 (cdlatex-tab) t)
14788 ((org-inside-LaTeX-fragment-p)
14789 (cdlatex-tab) t)
14790 (t nil))))
14792 (defun org-cdlatex-underscore-caret (&optional arg)
14793 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14794 Revert to the normal definition outside of these fragments."
14795 (interactive "P")
14796 (if (org-inside-LaTeX-fragment-p)
14797 (call-interactively 'cdlatex-sub-superscript)
14798 (let (org-cdlatex-mode)
14799 (call-interactively (key-binding (vector last-input-event))))))
14801 (defun org-cdlatex-math-modify (&optional arg)
14802 "Execute `cdlatex-math-modify' in LaTeX fragments.
14803 Revert to the normal definition outside of these fragments."
14804 (interactive "P")
14805 (if (org-inside-LaTeX-fragment-p)
14806 (call-interactively 'cdlatex-math-modify)
14807 (let (org-cdlatex-mode)
14808 (call-interactively (key-binding (vector last-input-event))))))
14810 (defvar org-latex-fragment-image-overlays nil
14811 "List of overlays carrying the images of latex fragments.")
14812 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14814 (defun org-remove-latex-fragment-image-overlays ()
14815 "Remove all overlays with LaTeX fragment images in current buffer."
14816 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14817 (setq org-latex-fragment-image-overlays nil))
14819 (defun org-preview-latex-fragment (&optional subtree)
14820 "Preview the LaTeX fragment at point, or all locally or globally.
14821 If the cursor is in a LaTeX fragment, create the image and overlay
14822 it over the source code. If there is no fragment at point, display
14823 all fragments in the current text, from one headline to the next. With
14824 prefix SUBTREE, display all fragments in the current subtree. With a
14825 double prefix `C-u C-u', or when the cursor is before the first headline,
14826 display all fragments in the buffer.
14827 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14828 (interactive "P")
14829 (org-remove-latex-fragment-image-overlays)
14830 (save-excursion
14831 (save-restriction
14832 (let (beg end at msg)
14833 (cond
14834 ((or (equal subtree '(16))
14835 (not (save-excursion
14836 (re-search-backward (concat "^" outline-regexp) nil t))))
14837 (setq beg (point-min) end (point-max)
14838 msg "Creating images for buffer...%s"))
14839 ((equal subtree '(4))
14840 (org-back-to-heading)
14841 (setq beg (point) end (org-end-of-subtree t)
14842 msg "Creating images for subtree...%s"))
14844 (if (setq at (org-inside-LaTeX-fragment-p))
14845 (goto-char (max (point-min) (- (cdr at) 2)))
14846 (org-back-to-heading))
14847 (setq beg (point) end (progn (outline-next-heading) (point))
14848 msg (if at "Creating image...%s"
14849 "Creating images for entry...%s"))))
14850 (message msg "")
14851 (narrow-to-region beg end)
14852 (goto-char beg)
14853 (org-format-latex
14854 (concat "ltxpng/" (file-name-sans-extension
14855 (file-name-nondirectory
14856 buffer-file-name)))
14857 default-directory 'overlays msg at 'forbuffer)
14858 (message msg "done. Use `C-c C-c' to remove images.")))))
14860 (defvar org-latex-regexps
14861 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14862 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14863 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14864 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14865 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14866 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14867 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14868 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14869 "Regular expressions for matching embedded LaTeX.")
14871 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14872 "Replace LaTeX fragments with links to an image, and produce images.
14873 Some of the options can be changed using the variable
14874 `org-format-latex-options'."
14875 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14876 (let* ((prefixnodir (file-name-nondirectory prefix))
14877 (absprefix (expand-file-name prefix dir))
14878 (todir (file-name-directory absprefix))
14879 (opt org-format-latex-options)
14880 (matchers (plist-get opt :matchers))
14881 (re-list org-latex-regexps)
14882 (org-format-latex-header-extra
14883 (plist-get (org-infile-export-plist) :latex-header-extra))
14884 (cnt 0) txt hash link beg end re e checkdir
14885 executables-checked
14886 m n block linkfile movefile ov)
14887 ;; Check the different regular expressions
14888 (while (setq e (pop re-list))
14889 (setq m (car e) re (nth 1 e) n (nth 2 e)
14890 block (if (nth 3 e) "\n\n" ""))
14891 (when (member m matchers)
14892 (goto-char (point-min))
14893 (while (re-search-forward re nil t)
14894 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14895 (not (get-text-property (match-beginning n)
14896 'org-protected))
14897 (or (not overlays)
14898 (not (eq (get-char-property (match-beginning n)
14899 'org-overlay-type)
14900 'org-latex-overlay))))
14901 (setq txt (match-string n)
14902 beg (match-beginning n) end (match-end n)
14903 cnt (1+ cnt))
14904 (let (print-length print-level) ; make sure full list is printed
14905 (setq hash (sha1 (prin1-to-string
14906 (list org-format-latex-header
14907 org-format-latex-header-extra
14908 org-export-latex-packages-alist
14909 org-format-latex-options
14910 forbuffer txt)))
14911 linkfile (format "%s_%s.png" prefix hash)
14912 movefile (format "%s_%s.png" absprefix hash)))
14913 (setq link (concat block "[[file:" linkfile "]]" block))
14914 (if msg (message msg cnt))
14915 (goto-char beg)
14916 (unless checkdir ; make sure the directory exists
14917 (setq checkdir t)
14918 (or (file-directory-p todir) (make-directory todir)))
14920 (unless executables-checked
14921 (org-check-external-command
14922 "latex" "needed to convert LaTeX fragments to images")
14923 (org-check-external-command
14924 "dvipng" "needed to convert LaTeX fragments to images")
14925 (setq executables-checked t))
14927 (unless (file-exists-p movefile)
14928 (org-create-formula-image
14929 txt movefile opt forbuffer))
14930 (if overlays
14931 (progn
14932 (mapc (lambda (o)
14933 (if (eq (org-overlay-get o 'org-overlay-type)
14934 'org-latex-overlay)
14935 (org-delete-overlay o)))
14936 (org-overlays-in beg end))
14937 (setq ov (org-make-overlay beg end))
14938 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14939 (if (featurep 'xemacs)
14940 (progn
14941 (org-overlay-put ov 'invisible t)
14942 (org-overlay-put
14943 ov 'end-glyph
14944 (make-glyph (vector 'png :file movefile))))
14945 (org-overlay-put
14946 ov 'display
14947 (list 'image :type 'png :file movefile :ascent 'center)))
14948 (push ov org-latex-fragment-image-overlays)
14949 (goto-char end))
14950 (delete-region beg end)
14951 (insert link))))))))
14953 ;; This function borrows from Ganesh Swami's latex2png.el
14954 (defun org-create-formula-image (string tofile options buffer)
14955 "This calls dvipng."
14956 (require 'org-latex)
14957 (let* ((tmpdir (if (featurep 'xemacs)
14958 (temp-directory)
14959 temporary-file-directory))
14960 (texfilebase (make-temp-name
14961 (expand-file-name "orgtex" tmpdir)))
14962 (texfile (concat texfilebase ".tex"))
14963 (dvifile (concat texfilebase ".dvi"))
14964 (pngfile (concat texfilebase ".png"))
14965 (fnh (if (featurep 'xemacs)
14966 (font-height (get-face-font 'default))
14967 (face-attribute 'default :height nil)))
14968 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14969 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14970 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14971 "Black"))
14972 (bg (or (plist-get options (if buffer :background :html-background))
14973 "Transparent")))
14974 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14975 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14976 (with-temp-file texfile
14977 (insert org-format-latex-header
14978 (if org-export-latex-packages-alist
14979 (concat "\n"
14980 (mapconcat (lambda(p)
14981 (if (equal "" (car p))
14982 (format "\\usepackage{%s}" (cadr p))
14983 (format "\\usepackage[%s]{%s}"
14984 (car p) (cadr p))))
14985 org-export-latex-packages-alist "\n"))
14987 (if org-format-latex-header-extra
14988 (concat "\n" org-format-latex-header-extra)
14990 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14991 (let ((dir default-directory))
14992 (condition-case nil
14993 (progn
14994 (cd tmpdir)
14995 (call-process "latex" nil nil nil texfile))
14996 (error nil))
14997 (cd dir))
14998 (if (not (file-exists-p dvifile))
14999 (progn (message "Failed to create dvi file from %s" texfile) nil)
15000 (condition-case nil
15001 (call-process "dvipng" nil nil nil
15002 "-fg" fg "-bg" bg
15003 "-D" dpi
15004 ;;"-x" scale "-y" scale
15005 "-T" "tight"
15006 "-o" pngfile
15007 dvifile)
15008 (error nil))
15009 (if (not (file-exists-p pngfile))
15010 (if org-format-latex-signal-error
15011 (error "Failed to create png file from %s" texfile)
15012 (message "Failed to create png file from %s" texfile)
15013 nil)
15014 ;; Use the requested file name and clean up
15015 (copy-file pngfile tofile 'replace)
15016 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15017 (delete-file (concat texfilebase e)))
15018 pngfile))))
15020 (defun org-dvipng-color (attr)
15021 "Return an rgb color specification for dvipng."
15022 (apply 'format "rgb %s %s %s"
15023 (mapcar 'org-normalize-color
15024 (color-values (face-attribute 'default attr nil)))))
15026 (defun org-normalize-color (value)
15027 "Return string to be used as color value for an RGB component."
15028 (format "%g" (/ value 65535.0)))
15030 ;;;; Key bindings
15032 ;; Make `C-c C-x' a prefix key
15033 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15035 ;; TAB key with modifiers
15036 (org-defkey org-mode-map "\C-i" 'org-cycle)
15037 (org-defkey org-mode-map [(tab)] 'org-cycle)
15038 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15039 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15040 (org-defkey org-mode-map "\M-\t" 'org-complete)
15041 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15042 ;; The following line is necessary under Suse GNU/Linux
15043 (unless (featurep 'xemacs)
15044 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15045 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15046 (define-key org-mode-map [backtab] 'org-shifttab)
15048 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15049 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15050 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15052 ;; Cursor keys with modifiers
15053 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15054 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15055 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15056 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15058 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15059 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15060 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15061 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15063 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15064 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15065 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15066 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15068 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15069 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15071 ;;; Extra keys for tty access.
15072 ;; We only set them when really needed because otherwise the
15073 ;; menus don't show the simple keys
15075 (when (or org-use-extra-keys
15076 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15077 (not window-system))
15078 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15079 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15080 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15081 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15082 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15083 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15084 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15085 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15086 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15087 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15088 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15089 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15090 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15091 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15092 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15093 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15094 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15095 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15096 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15097 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15098 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15099 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15100 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15101 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15102 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15103 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15104 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15105 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15107 ;; All the other keys
15109 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15110 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15111 (if (boundp 'narrow-map)
15112 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15113 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15114 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15115 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15116 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15117 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15118 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15119 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15120 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15121 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15122 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15123 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15124 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15125 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15126 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15127 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15128 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15129 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15130 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15131 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15132 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15133 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15134 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15135 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15136 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15137 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15138 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15139 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15140 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15141 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15142 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15143 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15144 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15145 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15146 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15147 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15148 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15149 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15150 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15151 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15152 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15153 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15154 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15155 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15156 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15157 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15158 (org-defkey org-mode-map "\C-c^" 'org-sort)
15159 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15160 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15161 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15162 (org-defkey org-mode-map "\C-m" 'org-return)
15163 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15164 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15165 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15166 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15167 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15168 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15169 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15170 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15171 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15172 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15173 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15174 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15175 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15176 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15177 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15178 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15179 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15180 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15181 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15182 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15183 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15185 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15186 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15187 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15188 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15190 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15191 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15192 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15193 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15194 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15195 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15196 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15197 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15198 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15199 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15200 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15201 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15202 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15203 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15204 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15206 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15207 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15208 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15209 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15211 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15213 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15215 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15216 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15218 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15221 (when (featurep 'xemacs)
15222 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15225 (defconst org-speed-commands-default
15227 ("Outline Navigation")
15228 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15229 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15230 ("f" . (org-speed-move-safe 'org-forward-same-level))
15231 ("b" . (org-speed-move-safe 'org-backward-same-level))
15232 ("u" . (org-speed-move-safe 'outline-up-heading))
15233 ("j" . org-goto)
15234 ("g" . (org-refile t))
15235 ("Outline Visibility")
15236 ("c" . org-cycle)
15237 ("C" . org-shifttab)
15238 (" " . org-display-outline-path)
15239 ("Outline Structure Editing")
15240 ("U" . org-shiftmetaup)
15241 ("D" . org-shiftmetadown)
15242 ("r" . org-metaright)
15243 ("l" . org-metaleft)
15244 ("R" . org-shiftmetaright)
15245 ("L" . org-shiftmetaleft)
15246 ("i" . (progn (forward-char 1) (call-interactively
15247 'org-insert-heading-respect-content)))
15248 ("^" . org-sort)
15249 ("w" . org-refile)
15250 ("a" . org-archive-subtree-default-with-confirmation)
15251 ("." . outline-mark-subtree)
15252 ("Clock Commands")
15253 ("I" . org-clock-in)
15254 ("O" . org-clock-out)
15255 ("Meta Data Editing")
15256 ("t" . org-todo)
15257 ("0" . (org-priority ?\ ))
15258 ("1" . (org-priority ?A))
15259 ("2" . (org-priority ?B))
15260 ("3" . (org-priority ?C))
15261 (";" . org-set-tags-command)
15262 ("e" . org-set-effort)
15263 ("Agenda Views etc")
15264 ("v" . org-agenda)
15265 ("/" . org-sparse-tree)
15266 ("Misc")
15267 ("o" . org-open-at-point)
15268 ("?" . org-speed-command-help)
15270 "The default speed commands.")
15272 (defun org-print-speed-command (e)
15273 (if (> (length (car e)) 1)
15274 (progn
15275 (princ "\n")
15276 (princ (car e))
15277 (princ "\n")
15278 (princ (make-string (length (car e)) ?-))
15279 (princ "\n"))
15280 (princ (car e))
15281 (princ " ")
15282 (if (symbolp (cdr e))
15283 (princ (symbol-name (cdr e)))
15284 (prin1 (cdr e)))
15285 (princ "\n")))
15287 (defun org-speed-command-help ()
15288 "Show the available speed commands."
15289 (interactive)
15290 (if (not org-use-speed-commands)
15291 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15292 (with-output-to-temp-buffer "*Help*"
15293 (princ "User-defined Speed commands\n===========================\n")
15294 (mapc 'org-print-speed-command org-speed-commands-user)
15295 (princ "\n")
15296 (princ "Built-in Speed commands\n=======================\n")
15297 (mapc 'org-print-speed-command org-speed-commands-default))
15298 (with-current-buffer "*Help*"
15299 (setq truncate-lines t))))
15301 (defun org-speed-move-safe (cmd)
15302 "Execute CMD, but make sure that the cursor always ends up in a headline.
15303 If not, return to the original position and throw an error."
15304 (interactive)
15305 (let ((pos (point)))
15306 (call-interactively cmd)
15307 (unless (and (bolp) (org-on-heading-p))
15308 (goto-char pos)
15309 (error "Boundary reached while executing %s" cmd))))
15311 (defvar org-self-insert-command-undo-counter 0)
15313 (defvar org-table-auto-blank-field) ; defined in org-table.el
15314 (defvar org-speed-command nil)
15315 (defun org-self-insert-command (N)
15316 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15317 If the cursor is in a table looking at whitespace, the whitespace is
15318 overwritten, and the table is not marked as requiring realignment."
15319 (interactive "p")
15320 (cond
15321 ((and org-use-speed-commands
15322 (or (and (bolp) (looking-at outline-regexp))
15323 (and (functionp org-use-speed-commands)
15324 (funcall org-use-speed-commands)))
15325 (setq
15326 org-speed-command
15327 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15328 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15329 (cond
15330 ((commandp org-speed-command)
15331 (setq this-command org-speed-command)
15332 (call-interactively org-speed-command))
15333 ((functionp org-speed-command)
15334 (funcall org-speed-command))
15335 ((and org-speed-command (listp org-speed-command))
15336 (eval org-speed-command))
15337 (t (let (org-use-speed-commands)
15338 (call-interactively 'org-self-insert-command)))))
15339 ((and
15340 (org-table-p)
15341 (progn
15342 ;; check if we blank the field, and if that triggers align
15343 (and (featurep 'org-table) org-table-auto-blank-field
15344 (member last-command
15345 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15346 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15347 ;; got extra space, this field does not determine column width
15348 (let (org-table-may-need-update) (org-table-blank-field))
15349 ;; no extra space, this field may determine column width
15350 (org-table-blank-field)))
15352 (eq N 1)
15353 (looking-at "[^|\n]* |"))
15354 (let (org-table-may-need-update)
15355 (goto-char (1- (match-end 0)))
15356 (delete-backward-char 1)
15357 (goto-char (match-beginning 0))
15358 (self-insert-command N)))
15360 (setq org-table-may-need-update t)
15361 (self-insert-command N)
15362 (org-fix-tags-on-the-fly)
15363 (if org-self-insert-cluster-for-undo
15364 (if (not (eq last-command 'org-self-insert-command))
15365 (setq org-self-insert-command-undo-counter 1)
15366 (if (>= org-self-insert-command-undo-counter 20)
15367 (setq org-self-insert-command-undo-counter 1)
15368 (and (> org-self-insert-command-undo-counter 0)
15369 buffer-undo-list
15370 (not (cadr buffer-undo-list)) ; remove nil entry
15371 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15372 (setq org-self-insert-command-undo-counter
15373 (1+ org-self-insert-command-undo-counter))))))))
15375 (defun org-fix-tags-on-the-fly ()
15376 (when (and (equal (char-after (point-at-bol)) ?*)
15377 (org-on-heading-p))
15378 (org-align-tags-here org-tags-column)))
15380 (defun org-delete-backward-char (N)
15381 "Like `delete-backward-char', insert whitespace at field end in tables.
15382 When deleting backwards, in tables this function will insert whitespace in
15383 front of the next \"|\" separator, to keep the table aligned. The table will
15384 still be marked for re-alignment if the field did fill the entire column,
15385 because, in this case the deletion might narrow the column."
15386 (interactive "p")
15387 (if (and (org-table-p)
15388 (eq N 1)
15389 (string-match "|" (buffer-substring (point-at-bol) (point)))
15390 (looking-at ".*?|"))
15391 (let ((pos (point))
15392 (noalign (looking-at "[^|\n\r]* |"))
15393 (c org-table-may-need-update))
15394 (backward-delete-char N)
15395 (skip-chars-forward "^|")
15396 (insert " ")
15397 (goto-char (1- pos))
15398 ;; noalign: if there were two spaces at the end, this field
15399 ;; does not determine the width of the column.
15400 (if noalign (setq org-table-may-need-update c)))
15401 (backward-delete-char N)
15402 (org-fix-tags-on-the-fly)))
15404 (defun org-delete-char (N)
15405 "Like `delete-char', but insert whitespace at field end in tables.
15406 When deleting characters, in tables this function will insert whitespace in
15407 front of the next \"|\" separator, to keep the table aligned. The table will
15408 still be marked for re-alignment if the field did fill the entire column,
15409 because, in this case the deletion might narrow the column."
15410 (interactive "p")
15411 (if (and (org-table-p)
15412 (not (bolp))
15413 (not (= (char-after) ?|))
15414 (eq N 1))
15415 (if (looking-at ".*?|")
15416 (let ((pos (point))
15417 (noalign (looking-at "[^|\n\r]* |"))
15418 (c org-table-may-need-update))
15419 (replace-match (concat
15420 (substring (match-string 0) 1 -1)
15421 " |"))
15422 (goto-char pos)
15423 ;; noalign: if there were two spaces at the end, this field
15424 ;; does not determine the width of the column.
15425 (if noalign (setq org-table-may-need-update c)))
15426 (delete-char N))
15427 (delete-char N)
15428 (org-fix-tags-on-the-fly)))
15430 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15431 (put 'org-self-insert-command 'delete-selection t)
15432 (put 'orgtbl-self-insert-command 'delete-selection t)
15433 (put 'org-delete-char 'delete-selection 'supersede)
15434 (put 'org-delete-backward-char 'delete-selection 'supersede)
15435 (put 'org-yank 'delete-selection 'yank)
15437 ;; Make `flyspell-mode' delay after some commands
15438 (put 'org-self-insert-command 'flyspell-delayed t)
15439 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15440 (put 'org-delete-char 'flyspell-delayed t)
15441 (put 'org-delete-backward-char 'flyspell-delayed t)
15443 ;; Make pabbrev-mode expand after org-mode commands
15444 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15445 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15447 ;; How to do this: Measure non-white length of current string
15448 ;; If equal to column width, we should realign.
15450 (defun org-remap (map &rest commands)
15451 "In MAP, remap the functions given in COMMANDS.
15452 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15453 (let (new old)
15454 (while commands
15455 (setq old (pop commands) new (pop commands))
15456 (if (fboundp 'command-remapping)
15457 (org-defkey map (vector 'remap old) new)
15458 (substitute-key-definition old new map global-map)))))
15460 (when (eq org-enable-table-editor 'optimized)
15461 ;; If the user wants maximum table support, we need to hijack
15462 ;; some standard editing functions
15463 (org-remap org-mode-map
15464 'self-insert-command 'org-self-insert-command
15465 'delete-char 'org-delete-char
15466 'delete-backward-char 'org-delete-backward-char)
15467 (org-defkey org-mode-map "|" 'org-force-self-insert))
15469 (defvar org-ctrl-c-ctrl-c-hook nil
15470 "Hook for functions attaching themselves to `C-c C-c'.
15471 This can be used to add additional functionality to the C-c C-c key which
15472 executes context-dependent commands.
15473 Each function will be called with no arguments. The function must check
15474 if the context is appropriate for it to act. If yes, it should do its
15475 thing and then return a non-nil value. If the context is wrong,
15476 just do nothing and return nil.")
15478 (defvar org-tab-first-hook nil
15479 "Hook for functions to attach themselves to TAB.
15480 See `org-ctrl-c-ctrl-c-hook' for more information.
15481 This hook runs as the first action when TAB is pressed, even before
15482 `org-cycle' messes around with the `outline-regexp' to cater for
15483 inline tasks and plain list item folding.
15484 If any function in this hook returns t, not other actions like table
15485 field motion visibility cycling will be done.")
15487 (defvar org-tab-after-check-for-table-hook nil
15488 "Hook for functions to attach themselves to TAB.
15489 See `org-ctrl-c-ctrl-c-hook' for more information.
15490 This hook runs after it has been established that the cursor is not in a
15491 table, but before checking if the cursor is in a headline or if global cycling
15492 should be done.
15493 If any function in this hook returns t, not other actions like visibility
15494 cycling will be done.")
15496 (defvar org-tab-after-check-for-cycling-hook nil
15497 "Hook for functions to attach themselves to TAB.
15498 See `org-ctrl-c-ctrl-c-hook' for more information.
15499 This hook runs after it has been established that not table field motion and
15500 not visibility should be done because of current context. This is probably
15501 the place where a package like yasnippets can hook in.")
15503 (defvar org-tab-before-tab-emulation-hook nil
15504 "Hook for functions to attach themselves to TAB.
15505 See `org-ctrl-c-ctrl-c-hook' for more information.
15506 This hook runs after every other options for TAB have been exhausted, but
15507 before indentation and \t insertion takes place.")
15509 (defvar org-metaleft-hook nil
15510 "Hook for functions attaching themselves to `M-left'.
15511 See `org-ctrl-c-ctrl-c-hook' for more information.")
15512 (defvar org-metaright-hook nil
15513 "Hook for functions attaching themselves to `M-right'.
15514 See `org-ctrl-c-ctrl-c-hook' for more information.")
15515 (defvar org-metaup-hook nil
15516 "Hook for functions attaching themselves to `M-up'.
15517 See `org-ctrl-c-ctrl-c-hook' for more information.")
15518 (defvar org-metadown-hook nil
15519 "Hook for functions attaching themselves to `M-down'.
15520 See `org-ctrl-c-ctrl-c-hook' for more information.")
15521 (defvar org-shiftmetaleft-hook nil
15522 "Hook for functions attaching themselves to `M-S-left'.
15523 See `org-ctrl-c-ctrl-c-hook' for more information.")
15524 (defvar org-shiftmetaright-hook nil
15525 "Hook for functions attaching themselves to `M-S-right'.
15526 See `org-ctrl-c-ctrl-c-hook' for more information.")
15527 (defvar org-shiftmetaup-hook nil
15528 "Hook for functions attaching themselves to `M-S-up'.
15529 See `org-ctrl-c-ctrl-c-hook' for more information.")
15530 (defvar org-shiftmetadown-hook nil
15531 "Hook for functions attaching themselves to `M-S-down'.
15532 See `org-ctrl-c-ctrl-c-hook' for more information.")
15533 (defvar org-metareturn-hook nil
15534 "Hook for functions attaching themselves to `M-RET'.
15535 See `org-ctrl-c-ctrl-c-hook' for more information.")
15537 (defun org-modifier-cursor-error ()
15538 "Throw an error, a modified cursor command was applied in wrong context."
15539 (error "This command is active in special context like tables, headlines or items"))
15541 (defun org-shiftselect-error ()
15542 "Throw an error because Shift-Cursor command was applied in wrong context."
15543 (if (and (boundp 'shift-select-mode) shift-select-mode)
15544 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15545 (error "This command works only in special context like headlines or timestamps")))
15547 (defun org-call-for-shift-select (cmd)
15548 (let ((this-command-keys-shift-translated t))
15549 (call-interactively cmd)))
15551 (defun org-shifttab (&optional arg)
15552 "Global visibility cycling or move to previous table field.
15553 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15554 on context.
15555 See the individual commands for more information."
15556 (interactive "P")
15557 (cond
15558 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15559 ((integerp arg)
15560 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15561 (message "Content view to level: %d" arg)
15562 (org-content (prefix-numeric-value arg2))
15563 (setq org-cycle-global-status 'overview)))
15564 (t (call-interactively 'org-global-cycle))))
15566 (defun org-shiftmetaleft ()
15567 "Promote subtree or delete table column.
15568 Calls `org-promote-subtree', `org-outdent-item',
15569 or `org-table-delete-column', depending on context.
15570 See the individual commands for more information."
15571 (interactive)
15572 (cond
15573 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15574 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15575 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15576 ((org-at-item-p) (call-interactively 'org-outdent-item))
15577 (t (org-modifier-cursor-error))))
15579 (defun org-shiftmetaright ()
15580 "Demote subtree or insert table column.
15581 Calls `org-demote-subtree', `org-indent-item',
15582 or `org-table-insert-column', depending on context.
15583 See the individual commands for more information."
15584 (interactive)
15585 (cond
15586 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15587 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15588 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15589 ((org-at-item-p) (call-interactively 'org-indent-item))
15590 (t (org-modifier-cursor-error))))
15592 (defun org-shiftmetaup (&optional arg)
15593 "Move subtree up or kill table row.
15594 Calls `org-move-subtree-up' or `org-table-kill-row' or
15595 `org-move-item-up' depending on context. See the individual commands
15596 for more information."
15597 (interactive "P")
15598 (cond
15599 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15600 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15601 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15602 ((org-at-item-p) (call-interactively 'org-move-item-up))
15603 (t (org-modifier-cursor-error))))
15605 (defun org-shiftmetadown (&optional arg)
15606 "Move subtree down or insert table row.
15607 Calls `org-move-subtree-down' or `org-table-insert-row' or
15608 `org-move-item-down', depending on context. See the individual
15609 commands for more information."
15610 (interactive "P")
15611 (cond
15612 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15613 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15614 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15615 ((org-at-item-p) (call-interactively 'org-move-item-down))
15616 (t (org-modifier-cursor-error))))
15618 (defun org-metaleft (&optional arg)
15619 "Promote heading or move table column to left.
15620 Calls `org-do-promote' or `org-table-move-column', depending on context.
15621 With no specific context, calls the Emacs default `backward-word'.
15622 See the individual commands for more information."
15623 (interactive "P")
15624 (cond
15625 ((run-hook-with-args-until-success 'org-metaleft-hook))
15626 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15627 ((or (org-on-heading-p)
15628 (and (org-region-active-p)
15629 (save-excursion
15630 (goto-char (region-beginning))
15631 (org-on-heading-p))))
15632 (call-interactively 'org-do-promote))
15633 ((or (org-at-item-p)
15634 (and (org-region-active-p)
15635 (save-excursion
15636 (goto-char (region-beginning))
15637 (org-at-item-p))))
15638 (call-interactively 'org-outdent-item))
15639 (t (call-interactively 'backward-word))))
15641 (defun org-metaright (&optional arg)
15642 "Demote subtree or move table column to right.
15643 Calls `org-do-demote' or `org-table-move-column', depending on context.
15644 With no specific context, calls the Emacs default `forward-word'.
15645 See the individual commands for more information."
15646 (interactive "P")
15647 (cond
15648 ((run-hook-with-args-until-success 'org-metaright-hook))
15649 ((org-at-table-p) (call-interactively 'org-table-move-column))
15650 ((or (org-on-heading-p)
15651 (and (org-region-active-p)
15652 (save-excursion
15653 (goto-char (region-beginning))
15654 (org-on-heading-p))))
15655 (call-interactively 'org-do-demote))
15656 ((or (org-at-item-p)
15657 (and (org-region-active-p)
15658 (save-excursion
15659 (goto-char (region-beginning))
15660 (org-at-item-p))))
15661 (call-interactively 'org-indent-item))
15662 (t (call-interactively 'forward-word))))
15664 (defun org-metaup (&optional arg)
15665 "Move subtree up or move table row up.
15666 Calls `org-move-subtree-up' or `org-table-move-row' or
15667 `org-move-item-up', depending on context. See the individual commands
15668 for more information."
15669 (interactive "P")
15670 (cond
15671 ((run-hook-with-args-until-success 'org-metaup-hook))
15672 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15673 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15674 ((org-at-item-p) (call-interactively 'org-move-item-up))
15675 (t (transpose-lines 1) (beginning-of-line -1))))
15677 (defun org-metadown (&optional arg)
15678 "Move subtree down or move table row down.
15679 Calls `org-move-subtree-down' or `org-table-move-row' or
15680 `org-move-item-down', depending on context. See the individual
15681 commands for more information."
15682 (interactive "P")
15683 (cond
15684 ((run-hook-with-args-until-success 'org-metadown-hook))
15685 ((org-at-table-p) (call-interactively 'org-table-move-row))
15686 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15687 ((org-at-item-p) (call-interactively 'org-move-item-down))
15688 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15690 (defun org-shiftup (&optional arg)
15691 "Increase item in timestamp or increase priority of current headline.
15692 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15693 depending on context. See the individual commands for more information."
15694 (interactive "P")
15695 (cond
15696 ((and org-support-shift-select (org-region-active-p))
15697 (org-call-for-shift-select 'previous-line))
15698 ((org-at-timestamp-p t)
15699 (call-interactively (if org-edit-timestamp-down-means-later
15700 'org-timestamp-down 'org-timestamp-up)))
15701 ((and (not (eq org-support-shift-select 'always))
15702 org-enable-priority-commands
15703 (org-on-heading-p))
15704 (call-interactively 'org-priority-up))
15705 ((and (not org-support-shift-select) (org-at-item-p))
15706 (call-interactively 'org-previous-item))
15707 ((org-clocktable-try-shift 'up arg))
15708 (org-support-shift-select
15709 (org-call-for-shift-select 'previous-line))
15710 (t (org-shiftselect-error))))
15712 (defun org-shiftdown (&optional arg)
15713 "Decrease item in timestamp or decrease priority of current headline.
15714 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15715 depending on context. See the individual commands for more information."
15716 (interactive "P")
15717 (cond
15718 ((and org-support-shift-select (org-region-active-p))
15719 (org-call-for-shift-select 'next-line))
15720 ((org-at-timestamp-p t)
15721 (call-interactively (if org-edit-timestamp-down-means-later
15722 'org-timestamp-up 'org-timestamp-down)))
15723 ((and (not (eq org-support-shift-select 'always))
15724 org-enable-priority-commands
15725 (org-on-heading-p))
15726 (call-interactively 'org-priority-down))
15727 ((and (not org-support-shift-select) (org-at-item-p))
15728 (call-interactively 'org-next-item))
15729 ((org-clocktable-try-shift 'down arg))
15730 (org-support-shift-select
15731 (org-call-for-shift-select 'next-line))
15732 (t (org-shiftselect-error))))
15734 (defun org-shiftright (&optional arg)
15735 "Cycle the thing at point or in the current line, depending on context.
15736 Depending on context, this does one of the following:
15738 - switch a timestamp at point one day into the future
15739 - on a headline, switch to the next TODO keyword.
15740 - on an item, switch entire list to the next bullet type
15741 - on a property line, switch to the next allowed value
15742 - on a clocktable definition line, move time block into the future"
15743 (interactive "P")
15744 (cond
15745 ((and org-support-shift-select (org-region-active-p))
15746 (org-call-for-shift-select 'forward-char))
15747 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15748 ((and (not (eq org-support-shift-select 'always))
15749 (org-on-heading-p))
15750 (let ((org-inhibit-logging
15751 (not org-treat-S-cursor-todo-selection-as-state-change))
15752 (org-inhibit-blocking
15753 (not org-treat-S-cursor-todo-selection-as-state-change)))
15754 (org-call-with-arg 'org-todo 'right)))
15755 ((or (and org-support-shift-select
15756 (not (eq org-support-shift-select 'always))
15757 (org-at-item-bullet-p))
15758 (and (not org-support-shift-select) (org-at-item-p)))
15759 (org-call-with-arg 'org-cycle-list-bullet nil))
15760 ((and (not (eq org-support-shift-select 'always))
15761 (org-at-property-p))
15762 (call-interactively 'org-property-next-allowed-value))
15763 ((org-clocktable-try-shift 'right arg))
15764 (org-support-shift-select
15765 (org-call-for-shift-select 'forward-char))
15766 (t (org-shiftselect-error))))
15768 (defun org-shiftleft (&optional arg)
15769 "Cycle the thing at point or in the current line, depending on context.
15770 Depending on context, this does one of the following:
15772 - switch a timestamp at point one day into the past
15773 - on a headline, switch to the previous TODO keyword.
15774 - on an item, switch entire list to the previous bullet type
15775 - on a property line, switch to the previous allowed value
15776 - on a clocktable definition line, move time block into the past"
15777 (interactive "P")
15778 (cond
15779 ((and org-support-shift-select (org-region-active-p))
15780 (org-call-for-shift-select 'backward-char))
15781 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15782 ((and (not (eq org-support-shift-select 'always))
15783 (org-on-heading-p))
15784 (let ((org-inhibit-logging
15785 (not org-treat-S-cursor-todo-selection-as-state-change))
15786 (org-inhibit-blocking
15787 (not org-treat-S-cursor-todo-selection-as-state-change)))
15788 (org-call-with-arg 'org-todo 'left)))
15789 ((or (and org-support-shift-select
15790 (not (eq org-support-shift-select 'always))
15791 (org-at-item-bullet-p))
15792 (and (not org-support-shift-select) (org-at-item-p)))
15793 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15794 ((and (not (eq org-support-shift-select 'always))
15795 (org-at-property-p))
15796 (call-interactively 'org-property-previous-allowed-value))
15797 ((org-clocktable-try-shift 'left arg))
15798 (org-support-shift-select
15799 (org-call-for-shift-select 'backward-char))
15800 (t (org-shiftselect-error))))
15802 (defun org-shiftcontrolright ()
15803 "Switch to next TODO set."
15804 (interactive)
15805 (cond
15806 ((and org-support-shift-select (org-region-active-p))
15807 (org-call-for-shift-select 'forward-word))
15808 ((and (not (eq org-support-shift-select 'always))
15809 (org-on-heading-p))
15810 (org-call-with-arg 'org-todo 'nextset))
15811 (org-support-shift-select
15812 (org-call-for-shift-select 'forward-word))
15813 (t (org-shiftselect-error))))
15815 (defun org-shiftcontrolleft ()
15816 "Switch to previous TODO set."
15817 (interactive)
15818 (cond
15819 ((and org-support-shift-select (org-region-active-p))
15820 (org-call-for-shift-select 'backward-word))
15821 ((and (not (eq org-support-shift-select 'always))
15822 (org-on-heading-p))
15823 (org-call-with-arg 'org-todo 'previousset))
15824 (org-support-shift-select
15825 (org-call-for-shift-select 'backward-word))
15826 (t (org-shiftselect-error))))
15828 (defun org-ctrl-c-ret ()
15829 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15830 (interactive)
15831 (cond
15832 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15833 (t (call-interactively 'org-insert-heading))))
15835 (defun org-copy-special ()
15836 "Copy region in table or copy current subtree.
15837 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15838 See the individual commands for more information."
15839 (interactive)
15840 (call-interactively
15841 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15843 (defun org-cut-special ()
15844 "Cut region in table or cut current subtree.
15845 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15846 See the individual commands for more information."
15847 (interactive)
15848 (call-interactively
15849 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15851 (defun org-paste-special (arg)
15852 "Paste rectangular region into table, or past subtree relative to level.
15853 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15854 See the individual commands for more information."
15855 (interactive "P")
15856 (if (org-at-table-p)
15857 (org-table-paste-rectangle)
15858 (org-paste-subtree arg)))
15860 (defun org-edit-special ()
15861 "Call a special editor for the stuff at point.
15862 When at a table, call the formula editor with `org-table-edit-formulas'.
15863 When at the first line of an src example, call `org-edit-src-code'.
15864 When in an #+include line, visit the include file. Otherwise call
15865 `ffap' to visit the file at point."
15866 (interactive)
15867 (cond
15868 ((org-at-table-p)
15869 (call-interactively 'org-table-edit-formulas))
15870 ((save-excursion
15871 (beginning-of-line 1)
15872 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15873 (find-file (org-trim (match-string 1))))
15874 ((org-edit-src-code))
15875 ((org-edit-fixed-width-region))
15876 (t (call-interactively 'ffap))))
15879 (defun org-ctrl-c-ctrl-c (&optional arg)
15880 "Set tags in headline, or update according to changed information at point.
15882 This command does many different things, depending on context:
15884 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15885 this is what we do.
15887 - If the cursor is on a statistics cookie, update it.
15889 - If the cursor is in a headline, prompt for tags and insert them
15890 into the current line, aligned to `org-tags-column'. When called
15891 with prefix arg, realign all tags in the current buffer.
15893 - If the cursor is in one of the special #+KEYWORD lines, this
15894 triggers scanning the buffer for these lines and updating the
15895 information.
15897 - If the cursor is inside a table, realign the table. This command
15898 works even if the automatic table editor has been turned off.
15900 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15901 the entire table.
15903 - If the cursor is at a footnote reference or definition, jump to
15904 the corresponding definition or references, respectively.
15906 - If the cursor is a the beginning of a dynamic block, update it.
15908 - If the cursor is inside a table created by the table.el package,
15909 activate that table.
15911 - If the current buffer is a remember buffer, close note and file
15912 it. A prefix argument of 1 files to the default location
15913 without further interaction. A prefix argument of 2 files to
15914 the currently clocking task.
15916 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15917 links in this buffer.
15919 - If the cursor is on a numbered item in a plain list, renumber the
15920 ordered list.
15922 - If the cursor is on a checkbox, toggle it."
15923 (interactive "P")
15924 (let ((org-enable-table-editor t))
15925 (cond
15926 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15927 org-occur-highlights
15928 org-latex-fragment-image-overlays)
15929 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15930 (org-remove-occur-highlights)
15931 (org-remove-latex-fragment-image-overlays)
15932 (message "Temporary highlights/overlays removed from current buffer"))
15933 ((and (local-variable-p 'org-finish-function (current-buffer))
15934 (fboundp org-finish-function))
15935 (funcall org-finish-function))
15936 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15937 ((org-at-property-p)
15938 (call-interactively 'org-property-action))
15939 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15940 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15941 (or (org-on-heading-p) (org-at-item-p)))
15942 (call-interactively 'org-update-statistics-cookies))
15943 ((org-on-heading-p) (call-interactively 'org-set-tags))
15944 ((org-at-table.el-p)
15945 (require 'table)
15946 (beginning-of-line 1)
15947 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15948 (call-interactively 'table-recognize-table))
15949 ((org-at-table-p)
15950 (org-table-maybe-eval-formula)
15951 (if arg
15952 (call-interactively 'org-table-recalculate)
15953 (org-table-maybe-recalculate-line))
15954 (call-interactively 'org-table-align))
15955 ((or (org-footnote-at-reference-p)
15956 (org-footnote-at-definition-p))
15957 (call-interactively 'org-footnote-action))
15958 ((org-at-item-checkbox-p)
15959 (call-interactively 'org-toggle-checkbox))
15960 ((org-at-item-p)
15961 (if arg
15962 (call-interactively 'org-toggle-checkbox)
15963 (call-interactively 'org-maybe-renumber-ordered-list)))
15964 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15965 ;; Dynamic block
15966 (beginning-of-line 1)
15967 (save-excursion (org-update-dblock)))
15968 ((save-excursion
15969 (beginning-of-line 1)
15970 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15971 (cond
15972 ((equal (match-string 1) "TBLFM")
15973 ;; Recalculate the table before this line
15974 (save-excursion
15975 (beginning-of-line 1)
15976 (skip-chars-backward " \r\n\t")
15977 (if (org-at-table-p)
15978 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15980 (let ((org-inhibit-startup-visibility-stuff t)
15981 (org-startup-align-all-tables nil))
15982 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15983 (message "Local setup has been refreshed"))))
15984 ((org-clock-update-time-maybe))
15985 (t (error "C-c C-c can do nothing useful at this location")))))
15987 (defun org-mode-restart ()
15988 "Restart Org-mode, to scan again for special lines.
15989 Also updates the keyword regular expressions."
15990 (interactive)
15991 (org-mode)
15992 (message "Org-mode restarted"))
15994 (defun org-kill-note-or-show-branches ()
15995 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15996 (interactive)
15997 (if (not org-finish-function)
15998 (call-interactively 'show-branches)
15999 (let ((org-note-abort t))
16000 (funcall org-finish-function))))
16002 (defun org-return (&optional indent)
16003 "Goto next table row or insert a newline.
16004 Calls `org-table-next-row' or `newline', depending on context.
16005 See the individual commands for more information."
16006 (interactive)
16007 (cond
16008 ((bobp) (if indent (newline-and-indent) (newline)))
16009 ((org-at-table-p)
16010 (org-table-justify-field-maybe)
16011 (call-interactively 'org-table-next-row))
16012 ((and org-return-follows-link
16013 (eq (get-text-property (point) 'face) 'org-link))
16014 (call-interactively 'org-open-at-point))
16015 ((and (org-at-heading-p)
16016 (looking-at
16017 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16018 (org-show-entry)
16019 (end-of-line 1)
16020 (newline))
16021 (t (if indent (newline-and-indent) (newline)))))
16023 (defun org-return-indent ()
16024 "Goto next table row or insert a newline and indent.
16025 Calls `org-table-next-row' or `newline-and-indent', depending on
16026 context. See the individual commands for more information."
16027 (interactive)
16028 (org-return t))
16030 (defun org-ctrl-c-star ()
16031 "Compute table, or change heading status of lines.
16032 Calls `org-table-recalculate' or `org-toggle-heading',
16033 depending on context."
16034 (interactive)
16035 (cond
16036 ((org-at-table-p)
16037 (call-interactively 'org-table-recalculate))
16039 ;; Convert all lines in region to list items
16040 (call-interactively 'org-toggle-heading))))
16042 (defun org-ctrl-c-minus ()
16043 "Insert separator line in table or modify bullet status of line.
16044 Also turns a plain line or a region of lines into list items.
16045 Calls `org-table-insert-hline', `org-toggle-item', or
16046 `org-cycle-list-bullet', depending on context."
16047 (interactive)
16048 (cond
16049 ((org-at-table-p)
16050 (call-interactively 'org-table-insert-hline))
16051 ((org-region-active-p)
16052 (call-interactively 'org-toggle-item))
16053 ((org-in-item-p)
16054 (call-interactively 'org-cycle-list-bullet))
16056 (call-interactively 'org-toggle-item))))
16058 (defun org-toggle-item ()
16059 "Convert headings or normal lines to items, items to normal lines.
16060 If there is no active region, only the current line is considered.
16062 If the first line in the region is a headline, convert all headlines to items.
16064 If the first line in the region is an item, convert all items to normal lines.
16066 If the first line is normal text, add an item bullet to each line."
16067 (interactive)
16068 (let (l2 l beg end)
16069 (if (org-region-active-p)
16070 (setq beg (region-beginning) end (region-end))
16071 (setq beg (point-at-bol)
16072 end (min (1+ (point-at-eol)) (point-max))))
16073 (save-excursion
16074 (goto-char end)
16075 (setq l2 (org-current-line))
16076 (goto-char beg)
16077 (beginning-of-line 1)
16078 (setq l (1- (org-current-line)))
16079 (if (org-at-item-p)
16080 ;; We already have items, de-itemize
16081 (while (< (setq l (1+ l)) l2)
16082 (when (org-at-item-p)
16083 (goto-char (match-beginning 2))
16084 (delete-region (match-beginning 2) (match-end 2))
16085 (and (looking-at "[ \t]+") (replace-match "")))
16086 (beginning-of-line 2))
16087 (if (org-on-heading-p)
16088 ;; Headings, convert to items
16089 (while (< (setq l (1+ l)) l2)
16090 (if (looking-at org-outline-regexp)
16091 (replace-match "- " t t))
16092 (beginning-of-line 2))
16093 ;; normal lines, turn them into items
16094 (while (< (setq l (1+ l)) l2)
16095 (unless (org-at-item-p)
16096 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16097 (replace-match "\\1- \\2")))
16098 (beginning-of-line 2)))))))
16100 (defun org-toggle-heading (&optional nstars)
16101 "Convert headings to normal text, or items or text to headings.
16102 If there is no active region, only the current line is considered.
16104 If the first line is a heading, remove the stars from all headlines
16105 in the region.
16107 If the first line is a plain list item, turn all plain list items
16108 into headings.
16110 If the first line is a normal line, turn each and every line in the
16111 region into a heading.
16113 When converting a line into a heading, the number of stars is chosen
16114 such that the lines become children of the current entry. However,
16115 when a prefix argument is given, its value determines the number of
16116 stars to add."
16117 (interactive "P")
16118 (let (l2 l itemp beg end)
16119 (if (org-region-active-p)
16120 (setq beg (region-beginning) end (region-end))
16121 (setq beg (point-at-bol)
16122 end (min (1+ (point-at-eol)) (point-max))))
16123 (save-excursion
16124 (goto-char end)
16125 (setq l2 (org-current-line))
16126 (goto-char beg)
16127 (beginning-of-line 1)
16128 (setq l (1- (org-current-line)))
16129 (if (org-on-heading-p)
16130 ;; We already have headlines, de-star them
16131 (while (< (setq l (1+ l)) l2)
16132 (when (org-on-heading-p t)
16133 (and (looking-at outline-regexp) (replace-match "")))
16134 (beginning-of-line 2))
16135 (setq itemp (org-at-item-p))
16136 (let* ((stars
16137 (if nstars
16138 (make-string (prefix-numeric-value current-prefix-arg)
16140 (save-excursion
16141 (if (re-search-backward org-complex-heading-regexp nil t)
16142 (match-string 1) ""))))
16143 (add-stars (cond (nstars "")
16144 ((equal stars "") "*")
16145 (org-odd-levels-only "**")
16146 (t "*")))
16147 (rpl (concat stars add-stars " ")))
16148 (while (< (setq l (1+ l)) l2)
16149 (if itemp
16150 (and (org-at-item-p) (replace-match rpl t t))
16151 (unless (org-on-heading-p)
16152 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16153 (replace-match (concat rpl (match-string 2))))))
16154 (beginning-of-line 2)))))))
16156 (defun org-meta-return (&optional arg)
16157 "Insert a new heading or wrap a region in a table.
16158 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16159 See the individual commands for more information."
16160 (interactive "P")
16161 (cond
16162 ((run-hook-with-args-until-success 'org-metareturn-hook))
16163 ((org-at-table-p)
16164 (call-interactively 'org-table-wrap-region))
16165 (t (call-interactively 'org-insert-heading))))
16167 ;;; Menu entries
16169 ;; Define the Org-mode menus
16170 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16171 '("Tbl"
16172 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16173 ["Next Field" org-cycle (org-at-table-p)]
16174 ["Previous Field" org-shifttab (org-at-table-p)]
16175 ["Next Row" org-return (org-at-table-p)]
16176 "--"
16177 ["Blank Field" org-table-blank-field (org-at-table-p)]
16178 ["Edit Field" org-table-edit-field (org-at-table-p)]
16179 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16180 "--"
16181 ("Column"
16182 ["Move Column Left" org-metaleft (org-at-table-p)]
16183 ["Move Column Right" org-metaright (org-at-table-p)]
16184 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16185 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16186 ("Row"
16187 ["Move Row Up" org-metaup (org-at-table-p)]
16188 ["Move Row Down" org-metadown (org-at-table-p)]
16189 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16190 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16191 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16192 "--"
16193 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16194 ("Rectangle"
16195 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16196 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16197 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16198 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16199 "--"
16200 ("Calculate"
16201 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16202 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16203 ["Edit Formulas" org-edit-special (org-at-table-p)]
16204 "--"
16205 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16206 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16207 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16208 "--"
16209 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16210 "--"
16211 ["Sum Column/Rectangle" org-table-sum
16212 (or (org-at-table-p) (org-region-active-p))]
16213 ["Which Column?" org-table-current-column (org-at-table-p)])
16214 ["Debug Formulas"
16215 org-table-toggle-formula-debugger
16216 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16217 ["Show Col/Row Numbers"
16218 org-table-toggle-coordinate-overlays
16219 :style toggle
16220 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16221 "--"
16222 ["Create" org-table-create (and (not (org-at-table-p))
16223 org-enable-table-editor)]
16224 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16225 ["Import from File" org-table-import (not (org-at-table-p))]
16226 ["Export to File" org-table-export (org-at-table-p)]
16227 "--"
16228 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16230 (easy-menu-define org-org-menu org-mode-map "Org menu"
16231 '("Org"
16232 ("Show/Hide"
16233 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16234 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16235 ["Sparse Tree..." org-sparse-tree t]
16236 ["Reveal Context" org-reveal t]
16237 ["Show All" show-all t]
16238 "--"
16239 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16240 "--"
16241 ["New Heading" org-insert-heading t]
16242 ("Navigate Headings"
16243 ["Up" outline-up-heading t]
16244 ["Next" outline-next-visible-heading t]
16245 ["Previous" outline-previous-visible-heading t]
16246 ["Next Same Level" outline-forward-same-level t]
16247 ["Previous Same Level" outline-backward-same-level t]
16248 "--"
16249 ["Jump" org-goto t])
16250 ("Edit Structure"
16251 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16252 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16253 "--"
16254 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16255 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16256 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16257 "--"
16258 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16259 "--"
16260 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16261 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16262 ["Demote Heading" org-metaright (not (org-at-table-p))]
16263 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16264 "--"
16265 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16266 "--"
16267 ["Convert to odd levels" org-convert-to-odd-levels t]
16268 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16269 ("Editing"
16270 ["Emphasis..." org-emphasize t]
16271 ["Edit Source Example" org-edit-special t]
16272 "--"
16273 ["Footnote new/jump" org-footnote-action t]
16274 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16275 ("Archive"
16276 ["Archive (default method)" org-archive-subtree-default t]
16277 "--"
16278 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16279 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16280 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16282 "--"
16283 ("Hyperlinks"
16284 ["Store Link (Global)" org-store-link t]
16285 ["Find existing link to here" org-occur-link-in-agenda-files t]
16286 ["Insert Link" org-insert-link t]
16287 ["Follow Link" org-open-at-point t]
16288 "--"
16289 ["Next link" org-next-link t]
16290 ["Previous link" org-previous-link t]
16291 "--"
16292 ["Descriptive Links"
16293 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16294 :style radio
16295 :selected (member '(org-link) buffer-invisibility-spec)]
16296 ["Literal Links"
16297 (progn
16298 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16299 :style radio
16300 :selected (not (member '(org-link) buffer-invisibility-spec))])
16301 "--"
16302 ("TODO Lists"
16303 ["TODO/DONE/-" org-todo t]
16304 ("Select keyword"
16305 ["Next keyword" org-shiftright (org-on-heading-p)]
16306 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16307 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16308 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16309 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16310 ["Show TODO Tree" org-show-todo-tree t]
16311 ["Global TODO list" org-todo-list t]
16312 "--"
16313 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16314 :selected org-enforce-todo-dependencies :style toggle :active t]
16315 "Settings for tree at point"
16316 ["Do Children sequentially" org-toggle-ordered-property :style radio
16317 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16318 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16319 ["Do Children parallel" org-toggle-ordered-property :style radio
16320 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16321 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16322 "--"
16323 ["Set Priority" org-priority t]
16324 ["Priority Up" org-shiftup t]
16325 ["Priority Down" org-shiftdown t]
16326 "--"
16327 ["Get news from all feeds" org-feed-update-all t]
16328 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16329 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16330 ("TAGS and Properties"
16331 ["Set Tags" org-set-tags-command t]
16332 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16333 "--"
16334 ["Set property" org-set-property t]
16335 ["Column view of properties" org-columns t]
16336 ["Insert Column View DBlock" org-insert-columns-dblock t])
16337 ("Dates and Scheduling"
16338 ["Timestamp" org-time-stamp t]
16339 ["Timestamp (inactive)" org-time-stamp-inactive t]
16340 ("Change Date"
16341 ["1 Day Later" org-shiftright t]
16342 ["1 Day Earlier" org-shiftleft t]
16343 ["1 ... Later" org-shiftup t]
16344 ["1 ... Earlier" org-shiftdown t])
16345 ["Compute Time Range" org-evaluate-time-range t]
16346 ["Schedule Item" org-schedule t]
16347 ["Deadline" org-deadline t]
16348 "--"
16349 ["Custom time format" org-toggle-time-stamp-overlays
16350 :style radio :selected org-display-custom-times]
16351 "--"
16352 ["Goto Calendar" org-goto-calendar t]
16353 ["Date from Calendar" org-date-from-calendar t]
16354 "--"
16355 ["Start/Restart Timer" org-timer-start t]
16356 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16357 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16358 ["Insert Timer String" org-timer t]
16359 ["Insert Timer Item" org-timer-item t])
16360 ("Logging work"
16361 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16362 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16363 ["Clock out" org-clock-out t]
16364 ["Clock cancel" org-clock-cancel t]
16365 "--"
16366 ["Mark as default task" org-clock-mark-default-task t]
16367 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16368 ["Goto running clock" org-clock-goto t]
16369 "--"
16370 ["Display times" org-clock-display t]
16371 ["Create clock table" org-clock-report t]
16372 "--"
16373 ["Record DONE time"
16374 (progn (setq org-log-done (not org-log-done))
16375 (message "Switching to %s will %s record a timestamp"
16376 (car org-done-keywords)
16377 (if org-log-done "automatically" "not")))
16378 :style toggle :selected org-log-done])
16379 "--"
16380 ["Agenda Command..." org-agenda t]
16381 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16382 ("File List for Agenda")
16383 ("Special views current file"
16384 ["TODO Tree" org-show-todo-tree t]
16385 ["Check Deadlines" org-check-deadlines t]
16386 ["Timeline" org-timeline t]
16387 ["Tags/Property tree" org-match-sparse-tree t])
16388 "--"
16389 ["Export/Publish..." org-export t]
16390 ("LaTeX"
16391 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16392 :selected org-cdlatex-mode]
16393 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16394 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16395 ["Modify math symbol" org-cdlatex-math-modify
16396 (org-inside-LaTeX-fragment-p)]
16397 ["Insert citation" org-reftex-citation t]
16398 "--"
16399 ["Export LaTeX fragments as images"
16400 (if (featurep 'org-exp)
16401 (setq org-export-with-LaTeX-fragments
16402 (not org-export-with-LaTeX-fragments))
16403 (require 'org-exp))
16404 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16405 org-export-with-LaTeX-fragments)]
16406 "--"
16407 ["Template for BEAMER" org-beamer-settings-template t])
16408 "--"
16409 ("MobileOrg"
16410 ["Push Files and Views" org-mobile-push t]
16411 ["Get Captured and Flagged" org-mobile-pull t]
16412 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16413 "--"
16414 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16415 "--"
16416 ("Documentation"
16417 ["Show Version" org-version t]
16418 ["Info Documentation" org-info t])
16419 ("Customize"
16420 ["Browse Org Group" org-customize t]
16421 "--"
16422 ["Expand This Menu" org-create-customize-menu
16423 (fboundp 'customize-menu-create)])
16424 ["Send bug report" org-submit-bug-report t]
16425 "--"
16426 ("Refresh/Reload"
16427 ["Refresh setup current buffer" org-mode-restart t]
16428 ["Reload Org (after update)" org-reload t]
16429 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16432 (defun org-info (&optional node)
16433 "Read documentation for Org-mode in the info system.
16434 With optional NODE, go directly to that node."
16435 (interactive)
16436 (info (format "(org)%s" (or node ""))))
16438 ;;;###autoload
16439 (defun org-submit-bug-report ()
16440 "Submit a bug report on Org-mode via mail.
16442 Don't hesitate to report any problems or inaccurate documentation.
16444 If you don't have setup sending mail from (X)Emacs, please copy the
16445 output buffer into your mail program, as it gives us important
16446 information about your Org-mode version and configuration."
16447 (interactive)
16448 (require 'reporter)
16449 (org-load-modules-maybe)
16450 (org-require-autoloaded-modules)
16451 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16452 (reporter-submit-bug-report
16453 "emacs-orgmode@gnu.org"
16454 (org-version)
16455 (let (list)
16456 (save-window-excursion
16457 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16458 (delete-other-windows)
16459 (erase-buffer)
16460 (insert "You are about to submit a bug report to the Org-mode mailing list.
16462 We would like to add your full Org-mode and Outline configuration to the
16463 bug report. This greatly simplifies the work of the maintainer and
16464 other experts on the mailing list.
16466 HOWEVER, some variables you have customized may contain private
16467 information. The names of customers, colleagues, or friends, might
16468 appear in the form of file names, tags, todo states, or search strings.
16469 If you answer yes to the prompt, you might want to check and remove
16470 such private information before sending the email.")
16471 (add-text-properties (point-min) (point-max) '(face org-warning))
16472 (when (yes-or-no-p "Include your Org-mode configuration ")
16473 (mapatoms
16474 (lambda (v)
16475 (and (boundp v)
16476 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16477 (or (and (symbol-value v)
16478 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16479 (and
16480 (get v 'custom-type) (get v 'standard-value)
16481 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16482 (push v list)))))
16483 (kill-buffer (get-buffer "*Warn about privacy*"))
16484 list))
16485 nil nil
16486 "Remember to cover the basics, that is, what you expected to happen and
16487 what in fact did happen. You don't know how to make a good report? See
16489 http://orgmode.org/manual/Feedback.html#Feedback
16491 Your bug report will be posted to the Org-mode mailing list.
16492 ------------------------------------------------------------------------")
16493 (save-excursion
16494 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16495 (replace-match "\\1Bug: \\3 [\\2]")))))
16498 (defun org-install-agenda-files-menu ()
16499 (let ((bl (buffer-list)))
16500 (save-excursion
16501 (while bl
16502 (set-buffer (pop bl))
16503 (if (org-mode-p) (setq bl nil)))
16504 (when (org-mode-p)
16505 (easy-menu-change
16506 '("Org") "File List for Agenda"
16507 (append
16508 (list
16509 ["Edit File List" (org-edit-agenda-file-list) t]
16510 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16511 ["Remove Current File from List" org-remove-file t]
16512 ["Cycle through agenda files" org-cycle-agenda-files t]
16513 ["Occur in all agenda files" org-occur-in-agenda-files t]
16514 "--")
16515 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16517 ;;;; Documentation
16519 ;;;###autoload
16520 (defun org-require-autoloaded-modules ()
16521 (interactive)
16522 (mapc 'require
16523 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16524 org-docbook org-exp org-html org-icalendar
16525 org-id org-latex
16526 org-publish org-remember org-table
16527 org-timer org-xoxo)))
16529 ;;;###autoload
16530 (defun org-reload (&optional uncompiled)
16531 "Reload all org lisp files.
16532 With prefix arg UNCOMPILED, load the uncompiled versions."
16533 (interactive "P")
16534 (require 'find-func)
16535 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16536 (dir-org (file-name-directory (org-find-library-name "org")))
16537 (dir-org-contrib (ignore-errors
16538 (file-name-directory
16539 (org-find-library-name "org-contribdir"))))
16540 (files
16541 (append (directory-files dir-org t file-re)
16542 (and dir-org-contrib
16543 (directory-files dir-org-contrib t file-re))))
16544 (remove-re (concat (if (featurep 'xemacs)
16545 "org-colview" "org-colview-xemacs")
16546 "\\'")))
16547 (setq files (mapcar 'file-name-sans-extension files))
16548 (setq files (mapcar
16549 (lambda (x) (if (string-match remove-re x) nil x))
16550 files))
16551 (setq files (delq nil files))
16552 (mapc
16553 (lambda (f)
16554 (when (featurep (intern (file-name-nondirectory f)))
16555 (if (and (not uncompiled)
16556 (file-exists-p (concat f ".elc")))
16557 (load (concat f ".elc") nil nil t)
16558 (load (concat f ".el") nil nil t))))
16559 files))
16560 (org-version))
16562 ;;;###autoload
16563 (defun org-customize ()
16564 "Call the customize function with org as argument."
16565 (interactive)
16566 (org-load-modules-maybe)
16567 (org-require-autoloaded-modules)
16568 (customize-browse 'org))
16570 (defun org-create-customize-menu ()
16571 "Create a full customization menu for Org-mode, insert it into the menu."
16572 (interactive)
16573 (org-load-modules-maybe)
16574 (org-require-autoloaded-modules)
16575 (if (fboundp 'customize-menu-create)
16576 (progn
16577 (easy-menu-change
16578 '("Org") "Customize"
16579 `(["Browse Org group" org-customize t]
16580 "--"
16581 ,(customize-menu-create 'org)
16582 ["Set" Custom-set t]
16583 ["Save" Custom-save t]
16584 ["Reset to Current" Custom-reset-current t]
16585 ["Reset to Saved" Custom-reset-saved t]
16586 ["Reset to Standard Settings" Custom-reset-standard t]))
16587 (message "\"Org\"-menu now contains full customization menu"))
16588 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16590 ;;;; Miscellaneous stuff
16592 ;;; Generally useful functions
16594 (defun org-get-at-bol (property)
16595 "Get text property PROPERTY at beginning of line."
16596 (get-text-property (point-at-bol) property))
16598 (defun org-find-text-property-in-string (prop s)
16599 "Return the first non-nil value of property PROP in string S."
16600 (or (get-text-property 0 prop s)
16601 (get-text-property (or (next-single-property-change 0 prop s) 0)
16602 prop s)))
16604 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16605 "Display the given MESSAGE as a warning."
16606 (if (fboundp 'display-warning)
16607 (display-warning 'org message
16608 (if (featurep 'xemacs)
16609 'warning
16610 :warning))
16611 (let ((buf (get-buffer-create "*Org warnings*")))
16612 (with-current-buffer buf
16613 (goto-char (point-max))
16614 (insert "Warning (Org): " message)
16615 (unless (bolp)
16616 (newline)))
16617 (display-buffer buf)
16618 (sit-for 0))))
16620 (defun org-in-commented-line ()
16621 "Is point in a line starting with `#'?"
16622 (equal (char-after (point-at-bol)) ?#))
16624 (defun org-in-verbatim-emphasis ()
16625 (save-match-data
16626 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16628 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16629 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16630 (if (and marker (marker-buffer marker)
16631 (buffer-live-p (marker-buffer marker)))
16632 (progn
16633 (switch-to-buffer (marker-buffer marker))
16634 (if (or (> marker (point-max)) (< marker (point-min)))
16635 (widen))
16636 (goto-char marker)
16637 (org-show-context 'org-goto))
16638 (if bookmark
16639 (bookmark-jump bookmark)
16640 (error "Cannot find location"))))
16642 (defun org-quote-csv-field (s)
16643 "Quote field for inclusion in CSV material."
16644 (if (string-match "[\",]" s)
16645 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16648 (defun org-plist-delete (plist property)
16649 "Delete PROPERTY from PLIST.
16650 This is in contrast to merely setting it to 0."
16651 (let (p)
16652 (while plist
16653 (if (not (eq property (car plist)))
16654 (setq p (plist-put p (car plist) (nth 1 plist))))
16655 (setq plist (cddr plist)))
16658 (defun org-force-self-insert (N)
16659 "Needed to enforce self-insert under remapping."
16660 (interactive "p")
16661 (self-insert-command N))
16663 (defun org-string-width (s)
16664 "Compute width of string, ignoring invisible characters.
16665 This ignores character with invisibility property `org-link', and also
16666 characters with property `org-cwidth', because these will become invisible
16667 upon the next fontification round."
16668 (let (b l)
16669 (when (or (eq t buffer-invisibility-spec)
16670 (assq 'org-link buffer-invisibility-spec))
16671 (while (setq b (text-property-any 0 (length s)
16672 'invisible 'org-link s))
16673 (setq s (concat (substring s 0 b)
16674 (substring s (or (next-single-property-change
16675 b 'invisible s) (length s)))))))
16676 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16677 (setq s (concat (substring s 0 b)
16678 (substring s (or (next-single-property-change
16679 b 'org-cwidth s) (length s))))))
16680 (setq l (string-width s) b -1)
16681 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16682 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16685 (defun org-get-indentation (&optional line)
16686 "Get the indentation of the current line, interpreting tabs.
16687 When LINE is given, assume it represents a line and compute its indentation."
16688 (if line
16689 (if (string-match "^ *" (org-remove-tabs line))
16690 (match-end 0))
16691 (save-excursion
16692 (beginning-of-line 1)
16693 (skip-chars-forward " \t")
16694 (current-column))))
16696 (defun org-remove-tabs (s &optional width)
16697 "Replace tabulators in S with spaces.
16698 Assumes that s is a single line, starting in column 0."
16699 (setq width (or width tab-width))
16700 (while (string-match "\t" s)
16701 (setq s (replace-match
16702 (make-string
16703 (- (* width (/ (+ (match-beginning 0) width) width))
16704 (match-beginning 0)) ?\ )
16705 t t s)))
16708 (defun org-fix-indentation (line ind)
16709 "Fix indentation in LINE.
16710 IND is a cons cell with target and minimum indentation.
16711 If the current indentation in LINE is smaller than the minimum,
16712 leave it alone. If it is larger than ind, set it to the target."
16713 (let* ((l (org-remove-tabs line))
16714 (i (org-get-indentation l))
16715 (i1 (car ind)) (i2 (cdr ind)))
16716 (if (>= i i2) (setq l (substring line i2)))
16717 (if (> i1 0)
16718 (concat (make-string i1 ?\ ) l)
16719 l)))
16721 (defun org-remove-indentation (code &optional n)
16722 "Remove the maximum common indentation from the lines in CODE.
16723 N may optionally be the number of spaces to remove."
16724 (with-temp-buffer
16725 (insert code)
16726 (org-do-remove-indentation n)
16727 (buffer-string)))
16729 (defun org-do-remove-indentation (&optional n)
16730 "Remove the maximum common indentation from the buffer."
16731 (untabify (point-min) (point-max))
16732 (let ((min 10000) re)
16733 (if n
16734 (setq min n)
16735 (goto-char (point-min))
16736 (while (re-search-forward "^ *[^ \n]" nil t)
16737 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16738 (unless (or (= min 0) (= min 10000))
16739 (setq re (format "^ \\{%d\\}" min))
16740 (goto-char (point-min))
16741 (while (re-search-forward re nil t)
16742 (replace-match "")
16743 (end-of-line 1))
16744 min)))
16746 (defun org-fill-template (template alist)
16747 "Find each %key of ALIST in TEMPLATE and replace it."
16748 (let ((case-fold-search nil)
16749 entry key value)
16750 (setq alist (sort (copy-sequence alist)
16751 (lambda (a b) (< (length (car a)) (length (car b))))))
16752 (while (setq entry (pop alist))
16753 (setq template
16754 (replace-regexp-in-string
16755 (concat "%" (regexp-quote (car entry)))
16756 (cdr entry) template t t)))
16757 template))
16759 (defun org-base-buffer (buffer)
16760 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16761 (if (not buffer)
16762 buffer
16763 (or (buffer-base-buffer buffer)
16764 buffer)))
16766 (defun org-trim (s)
16767 "Remove whitespace at beginning and end of string."
16768 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16769 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16772 (defun org-wrap (string &optional width lines)
16773 "Wrap string to either a number of lines, or a width in characters.
16774 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16775 that costs. If there is a word longer than WIDTH, the text is actually
16776 wrapped to the length of that word.
16777 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16778 many lines, whatever width that takes.
16779 The return value is a list of lines, without newlines at the end."
16780 (let* ((words (org-split-string string "[ \t\n]+"))
16781 (maxword (apply 'max (mapcar 'org-string-width words)))
16782 w ll)
16783 (cond (width
16784 (org-do-wrap words (max maxword width)))
16785 (lines
16786 (setq w maxword)
16787 (setq ll (org-do-wrap words maxword))
16788 (if (<= (length ll) lines)
16790 (setq ll words)
16791 (while (> (length ll) lines)
16792 (setq w (1+ w))
16793 (setq ll (org-do-wrap words w)))
16794 ll))
16795 (t (error "Cannot wrap this")))))
16797 (defun org-do-wrap (words width)
16798 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16799 (let (lines line)
16800 (while words
16801 (setq line (pop words))
16802 (while (and words (< (+ (length line) (length (car words))) width))
16803 (setq line (concat line " " (pop words))))
16804 (setq lines (push line lines)))
16805 (nreverse lines)))
16807 (defun org-split-string (string &optional separators)
16808 "Splits STRING into substrings at SEPARATORS.
16809 No empty strings are returned if there are matches at the beginning
16810 and end of string."
16811 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16812 (start 0)
16813 notfirst
16814 (list nil))
16815 (while (and (string-match rexp string
16816 (if (and notfirst
16817 (= start (match-beginning 0))
16818 (< start (length string)))
16819 (1+ start) start))
16820 (< (match-beginning 0) (length string)))
16821 (setq notfirst t)
16822 (or (eq (match-beginning 0) 0)
16823 (and (eq (match-beginning 0) (match-end 0))
16824 (eq (match-beginning 0) start))
16825 (setq list
16826 (cons (substring string start (match-beginning 0))
16827 list)))
16828 (setq start (match-end 0)))
16829 (or (eq start (length string))
16830 (setq list
16831 (cons (substring string start)
16832 list)))
16833 (nreverse list)))
16835 (defun org-quote-vert (s)
16836 "Replace \"|\" with \"\\vert\"."
16837 (while (string-match "|" s)
16838 (setq s (replace-match "\\vert" t t s)))
16841 (defun org-uuidgen-p (s)
16842 "Is S an ID created by UUIDGEN?"
16843 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16845 (defun org-context ()
16846 "Return a list of contexts of the current cursor position.
16847 If several contexts apply, all are returned.
16848 Each context entry is a list with a symbol naming the context, and
16849 two positions indicating start and end of the context. Possible
16850 contexts are:
16852 :headline anywhere in a headline
16853 :headline-stars on the leading stars in a headline
16854 :todo-keyword on a TODO keyword (including DONE) in a headline
16855 :tags on the TAGS in a headline
16856 :priority on the priority cookie in a headline
16857 :item on the first line of a plain list item
16858 :item-bullet on the bullet/number of a plain list item
16859 :checkbox on the checkbox in a plain list item
16860 :table in an org-mode table
16861 :table-special on a special filed in a table
16862 :table-table in a table.el table
16863 :link on a hyperlink
16864 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16865 :target on a <<target>>
16866 :radio-target on a <<<radio-target>>>
16867 :latex-fragment on a LaTeX fragment
16868 :latex-preview on a LaTeX fragment with overlayed preview image
16870 This function expects the position to be visible because it uses font-lock
16871 faces as a help to recognize the following contexts: :table-special, :link,
16872 and :keyword."
16873 (let* ((f (get-text-property (point) 'face))
16874 (faces (if (listp f) f (list f)))
16875 (p (point)) clist o)
16876 ;; First the large context
16877 (cond
16878 ((org-on-heading-p t)
16879 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16880 (when (progn
16881 (beginning-of-line 1)
16882 (looking-at org-todo-line-tags-regexp))
16883 (push (org-point-in-group p 1 :headline-stars) clist)
16884 (push (org-point-in-group p 2 :todo-keyword) clist)
16885 (push (org-point-in-group p 4 :tags) clist))
16886 (goto-char p)
16887 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16888 (if (looking-at "\\[#[A-Z0-9]\\]")
16889 (push (org-point-in-group p 0 :priority) clist)))
16891 ((org-at-item-p)
16892 (push (org-point-in-group p 2 :item-bullet) clist)
16893 (push (list :item (point-at-bol)
16894 (save-excursion (org-end-of-item) (point)))
16895 clist)
16896 (and (org-at-item-checkbox-p)
16897 (push (org-point-in-group p 0 :checkbox) clist)))
16899 ((org-at-table-p)
16900 (push (list :table (org-table-begin) (org-table-end)) clist)
16901 (if (memq 'org-formula faces)
16902 (push (list :table-special
16903 (previous-single-property-change p 'face)
16904 (next-single-property-change p 'face)) clist)))
16905 ((org-at-table-p 'any)
16906 (push (list :table-table) clist)))
16907 (goto-char p)
16909 ;; Now the small context
16910 (cond
16911 ((org-at-timestamp-p)
16912 (push (org-point-in-group p 0 :timestamp) clist))
16913 ((memq 'org-link faces)
16914 (push (list :link
16915 (previous-single-property-change p 'face)
16916 (next-single-property-change p 'face)) clist))
16917 ((memq 'org-special-keyword faces)
16918 (push (list :keyword
16919 (previous-single-property-change p 'face)
16920 (next-single-property-change p 'face)) clist))
16921 ((org-on-target-p)
16922 (push (org-point-in-group p 0 :target) clist)
16923 (goto-char (1- (match-beginning 0)))
16924 (if (looking-at org-radio-target-regexp)
16925 (push (org-point-in-group p 0 :radio-target) clist))
16926 (goto-char p))
16927 ((setq o (car (delq nil
16928 (mapcar
16929 (lambda (x)
16930 (if (memq x org-latex-fragment-image-overlays) x))
16931 (org-overlays-at (point))))))
16932 (push (list :latex-fragment
16933 (org-overlay-start o) (org-overlay-end o)) clist)
16934 (push (list :latex-preview
16935 (org-overlay-start o) (org-overlay-end o)) clist))
16936 ((org-inside-LaTeX-fragment-p)
16937 ;; FIXME: positions wrong.
16938 (push (list :latex-fragment (point) (point)) clist)))
16940 (setq clist (nreverse (delq nil clist)))
16941 clist))
16943 ;; FIXME: Compare with at-regexp-p Do we need both?
16944 (defun org-in-regexp (re &optional nlines visually)
16945 "Check if point is inside a match of regexp.
16946 Normally only the current line is checked, but you can include NLINES extra
16947 lines both before and after point into the search.
16948 If VISUALLY is set, require that the cursor is not after the match but
16949 really on, so that the block visually is on the match."
16950 (catch 'exit
16951 (let ((pos (point))
16952 (eol (point-at-eol (+ 1 (or nlines 0))))
16953 (inc (if visually 1 0)))
16954 (save-excursion
16955 (beginning-of-line (- 1 (or nlines 0)))
16956 (while (re-search-forward re eol t)
16957 (if (and (<= (match-beginning 0) pos)
16958 (>= (+ inc (match-end 0)) pos))
16959 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16961 (defun org-at-regexp-p (regexp)
16962 "Is point inside a match of REGEXP in the current line?"
16963 (catch 'exit
16964 (save-excursion
16965 (let ((pos (point)) (end (point-at-eol)))
16966 (beginning-of-line 1)
16967 (while (re-search-forward regexp end t)
16968 (if (and (<= (match-beginning 0) pos)
16969 (>= (match-end 0) pos))
16970 (throw 'exit t)))
16971 nil))))
16973 (defun org-occur-in-agenda-files (regexp &optional nlines)
16974 "Call `multi-occur' with buffers for all agenda files."
16975 (interactive "sOrg-files matching: \np")
16976 (let* ((files (org-agenda-files))
16977 (tnames (mapcar 'file-truename files))
16978 (extra org-agenda-text-search-extra-files)
16980 (when (eq (car extra) 'agenda-archives)
16981 (setq extra (cdr extra))
16982 (setq files (org-add-archive-files files)))
16983 (while (setq f (pop extra))
16984 (unless (member (file-truename f) tnames)
16985 (add-to-list 'files f 'append)
16986 (add-to-list 'tnames (file-truename f) 'append)))
16987 (multi-occur
16988 (mapcar (lambda (x)
16989 (with-current-buffer
16990 (or (get-file-buffer x) (find-file-noselect x))
16991 (widen)
16992 (current-buffer)))
16993 files)
16994 regexp)))
16996 (if (boundp 'occur-mode-find-occurrence-hook)
16997 ;; Emacs 23
16998 (add-hook 'occur-mode-find-occurrence-hook
16999 (lambda ()
17000 (when (org-mode-p)
17001 (org-reveal))))
17002 ;; Emacs 22
17003 (defadvice occur-mode-goto-occurrence
17004 (after org-occur-reveal activate)
17005 (and (org-mode-p) (org-reveal)))
17006 (defadvice occur-mode-goto-occurrence-other-window
17007 (after org-occur-reveal activate)
17008 (and (org-mode-p) (org-reveal)))
17009 (defadvice occur-mode-display-occurrence
17010 (after org-occur-reveal activate)
17011 (when (org-mode-p)
17012 (let ((pos (occur-mode-find-occurrence)))
17013 (with-current-buffer (marker-buffer pos)
17014 (save-excursion
17015 (goto-char pos)
17016 (org-reveal)))))))
17018 (defun org-occur-link-in-agenda-files ()
17019 "Create a link and search for it in the agendas.
17020 The link is not stored in `org-stored-links', it is just created
17021 for the search purpose."
17022 (interactive)
17023 (let ((link (condition-case nil
17024 (org-store-link nil)
17025 (error "Unable to create a link to here"))))
17026 (org-occur-in-agenda-files (regexp-quote link))))
17028 (defun org-uniquify (list)
17029 "Remove duplicate elements from LIST."
17030 (let (res)
17031 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17032 res))
17034 (defun org-delete-all (elts list)
17035 "Remove all elements in ELTS from LIST."
17036 (while elts
17037 (setq list (delete (pop elts) list)))
17038 list)
17040 (defun org-back-over-empty-lines ()
17041 "Move backwards over whitespace, to the beginning of the first empty line.
17042 Returns the number of empty lines passed."
17043 (let ((pos (point)))
17044 (skip-chars-backward " \t\n\r")
17045 (beginning-of-line 2)
17046 (goto-char (min (point) pos))
17047 (count-lines (point) pos)))
17049 (defun org-skip-whitespace ()
17050 (skip-chars-forward " \t\n\r"))
17052 (defun org-point-in-group (point group &optional context)
17053 "Check if POINT is in match-group GROUP.
17054 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17055 match. If the match group does ot exist or point is not inside it,
17056 return nil."
17057 (and (match-beginning group)
17058 (>= point (match-beginning group))
17059 (<= point (match-end group))
17060 (if context
17061 (list context (match-beginning group) (match-end group))
17062 t)))
17064 (defun org-switch-to-buffer-other-window (&rest args)
17065 "Switch to buffer in a second window on the current frame.
17066 In particular, do not allow pop-up frames."
17067 (let (pop-up-frames special-display-buffer-names special-display-regexps
17068 special-display-function)
17069 (apply 'switch-to-buffer-other-window args)))
17071 (defun org-combine-plists (&rest plists)
17072 "Create a single property list from all plists in PLISTS.
17073 The process starts by copying the first list, and then setting properties
17074 from the other lists. Settings in the last list are the most significant
17075 ones and overrule settings in the other lists."
17076 (let ((rtn (copy-sequence (pop plists)))
17077 p v ls)
17078 (while plists
17079 (setq ls (pop plists))
17080 (while ls
17081 (setq p (pop ls) v (pop ls))
17082 (setq rtn (plist-put rtn p v))))
17083 rtn))
17085 (defun org-move-line-down (arg)
17086 "Move the current line down. With prefix argument, move it past ARG lines."
17087 (interactive "p")
17088 (let ((col (current-column))
17089 beg end pos)
17090 (beginning-of-line 1) (setq beg (point))
17091 (beginning-of-line 2) (setq end (point))
17092 (beginning-of-line (+ 1 arg))
17093 (setq pos (move-marker (make-marker) (point)))
17094 (insert (delete-and-extract-region beg end))
17095 (goto-char pos)
17096 (org-move-to-column col)))
17098 (defun org-move-line-up (arg)
17099 "Move the current line up. With prefix argument, move it past ARG lines."
17100 (interactive "p")
17101 (let ((col (current-column))
17102 beg end pos)
17103 (beginning-of-line 1) (setq beg (point))
17104 (beginning-of-line 2) (setq end (point))
17105 (beginning-of-line (- arg))
17106 (setq pos (move-marker (make-marker) (point)))
17107 (insert (delete-and-extract-region beg end))
17108 (goto-char pos)
17109 (org-move-to-column col)))
17111 (defun org-replace-escapes (string table)
17112 "Replace %-escapes in STRING with values in TABLE.
17113 TABLE is an association list with keys like \"%a\" and string values.
17114 The sequences in STRING may contain normal field width and padding information,
17115 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17116 so values can contain further %-escapes if they are define later in TABLE."
17117 (let ((case-fold-search nil)
17118 e re rpl)
17119 (while (setq e (pop table))
17120 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17121 (while (string-match re string)
17122 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17123 (cdr e)))
17124 (setq string (replace-match rpl t t string))))
17125 string))
17128 (defun org-sublist (list start end)
17129 "Return a section of LIST, from START to END.
17130 Counting starts at 1."
17131 (let (rtn (c start))
17132 (setq list (nthcdr (1- start) list))
17133 (while (and list (<= c end))
17134 (push (pop list) rtn)
17135 (setq c (1+ c)))
17136 (nreverse rtn)))
17138 (defun org-find-base-buffer-visiting (file)
17139 "Like `find-buffer-visiting' but always return the base buffer and
17140 not an indirect buffer."
17141 (let ((buf (or (get-file-buffer file)
17142 (find-buffer-visiting file))))
17143 (if buf
17144 (or (buffer-base-buffer buf) buf)
17145 nil)))
17147 (defun org-image-file-name-regexp (&optional extensions)
17148 "Return regexp matching the file names of images.
17149 If EXTENSIONS is given, only match these."
17150 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17151 (image-file-name-regexp)
17152 (let ((image-file-name-extensions
17153 (or extensions
17154 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17155 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17156 (concat "\\."
17157 (regexp-opt (nconc (mapcar 'upcase
17158 image-file-name-extensions)
17159 image-file-name-extensions)
17161 "\\'"))))
17163 (defun org-file-image-p (file &optional extensions)
17164 "Return non-nil if FILE is an image."
17165 (save-match-data
17166 (string-match (org-image-file-name-regexp extensions) file)))
17168 (defun org-get-cursor-date ()
17169 "Return the date at cursor in as a time.
17170 This works in the calendar and in the agenda, anywhere else it just
17171 returns the current time."
17172 (let (date day defd)
17173 (cond
17174 ((eq major-mode 'calendar-mode)
17175 (setq date (calendar-cursor-to-date)
17176 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17177 ((eq major-mode 'org-agenda-mode)
17178 (setq day (get-text-property (point) 'day))
17179 (if day
17180 (setq date (calendar-gregorian-from-absolute day)
17181 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17182 (nth 2 date))))))
17183 (or defd (current-time))))
17185 (defvar org-agenda-action-marker (make-marker)
17186 "Marker pointing to the entry for the next agenda action.")
17188 (defun org-mark-entry-for-agenda-action ()
17189 "Mark the current entry as target of an agenda action.
17190 Agenda actions are actions executed from the agenda with the key `k',
17191 which make use of the date at the cursor."
17192 (interactive)
17193 (move-marker org-agenda-action-marker
17194 (save-excursion (org-back-to-heading t) (point))
17195 (current-buffer))
17196 (message
17197 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17199 ;;; Paragraph filling stuff.
17200 ;; We want this to be just right, so use the full arsenal.
17202 (defun org-indent-line-function ()
17203 "Indent line like previous, but further if previous was headline or item."
17204 (interactive)
17205 (let* ((pos (point))
17206 (itemp (org-at-item-p))
17207 (case-fold-search t)
17208 (org-drawer-regexp (or org-drawer-regexp "\000"))
17209 column bpos bcol tpos tcol bullet btype bullet-type)
17210 ;; Find the previous relevant line
17211 (beginning-of-line 1)
17212 (cond
17213 ((looking-at "#") (setq column 0))
17214 ((looking-at "\\*+ ") (setq column 0))
17215 ((and (looking-at "[ \t]*:END:")
17216 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17217 (save-excursion
17218 (goto-char (1- (match-beginning 1)))
17219 (setq column (current-column))))
17220 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17221 (save-excursion
17222 (re-search-backward
17223 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17224 (setq column (org-get-indentation (match-string 0))))
17226 (beginning-of-line 0)
17227 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17228 (not (looking-at "[ \t]*:END:"))
17229 (not (looking-at org-drawer-regexp)))
17230 (beginning-of-line 0))
17231 (cond
17232 ((looking-at "\\*+[ \t]+")
17233 (if (not org-adapt-indentation)
17234 (setq column 0)
17235 (goto-char (match-end 0))
17236 (setq column (current-column))))
17237 ((looking-at org-drawer-regexp)
17238 (goto-char (1- (match-beginning 1)))
17239 (setq column (current-column)))
17240 ((looking-at "\\([ \t]*\\):END:")
17241 (goto-char (match-end 1))
17242 (setq column (current-column)))
17243 ((org-in-item-p)
17244 (org-beginning-of-item)
17245 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17246 (setq bpos (match-beginning 1) tpos (match-end 0)
17247 bcol (progn (goto-char bpos) (current-column))
17248 tcol (progn (goto-char tpos) (current-column))
17249 bullet (match-string 1)
17250 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17251 (if (> tcol (+ bcol org-description-max-indent))
17252 (setq tcol (+ bcol 5)))
17253 (if (not itemp)
17254 (setq column tcol)
17255 (goto-char pos)
17256 (beginning-of-line 1)
17257 (if (looking-at "\\S-")
17258 (progn
17259 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17260 (setq bullet (match-string 1)
17261 btype (if (string-match "[0-9]" bullet) "n" bullet))
17262 (setq column (if (equal btype bullet-type) bcol tcol)))
17263 (setq column (org-get-indentation)))))
17264 (t (setq column (org-get-indentation))))))
17265 (goto-char pos)
17266 (if (<= (current-column) (current-indentation))
17267 (org-indent-line-to column)
17268 (save-excursion (org-indent-line-to column)))
17269 (setq column (current-column))
17270 (beginning-of-line 1)
17271 (if (looking-at
17272 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17273 (replace-match (concat (match-string 1)
17274 (format org-property-format
17275 (match-string 2) (match-string 3)))
17276 t t))
17277 (org-move-to-column column)))
17279 (defun org-set-autofill-regexps ()
17280 (interactive)
17281 ;; In the paragraph separator we include headlines, because filling
17282 ;; text in a line directly attached to a headline would otherwise
17283 ;; fill the headline as well.
17284 (org-set-local 'comment-start-skip "^#+[ \t]*")
17285 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17286 ;; The paragraph starter includes hand-formatted lists.
17287 (org-set-local
17288 'paragraph-start
17289 (concat
17290 "\f" "\\|"
17291 "[ ]*$" "\\|"
17292 "\\*+ " "\\|"
17293 "[ \t]*#" "\\|"
17294 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17295 "[ \t]*[:|]" "\\|"
17296 "\\$\\$" "\\|"
17297 "\\\\\\(begin\\|end\\|[][]\\)"))
17298 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17299 ;; But only if the user has not turned off tables or fixed-width regions
17300 (org-set-local
17301 'auto-fill-inhibit-regexp
17302 (concat "\\*+ \\|#\\+"
17303 "\\|[ \t]*" org-keyword-time-regexp
17304 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17305 (concat
17306 "\\|[ \t]*["
17307 (if org-enable-table-editor "|" "")
17308 (if org-enable-fixed-width-editor ":" "")
17309 "]"))))
17310 ;; We use our own fill-paragraph function, to make sure that tables
17311 ;; and fixed-width regions are not wrapped. That function will pass
17312 ;; through to `fill-paragraph' when appropriate.
17313 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17314 ; Adaptive filling: To get full control, first make sure that
17315 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17316 (org-set-local 'adaptive-fill-regexp "\000")
17317 (org-set-local 'adaptive-fill-function
17318 'org-adaptive-fill-function)
17319 (org-set-local
17320 'align-mode-rules-list
17321 '((org-in-buffer-settings
17322 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17323 (modes . '(org-mode))))))
17325 (defun org-fill-paragraph (&optional justify)
17326 "Re-align a table, pass through to fill-paragraph if no table."
17327 (let ((table-p (org-at-table-p))
17328 (table.el-p (org-at-table.el-p)))
17329 (cond ((and (equal (char-after (point-at-bol)) ?*)
17330 (save-excursion (goto-char (point-at-bol))
17331 (looking-at outline-regexp)))
17332 t) ; skip headlines
17333 (table.el-p t) ; skip table.el tables
17334 (table-p (org-table-align) t) ; align org-mode tables
17335 (t nil)))) ; call paragraph-fill
17337 ;; For reference, this is the default value of adaptive-fill-regexp
17338 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17340 (defun org-adaptive-fill-function ()
17341 "Return a fill prefix for org-mode files.
17342 In particular, this makes sure hanging paragraphs for hand-formatted lists
17343 work correctly."
17344 (cond ((looking-at "#[ \t]+")
17345 (match-string 0))
17346 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17347 (save-excursion
17348 (if (> (match-end 1) (+ (match-beginning 1)
17349 org-description-max-indent))
17350 (goto-char (+ (match-beginning 1) 5))
17351 (goto-char (match-end 0)))
17352 (make-string (current-column) ?\ )))
17353 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17354 (save-excursion
17355 (goto-char (match-end 0))
17356 (make-string (current-column) ?\ )))
17357 (t nil)))
17359 ;;; Other stuff.
17361 (defun org-toggle-fixed-width-section (arg)
17362 "Toggle the fixed-width export.
17363 If there is no active region, the QUOTE keyword at the current headline is
17364 inserted or removed. When present, it causes the text between this headline
17365 and the next to be exported as fixed-width text, and unmodified.
17366 If there is an active region, this command adds or removes a colon as the
17367 first character of this line. If the first character of a line is a colon,
17368 this line is also exported in fixed-width font."
17369 (interactive "P")
17370 (let* ((cc 0)
17371 (regionp (org-region-active-p))
17372 (beg (if regionp (region-beginning) (point)))
17373 (end (if regionp (region-end)))
17374 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17375 (case-fold-search nil)
17376 (re "[ \t]*\\(: \\)")
17377 off)
17378 (if regionp
17379 (save-excursion
17380 (goto-char beg)
17381 (setq cc (current-column))
17382 (beginning-of-line 1)
17383 (setq off (looking-at re))
17384 (while (> nlines 0)
17385 (setq nlines (1- nlines))
17386 (beginning-of-line 1)
17387 (cond
17388 (arg
17389 (org-move-to-column cc t)
17390 (insert ": \n")
17391 (forward-line -1))
17392 ((and off (looking-at re))
17393 (replace-match "" t t nil 1))
17394 ((not off) (org-move-to-column cc t) (insert ": ")))
17395 (forward-line 1)))
17396 (save-excursion
17397 (org-back-to-heading)
17398 (if (looking-at (concat outline-regexp
17399 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17400 (replace-match "" t t nil 1)
17401 (if (looking-at outline-regexp)
17402 (progn
17403 (goto-char (match-end 0))
17404 (insert org-quote-string " "))))))))
17406 (defun org-reftex-citation ()
17407 "Use reftex-citation to insert a citation into the buffer.
17408 This looks for a line like
17410 #+BIBLIOGRAPHY: foo plain option:-d
17412 and derives from it that foo.bib is the bibliography file relevant
17413 for this document. It then installs the necessary environment for RefTeX
17414 to work in this buffer and calls `reftex-citation' to insert a citation
17415 into the buffer.
17417 Export of such citations to both LaTeX and HTML is handled by the contributed
17418 package org-exp-bibtex by Taru Karttunen."
17419 (interactive)
17420 (let ((reftex-docstruct-symbol 'rds)
17421 (reftex-cite-format "\\cite{%l}")
17422 rds bib)
17423 (save-excursion
17424 (save-restriction
17425 (widen)
17426 (let ((case-fold-search t)
17427 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17428 (if (not (save-excursion
17429 (or (re-search-forward re nil t)
17430 (re-search-backward re nil t))))
17431 (error "No bibliography defined in file")
17432 (setq bib (concat (match-string 1) ".bib")
17433 rds (list (list 'bib bib)))))))
17434 (call-interactively 'reftex-citation)))
17436 ;;;; Functions extending outline functionality
17438 (defun org-beginning-of-line (&optional arg)
17439 "Go to the beginning of the current line. If that is invisible, continue
17440 to a visible line beginning. This makes the function of C-a more intuitive.
17441 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17442 first attempt, and only move to after the tags when the cursor is already
17443 beyond the end of the headline."
17444 (interactive "P")
17445 (let ((pos (point))
17446 (special (if (consp org-special-ctrl-a/e)
17447 (car org-special-ctrl-a/e)
17448 org-special-ctrl-a/e))
17449 refpos)
17450 (if (org-bound-and-true-p line-move-visual)
17451 (beginning-of-visual-line 1)
17452 (beginning-of-line 1))
17453 (if (and arg (fboundp 'move-beginning-of-line))
17454 (call-interactively 'move-beginning-of-line)
17455 (if (bobp)
17457 (backward-char 1)
17458 (if (org-invisible-p)
17459 (while (and (not (bobp)) (org-invisible-p))
17460 (backward-char 1)
17461 (beginning-of-line 1))
17462 (forward-char 1))))
17463 (when special
17464 (cond
17465 ((and (looking-at org-complex-heading-regexp)
17466 (= (char-after (match-end 1)) ?\ ))
17467 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17468 (point-at-eol)))
17469 (goto-char
17470 (if (eq special t)
17471 (cond ((> pos refpos) refpos)
17472 ((= pos (point)) refpos)
17473 (t (point)))
17474 (cond ((> pos (point)) (point))
17475 ((not (eq last-command this-command)) (point))
17476 (t refpos)))))
17477 ((org-at-item-p)
17478 (goto-char
17479 (if (eq special t)
17480 (cond ((> pos (match-end 4)) (match-end 4))
17481 ((= pos (point)) (match-end 4))
17482 (t (point)))
17483 (cond ((> pos (point)) (point))
17484 ((not (eq last-command this-command)) (point))
17485 (t (match-end 4))))))))
17486 (org-no-warnings
17487 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17489 (defun org-end-of-line (&optional arg)
17490 "Go to the end of the line.
17491 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17492 first attempt, and only move to after the tags when the cursor is already
17493 beyond the end of the headline."
17494 (interactive "P")
17495 (let ((special (if (consp org-special-ctrl-a/e)
17496 (cdr org-special-ctrl-a/e)
17497 org-special-ctrl-a/e)))
17498 (if (or (not special)
17499 (not (org-on-heading-p))
17500 arg)
17501 (call-interactively
17502 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17503 ((fboundp 'move-end-of-line) 'move-end-of-line)
17504 (t 'end-of-line)))
17505 (let ((pos (point)))
17506 (beginning-of-line 1)
17507 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17508 (if (eq special t)
17509 (if (or (< pos (match-beginning 1))
17510 (= pos (match-end 0)))
17511 (goto-char (match-beginning 1))
17512 (goto-char (match-end 0)))
17513 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17514 (goto-char (match-end 0))
17515 (goto-char (match-beginning 1))))
17516 (call-interactively (if (fboundp 'move-end-of-line)
17517 'move-end-of-line
17518 'end-of-line)))))
17519 (org-no-warnings
17520 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17522 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17523 (define-key org-mode-map "\C-e" 'org-end-of-line)
17524 (define-key org-mode-map [home] 'org-beginning-of-line)
17525 (define-key org-mode-map [end] 'org-end-of-line)
17527 (defun org-backward-sentence (&optional arg)
17528 "Go to beginning of sentence, or beginning of table field.
17529 This will call `backward-sentence' or `org-table-beginning-of-field',
17530 depending on context."
17531 (interactive "P")
17532 (cond
17533 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17534 (t (call-interactively 'backward-sentence))))
17536 (defun org-forward-sentence (&optional arg)
17537 "Go to end of sentence, or end of table field.
17538 This will call `forward-sentence' or `org-table-end-of-field',
17539 depending on context."
17540 (interactive "P")
17541 (cond
17542 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17543 (t (call-interactively 'forward-sentence))))
17545 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17546 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17548 (defun org-kill-line (&optional arg)
17549 "Kill line, to tags or end of line."
17550 (interactive "P")
17551 (cond
17552 ((or (not org-special-ctrl-k)
17553 (bolp)
17554 (not (org-on-heading-p)))
17555 (call-interactively 'kill-line))
17556 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17557 (kill-region (point) (match-beginning 1))
17558 (org-set-tags nil t))
17559 (t (kill-region (point) (point-at-eol)))))
17561 (define-key org-mode-map "\C-k" 'org-kill-line)
17563 (defun org-yank (&optional arg)
17564 "Yank. If the kill is a subtree, treat it specially.
17565 This command will look at the current kill and check if is a single
17566 subtree, or a series of subtrees[1]. If it passes the test, and if the
17567 cursor is at the beginning of a line or after the stars of a currently
17568 empty headline, then the yank is handled specially. How exactly depends
17569 on the value of the following variables, both set by default.
17571 org-yank-folded-subtrees
17572 When set, the subtree(s) will be folded after insertion, but only
17573 if doing so would now swallow text after the yanked text.
17575 org-yank-adjusted-subtrees
17576 When set, the subtree will be promoted or demoted in order to
17577 fit into the local outline tree structure, which means that the level
17578 will be adjusted so that it becomes the smaller one of the two
17579 *visible* surrounding headings.
17581 Any prefix to this command will cause `yank' to be called directly with
17582 no special treatment. In particular, a simple `C-u' prefix will just
17583 plainly yank the text as it is.
17585 \[1] The test checks if the first non-white line is a heading
17586 and if there are no other headings with fewer stars."
17587 (interactive "P")
17588 (org-yank-generic 'yank arg))
17590 (defun org-yank-generic (command arg)
17591 "Perform some yank-like command.
17593 This function implements the behavior described in the `org-yank'
17594 documentation. However, it has been generalized to work for any
17595 interactive command with similar behavior."
17597 ;; pretend to be command COMMAND
17598 (setq this-command command)
17600 (if arg
17601 (call-interactively command)
17603 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17604 (and (org-kill-is-subtree-p)
17605 (or (bolp)
17606 (and (looking-at "[ \t]*$")
17607 (string-match
17608 "\\`\\*+\\'"
17609 (buffer-substring (point-at-bol) (point)))))))
17610 swallowp)
17611 (cond
17612 ((and subtreep org-yank-folded-subtrees)
17613 (let ((beg (point))
17614 end)
17615 (if (and subtreep org-yank-adjusted-subtrees)
17616 (org-paste-subtree nil nil 'for-yank)
17617 (call-interactively command))
17619 (setq end (point))
17620 (goto-char beg)
17621 (when (and (bolp) subtreep
17622 (not (setq swallowp
17623 (org-yank-folding-would-swallow-text beg end))))
17624 (or (looking-at outline-regexp)
17625 (re-search-forward (concat "^" outline-regexp) end t))
17626 (while (and (< (point) end) (looking-at outline-regexp))
17627 (hide-subtree)
17628 (org-cycle-show-empty-lines 'folded)
17629 (condition-case nil
17630 (outline-forward-same-level 1)
17631 (error (goto-char end)))))
17632 (when swallowp
17633 (message
17634 "Inserted text not folded because that would swallow text"))
17636 (goto-char end)
17637 (skip-chars-forward " \t\n\r")
17638 (beginning-of-line 1)
17639 (push-mark beg 'nomsg)))
17640 ((and subtreep org-yank-adjusted-subtrees)
17641 (let ((beg (point-at-bol)))
17642 (org-paste-subtree nil nil 'for-yank)
17643 (push-mark beg 'nomsg)))
17645 (call-interactively command))))))
17647 (defun org-yank-folding-would-swallow-text (beg end)
17648 "Would hide-subtree at BEG swallow any text after END?"
17649 (let (level)
17650 (save-excursion
17651 (goto-char beg)
17652 (when (or (looking-at outline-regexp)
17653 (re-search-forward (concat "^" outline-regexp) end t))
17654 (setq level (org-outline-level)))
17655 (goto-char end)
17656 (skip-chars-forward " \t\r\n\v\f")
17657 (if (or (eobp)
17658 (and (bolp) (looking-at org-outline-regexp)
17659 (<= (org-outline-level) level)))
17660 nil ; Nothing would be swallowed
17661 t)))) ; something would swallow
17663 (define-key org-mode-map "\C-y" 'org-yank)
17665 (defun org-invisible-p ()
17666 "Check if point is at a character currently not visible."
17667 ;; Early versions of noutline don't have `outline-invisible-p'.
17668 (if (fboundp 'outline-invisible-p)
17669 (outline-invisible-p)
17670 (get-char-property (point) 'invisible)))
17672 (defun org-invisible-p2 ()
17673 "Check if point is at a character currently not visible."
17674 (save-excursion
17675 (if (and (eolp) (not (bobp))) (backward-char 1))
17676 ;; Early versions of noutline don't have `outline-invisible-p'.
17677 (if (fboundp 'outline-invisible-p)
17678 (outline-invisible-p)
17679 (get-char-property (point) 'invisible))))
17681 (defun org-back-to-heading (&optional invisible-ok)
17682 "Call `outline-back-to-heading', but provide a better error message."
17683 (condition-case nil
17684 (outline-back-to-heading invisible-ok)
17685 (error (error "Before first headline at position %d in buffer %s"
17686 (point) (current-buffer)))))
17688 (defun org-before-first-heading-p ()
17689 "Before first heading?"
17690 (save-excursion
17691 (null (re-search-backward "^\\*+ " nil t))))
17693 (defun org-on-heading-p (&optional ignored)
17694 (outline-on-heading-p t))
17695 (defun org-at-heading-p (&optional ignored)
17696 (outline-on-heading-p t))
17698 (defun org-at-heading-or-item-p ()
17699 (or (org-on-heading-p) (org-at-item-p)))
17701 (defun org-on-target-p ()
17702 (or (org-in-regexp org-radio-target-regexp)
17703 (org-in-regexp org-target-regexp)))
17705 (defun org-up-heading-all (arg)
17706 "Move to the heading line of which the present line is a subheading.
17707 This function considers both visible and invisible heading lines.
17708 With argument, move up ARG levels."
17709 (if (fboundp 'outline-up-heading-all)
17710 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17711 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17713 (defun org-up-heading-safe ()
17714 "Move to the heading line of which the present line is a subheading.
17715 This version will not throw an error. It will return the level of the
17716 headline found, or nil if no higher level is found.
17718 Also, this function will be a lot faster than `outline-up-heading',
17719 because it relies on stars being the outline starters. This can really
17720 make a significant difference in outlines with very many siblings."
17721 (let (start-level re)
17722 (org-back-to-heading t)
17723 (setq start-level (funcall outline-level))
17724 (if (equal start-level 1)
17726 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17727 (if (re-search-backward re nil t)
17728 (funcall outline-level)))))
17730 (defun org-first-sibling-p ()
17731 "Is this heading the first child of its parents?"
17732 (interactive)
17733 (let ((re (concat "^" outline-regexp))
17734 level l)
17735 (unless (org-at-heading-p t)
17736 (error "Not at a heading"))
17737 (setq level (funcall outline-level))
17738 (save-excursion
17739 (if (not (re-search-backward re nil t))
17741 (setq l (funcall outline-level))
17742 (< l level)))))
17744 (defun org-goto-sibling (&optional previous)
17745 "Goto the next sibling, even if it is invisible.
17746 When PREVIOUS is set, go to the previous sibling instead. Returns t
17747 when a sibling was found. When none is found, return nil and don't
17748 move point."
17749 (let ((fun (if previous 're-search-backward 're-search-forward))
17750 (pos (point))
17751 (re (concat "^" outline-regexp))
17752 level l)
17753 (when (condition-case nil (org-back-to-heading t) (error nil))
17754 (setq level (funcall outline-level))
17755 (catch 'exit
17756 (or previous (forward-char 1))
17757 (while (funcall fun re nil t)
17758 (setq l (funcall outline-level))
17759 (when (< l level) (goto-char pos) (throw 'exit nil))
17760 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17761 (goto-char pos)
17762 nil))))
17764 (defun org-show-siblings ()
17765 "Show all siblings of the current headline."
17766 (save-excursion
17767 (while (org-goto-sibling) (org-flag-heading nil)))
17768 (save-excursion
17769 (while (org-goto-sibling 'previous)
17770 (org-flag-heading nil))))
17772 (defun org-show-hidden-entry ()
17773 "Show an entry where even the heading is hidden."
17774 (save-excursion
17775 (org-show-entry)))
17777 (defun org-flag-heading (flag &optional entry)
17778 "Flag the current heading. FLAG non-nil means make invisible.
17779 When ENTRY is non-nil, show the entire entry."
17780 (save-excursion
17781 (org-back-to-heading t)
17782 ;; Check if we should show the entire entry
17783 (if entry
17784 (progn
17785 (org-show-entry)
17786 (save-excursion
17787 (and (outline-next-heading)
17788 (org-flag-heading nil))))
17789 (outline-flag-region (max (point-min) (1- (point)))
17790 (save-excursion (outline-end-of-heading) (point))
17791 flag))))
17793 (defun org-get-next-sibling ()
17794 "Move to next heading of the same level, and return point.
17795 If there is no such heading, return nil.
17796 This is like outline-next-sibling, but invisible headings are ok."
17797 (let ((level (funcall outline-level)))
17798 (outline-next-heading)
17799 (while (and (not (eobp)) (> (funcall outline-level) level))
17800 (outline-next-heading))
17801 (if (or (eobp) (< (funcall outline-level) level))
17803 (point))))
17805 (defun org-get-last-sibling ()
17806 "Move to previous heading of the same level, and return point.
17807 If there is no such heading, return nil."
17808 (let ((opoint (point))
17809 (level (funcall outline-level)))
17810 (outline-previous-heading)
17811 (when (and (/= (point) opoint) (outline-on-heading-p t))
17812 (while (and (> (funcall outline-level) level)
17813 (not (bobp)))
17814 (outline-previous-heading))
17815 (if (< (funcall outline-level) level)
17817 (point)))))
17819 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17820 ;; This contains an exact copy of the original function, but it uses
17821 ;; `org-back-to-heading', to make it work also in invisible
17822 ;; trees. And is uses an invisible-OK argument.
17823 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17824 ;; Furthermore, when used inside Org, finding the end of a large subtree
17825 ;; with many children and grandchildren etc, this can be much faster
17826 ;; than the outline version.
17827 (org-back-to-heading invisible-OK)
17828 (let ((first t)
17829 (level (funcall outline-level)))
17830 (if (and (org-mode-p) (< level 1000))
17831 ;; A true heading (not a plain list item), in Org-mode
17832 ;; This means we can easily find the end by looking
17833 ;; only for the right number of stars. Using a regexp to do
17834 ;; this is so much faster than using a Lisp loop.
17835 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17836 (forward-char 1)
17837 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17838 ;; something else, do it the slow way
17839 (while (and (not (eobp))
17840 (or first (> (funcall outline-level) level)))
17841 (setq first nil)
17842 (outline-next-heading)))
17843 (unless to-heading
17844 (if (memq (preceding-char) '(?\n ?\^M))
17845 (progn
17846 ;; Go to end of line before heading
17847 (forward-char -1)
17848 (if (memq (preceding-char) '(?\n ?\^M))
17849 ;; leave blank line before heading
17850 (forward-char -1))))))
17851 (point))
17853 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17854 "Use Org version in org-mode, for dramatic speed-up."
17855 (if (eq major-mode 'org-mode)
17856 (progn
17857 (org-end-of-subtree nil t)
17858 (unless (eobp) (backward-char 1)))
17859 ad-do-it))
17861 (defun org-forward-same-level (arg &optional invisible-ok)
17862 "Move forward to the arg'th subheading at same level as this one.
17863 Stop at the first and last subheadings of a superior heading."
17864 (interactive "p")
17865 (org-back-to-heading invisible-ok)
17866 (org-on-heading-p)
17867 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17868 (re (format "^\\*\\{1,%d\\} " level))
17870 (forward-char 1)
17871 (while (> arg 0)
17872 (while (and (re-search-forward re nil 'move)
17873 (setq l (- (match-end 0) (match-beginning 0) 1))
17874 (= l level)
17875 (not invisible-ok)
17876 (progn (backward-char 1) (org-invisible-p)))
17877 (if (< l level) (setq arg 1)))
17878 (setq arg (1- arg)))
17879 (beginning-of-line 1)))
17881 (defun org-backward-same-level (arg &optional invisible-ok)
17882 "Move backward to the arg'th subheading at same level as this one.
17883 Stop at the first and last subheadings of a superior heading."
17884 (interactive "p")
17885 (org-back-to-heading)
17886 (org-on-heading-p)
17887 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17888 (re (format "^\\*\\{1,%d\\} " level))
17890 (while (> arg 0)
17891 (while (and (re-search-backward re nil 'move)
17892 (setq l (- (match-end 0) (match-beginning 0) 1))
17893 (= l level)
17894 (not invisible-ok)
17895 (org-invisible-p))
17896 (if (< l level) (setq arg 1)))
17897 (setq arg (1- arg)))))
17899 (defun org-show-subtree ()
17900 "Show everything after this heading at deeper levels."
17901 (outline-flag-region
17902 (point)
17903 (save-excursion
17904 (org-end-of-subtree t t))
17905 nil))
17907 (defun org-show-entry ()
17908 "Show the body directly following this heading.
17909 Show the heading too, if it is currently invisible."
17910 (interactive)
17911 (save-excursion
17912 (condition-case nil
17913 (progn
17914 (org-back-to-heading t)
17915 (outline-flag-region
17916 (max (point-min) (1- (point)))
17917 (save-excursion
17918 (if (re-search-forward
17919 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17920 (match-beginning 1)
17921 (point-max)))
17922 nil)
17923 (org-cycle-hide-drawers 'children))
17924 (error nil))))
17926 (defun org-make-options-regexp (kwds &optional extra)
17927 "Make a regular expression for keyword lines."
17928 (concat
17930 "#?[ \t]*\\+\\("
17931 (mapconcat 'regexp-quote kwds "\\|")
17932 (if extra (concat "\\|" extra))
17933 "\\):[ \t]*"
17934 "\\(.*\\)"))
17936 ;; Make isearch reveal the necessary context
17937 (defun org-isearch-end ()
17938 "Reveal context after isearch exits."
17939 (when isearch-success ; only if search was successful
17940 (if (featurep 'xemacs)
17941 ;; Under XEmacs, the hook is run in the correct place,
17942 ;; we directly show the context.
17943 (org-show-context 'isearch)
17944 ;; In Emacs the hook runs *before* restoring the overlays.
17945 ;; So we have to use a one-time post-command-hook to do this.
17946 ;; (Emacs 22 has a special variable, see function `org-mode')
17947 (unless (and (boundp 'isearch-mode-end-hook-quit)
17948 isearch-mode-end-hook-quit)
17949 ;; Only when the isearch was not quitted.
17950 (org-add-hook 'post-command-hook 'org-isearch-post-command
17951 'append 'local)))))
17953 (defun org-isearch-post-command ()
17954 "Remove self from hook, and show context."
17955 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17956 (org-show-context 'isearch))
17959 ;;;; Integration with and fixes for other packages
17961 ;;; Imenu support
17963 (defvar org-imenu-markers nil
17964 "All markers currently used by Imenu.")
17965 (make-variable-buffer-local 'org-imenu-markers)
17967 (defun org-imenu-new-marker (&optional pos)
17968 "Return a new marker for use by Imenu, and remember the marker."
17969 (let ((m (make-marker)))
17970 (move-marker m (or pos (point)))
17971 (push m org-imenu-markers)
17974 (defun org-imenu-get-tree ()
17975 "Produce the index for Imenu."
17976 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17977 (setq org-imenu-markers nil)
17978 (let* ((n org-imenu-depth)
17979 (re (concat "^" outline-regexp))
17980 (subs (make-vector (1+ n) nil))
17981 (last-level 0)
17982 m level head)
17983 (save-excursion
17984 (save-restriction
17985 (widen)
17986 (goto-char (point-max))
17987 (while (re-search-backward re nil t)
17988 (setq level (org-reduced-level (funcall outline-level)))
17989 (when (<= level n)
17990 (looking-at org-complex-heading-regexp)
17991 (setq head (org-link-display-format
17992 (org-match-string-no-properties 4))
17993 m (org-imenu-new-marker))
17994 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17995 (if (>= level last-level)
17996 (push (cons head m) (aref subs level))
17997 (push (cons head (aref subs (1+ level))) (aref subs level))
17998 (loop for i from (1+ level) to n do (aset subs i nil)))
17999 (setq last-level level)))))
18000 (aref subs 1)))
18002 (eval-after-load "imenu"
18003 '(progn
18004 (add-hook 'imenu-after-jump-hook
18005 (lambda ()
18006 (if (eq major-mode 'org-mode)
18007 (org-show-context 'org-goto))))))
18009 (defun org-link-display-format (link)
18010 "Replace a link with either the description, or the link target
18011 if no description is present"
18012 (save-match-data
18013 (if (string-match org-bracket-link-analytic-regexp link)
18014 (replace-match (if (match-end 5)
18015 (match-string 5 link)
18016 (concat (match-string 1 link)
18017 (match-string 3 link)))
18018 nil t link)
18019 link)))
18021 ;; Speedbar support
18023 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18024 "Overlay marking the agenda restriction line in speedbar.")
18025 (org-overlay-put org-speedbar-restriction-lock-overlay
18026 'face 'org-agenda-restriction-lock)
18027 (org-overlay-put org-speedbar-restriction-lock-overlay
18028 'help-echo "Agendas are currently limited to this item.")
18029 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18031 (defun org-speedbar-set-agenda-restriction ()
18032 "Restrict future agenda commands to the location at point in speedbar.
18033 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18034 (interactive)
18035 (require 'org-agenda)
18036 (let (p m tp np dir txt)
18037 (cond
18038 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18039 'org-imenu t))
18040 (setq m (get-text-property p 'org-imenu-marker))
18041 (with-current-buffer (marker-buffer m)
18042 (goto-char m)
18043 (org-agenda-set-restriction-lock 'subtree)))
18044 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18045 'speedbar-function 'speedbar-find-file))
18046 (setq tp (previous-single-property-change
18047 (1+ p) 'speedbar-function)
18048 np (next-single-property-change
18049 tp 'speedbar-function)
18050 dir (speedbar-line-directory)
18051 txt (buffer-substring-no-properties (or tp (point-min))
18052 (or np (point-max))))
18053 (with-current-buffer (find-file-noselect
18054 (let ((default-directory dir))
18055 (expand-file-name txt)))
18056 (unless (org-mode-p)
18057 (error "Cannot restrict to non-Org-mode file"))
18058 (org-agenda-set-restriction-lock 'file)))
18059 (t (error "Don't know how to restrict Org-mode's agenda")))
18060 (org-move-overlay org-speedbar-restriction-lock-overlay
18061 (point-at-bol) (point-at-eol))
18062 (setq current-prefix-arg nil)
18063 (org-agenda-maybe-redo)))
18065 (eval-after-load "speedbar"
18066 '(progn
18067 (speedbar-add-supported-extension ".org")
18068 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18069 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18070 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18071 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18072 (add-hook 'speedbar-visiting-tag-hook
18073 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18076 ;;; Fixes and Hacks for problems with other packages
18078 ;; Make flyspell not check words in links, to not mess up our keymap
18079 (defun org-mode-flyspell-verify ()
18080 "Don't let flyspell put overlays at active buttons."
18081 (and (not (get-text-property (point) 'keymap))
18082 (not (get-text-property (point) 'org-no-flyspell))))
18084 (defun org-remove-flyspell-overlays-in (beg end)
18085 "Remove flyspell overlays in region."
18086 (and (org-bound-and-true-p flyspell-mode)
18087 (fboundp 'flyspell-delete-region-overlays)
18088 (flyspell-delete-region-overlays beg end))
18089 (add-text-properties beg end '(org-no-flyspell t)))
18091 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18092 (eval-after-load "bookmark"
18093 '(if (boundp 'bookmark-after-jump-hook)
18094 ;; We can use the hook
18095 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18096 ;; Hook not available, use advice
18097 (defadvice bookmark-jump (after org-make-visible activate)
18098 "Make the position visible."
18099 (org-bookmark-jump-unhide))))
18101 ;; Make sure saveplace shows the location if it was hidden
18102 (eval-after-load "saveplace"
18103 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18104 "Make the position visible."
18105 (org-bookmark-jump-unhide)))
18107 ;; Make sure ecb shows the location if it was hidden
18108 (eval-after-load "ecb"
18109 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18110 "Make hierarchy visible when jumping into location from ECB tree buffer."
18111 (if (eq major-mode 'org-mode)
18112 (org-show-context))))
18114 (defun org-bookmark-jump-unhide ()
18115 "Unhide the current position, to show the bookmark location."
18116 (and (org-mode-p)
18117 (or (org-invisible-p)
18118 (save-excursion (goto-char (max (point-min) (1- (point))))
18119 (org-invisible-p)))
18120 (org-show-context 'bookmark-jump)))
18122 ;; Make session.el ignore our circular variable
18123 (eval-after-load "session"
18124 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18126 ;;;; Experimental code
18128 (defun org-closed-in-range ()
18129 "Sparse tree of items closed in a certain time range.
18130 Still experimental, may disappear in the future."
18131 (interactive)
18132 ;; Get the time interval from the user.
18133 (let* ((time1 (org-float-time
18134 (org-read-date nil 'to-time nil "Starting date: ")))
18135 (time2 (org-float-time
18136 (org-read-date nil 'to-time nil "End date:")))
18137 ;; callback function
18138 (callback (lambda ()
18139 (let ((time
18140 (org-float-time
18141 (apply 'encode-time
18142 (org-parse-time-string
18143 (match-string 1))))))
18144 ;; check if time in interval
18145 (and (>= time time1) (<= time time2))))))
18146 ;; make tree, check each match with the callback
18147 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18149 ;;;; Finish up
18151 (provide 'org)
18153 (run-hooks 'org-load-hook)
18155 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18157 ;;; org.el ends here