Merge branch 'master' of git+ssh://repo.or.cz/srv/git/org-mode
[rgr-org-mode.git] / lisp / org.el
blobcb91ae3655f2c4f10967eef978cf37767f7fe972
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 (and (org-on-heading-p) (org-flag-subtree t))
3601 (org-end-of-subtree t)))))
3603 (defun org-flag-subtree (flag)
3604 (save-excursion
3605 (org-back-to-heading t)
3606 (outline-end-of-heading)
3607 (outline-flag-region (point)
3608 (progn (org-end-of-subtree t) (point))
3609 flag)))
3611 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3613 (eval-and-compile
3614 (org-autoload "org-archive"
3615 '(org-add-archive-files org-archive-subtree
3616 org-archive-to-archive-sibling org-toggle-archive-tag
3617 org-archive-subtree-default
3618 org-archive-subtree-default-with-confirmation)))
3620 ;; Autoload Column View Code
3622 (declare-function org-columns-number-to-string "org-colview")
3623 (declare-function org-columns-get-format-and-top-level "org-colview")
3624 (declare-function org-columns-compute "org-colview")
3626 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3627 '(org-columns-number-to-string org-columns-get-format-and-top-level
3628 org-columns-compute org-agenda-columns org-columns-remove-overlays
3629 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3631 ;; Autoload ID code
3633 (declare-function org-id-store-link "org-id")
3634 (declare-function org-id-locations-load "org-id")
3635 (declare-function org-id-locations-save "org-id")
3636 (defvar org-id-track-globally)
3637 (org-autoload "org-id"
3638 '(org-id-get-create org-id-new org-id-copy org-id-get
3639 org-id-get-with-outline-path-completion
3640 org-id-get-with-outline-drilling
3641 org-id-goto org-id-find org-id-store-link))
3643 ;; Autoload Plotting Code
3645 (org-autoload "org-plot"
3646 '(org-plot/gnuplot))
3648 ;;; Variables for pre-computed regular expressions, all buffer local
3650 (defvar org-drawer-regexp nil
3651 "Matches first line of a hidden block.")
3652 (make-variable-buffer-local 'org-drawer-regexp)
3653 (defvar org-todo-regexp nil
3654 "Matches any of the TODO state keywords.")
3655 (make-variable-buffer-local 'org-todo-regexp)
3656 (defvar org-not-done-regexp nil
3657 "Matches any of the TODO state keywords except the last one.")
3658 (make-variable-buffer-local 'org-not-done-regexp)
3659 (defvar org-not-done-heading-regexp nil
3660 "Matches a TODO headline that is not done.")
3661 (make-variable-buffer-local 'org-not-done-regexp)
3662 (defvar org-todo-line-regexp nil
3663 "Matches a headline and puts TODO state into group 2 if present.")
3664 (make-variable-buffer-local 'org-todo-line-regexp)
3665 (defvar org-complex-heading-regexp nil
3666 "Matches a headline and puts everything into groups:
3667 group 1: the stars
3668 group 2: The todo keyword, maybe
3669 group 3: Priority cookie
3670 group 4: True headline
3671 group 5: Tags")
3672 (make-variable-buffer-local 'org-complex-heading-regexp)
3673 (defvar org-complex-heading-regexp-format nil)
3674 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3675 (defvar org-todo-line-tags-regexp nil
3676 "Matches a headline and puts TODO state into group 2 if present.
3677 Also put tags into group 4 if tags are present.")
3678 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3679 (defvar org-nl-done-regexp nil
3680 "Matches newline followed by a headline with the DONE keyword.")
3681 (make-variable-buffer-local 'org-nl-done-regexp)
3682 (defvar org-looking-at-done-regexp nil
3683 "Matches the DONE keyword a point.")
3684 (make-variable-buffer-local 'org-looking-at-done-regexp)
3685 (defvar org-ds-keyword-length 12
3686 "Maximum length of the Deadline and SCHEDULED keywords.")
3687 (make-variable-buffer-local 'org-ds-keyword-length)
3688 (defvar org-deadline-regexp nil
3689 "Matches the DEADLINE keyword.")
3690 (make-variable-buffer-local 'org-deadline-regexp)
3691 (defvar org-deadline-time-regexp nil
3692 "Matches the DEADLINE keyword together with a time stamp.")
3693 (make-variable-buffer-local 'org-deadline-time-regexp)
3694 (defvar org-deadline-line-regexp nil
3695 "Matches the DEADLINE keyword and the rest of the line.")
3696 (make-variable-buffer-local 'org-deadline-line-regexp)
3697 (defvar org-scheduled-regexp nil
3698 "Matches the SCHEDULED keyword.")
3699 (make-variable-buffer-local 'org-scheduled-regexp)
3700 (defvar org-scheduled-time-regexp nil
3701 "Matches the SCHEDULED keyword together with a time stamp.")
3702 (make-variable-buffer-local 'org-scheduled-time-regexp)
3703 (defvar org-closed-time-regexp nil
3704 "Matches the CLOSED keyword together with a time stamp.")
3705 (make-variable-buffer-local 'org-closed-time-regexp)
3707 (defvar org-keyword-time-regexp nil
3708 "Matches any of the 4 keywords, together with the time stamp.")
3709 (make-variable-buffer-local 'org-keyword-time-regexp)
3710 (defvar org-keyword-time-not-clock-regexp nil
3711 "Matches any of the 3 keywords, together with the time stamp.")
3712 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3713 (defvar org-maybe-keyword-time-regexp nil
3714 "Matches a timestamp, possibly preceeded by a keyword.")
3715 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3716 (defvar org-planning-or-clock-line-re nil
3717 "Matches a line with planning or clock info.")
3718 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3719 (defvar org-all-time-keywords nil
3720 "List of time keywords.")
3721 (make-variable-buffer-local 'org-all-time-keywords)
3723 (defconst org-plain-time-of-day-regexp
3724 (concat
3725 "\\(\\<[012]?[0-9]"
3726 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3727 "\\(--?"
3728 "\\(\\<[012]?[0-9]"
3729 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3730 "\\)?")
3731 "Regular expression to match a plain time or time range.
3732 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3733 groups carry important information:
3734 0 the full match
3735 1 the first time, range or not
3736 8 the second time, if it is a range.")
3738 (defconst org-plain-time-extension-regexp
3739 (concat
3740 "\\(\\<[012]?[0-9]"
3741 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3742 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3743 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3744 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3745 groups carry important information:
3746 0 the full match
3747 7 hours of duration
3748 9 minutes of duration")
3750 (defconst org-stamp-time-of-day-regexp
3751 (concat
3752 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3753 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3754 "\\(--?"
3755 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3756 "Regular expression to match a timestamp time or time range.
3757 After a match, the following groups carry important information:
3758 0 the full match
3759 1 date plus weekday, for back referencing to make sure both times are on the same day
3760 2 the first time, range or not
3761 4 the second time, if it is a range.")
3763 (defconst org-startup-options
3764 '(("fold" org-startup-folded t)
3765 ("overview" org-startup-folded t)
3766 ("nofold" org-startup-folded nil)
3767 ("showall" org-startup-folded nil)
3768 ("showeverything" org-startup-folded showeverything)
3769 ("content" org-startup-folded content)
3770 ("indent" org-startup-indented t)
3771 ("noindent" org-startup-indented nil)
3772 ("hidestars" org-hide-leading-stars t)
3773 ("showstars" org-hide-leading-stars nil)
3774 ("odd" org-odd-levels-only t)
3775 ("oddeven" org-odd-levels-only nil)
3776 ("align" org-startup-align-all-tables t)
3777 ("noalign" org-startup-align-all-tables nil)
3778 ("customtime" org-display-custom-times t)
3779 ("logdone" org-log-done time)
3780 ("lognotedone" org-log-done note)
3781 ("nologdone" org-log-done nil)
3782 ("lognoteclock-out" org-log-note-clock-out t)
3783 ("nolognoteclock-out" org-log-note-clock-out nil)
3784 ("logrepeat" org-log-repeat state)
3785 ("lognoterepeat" org-log-repeat note)
3786 ("nologrepeat" org-log-repeat nil)
3787 ("logreschedule" org-log-reschedule time)
3788 ("lognotereschedule" org-log-reschedule note)
3789 ("nologreschedule" org-log-reschedule nil)
3790 ("logredeadline" org-log-redeadline time)
3791 ("lognoteredeadline" org-log-redeadline note)
3792 ("nologredeadline" org-log-redeadline nil)
3793 ("fninline" org-footnote-define-inline t)
3794 ("nofninline" org-footnote-define-inline nil)
3795 ("fnlocal" org-footnote-section nil)
3796 ("fnauto" org-footnote-auto-label t)
3797 ("fnprompt" org-footnote-auto-label nil)
3798 ("fnconfirm" org-footnote-auto-label confirm)
3799 ("fnplain" org-footnote-auto-label plain)
3800 ("fnadjust" org-footnote-auto-adjust t)
3801 ("nofnadjust" org-footnote-auto-adjust nil)
3802 ("constcgs" constants-unit-system cgs)
3803 ("constSI" constants-unit-system SI)
3804 ("noptag" org-tag-persistent-alist nil)
3805 ("hideblocks" org-hide-block-startup t)
3806 ("nohideblocks" org-hide-block-startup nil)
3807 ("beamer" org-startup-with-beamer-mode t))
3808 "Variable associated with STARTUP options for org-mode.
3809 Each element is a list of three items: The startup options as written
3810 in the #+STARTUP line, the corresponding variable, and the value to
3811 set this variable to if the option is found. An optional forth element PUSH
3812 means to push this value onto the list in the variable.")
3814 (defun org-set-regexps-and-options ()
3815 "Precompute regular expressions for current buffer."
3816 (when (org-mode-p)
3817 (org-set-local 'org-todo-kwd-alist nil)
3818 (org-set-local 'org-todo-key-alist nil)
3819 (org-set-local 'org-todo-key-trigger nil)
3820 (org-set-local 'org-todo-keywords-1 nil)
3821 (org-set-local 'org-done-keywords nil)
3822 (org-set-local 'org-todo-heads nil)
3823 (org-set-local 'org-todo-sets nil)
3824 (org-set-local 'org-todo-log-states nil)
3825 (org-set-local 'org-file-properties nil)
3826 (org-set-local 'org-file-tags nil)
3827 (let ((re (org-make-options-regexp
3828 '("CATEGORY" "TODO" "COLUMNS"
3829 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3830 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3831 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3832 (splitre "[ \t]+")
3833 kwds kws0 kwsa key log value cat arch tags const links hw dws
3834 tail sep kws1 prio props ftags drawers beamer-p
3835 ext-setup-or-nil setup-contents (start 0))
3836 (save-excursion
3837 (save-restriction
3838 (widen)
3839 (goto-char (point-min))
3840 (while (or (and ext-setup-or-nil
3841 (string-match re ext-setup-or-nil start)
3842 (setq start (match-end 0)))
3843 (and (setq ext-setup-or-nil nil start 0)
3844 (re-search-forward re nil t)))
3845 (setq key (upcase (match-string 1 ext-setup-or-nil))
3846 value (org-match-string-no-properties 2 ext-setup-or-nil))
3847 (cond
3848 ((equal key "CATEGORY")
3849 (if (string-match "[ \t]+$" value)
3850 (setq value (replace-match "" t t value)))
3851 (setq cat value))
3852 ((member key '("SEQ_TODO" "TODO"))
3853 (push (cons 'sequence (org-split-string value splitre)) kwds))
3854 ((equal key "TYP_TODO")
3855 (push (cons 'type (org-split-string value splitre)) kwds))
3856 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3857 ;; general TODO-like setup
3858 (push (cons (intern (downcase (match-string 1 key)))
3859 (org-split-string value splitre)) kwds))
3860 ((equal key "TAGS")
3861 (setq tags (append tags (if tags '("\\n") nil)
3862 (org-split-string value splitre))))
3863 ((equal key "COLUMNS")
3864 (org-set-local 'org-columns-default-format value))
3865 ((equal key "LINK")
3866 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3867 (push (cons (match-string 1 value)
3868 (org-trim (match-string 2 value)))
3869 links)))
3870 ((equal key "PRIORITIES")
3871 (setq prio (org-split-string value " +")))
3872 ((equal key "PROPERTY")
3873 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3874 (push (cons (match-string 1 value) (match-string 2 value))
3875 props)))
3876 ((equal key "FILETAGS")
3877 (when (string-match "\\S-" value)
3878 (setq ftags
3879 (append
3880 ftags
3881 (apply 'append
3882 (mapcar (lambda (x) (org-split-string x ":"))
3883 (org-split-string value)))))))
3884 ((equal key "DRAWERS")
3885 (setq drawers (org-split-string value splitre)))
3886 ((equal key "CONSTANTS")
3887 (setq const (append const (org-split-string value splitre))))
3888 ((equal key "STARTUP")
3889 (let ((opts (org-split-string value splitre))
3890 l var val)
3891 (while (setq l (pop opts))
3892 (when (setq l (assoc l org-startup-options))
3893 (setq var (nth 1 l) val (nth 2 l))
3894 (if (not (nth 3 l))
3895 (set (make-local-variable var) val)
3896 (if (not (listp (symbol-value var)))
3897 (set (make-local-variable var) nil))
3898 (set (make-local-variable var) (symbol-value var))
3899 (add-to-list var val))))))
3900 ((equal key "ARCHIVE")
3901 (string-match " *$" value)
3902 (setq arch (replace-match "" t t value))
3903 (remove-text-properties 0 (length arch)
3904 '(face t fontified t) arch))
3905 ((equal key "LATEX_CLASS")
3906 (setq beamer-p (equal value "beamer")))
3907 ((equal key "SETUPFILE")
3908 (setq setup-contents (org-file-contents
3909 (expand-file-name
3910 (org-remove-double-quotes value))
3911 'noerror))
3912 (if (not ext-setup-or-nil)
3913 (setq ext-setup-or-nil setup-contents start 0)
3914 (setq ext-setup-or-nil
3915 (concat (substring ext-setup-or-nil 0 start)
3916 "\n" setup-contents "\n"
3917 (substring ext-setup-or-nil start)))))
3918 ))))
3919 (when cat
3920 (org-set-local 'org-category (intern cat))
3921 (push (cons "CATEGORY" cat) props))
3922 (when prio
3923 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3924 (setq prio (mapcar 'string-to-char prio))
3925 (org-set-local 'org-highest-priority (nth 0 prio))
3926 (org-set-local 'org-lowest-priority (nth 1 prio))
3927 (org-set-local 'org-default-priority (nth 2 prio)))
3928 (and props (org-set-local 'org-file-properties (nreverse props)))
3929 (and ftags (org-set-local 'org-file-tags
3930 (mapcar 'org-add-prop-inherited ftags)))
3931 (and drawers (org-set-local 'org-drawers drawers))
3932 (and arch (org-set-local 'org-archive-location arch))
3933 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3934 ;; Process the TODO keywords
3935 (unless kwds
3936 ;; Use the global values as if they had been given locally.
3937 (setq kwds (default-value 'org-todo-keywords))
3938 (if (stringp (car kwds))
3939 (setq kwds (list (cons org-todo-interpretation
3940 (default-value 'org-todo-keywords)))))
3941 (setq kwds (reverse kwds)))
3942 (setq kwds (nreverse kwds))
3943 (let (inter kws kw)
3944 (while (setq kws (pop kwds))
3945 (let ((kws (or
3946 (run-hook-with-args-until-success
3947 'org-todo-setup-filter-hook kws)
3948 kws)))
3949 (setq inter (pop kws) sep (member "|" kws)
3950 kws0 (delete "|" (copy-sequence kws))
3951 kwsa nil
3952 kws1 (mapcar
3953 (lambda (x)
3954 ;; 1 2
3955 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3956 (progn
3957 (setq kw (match-string 1 x)
3958 key (and (match-end 2) (match-string 2 x))
3959 log (org-extract-log-state-settings x))
3960 (push (cons kw (and key (string-to-char key))) kwsa)
3961 (and log (push log org-todo-log-states))
3963 (error "Invalid TODO keyword %s" x)))
3964 kws0)
3965 kwsa (if kwsa (append '((:startgroup))
3966 (nreverse kwsa)
3967 '((:endgroup))))
3968 hw (car kws1)
3969 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3970 tail (list inter hw (car dws) (org-last dws))))
3971 (add-to-list 'org-todo-heads hw 'append)
3972 (push kws1 org-todo-sets)
3973 (setq org-done-keywords (append org-done-keywords dws nil))
3974 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3975 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3976 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3977 (setq org-todo-sets (nreverse org-todo-sets)
3978 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3979 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3980 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3981 ;; Process the constants
3982 (when const
3983 (let (e cst)
3984 (while (setq e (pop const))
3985 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3986 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3987 (setq org-table-formula-constants-local cst)))
3989 ;; Process the tags.
3990 (when tags
3991 (let (e tgs)
3992 (while (setq e (pop tags))
3993 (cond
3994 ((equal e "{") (push '(:startgroup) tgs))
3995 ((equal e "}") (push '(:endgroup) tgs))
3996 ((equal e "\\n") (push '(:newline) tgs))
3997 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3998 (push (cons (match-string 1 e)
3999 (string-to-char (match-string 2 e)))
4000 tgs))
4001 (t (push (list e) tgs))))
4002 (org-set-local 'org-tag-alist nil)
4003 (while (setq e (pop tgs))
4004 (or (and (stringp (car e))
4005 (assoc (car e) org-tag-alist))
4006 (push e org-tag-alist)))))
4008 ;; Compute the regular expressions and other local variables
4009 (if (not org-done-keywords)
4010 (setq org-done-keywords (and org-todo-keywords-1
4011 (list (org-last org-todo-keywords-1)))))
4012 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4013 (length org-scheduled-string)
4014 (length org-clock-string)
4015 (length org-closed-string)))
4016 org-drawer-regexp
4017 (concat "^[ \t]*:\\("
4018 (mapconcat 'regexp-quote org-drawers "\\|")
4019 "\\):[ \t]*$")
4020 org-not-done-keywords
4021 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4022 org-todo-regexp
4023 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4024 "\\|") "\\)\\>")
4025 org-not-done-regexp
4026 (concat "\\<\\("
4027 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4028 "\\)\\>")
4029 org-not-done-heading-regexp
4030 (concat "^\\(\\*+\\)[ \t]+\\("
4031 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4032 "\\)\\>")
4033 org-todo-line-regexp
4034 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4035 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4036 "\\)\\>\\)?[ \t]*\\(.*\\)")
4037 org-complex-heading-regexp
4038 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4039 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4040 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4041 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4042 org-complex-heading-regexp-format
4043 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4044 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4045 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4046 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4047 org-nl-done-regexp
4048 (concat "\n\\*+[ \t]+"
4049 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4050 "\\)" "\\>")
4051 org-todo-line-tags-regexp
4052 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4053 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4054 (org-re
4055 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4056 org-looking-at-done-regexp
4057 (concat "^" "\\(?:"
4058 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4059 "\\>")
4060 org-deadline-regexp (concat "\\<" org-deadline-string)
4061 org-deadline-time-regexp
4062 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4063 org-deadline-line-regexp
4064 (concat "\\<\\(" org-deadline-string "\\).*")
4065 org-scheduled-regexp
4066 (concat "\\<" org-scheduled-string)
4067 org-scheduled-time-regexp
4068 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4069 org-closed-time-regexp
4070 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4071 org-keyword-time-regexp
4072 (concat "\\<\\(" org-scheduled-string
4073 "\\|" org-deadline-string
4074 "\\|" org-closed-string
4075 "\\|" org-clock-string "\\)"
4076 " *[[<]\\([^]>]+\\)[]>]")
4077 org-keyword-time-not-clock-regexp
4078 (concat "\\<\\(" org-scheduled-string
4079 "\\|" org-deadline-string
4080 "\\|" org-closed-string
4081 "\\)"
4082 " *[[<]\\([^]>]+\\)[]>]")
4083 org-maybe-keyword-time-regexp
4084 (concat "\\(\\<\\(" org-scheduled-string
4085 "\\|" org-deadline-string
4086 "\\|" org-closed-string
4087 "\\|" org-clock-string "\\)\\)?"
4088 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4089 org-planning-or-clock-line-re
4090 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4091 "\\|" org-deadline-string
4092 "\\|" org-closed-string "\\|" org-clock-string
4093 "\\)\\>\\)")
4094 org-all-time-keywords
4095 (mapcar (lambda (w) (substring w 0 -1))
4096 (list org-scheduled-string org-deadline-string
4097 org-clock-string org-closed-string))
4099 (org-compute-latex-and-specials-regexp)
4100 (org-set-font-lock-defaults))))
4102 (defun org-file-contents (file &optional noerror)
4103 "Return the contents of FILE, as a string."
4104 (if (or (not file)
4105 (not (file-readable-p file)))
4106 (if noerror
4107 (progn
4108 (message "Cannot read file %s" file)
4109 (ding) (sit-for 2)
4111 (error "Cannot read file %s" file))
4112 (with-temp-buffer
4113 (insert-file-contents file)
4114 (buffer-string))))
4116 (defun org-extract-log-state-settings (x)
4117 "Extract the log state setting from a TODO keyword string.
4118 This will extract info from a string like \"WAIT(w@/!)\"."
4119 (let (kw key log1 log2)
4120 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4121 (setq kw (match-string 1 x)
4122 key (and (match-end 2) (match-string 2 x))
4123 log1 (and (match-end 3) (match-string 3 x))
4124 log2 (and (match-end 4) (match-string 4 x)))
4125 (and (or log1 log2)
4126 (list kw
4127 (and log1 (if (equal log1 "!") 'time 'note))
4128 (and log2 (if (equal log2 "!") 'time 'note)))))))
4130 (defun org-remove-keyword-keys (list)
4131 "Remove a pair of parenthesis at the end of each string in LIST."
4132 (mapcar (lambda (x)
4133 (if (string-match "(.*)$" x)
4134 (substring x 0 (match-beginning 0))
4136 list))
4138 (defun org-assign-fast-keys (alist)
4139 "Assign fast keys to a keyword-key alist.
4140 Respect keys that are already there."
4141 (let (new e (alt ?0))
4142 (while (setq e (pop alist))
4143 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4144 (cdr e)) ;; Key already assigned.
4145 (push e new)
4146 (let ((clist (string-to-list (downcase (car e))))
4147 (used (append new alist)))
4148 (when (= (car clist) ?@)
4149 (pop clist))
4150 (while (and clist (rassoc (car clist) used))
4151 (pop clist))
4152 (unless clist
4153 (while (rassoc alt used)
4154 (incf alt)))
4155 (push (cons (car e) (or (car clist) alt)) new))))
4156 (nreverse new)))
4158 ;;; Some variables used in various places
4160 (defvar org-window-configuration nil
4161 "Used in various places to store a window configuration.")
4162 (defvar org-selected-window nil
4163 "Used in various places to store a window configuration.")
4164 (defvar org-finish-function nil
4165 "Function to be called when `C-c C-c' is used.
4166 This is for getting out of special buffers like remember.")
4169 ;; FIXME: Occasionally check by commenting these, to make sure
4170 ;; no other functions uses these, forgetting to let-bind them.
4171 (defvar entry)
4172 (defvar last-state)
4173 (defvar date)
4175 ;; Defined somewhere in this file, but used before definition.
4176 (defvar org-html-entities)
4177 (defvar org-struct-menu)
4178 (defvar org-org-menu)
4179 (defvar org-tbl-menu)
4181 ;;;; Define the Org-mode
4183 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4184 (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."))
4187 ;; We use a before-change function to check if a table might need
4188 ;; an update.
4189 (defvar org-table-may-need-update t
4190 "Indicates that a table might need an update.
4191 This variable is set by `org-before-change-function'.
4192 `org-table-align' sets it back to nil.")
4193 (defun org-before-change-function (beg end)
4194 "Every change indicates that a table might need an update."
4195 (setq org-table-may-need-update t))
4196 (defvar org-mode-map)
4197 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4198 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4199 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4200 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4201 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4202 (defvar org-table-buffer-is-an nil)
4203 (defconst org-outline-regexp "\\*+ ")
4205 ;;;###autoload
4206 (define-derived-mode org-mode outline-mode "Org"
4207 "Outline-based notes management and organizer, alias
4208 \"Carsten's outline-mode for keeping track of everything.\"
4210 Org-mode develops organizational tasks around a NOTES file which
4211 contains information about projects as plain text. Org-mode is
4212 implemented on top of outline-mode, which is ideal to keep the content
4213 of large files well structured. It supports ToDo items, deadlines and
4214 time stamps, which magically appear in the diary listing of the Emacs
4215 calendar. Tables are easily created with a built-in table editor.
4216 Plain text URL-like links connect to websites, emails (VM), Usenet
4217 messages (Gnus), BBDB entries, and any files related to the project.
4218 For printing and sharing of notes, an Org-mode file (or a part of it)
4219 can be exported as a structured ASCII or HTML file.
4221 The following commands are available:
4223 \\{org-mode-map}"
4225 ;; Get rid of Outline menus, they are not needed
4226 ;; Need to do this here because define-derived-mode sets up
4227 ;; the keymap so late. Still, it is a waste to call this each time
4228 ;; we switch another buffer into org-mode.
4229 (if (featurep 'xemacs)
4230 (when (boundp 'outline-mode-menu-heading)
4231 ;; Assume this is Greg's port, it used easymenu
4232 (easy-menu-remove outline-mode-menu-heading)
4233 (easy-menu-remove outline-mode-menu-show)
4234 (easy-menu-remove outline-mode-menu-hide))
4235 (define-key org-mode-map [menu-bar headings] 'undefined)
4236 (define-key org-mode-map [menu-bar hide] 'undefined)
4237 (define-key org-mode-map [menu-bar show] 'undefined))
4239 (org-load-modules-maybe)
4240 (easy-menu-add org-org-menu)
4241 (easy-menu-add org-tbl-menu)
4242 (org-install-agenda-files-menu)
4243 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4244 (org-add-to-invisibility-spec '(org-cwidth))
4245 (org-add-to-invisibility-spec '(org-hide-block . t))
4246 (when (featurep 'xemacs)
4247 (org-set-local 'line-move-ignore-invisible t))
4248 (org-set-local 'outline-regexp org-outline-regexp)
4249 (org-set-local 'outline-level 'org-outline-level)
4250 (when (and org-ellipsis
4251 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4252 (fboundp 'make-glyph-code))
4253 (unless org-display-table
4254 (setq org-display-table (make-display-table)))
4255 (set-display-table-slot
4256 org-display-table 4
4257 (vconcat (mapcar
4258 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4259 org-ellipsis)))
4260 (if (stringp org-ellipsis) org-ellipsis "..."))))
4261 (setq buffer-display-table org-display-table))
4262 (org-set-regexps-and-options)
4263 (when (and org-tag-faces (not org-tags-special-faces-re))
4264 ;; tag faces set outside customize.... force initialization.
4265 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4266 ;; Calc embedded
4267 (org-set-local 'calc-embedded-open-mode "# ")
4268 (modify-syntax-entry ?# "<")
4269 (modify-syntax-entry ?@ "w")
4270 (if org-startup-truncated (setq truncate-lines t))
4271 (org-set-local 'font-lock-unfontify-region-function
4272 'org-unfontify-region)
4273 ;; Activate before-change-function
4274 (org-set-local 'org-table-may-need-update t)
4275 (org-add-hook 'before-change-functions 'org-before-change-function nil
4276 'local)
4277 ;; Check for running clock before killing a buffer
4278 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4279 ;; Paragraphs and auto-filling
4280 (org-set-autofill-regexps)
4281 (setq indent-line-function 'org-indent-line-function)
4282 (org-update-radio-target-regexp)
4283 ;; Make sure dependence stuff works reliably, even for users who set it
4284 ;; too late :-(
4285 (if org-enforce-todo-dependencies
4286 (add-hook 'org-blocker-hook
4287 'org-block-todo-from-children-or-siblings-or-parent)
4288 (remove-hook 'org-blocker-hook
4289 'org-block-todo-from-children-or-siblings-or-parent))
4290 (if org-enforce-todo-checkbox-dependencies
4291 (add-hook 'org-blocker-hook
4292 'org-block-todo-from-checkboxes)
4293 (remove-hook 'org-blocker-hook
4294 'org-block-todo-from-checkboxes))
4296 ;; Comment characters
4297 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4298 (org-set-local 'comment-padding " ")
4300 ;; Align options lines
4301 (org-set-local
4302 'align-mode-rules-list
4303 '((org-in-buffer-settings
4304 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4305 (modes . '(org-mode)))))
4307 ;; Imenu
4308 (org-set-local 'imenu-create-index-function
4309 'org-imenu-get-tree)
4311 ;; Make isearch reveal context
4312 (if (or (featurep 'xemacs)
4313 (not (boundp 'outline-isearch-open-invisible-function)))
4314 ;; Emacs 21 and XEmacs make use of the hook
4315 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4316 ;; Emacs 22 deals with this through a special variable
4317 (org-set-local 'outline-isearch-open-invisible-function
4318 (lambda (&rest ignore) (org-show-context 'isearch))))
4320 ;; Turn on org-beamer-mode?
4321 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4323 ;; If empty file that did not turn on org-mode automatically, make it to.
4324 (if (and org-insert-mode-line-in-empty-file
4325 (interactive-p)
4326 (= (point-min) (point-max)))
4327 (insert "# -*- mode: org -*-\n\n"))
4328 (unless org-inhibit-startup
4329 (when org-startup-align-all-tables
4330 (let ((bmp (buffer-modified-p)))
4331 (org-table-map-tables 'org-table-align)
4332 (set-buffer-modified-p bmp)))
4333 (when org-startup-indented
4334 (require 'org-indent)
4335 (org-indent-mode 1))
4336 (unless org-inhibit-startup-visibility-stuff
4337 (org-set-startup-visibility))))
4339 (when (fboundp 'abbrev-table-put)
4340 (abbrev-table-put org-mode-abbrev-table
4341 :parents (list text-mode-abbrev-table)))
4343 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4345 (defun org-current-time ()
4346 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4347 (if (> (car org-time-stamp-rounding-minutes) 1)
4348 (let ((r (car org-time-stamp-rounding-minutes))
4349 (time (decode-time)))
4350 (apply 'encode-time
4351 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4352 (nthcdr 2 time))))
4353 (current-time)))
4355 ;;;; Font-Lock stuff, including the activators
4357 (defvar org-mouse-map (make-sparse-keymap))
4358 (org-defkey org-mouse-map
4359 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4360 (org-defkey org-mouse-map
4361 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4362 (when org-mouse-1-follows-link
4363 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4364 (when org-tab-follows-link
4365 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4366 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4368 (require 'font-lock)
4370 (defconst org-non-link-chars "]\t\n\r<>")
4371 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4372 "shell" "elisp"))
4373 (defvar org-link-types-re nil
4374 "Matches a link that has a url-like prefix like \"http:\"")
4375 (defvar org-link-re-with-space nil
4376 "Matches a link with spaces, optional angular brackets around it.")
4377 (defvar org-link-re-with-space2 nil
4378 "Matches a link with spaces, optional angular brackets around it.")
4379 (defvar org-link-re-with-space3 nil
4380 "Matches a link with spaces, only for internal part in bracket links.")
4381 (defvar org-angle-link-re nil
4382 "Matches link with angular brackets, spaces are allowed.")
4383 (defvar org-plain-link-re nil
4384 "Matches plain link, without spaces.")
4385 (defvar org-bracket-link-regexp nil
4386 "Matches a link in double brackets.")
4387 (defvar org-bracket-link-analytic-regexp nil
4388 "Regular expression used to analyze links.
4389 Here is what the match groups contain after a match:
4390 1: http:
4391 2: http
4392 3: path
4393 4: [desc]
4394 5: desc")
4395 (defvar org-bracket-link-analytic-regexp++ nil
4396 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4397 (defvar org-any-link-re nil
4398 "Regular expression matching any link.")
4400 (defun org-make-link-regexps ()
4401 "Update the link regular expressions.
4402 This should be called after the variable `org-link-types' has changed."
4403 (setq org-link-types-re
4404 (concat
4405 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4406 org-link-re-with-space
4407 (concat
4408 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4409 "\\([^" org-non-link-chars " ]"
4410 "[^" org-non-link-chars "]*"
4411 "[^" org-non-link-chars " ]\\)>?")
4412 org-link-re-with-space2
4413 (concat
4414 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4415 "\\([^" org-non-link-chars " ]"
4416 "[^\t\n\r]*"
4417 "[^" org-non-link-chars " ]\\)>?")
4418 org-link-re-with-space3
4419 (concat
4420 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4421 "\\([^" org-non-link-chars " ]"
4422 "[^\t\n\r]*\\)")
4423 org-angle-link-re
4424 (concat
4425 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4426 "\\([^" org-non-link-chars " ]"
4427 "[^" org-non-link-chars "]*"
4428 "\\)>")
4429 org-plain-link-re
4430 (concat
4431 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4432 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4433 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4434 org-bracket-link-regexp
4435 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4436 org-bracket-link-analytic-regexp
4437 (concat
4438 "\\[\\["
4439 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4440 "\\([^]]+\\)"
4441 "\\]"
4442 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4443 "\\]")
4444 org-bracket-link-analytic-regexp++
4445 (concat
4446 "\\[\\["
4447 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4448 "\\([^]]+\\)"
4449 "\\]"
4450 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4451 "\\]")
4452 org-any-link-re
4453 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4454 org-angle-link-re "\\)\\|\\("
4455 org-plain-link-re "\\)")))
4457 (org-make-link-regexps)
4459 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4460 "Regular expression for fast time stamp matching.")
4461 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4462 "Regular expression for fast time stamp matching.")
4463 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4464 "Regular expression matching time strings for analysis.
4465 This one does not require the space after the date, so it can be used
4466 on a string that terminates immediately after the date.")
4467 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4468 "Regular expression matching time strings for analysis.")
4469 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4470 "Regular expression matching time stamps, with groups.")
4471 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4472 "Regular expression matching time stamps (also [..]), with groups.")
4473 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4474 "Regular expression matching a time stamp range.")
4475 (defconst org-tr-regexp-both
4476 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4477 "Regular expression matching a time stamp range.")
4478 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4479 org-ts-regexp "\\)?")
4480 "Regular expression matching a time stamp or time stamp range.")
4481 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4482 org-ts-regexp-both "\\)?")
4483 "Regular expression matching a time stamp or time stamp range.
4484 The time stamps may be either active or inactive.")
4486 (defvar org-emph-face nil)
4488 (defun org-do-emphasis-faces (limit)
4489 "Run through the buffer and add overlays to links."
4490 (let (rtn a)
4491 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4492 (if (not (= (char-after (match-beginning 3))
4493 (char-after (match-beginning 4))))
4494 (progn
4495 (setq rtn t)
4496 (setq a (assoc (match-string 3) org-emphasis-alist))
4497 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4498 'face
4499 (nth 1 a))
4500 (and (nth 4 a)
4501 (org-remove-flyspell-overlays-in
4502 (match-beginning 0) (match-end 0)))
4503 (add-text-properties (match-beginning 2) (match-end 2)
4504 '(font-lock-multiline t))
4505 (when org-hide-emphasis-markers
4506 (add-text-properties (match-end 4) (match-beginning 5)
4507 '(invisible org-link))
4508 (add-text-properties (match-beginning 3) (match-end 3)
4509 '(invisible org-link)))))
4510 (backward-char 1))
4511 rtn))
4513 (defun org-emphasize (&optional char)
4514 "Insert or change an emphasis, i.e. a font like bold or italic.
4515 If there is an active region, change that region to a new emphasis.
4516 If there is no region, just insert the marker characters and position
4517 the cursor between them.
4518 CHAR should be either the marker character, or the first character of the
4519 HTML tag associated with that emphasis. If CHAR is a space, the means
4520 to remove the emphasis of the selected region.
4521 If char is not given (for example in an interactive call) it
4522 will be prompted for."
4523 (interactive)
4524 (let ((eal org-emphasis-alist) e det
4525 (erc org-emphasis-regexp-components)
4526 (prompt "")
4527 (string "") beg end move tag c s)
4528 (if (org-region-active-p)
4529 (setq beg (region-beginning) end (region-end)
4530 string (buffer-substring beg end))
4531 (setq move t))
4533 (while (setq e (pop eal))
4534 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4535 c (aref tag 0))
4536 (push (cons c (string-to-char (car e))) det)
4537 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4538 (substring tag 1)))))
4539 (setq det (nreverse det))
4540 (unless char
4541 (message "%s" (concat "Emphasis marker or tag:" prompt))
4542 (setq char (read-char-exclusive)))
4543 (setq char (or (cdr (assoc char det)) char))
4544 (if (equal char ?\ )
4545 (setq s "" move nil)
4546 (unless (assoc (char-to-string char) org-emphasis-alist)
4547 (error "No such emphasis marker: \"%c\"" char))
4548 (setq s (char-to-string char)))
4549 (while (and (> (length string) 1)
4550 (equal (substring string 0 1) (substring string -1))
4551 (assoc (substring string 0 1) org-emphasis-alist))
4552 (setq string (substring string 1 -1)))
4553 (setq string (concat s string s))
4554 (if beg (delete-region beg end))
4555 (unless (or (bolp)
4556 (string-match (concat "[" (nth 0 erc) "\n]")
4557 (char-to-string (char-before (point)))))
4558 (insert " "))
4559 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4560 (char-to-string (char-after (point))))
4561 (insert " ") (backward-char 1))
4562 (insert string)
4563 (and move (backward-char 1))))
4565 (defconst org-nonsticky-props
4566 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4568 (defsubst org-rear-nonsticky-at (pos)
4569 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4571 (defun org-activate-plain-links (limit)
4572 "Run through the buffer and add overlays to links."
4573 (catch 'exit
4574 (let (f)
4575 (if (re-search-forward org-plain-link-re limit t)
4576 (progn
4577 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4578 (setq f (get-text-property (match-beginning 0) 'face))
4579 (if (or (eq f 'org-tag)
4580 (and (listp f) (memq 'org-tag f)))
4582 (add-text-properties (match-beginning 0) (match-end 0)
4583 (list 'mouse-face 'highlight
4584 'face 'org-link
4585 'keymap org-mouse-map))
4586 (org-rear-nonsticky-at (match-end 0)))
4587 t)))))
4589 (defun org-activate-code (limit)
4590 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4591 (progn
4592 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4593 (remove-text-properties (match-beginning 0) (match-end 0)
4594 '(display t invisible t intangible t))
4595 t)))
4597 (defun org-fontify-meta-lines-and-blocks (limit)
4598 "Fontify #+ lines and blocks, in the correct ways."
4599 (let ((case-fold-search t))
4600 (if (re-search-forward
4601 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4602 limit t)
4603 (let ((beg (match-beginning 0))
4604 (beg1 (line-beginning-position 2))
4605 (dc1 (downcase (match-string 2)))
4606 (dc3 (downcase (match-string 3)))
4607 end end1 quoting block-type)
4608 (cond
4609 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4610 ;; a single line of backend-specific content
4611 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4612 (remove-text-properties (match-beginning 0) (match-end 0)
4613 '(display t invisible t intangible t))
4614 (add-text-properties (match-beginning 1) (match-end 3)
4615 '(font-lock-fontified t face org-meta-line))
4616 (add-text-properties (match-beginning 6) (match-end 6)
4617 '(font-lock-fontified t face org-block))
4619 ((and (match-end 4) (equal dc3 "begin"))
4620 ;; Truely a block
4621 (setq block-type (downcase (match-string 5))
4622 quoting (member block-type org-protecting-blocks))
4623 (when (re-search-forward
4624 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4625 nil t) ;; on purpose, we look further than LIMIT
4626 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4627 (when quoting
4628 (remove-text-properties beg end
4629 '(display t invisible t intangible t)))
4630 (add-text-properties
4631 beg end
4632 '(font-lock-fontified t font-lock-multiline t))
4633 (add-text-properties beg beg1 '(face org-meta-line))
4634 (add-text-properties end1 end '(face org-meta-line))
4635 (cond
4636 (quoting
4637 (add-text-properties beg1 end1 '(face org-block)))
4638 ((string= block-type "quote")
4639 (add-text-properties beg1 end1 '(face org-quote)))
4640 ((string= block-type "verse")
4641 (add-text-properties beg1 end1 '(face org-verse))))
4643 ((not (member (char-after beg) '(?\ ?\t)))
4644 ;; just any other in-buffer setting, but not indented
4645 (add-text-properties
4646 beg (match-end 0)
4647 '(font-lock-fontified t face org-meta-line))
4649 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4650 "orgtbl:" "tblfm:" "tblname:"))
4651 (and (match-end 4) (equal dc3 "attr")))
4652 (add-text-properties
4653 beg (match-end 0)
4654 '(font-lock-fontified t face org-meta-line))
4656 ((member dc3 '(" " ""))
4657 (add-text-properties
4658 beg (match-end 0)
4659 '(font-lock-fontified t face font-lock-comment-face)))
4660 (t nil))))))
4662 (defun org-activate-angle-links (limit)
4663 "Run through the buffer and add overlays to links."
4664 (if (re-search-forward org-angle-link-re limit t)
4665 (progn
4666 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4667 (add-text-properties (match-beginning 0) (match-end 0)
4668 (list 'mouse-face 'highlight
4669 'keymap org-mouse-map))
4670 (org-rear-nonsticky-at (match-end 0))
4671 t)))
4673 (defun org-activate-footnote-links (limit)
4674 "Run through the buffer and add overlays to links."
4675 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4676 limit t)
4677 (progn
4678 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4679 (add-text-properties (match-beginning 2) (match-end 2)
4680 (list 'mouse-face 'highlight
4681 'keymap org-mouse-map
4682 'help-echo
4683 (if (= (point-at-bol) (match-beginning 2))
4684 "Footnote definition"
4685 "Footnote reference")
4687 (org-rear-nonsticky-at (match-end 2))
4688 t)))
4690 (defun org-activate-bracket-links (limit)
4691 "Run through the buffer and add overlays to bracketed links."
4692 (if (re-search-forward org-bracket-link-regexp limit t)
4693 (let* ((help (concat "LINK: "
4694 (org-match-string-no-properties 1)))
4695 ;; FIXME: above we should remove the escapes.
4696 ;; but that requires another match, protecting match data,
4697 ;; a lot of overhead for font-lock.
4698 (ip (org-maybe-intangible
4699 (list 'invisible 'org-link
4700 'keymap org-mouse-map 'mouse-face 'highlight
4701 'font-lock-multiline t 'help-echo help)))
4702 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4703 'font-lock-multiline t 'help-echo help)))
4704 ;; We need to remove the invisible property here. Table narrowing
4705 ;; may have made some of this invisible.
4706 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4707 (remove-text-properties (match-beginning 0) (match-end 0)
4708 '(invisible nil))
4709 (if (match-end 3)
4710 (progn
4711 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4712 (org-rear-nonsticky-at (match-beginning 3))
4713 (add-text-properties (match-beginning 3) (match-end 3) vp)
4714 (org-rear-nonsticky-at (match-end 3))
4715 (add-text-properties (match-end 3) (match-end 0) ip)
4716 (org-rear-nonsticky-at (match-end 0)))
4717 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4718 (org-rear-nonsticky-at (match-beginning 1))
4719 (add-text-properties (match-beginning 1) (match-end 1) vp)
4720 (org-rear-nonsticky-at (match-end 1))
4721 (add-text-properties (match-end 1) (match-end 0) ip)
4722 (org-rear-nonsticky-at (match-end 0)))
4723 t)))
4725 (defun org-activate-dates (limit)
4726 "Run through the buffer and add overlays to dates."
4727 (if (re-search-forward org-tsr-regexp-both limit t)
4728 (progn
4729 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4730 (add-text-properties (match-beginning 0) (match-end 0)
4731 (list 'mouse-face 'highlight
4732 'keymap org-mouse-map))
4733 (org-rear-nonsticky-at (match-end 0))
4734 (when org-display-custom-times
4735 (if (match-end 3)
4736 (org-display-custom-time (match-beginning 3) (match-end 3)))
4737 (org-display-custom-time (match-beginning 1) (match-end 1)))
4738 t)))
4740 (defvar org-target-link-regexp nil
4741 "Regular expression matching radio targets in plain text.")
4742 (make-variable-buffer-local 'org-target-link-regexp)
4743 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4744 "Regular expression matching a link target.")
4745 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4746 "Regular expression matching a radio target.")
4747 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4748 "Regular expression matching any target.")
4750 (defun org-activate-target-links (limit)
4751 "Run through the buffer and add overlays to target matches."
4752 (when org-target-link-regexp
4753 (let ((case-fold-search t))
4754 (if (re-search-forward org-target-link-regexp limit t)
4755 (progn
4756 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4757 (add-text-properties (match-beginning 0) (match-end 0)
4758 (list 'mouse-face 'highlight
4759 'keymap org-mouse-map
4760 'help-echo "Radio target link"
4761 'org-linked-text t))
4762 (org-rear-nonsticky-at (match-end 0))
4763 t)))))
4765 (defun org-update-radio-target-regexp ()
4766 "Find all radio targets in this file and update the regular expression."
4767 (interactive)
4768 (when (memq 'radio org-activate-links)
4769 (setq org-target-link-regexp
4770 (org-make-target-link-regexp (org-all-targets 'radio)))
4771 (org-restart-font-lock)))
4773 (defun org-hide-wide-columns (limit)
4774 (let (s e)
4775 (setq s (text-property-any (point) (or limit (point-max))
4776 'org-cwidth t))
4777 (when s
4778 (setq e (next-single-property-change s 'org-cwidth))
4779 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4780 (goto-char e)
4781 t)))
4783 (defvar org-latex-and-specials-regexp nil
4784 "Regular expression for highlighting export special stuff.")
4785 (defvar org-match-substring-regexp)
4786 (defvar org-match-substring-with-braces-regexp)
4788 ;; This should be with the exporter code, but we also use if for font-locking
4789 (defconst org-export-html-special-string-regexps
4790 '(("\\\\-" . "&shy;")
4791 ("---\\([^-]\\)" . "&mdash;\\1")
4792 ("--\\([^-]\\)" . "&ndash;\\1")
4793 ("\\.\\.\\." . "&hellip;"))
4794 "Regular expressions for special string conversion.")
4797 (defun org-compute-latex-and-specials-regexp ()
4798 "Compute regular expression for stuff treated specially by exporters."
4799 (if (not org-highlight-latex-fragments-and-specials)
4800 (org-set-local 'org-latex-and-specials-regexp nil)
4801 (require 'org-exp)
4802 (let*
4803 ((matchers (plist-get org-format-latex-options :matchers))
4804 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4805 org-latex-regexps)))
4806 (org-export-allow-BIND nil)
4807 (options (org-combine-plists (org-default-export-plist)
4808 (org-infile-export-plist)))
4809 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4810 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4811 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4812 (org-export-html-expand (plist-get options :expand-quoted-html))
4813 (org-export-with-special-strings (plist-get options :special-strings))
4814 (re-sub
4815 (cond
4816 ((equal org-export-with-sub-superscripts '{})
4817 (list org-match-substring-with-braces-regexp))
4818 (org-export-with-sub-superscripts
4819 (list org-match-substring-regexp))
4820 (t nil)))
4821 (re-latex
4822 (if org-export-with-LaTeX-fragments
4823 (mapcar (lambda (x) (nth 1 x)) latexs)))
4824 (re-macros
4825 (if org-export-with-TeX-macros
4826 (list (concat "\\\\"
4827 (regexp-opt
4828 (append (mapcar 'car org-html-entities)
4829 (if (boundp 'org-latex-entities)
4830 (mapcar (lambda (x)
4831 (or (car-safe x) x))
4832 org-latex-entities)
4833 nil))
4834 'words))) ; FIXME
4836 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4837 (re-special (if org-export-with-special-strings
4838 (mapcar (lambda (x) (car x))
4839 org-export-html-special-string-regexps)))
4840 (re-rest
4841 (delq nil
4842 (list
4843 (if org-export-html-expand "@<[^>\n]+>")
4844 ))))
4845 (org-set-local
4846 'org-latex-and-specials-regexp
4847 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4848 re-rest) "\\|")))))
4850 (defun org-do-latex-and-special-faces (limit)
4851 "Run through the buffer and add overlays to links."
4852 (when org-latex-and-specials-regexp
4853 (let (rtn d)
4854 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4855 limit t))
4856 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4857 'face))
4858 '(org-code org-verbatim underline)))
4859 (progn
4860 (setq rtn t
4861 d (cond ((member (char-after (1+ (match-beginning 0)))
4862 '(?_ ?^)) 1)
4863 (t 0)))
4864 (font-lock-prepend-text-property
4865 (+ d (match-beginning 0)) (match-end 0)
4866 'face 'org-latex-and-export-specials)
4867 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4868 '(font-lock-multiline t)))))
4869 rtn)))
4871 (defun org-restart-font-lock ()
4872 "Restart font-lock-mode, to force refontification."
4873 (when (and (boundp 'font-lock-mode) font-lock-mode)
4874 (font-lock-mode -1)
4875 (font-lock-mode 1)))
4877 (defun org-all-targets (&optional radio)
4878 "Return a list of all targets in this file.
4879 With optional argument RADIO, only find radio targets."
4880 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4881 rtn)
4882 (save-excursion
4883 (goto-char (point-min))
4884 (while (re-search-forward re nil t)
4885 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4886 rtn)))
4888 (defun org-make-target-link-regexp (targets)
4889 "Make regular expression matching all strings in TARGETS.
4890 The regular expression finds the targets also if there is a line break
4891 between words."
4892 (and targets
4893 (concat
4894 "\\<\\("
4895 (mapconcat
4896 (lambda (x)
4897 (while (string-match " +" x)
4898 (setq x (replace-match "\\s-+" t t x)))
4900 targets
4901 "\\|")
4902 "\\)\\>")))
4904 (defun org-activate-tags (limit)
4905 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4906 (progn
4907 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4908 (add-text-properties (match-beginning 1) (match-end 1)
4909 (list 'mouse-face 'highlight
4910 'keymap org-mouse-map))
4911 (org-rear-nonsticky-at (match-end 1))
4912 t)))
4914 (defun org-outline-level ()
4915 "Compute the outline level of the heading at point.
4916 This function assumes that the cursor is at the beginning of a line matched
4917 by outline-regexp. Otherwise it returns garbage.
4918 If this is called at a normal headline, the level is the number of stars.
4919 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4920 For plain list items, if they are matched by `outline-regexp', this returns
4921 1000 plus the line indentation."
4922 (save-excursion
4923 (looking-at outline-regexp)
4924 (if (match-beginning 1)
4925 (+ (org-get-string-indentation (match-string 1)) 1000)
4926 (1- (- (match-end 0) (match-beginning 0))))))
4928 (defvar org-font-lock-keywords nil)
4930 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4931 "Regular expression matching a property line.")
4933 (defvar org-font-lock-hook nil
4934 "Functions to be called for special font lock stuff.")
4936 (defun org-font-lock-hook (limit)
4937 (run-hook-with-args 'org-font-lock-hook limit))
4939 (defun org-set-font-lock-defaults ()
4940 (let* ((em org-fontify-emphasized-text)
4941 (lk org-activate-links)
4942 (org-font-lock-extra-keywords
4943 (list
4944 ;; Call the hook
4945 '(org-font-lock-hook)
4946 ;; Headlines
4947 `(,(if org-fontify-whole-heading-line
4948 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4949 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4950 (1 (org-get-level-face 1))
4951 (2 (org-get-level-face 2))
4952 (3 (org-get-level-face 3)))
4953 ;; Table lines
4954 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4955 (1 'org-table t))
4956 ;; Table internals
4957 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4958 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4959 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4960 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4961 ;; Drawers
4962 (list org-drawer-regexp '(0 'org-special-keyword t))
4963 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4964 ;; Properties
4965 (list org-property-re
4966 '(1 'org-special-keyword t)
4967 '(3 'org-property-value t))
4968 ;; Links
4969 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4970 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4971 (if (memq 'plain lk) '(org-activate-plain-links))
4972 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4973 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4974 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4975 (if (memq 'footnote lk) '(org-activate-footnote-links
4976 (2 'org-footnote t)))
4977 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4978 '(org-hide-wide-columns (0 nil append))
4979 ;; TODO lines
4980 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4981 '(1 (org-get-todo-face 1) t))
4982 ;; DONE
4983 (if org-fontify-done-headline
4984 (list (concat "^[*]+ +\\<\\("
4985 (mapconcat 'regexp-quote org-done-keywords "\\|")
4986 "\\)\\(.*\\)")
4987 '(2 'org-headline-done t))
4988 nil)
4989 ;; Priorities
4990 '(org-font-lock-add-priority-faces)
4991 ;; Tags
4992 '(org-font-lock-add-tag-faces)
4993 ;; Special keywords
4994 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4995 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4996 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4997 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4998 ;; Emphasis
4999 (if em
5000 (if (featurep 'xemacs)
5001 '(org-do-emphasis-faces (0 nil append))
5002 '(org-do-emphasis-faces)))
5003 ;; Checkboxes
5004 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5005 2 'org-checkbox prepend)
5006 (if org-provide-checkbox-statistics
5007 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5008 (0 (org-get-checkbox-statistics-face) t)))
5009 ;; Description list items
5010 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5011 2 'bold prepend)
5012 ;; ARCHIVEd headings
5013 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5014 '(1 'org-archived prepend))
5015 ;; Specials
5016 '(org-do-latex-and-special-faces)
5017 ;; Code
5018 '(org-activate-code (1 'org-code t))
5019 ;; COMMENT
5020 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5021 "\\|" org-quote-string "\\)\\>")
5022 '(1 'org-special-keyword t))
5023 '("^#.*" (0 'font-lock-comment-face t))
5024 ;; Blocks and meta lines
5025 '(org-fontify-meta-lines-and-blocks)
5027 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5028 ;; Now set the full font-lock-keywords
5029 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5030 (org-set-local 'font-lock-defaults
5031 '(org-font-lock-keywords t nil nil backward-paragraph))
5032 (kill-local-variable 'font-lock-keywords) nil))
5034 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5035 "Fontify string S like in Org-mode"
5036 (with-temp-buffer
5037 (insert s)
5038 (let ((org-odd-levels-only odd-levels))
5039 (org-mode)
5040 (font-lock-fontify-buffer)
5041 (buffer-string))))
5043 (defvar org-m nil)
5044 (defvar org-l nil)
5045 (defvar org-f nil)
5046 (defun org-get-level-face (n)
5047 "Get the right face for match N in font-lock matching of headlines."
5048 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5049 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5050 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5051 (cond
5052 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5053 ((eq n 2) org-f)
5054 (t (if org-level-color-stars-only nil org-f))))
5056 (defun org-get-todo-face (kwd)
5057 "Get the right face for a TODO keyword KWD.
5058 If KWD is a number, get the corresponding match group."
5059 (if (numberp kwd) (setq kwd (match-string kwd)))
5060 (or (cdr (assoc kwd org-todo-keyword-faces))
5061 (and (member kwd org-done-keywords) 'org-done)
5062 'org-todo))
5064 (defun org-font-lock-add-tag-faces (limit)
5065 "Add the special tag faces."
5066 (when (and org-tag-faces org-tags-special-faces-re)
5067 (while (re-search-forward org-tags-special-faces-re limit t)
5068 (add-text-properties (match-beginning 1) (match-end 1)
5069 (list 'face (org-get-tag-face 1)
5070 'font-lock-fontified t))
5071 (backward-char 1))))
5073 (defun org-font-lock-add-priority-faces (limit)
5074 "Add the special priority faces."
5075 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5076 (add-text-properties
5077 (match-beginning 0) (match-end 0)
5078 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5079 org-priority-faces))
5080 'org-special-keyword)
5081 'font-lock-fontified t))))
5083 (defun org-get-tag-face (kwd)
5084 "Get the right face for a TODO keyword KWD.
5085 If KWD is a number, get the corresponding match group."
5086 (if (numberp kwd) (setq kwd (match-string kwd)))
5087 (or (cdr (assoc kwd org-tag-faces))
5088 'org-tag))
5090 (defun org-unfontify-region (beg end &optional maybe_loudly)
5091 "Remove fontification and activation overlays from links."
5092 (font-lock-default-unfontify-region beg end)
5093 (let* ((buffer-undo-list t)
5094 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5095 (inhibit-modification-hooks t)
5096 deactivate-mark buffer-file-name buffer-file-truename)
5097 (remove-text-properties
5098 beg end
5099 (if org-indent-mode
5100 ;; also remove line-prefix and wrap-prefix properties
5101 '(mouse-face t keymap t org-linked-text t
5102 invisible t intangible t
5103 line-prefix t wrap-prefix t
5104 org-no-flyspell t)
5105 '(mouse-face t keymap t org-linked-text t
5106 invisible t intangible t
5107 org-no-flyspell t)))))
5109 ;;;; Visibility cycling, including org-goto and indirect buffer
5111 ;;; Cycling
5113 (defvar org-cycle-global-status nil)
5114 (make-variable-buffer-local 'org-cycle-global-status)
5115 (defvar org-cycle-subtree-status nil)
5116 (make-variable-buffer-local 'org-cycle-subtree-status)
5118 ;;;###autoload
5120 (defvar org-inlinetask-min-level)
5122 (defun org-cycle (&optional arg)
5123 "TAB-action and visibility cycling for Org-mode.
5125 This is the command invoked in Org-mode by the TAB key. Its main purpose
5126 is outline visibility cycling, but it also invokes other actions
5127 in special contexts.
5129 - When this function is called with a prefix argument, rotate the entire
5130 buffer through 3 states (global cycling)
5131 1. OVERVIEW: Show only top-level headlines.
5132 2. CONTENTS: Show all headlines of all levels, but no body text.
5133 3. SHOW ALL: Show everything.
5134 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5135 determined by the variable `org-startup-folded', and by any VISIBILITY
5136 properties in the buffer.
5137 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5138 including any drawers.
5140 - When inside a table, re-align the table and move to the next field.
5142 - When point is at the beginning of a headline, rotate the subtree started
5143 by this line through 3 different states (local cycling)
5144 1. FOLDED: Only the main headline is shown.
5145 2. CHILDREN: The main headline and the direct children are shown.
5146 From this state, you can move to one of the children
5147 and zoom in further.
5148 3. SUBTREE: Show the entire subtree, including body text.
5149 If there is no subtree, switch directly from CHILDREN to FOLDED.
5151 - When point is at the beginning of an empty headline and the variable
5152 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5153 of the headline by demoting and promoting it to likely levels. This
5154 speeds up creation document structure by presing TAB once or several
5155 times right after creating a new headline.
5157 - When there is a numeric prefix, go up to a heading with level ARG, do
5158 a `show-subtree' and return to the previous cursor position. If ARG
5159 is negative, go up that many levels.
5161 - When point is not at the beginning of a headline, execute the global
5162 binding for TAB, which is re-indenting the line. See the option
5163 `org-cycle-emulate-tab' for details.
5165 - Special case: if point is at the beginning of the buffer and there is
5166 no headline in line 1, this function will act as if called with prefix arg.
5167 But only if also the variable `org-cycle-global-at-bob' is t."
5168 (interactive "P")
5169 (org-load-modules-maybe)
5170 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5171 (and org-cycle-level-after-item/entry-creation
5172 (or (org-cycle-level)
5173 (org-cycle-item-indentation))))
5174 (let* ((limit-level
5175 (or org-cycle-max-level
5176 (and (boundp 'org-inlinetask-min-level)
5177 org-inlinetask-min-level
5178 (1- org-inlinetask-min-level))))
5179 (nstars (and limit-level
5180 (if org-odd-levels-only
5181 (and limit-level (1- (* limit-level 2)))
5182 limit-level)))
5183 (outline-regexp
5184 (cond
5185 ((not (org-mode-p)) outline-regexp)
5186 ((or (eq org-cycle-include-plain-lists 'integrate)
5187 (and org-cycle-include-plain-lists (org-at-item-p)))
5188 (concat "\\(?:\\*"
5189 (if nstars (format "\\{1,%d\\}" nstars) "+")
5190 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5191 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5192 (bob-special (and org-cycle-global-at-bob (bobp)
5193 (not (looking-at outline-regexp))))
5194 (org-cycle-hook
5195 (if bob-special
5196 (delq 'org-optimize-window-after-visibility-change
5197 (copy-sequence org-cycle-hook))
5198 org-cycle-hook))
5199 (pos (point)))
5201 (if (or bob-special (equal arg '(4)))
5202 ;; special case: use global cycling
5203 (setq arg t))
5205 (cond
5207 ((equal arg '(16))
5208 (org-set-startup-visibility)
5209 (message "Startup visibility, plus VISIBILITY properties"))
5211 ((equal arg '(64))
5212 (show-all)
5213 (message "Entire buffer visible, including drawers"))
5215 ((org-at-table-p 'any)
5216 ;; Enter the table or move to the next field in the table
5217 (or (org-table-recognize-table.el)
5218 (progn
5219 (if arg (org-table-edit-field t)
5220 (org-table-justify-field-maybe)
5221 (call-interactively 'org-table-next-field)))))
5223 ((run-hook-with-args-until-success
5224 'org-tab-after-check-for-table-hook))
5226 ((eq arg t) ;; Global cycling
5227 (org-cycle-internal-global))
5229 ((and org-drawers org-drawer-regexp
5230 (save-excursion
5231 (beginning-of-line 1)
5232 (looking-at org-drawer-regexp)))
5233 ;; Toggle block visibility
5234 (org-flag-drawer
5235 (not (get-char-property (match-end 0) 'invisible))))
5237 ((integerp arg)
5238 ;; Show-subtree, ARG levels up from here.
5239 (save-excursion
5240 (org-back-to-heading)
5241 (outline-up-heading (if (< arg 0) (- arg)
5242 (- (funcall outline-level) arg)))
5243 (org-show-subtree)))
5245 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5246 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5248 (org-cycle-internal-local))
5250 ;; TAB emulation and template completion
5251 (buffer-read-only (org-back-to-heading))
5253 ((run-hook-with-args-until-success
5254 'org-tab-after-check-for-cycling-hook))
5256 ((org-try-structure-completion))
5258 ((org-try-cdlatex-tab))
5260 ((run-hook-with-args-until-success
5261 'org-tab-before-tab-emulation-hook))
5263 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5264 (or (not (bolp))
5265 (not (looking-at outline-regexp))))
5266 (call-interactively (global-key-binding "\t")))
5268 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5269 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5270 (or (and (eq org-cycle-emulate-tab 'white)
5271 (= (match-end 0) (point-at-eol)))
5272 (and (eq org-cycle-emulate-tab 'whitestart)
5273 (>= (match-end 0) pos))))
5275 (eq org-cycle-emulate-tab t))
5276 (call-interactively (global-key-binding "\t")))
5278 (t (save-excursion
5279 (org-back-to-heading)
5280 (org-cycle)))))))
5282 (defun org-cycle-internal-global ()
5283 "Do the global cycling action."
5284 (cond
5285 ((and (eq last-command this-command)
5286 (eq org-cycle-global-status 'overview))
5287 ;; We just created the overview - now do table of contents
5288 ;; This can be slow in very large buffers, so indicate action
5289 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5290 (message "CONTENTS...")
5291 (org-content)
5292 (message "CONTENTS...done")
5293 (setq org-cycle-global-status 'contents)
5294 (run-hook-with-args 'org-cycle-hook 'contents))
5296 ((and (eq last-command this-command)
5297 (eq org-cycle-global-status 'contents))
5298 ;; We just showed the table of contents - now show everything
5299 (run-hook-with-args 'org-pre-cycle-hook 'all)
5300 (show-all)
5301 (message "SHOW ALL")
5302 (setq org-cycle-global-status 'all)
5303 (run-hook-with-args 'org-cycle-hook 'all))
5306 ;; Default action: go to overview
5307 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5308 (org-overview)
5309 (message "OVERVIEW")
5310 (setq org-cycle-global-status 'overview)
5311 (run-hook-with-args 'org-cycle-hook 'overview))))
5313 (defun org-cycle-internal-local ()
5314 "Do the local cycling action."
5315 (org-back-to-heading)
5316 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5317 ;; First, some boundaries
5318 (save-excursion
5319 (org-back-to-heading)
5320 (setq level (funcall outline-level))
5321 (save-excursion
5322 (beginning-of-line 2)
5323 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5324 ; XEmacs does not have `next-single-char-property-change'
5325 ; I'm not sure about Emacs 21.
5326 (while (and (not (eobp)) ;; this is like `next-line'
5327 (get-char-property (1- (point)) 'invisible))
5328 (beginning-of-line 2))
5329 (while (and (not (eobp)) ;; this is like `next-line'
5330 (get-char-property (1- (point)) 'invisible))
5331 (goto-char (next-single-char-property-change (point) 'invisible))
5332 ;;;??? (or (bolp) (beginning-of-line 2))))
5333 (and (eolp) (beginning-of-line 2))))
5334 (setq eol (point)))
5335 (outline-end-of-heading) (setq eoh (point))
5336 (save-excursion
5337 (outline-next-heading)
5338 (setq has-children (and (org-at-heading-p t)
5339 (> (funcall outline-level) level))))
5340 (org-end-of-subtree t)
5341 (unless (eobp)
5342 (skip-chars-forward " \t\n")
5343 (beginning-of-line 1) ; in case this is an item
5345 (setq eos (if (eobp) (point) (1- (point)))))
5346 ;; Find out what to do next and set `this-command'
5347 (cond
5348 ((= eos eoh)
5349 ;; Nothing is hidden behind this heading
5350 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5351 (message "EMPTY ENTRY")
5352 (setq org-cycle-subtree-status nil)
5353 (save-excursion
5354 (goto-char eos)
5355 (outline-next-heading)
5356 (if (org-invisible-p) (org-flag-heading nil))))
5357 ((and (or (>= eol eos)
5358 (not (string-match "\\S-" (buffer-substring eol eos))))
5359 (or has-children
5360 (not (setq children-skipped
5361 org-cycle-skip-children-state-if-no-children))))
5362 ;; Entire subtree is hidden in one line: children view
5363 (run-hook-with-args 'org-pre-cycle-hook 'children)
5364 (org-show-entry)
5365 (show-children)
5366 (message "CHILDREN")
5367 (save-excursion
5368 (goto-char eos)
5369 (outline-next-heading)
5370 (if (org-invisible-p) (org-flag-heading nil)))
5371 (setq org-cycle-subtree-status 'children)
5372 (run-hook-with-args 'org-cycle-hook 'children))
5373 ((or children-skipped
5374 (and (eq last-command this-command)
5375 (eq org-cycle-subtree-status 'children)))
5376 ;; We just showed the children, or no children are there,
5377 ;; now show everything.
5378 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5379 (org-show-subtree)
5380 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5381 (setq org-cycle-subtree-status 'subtree)
5382 (run-hook-with-args 'org-cycle-hook 'subtree))
5384 ;; Default action: hide the subtree.
5385 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5386 (hide-subtree)
5387 (message "FOLDED")
5388 (setq org-cycle-subtree-status 'folded)
5389 (run-hook-with-args 'org-cycle-hook 'folded)))))
5391 ;;;###autoload
5392 (defun org-global-cycle (&optional arg)
5393 "Cycle the global visibility. For details see `org-cycle'.
5394 With C-u prefix arg, switch to startup visibility.
5395 With a numeric prefix, show all headlines up to that level."
5396 (interactive "P")
5397 (let ((org-cycle-include-plain-lists
5398 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5399 (cond
5400 ((integerp arg)
5401 (show-all)
5402 (hide-sublevels arg)
5403 (setq org-cycle-global-status 'contents))
5404 ((equal arg '(4))
5405 (org-set-startup-visibility)
5406 (message "Startup visibility, plus VISIBILITY properties."))
5408 (org-cycle '(4))))))
5410 (defun org-set-startup-visibility ()
5411 "Set the visibility required by startup options and properties."
5412 (cond
5413 ((eq org-startup-folded t)
5414 (org-cycle '(4)))
5415 ((eq org-startup-folded 'content)
5416 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5417 (org-cycle '(4)) (org-cycle '(4)))))
5418 (unless (eq org-startup-folded 'showeverything)
5419 (if org-hide-block-startup (org-hide-block-all))
5420 (org-set-visibility-according-to-property 'no-cleanup)
5421 (org-cycle-hide-archived-subtrees 'all)
5422 (org-cycle-hide-drawers 'all)
5423 (org-cycle-show-empty-lines 'all)))
5425 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5426 "Switch subtree visibilities according to :VISIBILITY: property."
5427 (interactive)
5428 (let (org-show-entry-below state)
5429 (save-excursion
5430 (goto-char (point-min))
5431 (while (re-search-forward
5432 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5433 nil t)
5434 (setq state (match-string 1))
5435 (save-excursion
5436 (org-back-to-heading t)
5437 (hide-subtree)
5438 (org-reveal)
5439 (cond
5440 ((equal state '("fold" "folded"))
5441 (hide-subtree))
5442 ((equal state "children")
5443 (org-show-hidden-entry)
5444 (show-children))
5445 ((equal state "content")
5446 (save-excursion
5447 (save-restriction
5448 (org-narrow-to-subtree)
5449 (org-content))))
5450 ((member state '("all" "showall"))
5451 (show-subtree)))))
5452 (unless no-cleanup
5453 (org-cycle-hide-archived-subtrees 'all)
5454 (org-cycle-hide-drawers 'all)
5455 (org-cycle-show-empty-lines 'all)))))
5457 (defun org-overview ()
5458 "Switch to overview mode, showing only top-level headlines.
5459 Really, this shows all headlines with level equal or greater than the level
5460 of the first headline in the buffer. This is important, because if the
5461 first headline is not level one, then (hide-sublevels 1) gives confusing
5462 results."
5463 (interactive)
5464 (let ((level (save-excursion
5465 (goto-char (point-min))
5466 (if (re-search-forward (concat "^" outline-regexp) nil t)
5467 (progn
5468 (goto-char (match-beginning 0))
5469 (funcall outline-level))))))
5470 (and level (hide-sublevels level))))
5472 (defun org-content (&optional arg)
5473 "Show all headlines in the buffer, like a table of contents.
5474 With numerical argument N, show content up to level N."
5475 (interactive "P")
5476 (save-excursion
5477 ;; Visit all headings and show their offspring
5478 (and (integerp arg) (org-overview))
5479 (goto-char (point-max))
5480 (catch 'exit
5481 (while (and (progn (condition-case nil
5482 (outline-previous-visible-heading 1)
5483 (error (goto-char (point-min))))
5485 (looking-at outline-regexp))
5486 (if (integerp arg)
5487 (show-children (1- arg))
5488 (show-branches))
5489 (if (bobp) (throw 'exit nil))))))
5492 (defun org-optimize-window-after-visibility-change (state)
5493 "Adjust the window after a change in outline visibility.
5494 This function is the default value of the hook `org-cycle-hook'."
5495 (when (get-buffer-window (current-buffer))
5496 (cond
5497 ((eq state 'content) nil)
5498 ((eq state 'all) nil)
5499 ((eq state 'folded) nil)
5500 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5501 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5503 (defun org-remove-empty-overlays-at (pos)
5504 "Remove outline overlays that do not contain non-white stuff."
5505 (mapc
5506 (lambda (o)
5507 (and (eq 'outline (org-overlay-get o 'invisible))
5508 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5509 (org-overlay-end o))))
5510 (org-delete-overlay o)))
5511 (org-overlays-at pos)))
5513 (defun org-clean-visibility-after-subtree-move ()
5514 "Fix visibility issues after moving a subtree."
5515 ;; First, find a reasonable region to look at:
5516 ;; Start two siblings above, end three below
5517 (let* ((beg (save-excursion
5518 (and (org-get-last-sibling)
5519 (org-get-last-sibling))
5520 (point)))
5521 (end (save-excursion
5522 (and (org-get-next-sibling)
5523 (org-get-next-sibling)
5524 (org-get-next-sibling))
5525 (if (org-at-heading-p)
5526 (point-at-eol)
5527 (point))))
5528 (level (looking-at "\\*+"))
5529 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5530 (save-excursion
5531 (save-restriction
5532 (narrow-to-region beg end)
5533 (when re
5534 ;; Properly fold already folded siblings
5535 (goto-char (point-min))
5536 (while (re-search-forward re nil t)
5537 (if (and (not (org-invisible-p))
5538 (save-excursion
5539 (goto-char (point-at-eol)) (org-invisible-p)))
5540 (hide-entry))))
5541 (org-cycle-show-empty-lines 'overview)
5542 (org-cycle-hide-drawers 'overview)))))
5544 (defun org-cycle-show-empty-lines (state)
5545 "Show empty lines above all visible headlines.
5546 The region to be covered depends on STATE when called through
5547 `org-cycle-hook'. Lisp program can use t for STATE to get the
5548 entire buffer covered. Note that an empty line is only shown if there
5549 are at least `org-cycle-separator-lines' empty lines before the headline."
5550 (when (not (= org-cycle-separator-lines 0))
5551 (save-excursion
5552 (let* ((n (abs org-cycle-separator-lines))
5553 (re (cond
5554 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5555 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5556 (t (let ((ns (number-to-string (- n 2))))
5557 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5558 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5559 beg end b e)
5560 (cond
5561 ((memq state '(overview contents t))
5562 (setq beg (point-min) end (point-max)))
5563 ((memq state '(children folded))
5564 (setq beg (point) end (progn (org-end-of-subtree t t)
5565 (beginning-of-line 2)
5566 (point)))))
5567 (when beg
5568 (goto-char beg)
5569 (while (re-search-forward re end t)
5570 (unless (get-char-property (match-end 1) 'invisible)
5571 (setq e (match-end 1))
5572 (if (< org-cycle-separator-lines 0)
5573 (setq b (save-excursion
5574 (goto-char (match-beginning 0))
5575 (org-back-over-empty-lines)
5576 (if (save-excursion
5577 (goto-char (max (point-min) (1- (point))))
5578 (org-on-heading-p))
5579 (1- (point))
5580 (point))))
5581 (setq b (match-beginning 1)))
5582 (outline-flag-region b e nil)))))))
5583 ;; Never hide empty lines at the end of the file.
5584 (save-excursion
5585 (goto-char (point-max))
5586 (outline-previous-heading)
5587 (outline-end-of-heading)
5588 (if (and (looking-at "[ \t\n]+")
5589 (= (match-end 0) (point-max)))
5590 (outline-flag-region (point) (match-end 0) nil))))
5592 (defun org-show-empty-lines-in-parent ()
5593 "Move to the parent and re-show empty lines before visible headlines."
5594 (save-excursion
5595 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5596 (org-cycle-show-empty-lines context))))
5598 (defun org-files-list ()
5599 "Return `org-agenda-files' list, plus all open org-mode files.
5600 This is useful for operations that need to scan all of a user's
5601 open and agenda-wise Org files."
5602 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5603 (dolist (buf (buffer-list))
5604 (with-current-buffer buf
5605 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5606 (let ((file (expand-file-name (buffer-file-name))))
5607 (unless (member file files)
5608 (push file files))))))
5609 files))
5611 (defsubst org-entry-beginning-position ()
5612 "Return the beginning position of the current entry."
5613 (save-excursion (outline-back-to-heading t) (point)))
5615 (defsubst org-entry-end-position ()
5616 "Return the end position of the current entry."
5617 (save-excursion (outline-next-heading) (point)))
5619 (defun org-cycle-hide-drawers (state)
5620 "Re-hide all drawers after a visibility state change."
5621 (when (and (org-mode-p)
5622 (not (memq state '(overview folded contents))))
5623 (save-excursion
5624 (let* ((globalp (memq state '(contents all)))
5625 (beg (if globalp (point-min) (point)))
5626 (end (if globalp (point-max)
5627 (if (eq state 'children)
5628 (save-excursion (outline-next-heading) (point))
5629 (org-end-of-subtree t)))))
5630 (goto-char beg)
5631 (while (re-search-forward org-drawer-regexp end t)
5632 (org-flag-drawer t))))))
5634 (defun org-flag-drawer (flag)
5635 (save-excursion
5636 (beginning-of-line 1)
5637 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5638 (let ((b (match-end 0))
5639 (outline-regexp org-outline-regexp))
5640 (if (re-search-forward
5641 "^[ \t]*:END:"
5642 (save-excursion (outline-next-heading) (point)) t)
5643 (outline-flag-region b (point-at-eol) flag)
5644 (error ":END: line missing at position %s" b))))))
5646 (defun org-subtree-end-visible-p ()
5647 "Is the end of the current subtree visible?"
5648 (pos-visible-in-window-p
5649 (save-excursion (org-end-of-subtree t) (point))))
5651 (defun org-first-headline-recenter (&optional N)
5652 "Move cursor to the first headline and recenter the headline.
5653 Optional argument N means put the headline into the Nth line of the window."
5654 (goto-char (point-min))
5655 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5656 (beginning-of-line)
5657 (recenter (prefix-numeric-value N))))
5659 ;;; Saving and restoring visibility
5661 (defun org-outline-overlay-data (&optional use-markers)
5662 "Return a list of the locations of all outline overlays.
5663 The are overlays with the `invisible' property value `outline'.
5664 The return valus is a list of cons cells, with start and stop
5665 positions for each overlay.
5666 If USE-MARKERS is set, return the positions as markers."
5667 (let (beg end)
5668 (save-excursion
5669 (save-restriction
5670 (widen)
5671 (delq nil
5672 (mapcar (lambda (o)
5673 (when (eq (org-overlay-get o 'invisible) 'outline)
5674 (setq beg (org-overlay-start o)
5675 end (org-overlay-end o))
5676 (and beg end (> end beg)
5677 (if use-markers
5678 (cons (move-marker (make-marker) beg)
5679 (move-marker (make-marker) end))
5680 (cons beg end)))))
5681 (org-overlays-in (point-min) (point-max))))))))
5683 (defun org-set-outline-overlay-data (data)
5684 "Create visibility overlays for all positions in DATA.
5685 DATA should have been made by `org-outline-overlay-data'."
5686 (let (o)
5687 (save-excursion
5688 (save-restriction
5689 (widen)
5690 (show-all)
5691 (mapc (lambda (c)
5692 (setq o (org-make-overlay (car c) (cdr c)))
5693 (org-overlay-put o 'invisible 'outline))
5694 data)))))
5696 (defmacro org-save-outline-visibility (use-markers &rest body)
5697 "Save and restore outline visibility around BODY.
5698 If USE-MARKERS is non-nil, use markers for the positions.
5699 This means that the buffer may change while running BODY,
5700 but it also means that the buffer should stay alive
5701 during the operation, because otherwise all these markers will
5702 point nowhere."
5703 `(let ((data (org-outline-overlay-data ,use-markers)))
5704 (unwind-protect
5705 (progn
5706 ,@body
5707 (org-set-outline-overlay-data data))
5708 (when ,use-markers
5709 (mapc (lambda (c)
5710 (and (markerp (car c)) (move-marker (car c) nil))
5711 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5712 data)))))
5715 ;;; Folding of blocks
5717 (defconst org-block-regexp
5719 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5720 "Regular expression for hiding blocks.")
5722 (defvar org-hide-block-overlays nil
5723 "Overlays hiding blocks.")
5724 (make-variable-buffer-local 'org-hide-block-overlays)
5726 (defun org-block-map (function &optional start end)
5727 "Call func at the head of all source blocks in the current
5728 buffer. Optional arguments START and END can be used to limit
5729 the range."
5730 (let ((start (or start (point-min)))
5731 (end (or end (point-max))))
5732 (save-excursion
5733 (goto-char start)
5734 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5735 (save-excursion
5736 (save-match-data
5737 (goto-char (match-beginning 0))
5738 (funcall function)))))))
5740 (defun org-hide-block-toggle-all ()
5741 "Toggle the visibility of all blocks in the current buffer."
5742 (org-block-map #'org-hide-block-toggle))
5744 (defun org-hide-block-all ()
5745 "Fold all blocks in the current buffer."
5746 (interactive)
5747 (org-show-block-all)
5748 (org-block-map #'org-hide-block-toggle-maybe))
5750 (defun org-show-block-all ()
5751 "Unfold all blocks in the current buffer."
5752 (mapc 'org-delete-overlay org-hide-block-overlays)
5753 (setq org-hide-block-overlays nil))
5755 (defun org-hide-block-toggle-maybe ()
5756 "Toggle visibility of block at point."
5757 (interactive)
5758 (let ((case-fold-search t))
5759 (if (save-excursion
5760 (beginning-of-line 1)
5761 (looking-at org-block-regexp))
5762 (progn (org-hide-block-toggle)
5763 t) ;; to signal that we took action
5764 nil))) ;; to signal that we did not
5766 (defun org-hide-block-toggle (&optional force)
5767 "Toggle the visibility of the current block."
5768 (interactive)
5769 (save-excursion
5770 (beginning-of-line)
5771 (if (re-search-forward org-block-regexp nil t)
5772 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5773 (end (match-end 0)) ;; end of entire body
5775 (if (memq t (mapcar (lambda (overlay)
5776 (eq (org-overlay-get overlay 'invisible)
5777 'org-hide-block))
5778 (org-overlays-at start)))
5779 (if (or (not force) (eq force 'off))
5780 (mapc (lambda (ov)
5781 (when (member ov org-hide-block-overlays)
5782 (setq org-hide-block-overlays
5783 (delq ov org-hide-block-overlays)))
5784 (when (eq (org-overlay-get ov 'invisible)
5785 'org-hide-block)
5786 (org-delete-overlay ov)))
5787 (org-overlays-at start)))
5788 (setq ov (org-make-overlay start end))
5789 (org-overlay-put ov 'invisible 'org-hide-block)
5790 ;; make the block accessible to isearch
5791 (org-overlay-put
5792 ov 'isearch-open-invisible
5793 (lambda (ov)
5794 (when (member ov org-hide-block-overlays)
5795 (setq org-hide-block-overlays
5796 (delq ov org-hide-block-overlays)))
5797 (when (eq (org-overlay-get ov 'invisible)
5798 'org-hide-block)
5799 (org-delete-overlay ov))))
5800 (push ov org-hide-block-overlays)))
5801 (error "Not looking at a source block"))))
5803 ;; org-tab-after-check-for-cycling-hook
5804 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5805 ;; Remove overlays when changing major mode
5806 (add-hook 'org-mode-hook
5807 (lambda () (org-add-hook 'change-major-mode-hook
5808 'org-show-block-all 'append 'local)))
5810 ;;; Org-goto
5812 (defvar org-goto-window-configuration nil)
5813 (defvar org-goto-marker nil)
5814 (defvar org-goto-map
5815 (let ((map (make-sparse-keymap)))
5816 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5817 (while (setq cmd (pop cmds))
5818 (substitute-key-definition cmd cmd map global-map)))
5819 (suppress-keymap map)
5820 (org-defkey map "\C-m" 'org-goto-ret)
5821 (org-defkey map [(return)] 'org-goto-ret)
5822 (org-defkey map [(left)] 'org-goto-left)
5823 (org-defkey map [(right)] 'org-goto-right)
5824 (org-defkey map [(control ?g)] 'org-goto-quit)
5825 (org-defkey map "\C-i" 'org-cycle)
5826 (org-defkey map [(tab)] 'org-cycle)
5827 (org-defkey map [(down)] 'outline-next-visible-heading)
5828 (org-defkey map [(up)] 'outline-previous-visible-heading)
5829 (if org-goto-auto-isearch
5830 (if (fboundp 'define-key-after)
5831 (define-key-after map [t] 'org-goto-local-auto-isearch)
5832 nil)
5833 (org-defkey map "q" 'org-goto-quit)
5834 (org-defkey map "n" 'outline-next-visible-heading)
5835 (org-defkey map "p" 'outline-previous-visible-heading)
5836 (org-defkey map "f" 'outline-forward-same-level)
5837 (org-defkey map "b" 'outline-backward-same-level)
5838 (org-defkey map "u" 'outline-up-heading))
5839 (org-defkey map "/" 'org-occur)
5840 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5841 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5842 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5843 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5844 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5845 map))
5847 (defconst org-goto-help
5848 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5849 RET=jump to location [Q]uit and return to previous location
5850 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5852 (defvar org-goto-start-pos) ; dynamically scoped parameter
5854 ;; FIXME: Docstring does not mention both interfaces
5855 (defun org-goto (&optional alternative-interface)
5856 "Look up a different location in the current file, keeping current visibility.
5858 When you want look-up or go to a different location in a document, the
5859 fastest way is often to fold the entire buffer and then dive into the tree.
5860 This method has the disadvantage, that the previous location will be folded,
5861 which may not be what you want.
5863 This command works around this by showing a copy of the current buffer
5864 in an indirect buffer, in overview mode. You can dive into the tree in
5865 that copy, use org-occur and incremental search to find a location.
5866 When pressing RET or `Q', the command returns to the original buffer in
5867 which the visibility is still unchanged. After RET is will also jump to
5868 the location selected in the indirect buffer and expose the
5869 the headline hierarchy above."
5870 (interactive "P")
5871 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5872 (org-refile-use-outline-path t)
5873 (org-refile-target-verify-function nil)
5874 (interface
5875 (if (not alternative-interface)
5876 org-goto-interface
5877 (if (eq org-goto-interface 'outline)
5878 'outline-path-completion
5879 'outline)))
5880 (org-goto-start-pos (point))
5881 (selected-point
5882 (if (eq interface 'outline)
5883 (car (org-get-location (current-buffer) org-goto-help))
5884 (nth 3 (org-refile-get-location "Goto: ")))))
5885 (if selected-point
5886 (progn
5887 (org-mark-ring-push org-goto-start-pos)
5888 (goto-char selected-point)
5889 (if (or (org-invisible-p) (org-invisible-p2))
5890 (org-show-context 'org-goto)))
5891 (message "Quit"))))
5893 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5894 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5895 (defvar org-goto-local-auto-isearch-map) ; defined below
5897 (defun org-get-location (buf help)
5898 "Let the user select a location in the Org-mode buffer BUF.
5899 This function uses a recursive edit. It returns the selected position
5900 or nil."
5901 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5902 (isearch-hide-immediately nil)
5903 (isearch-search-fun-function
5904 (lambda () 'org-goto-local-search-headings))
5905 (org-goto-selected-point org-goto-exit-command))
5906 (save-excursion
5907 (save-window-excursion
5908 (delete-other-windows)
5909 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5910 (switch-to-buffer
5911 (condition-case nil
5912 (make-indirect-buffer (current-buffer) "*org-goto*")
5913 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5914 (with-output-to-temp-buffer "*Help*"
5915 (princ help))
5916 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5917 (setq buffer-read-only nil)
5918 (let ((org-startup-truncated t)
5919 (org-startup-folded nil)
5920 (org-startup-align-all-tables nil))
5921 (org-mode)
5922 (org-overview))
5923 (setq buffer-read-only t)
5924 (if (and (boundp 'org-goto-start-pos)
5925 (integer-or-marker-p org-goto-start-pos))
5926 (let ((org-show-hierarchy-above t)
5927 (org-show-siblings t)
5928 (org-show-following-heading t))
5929 (goto-char org-goto-start-pos)
5930 (and (org-invisible-p) (org-show-context)))
5931 (goto-char (point-min)))
5932 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5933 (message "Select location and press RET")
5934 (use-local-map org-goto-map)
5935 (recursive-edit)
5937 (kill-buffer "*org-goto*")
5938 (cons org-goto-selected-point org-goto-exit-command)))
5940 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5941 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5942 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5943 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5945 (defun org-goto-local-search-headings (string bound noerror)
5946 "Search and make sure that any matches are in headlines."
5947 (catch 'return
5948 (while (if isearch-forward
5949 (search-forward string bound noerror)
5950 (search-backward string bound noerror))
5951 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5952 (and (member :headline context)
5953 (not (member :tags context))))
5954 (throw 'return (point))))))
5956 (defun org-goto-local-auto-isearch ()
5957 "Start isearch."
5958 (interactive)
5959 (goto-char (point-min))
5960 (let ((keys (this-command-keys)))
5961 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5962 (isearch-mode t)
5963 (isearch-process-search-char (string-to-char keys)))))
5965 (defun org-goto-ret (&optional arg)
5966 "Finish `org-goto' by going to the new location."
5967 (interactive "P")
5968 (setq org-goto-selected-point (point)
5969 org-goto-exit-command 'return)
5970 (throw 'exit nil))
5972 (defun org-goto-left ()
5973 "Finish `org-goto' by going to the new location."
5974 (interactive)
5975 (if (org-on-heading-p)
5976 (progn
5977 (beginning-of-line 1)
5978 (setq org-goto-selected-point (point)
5979 org-goto-exit-command 'left)
5980 (throw 'exit nil))
5981 (error "Not on a heading")))
5983 (defun org-goto-right ()
5984 "Finish `org-goto' by going to the new location."
5985 (interactive)
5986 (if (org-on-heading-p)
5987 (progn
5988 (setq org-goto-selected-point (point)
5989 org-goto-exit-command 'right)
5990 (throw 'exit nil))
5991 (error "Not on a heading")))
5993 (defun org-goto-quit ()
5994 "Finish `org-goto' without cursor motion."
5995 (interactive)
5996 (setq org-goto-selected-point nil)
5997 (setq org-goto-exit-command 'quit)
5998 (throw 'exit nil))
6000 ;;; Indirect buffer display of subtrees
6002 (defvar org-indirect-dedicated-frame nil
6003 "This is the frame being used for indirect tree display.")
6004 (defvar org-last-indirect-buffer nil)
6006 (defun org-tree-to-indirect-buffer (&optional arg)
6007 "Create indirect buffer and narrow it to current subtree.
6008 With numerical prefix ARG, go up to this level and then take that tree.
6009 If ARG is negative, go up that many levels.
6010 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6011 indirect buffer previously made with this command, to avoid proliferation of
6012 indirect buffers. However, when you call the command with a `C-u' prefix, or
6013 when `org-indirect-buffer-display' is `new-frame', the last buffer
6014 is kept so that you can work with several indirect buffers at the same time.
6015 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6016 requests that a new frame be made for the new buffer, so that the dedicated
6017 frame is not changed."
6018 (interactive "P")
6019 (let ((cbuf (current-buffer))
6020 (cwin (selected-window))
6021 (pos (point))
6022 beg end level heading ibuf)
6023 (save-excursion
6024 (org-back-to-heading t)
6025 (when (numberp arg)
6026 (setq level (org-outline-level))
6027 (if (< arg 0) (setq arg (+ level arg)))
6028 (while (> (setq level (org-outline-level)) arg)
6029 (outline-up-heading 1 t)))
6030 (setq beg (point)
6031 heading (org-get-heading))
6032 (org-end-of-subtree t t)
6033 (if (org-on-heading-p) (backward-char 1))
6034 (setq end (point)))
6035 (if (and (buffer-live-p org-last-indirect-buffer)
6036 (not (eq org-indirect-buffer-display 'new-frame))
6037 (not arg))
6038 (kill-buffer org-last-indirect-buffer))
6039 (setq ibuf (org-get-indirect-buffer cbuf)
6040 org-last-indirect-buffer ibuf)
6041 (cond
6042 ((or (eq org-indirect-buffer-display 'new-frame)
6043 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6044 (select-frame (make-frame))
6045 (delete-other-windows)
6046 (switch-to-buffer ibuf)
6047 (org-set-frame-title heading))
6048 ((eq org-indirect-buffer-display 'dedicated-frame)
6049 (raise-frame
6050 (select-frame (or (and org-indirect-dedicated-frame
6051 (frame-live-p org-indirect-dedicated-frame)
6052 org-indirect-dedicated-frame)
6053 (setq org-indirect-dedicated-frame (make-frame)))))
6054 (delete-other-windows)
6055 (switch-to-buffer ibuf)
6056 (org-set-frame-title (concat "Indirect: " heading)))
6057 ((eq org-indirect-buffer-display 'current-window)
6058 (switch-to-buffer ibuf))
6059 ((eq org-indirect-buffer-display 'other-window)
6060 (pop-to-buffer ibuf))
6061 (t (error "Invalid value")))
6062 (if (featurep 'xemacs)
6063 (save-excursion (org-mode) (turn-on-font-lock)))
6064 (narrow-to-region beg end)
6065 (show-all)
6066 (goto-char pos)
6067 (and (window-live-p cwin) (select-window cwin))))
6069 (defun org-get-indirect-buffer (&optional buffer)
6070 (setq buffer (or buffer (current-buffer)))
6071 (let ((n 1) (base (buffer-name buffer)) bname)
6072 (while (buffer-live-p
6073 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6074 (setq n (1+ n)))
6075 (condition-case nil
6076 (make-indirect-buffer buffer bname 'clone)
6077 (error (make-indirect-buffer buffer bname)))))
6079 (defun org-set-frame-title (title)
6080 "Set the title of the current frame to the string TITLE."
6081 ;; FIXME: how to name a single frame in XEmacs???
6082 (unless (featurep 'xemacs)
6083 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6085 ;;;; Structure editing
6087 ;;; Inserting headlines
6089 (defun org-previous-line-empty-p ()
6090 (save-excursion
6091 (and (not (bobp))
6092 (or (beginning-of-line 0) t)
6093 (save-match-data
6094 (looking-at "[ \t]*$")))))
6096 (defun org-insert-heading (&optional force-heading invisible-ok)
6097 "Insert a new heading or item with same depth at point.
6098 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6099 If point is at the beginning of a headline, insert a sibling before the
6100 current headline. If point is not at the beginning, do not split the line,
6101 but create the new headline after the current line.
6102 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6103 This is important for non-interactive uses of the command."
6104 (interactive "P")
6105 (if (or (= (buffer-size) 0)
6106 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6107 (org-on-heading-p))))
6108 (not (org-in-item-p))))
6109 (insert "\n* ")
6110 (when (or force-heading (not (org-insert-item)))
6111 (let* ((empty-line-p nil)
6112 (head (save-excursion
6113 (condition-case nil
6114 (progn
6115 (org-back-to-heading invisible-ok)
6116 (setq empty-line-p (org-previous-line-empty-p))
6117 (match-string 0))
6118 (error "*"))))
6119 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6120 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6121 pos hide-previous previous-pos)
6122 (cond
6123 ((and (org-on-heading-p) (bolp)
6124 (or (bobp)
6125 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6126 ;; insert before the current line
6127 (open-line (if blank 2 1)))
6128 ((and (bolp)
6129 (not org-insert-heading-respect-content)
6130 (or (bobp)
6131 (save-excursion
6132 (backward-char 1) (not (org-invisible-p)))))
6133 ;; insert right here
6134 nil)
6136 ;; somewhere in the line
6137 (save-excursion
6138 (setq previous-pos (point-at-bol))
6139 (end-of-line)
6140 (setq hide-previous (org-invisible-p)))
6141 (and org-insert-heading-respect-content (org-show-subtree))
6142 (let ((split
6143 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6144 (save-excursion
6145 (let ((p (point)))
6146 (goto-char (point-at-bol))
6147 (and (looking-at org-complex-heading-regexp)
6148 (> p (match-beginning 4)))))))
6149 tags pos)
6150 (cond
6151 (org-insert-heading-respect-content
6152 (org-end-of-subtree nil t)
6153 (or (bolp) (newline))
6154 (or (org-previous-line-empty-p)
6155 (and blank (newline)))
6156 (open-line 1))
6157 ((org-on-heading-p)
6158 (when hide-previous
6159 (show-children)
6160 (org-show-entry))
6161 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6162 (setq tags (and (match-end 2) (match-string 2)))
6163 (and (match-end 1)
6164 (delete-region (match-beginning 1) (match-end 1)))
6165 (setq pos (point-at-bol))
6166 (or split (end-of-line 1))
6167 (delete-horizontal-space)
6168 (newline (if blank 2 1))
6169 (when tags
6170 (save-excursion
6171 (goto-char pos)
6172 (end-of-line 1)
6173 (insert " " tags)
6174 (org-set-tags nil 'align))))
6176 (or split (end-of-line 1))
6177 (newline (if blank 2 1)))))))
6178 (insert head) (just-one-space)
6179 (setq pos (point))
6180 (end-of-line 1)
6181 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6182 (when (and org-insert-heading-respect-content hide-previous)
6183 (save-excursion
6184 (goto-char previous-pos)
6185 (hide-subtree)))
6186 (run-hooks 'org-insert-heading-hook)))))
6188 (defun org-get-heading (&optional no-tags)
6189 "Return the heading of the current entry, without the stars."
6190 (save-excursion
6191 (org-back-to-heading t)
6192 (if (looking-at
6193 (if no-tags
6194 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6195 "\\*+[ \t]+\\([^\r\n]*\\)"))
6196 (match-string 1) "")))
6198 (defun org-heading-components ()
6199 "Return the components of the current heading.
6200 This is a list with the following elements:
6201 - the level as an integer
6202 - the reduced level, different if `org-odd-levels-only' is set.
6203 - the TODO keyword, or nil
6204 - the priority character, like ?A, or nil if no priority is given
6205 - the headline text itself, or the tags string if no headline text
6206 - the tags string, or nil."
6207 (save-excursion
6208 (org-back-to-heading t)
6209 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6210 (list (length (match-string 1))
6211 (org-reduced-level (length (match-string 1)))
6212 (org-match-string-no-properties 2)
6213 (and (match-end 3) (aref (match-string 3) 2))
6214 (org-match-string-no-properties 4)
6215 (org-match-string-no-properties 5)))))
6217 (defun org-get-entry ()
6218 "Get the entry text, after heading, entire subtree."
6219 (save-excursion
6220 (org-back-to-heading t)
6221 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6223 (defun org-insert-heading-after-current ()
6224 "Insert a new heading with same level as current, after current subtree."
6225 (interactive)
6226 (org-back-to-heading)
6227 (org-insert-heading)
6228 (org-move-subtree-down)
6229 (end-of-line 1))
6231 (defun org-insert-heading-respect-content ()
6232 (interactive)
6233 (let ((org-insert-heading-respect-content t))
6234 (org-insert-heading t)))
6236 (defun org-insert-todo-heading-respect-content (&optional force-state)
6237 (interactive "P")
6238 (let ((org-insert-heading-respect-content t))
6239 (org-insert-todo-heading force-state t)))
6241 (defun org-insert-todo-heading (arg &optional force-heading)
6242 "Insert a new heading with the same level and TODO state as current heading.
6243 If the heading has no TODO state, or if the state is DONE, use the first
6244 state (TODO by default). Also with prefix arg, force first state."
6245 (interactive "P")
6246 (when (or force-heading (not (org-insert-item 'checkbox)))
6247 (org-insert-heading force-heading)
6248 (save-excursion
6249 (org-back-to-heading)
6250 (outline-previous-heading)
6251 (looking-at org-todo-line-regexp))
6252 (let*
6253 ((new-mark-x
6254 (if (or arg
6255 (not (match-beginning 2))
6256 (member (match-string 2) org-done-keywords))
6257 (car org-todo-keywords-1)
6258 (match-string 2)))
6259 (new-mark
6261 (run-hook-with-args-until-success
6262 'org-todo-get-default-hook new-mark-x nil)
6263 new-mark-x)))
6264 (beginning-of-line 1)
6265 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6266 (if org-treat-insert-todo-heading-as-state-change
6267 (org-todo new-mark)
6268 (insert new-mark " "))))
6269 (when org-provide-todo-statistics
6270 (org-update-parent-todo-statistics))))
6272 (defun org-insert-subheading (arg)
6273 "Insert a new subheading and demote it.
6274 Works for outline headings and for plain lists alike."
6275 (interactive "P")
6276 (org-insert-heading arg)
6277 (cond
6278 ((org-on-heading-p) (org-do-demote))
6279 ((org-at-item-p) (org-indent-item 1))))
6281 (defun org-insert-todo-subheading (arg)
6282 "Insert a new subheading with TODO keyword or checkbox and demote it.
6283 Works for outline headings and for plain lists alike."
6284 (interactive "P")
6285 (org-insert-todo-heading arg)
6286 (cond
6287 ((org-on-heading-p) (org-do-demote))
6288 ((org-at-item-p) (org-indent-item 1))))
6290 ;;; Promotion and Demotion
6292 (defvar org-after-demote-entry-hook nil
6293 "Hook run after an entry has been demoted.
6294 The cursor will be at the beginning of the entry.
6295 When a subtree is being demoted, the hook will be called for each node.")
6297 (defvar org-after-promote-entry-hook nil
6298 "Hook run after an entry has been promoted.
6299 The cursor will be at the beginning of the entry.
6300 When a subtree is being promoted, the hook will be called for each node.")
6302 (defun org-promote-subtree ()
6303 "Promote the entire subtree.
6304 See also `org-promote'."
6305 (interactive)
6306 (save-excursion
6307 (org-map-tree 'org-promote))
6308 (org-fix-position-after-promote))
6310 (defun org-demote-subtree ()
6311 "Demote the entire subtree. See `org-demote'.
6312 See also `org-promote'."
6313 (interactive)
6314 (save-excursion
6315 (org-map-tree 'org-demote))
6316 (org-fix-position-after-promote))
6319 (defun org-do-promote ()
6320 "Promote the current heading higher up the tree.
6321 If the region is active in `transient-mark-mode', promote all headings
6322 in the region."
6323 (interactive)
6324 (save-excursion
6325 (if (org-region-active-p)
6326 (org-map-region 'org-promote (region-beginning) (region-end))
6327 (org-promote)))
6328 (org-fix-position-after-promote))
6330 (defun org-do-demote ()
6331 "Demote the current heading lower down the tree.
6332 If the region is active in `transient-mark-mode', demote all headings
6333 in the region."
6334 (interactive)
6335 (save-excursion
6336 (if (org-region-active-p)
6337 (org-map-region 'org-demote (region-beginning) (region-end))
6338 (org-demote)))
6339 (org-fix-position-after-promote))
6341 (defun org-fix-position-after-promote ()
6342 "Make sure that after pro/demotion cursor position is right."
6343 (let ((pos (point)))
6344 (when (save-excursion
6345 (beginning-of-line 1)
6346 (looking-at org-todo-line-regexp)
6347 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6348 (cond ((eobp) (insert " "))
6349 ((eolp) (insert " "))
6350 ((equal (char-after) ?\ ) (forward-char 1))))))
6352 (defun org-current-level ()
6353 "Return the level of the current entry, or nil if before the first headline.
6354 The level is the number of stars at the beginning of the headline."
6355 (save-excursion
6356 (condition-case nil
6357 (progn
6358 (org-back-to-heading t)
6359 (funcall outline-level))
6360 (error nil))))
6362 (defun org-reduced-level (l)
6363 "Compute the effective level of a heading.
6364 This takes into account the setting of `org-odd-levels-only'."
6365 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6367 (defun org-get-valid-level (level &optional change)
6368 "Rectify a level change under the influence of `org-odd-levels-only'
6369 LEVEL is a current level, CHANGE is by how much the level should be
6370 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6371 even level numbers will become the next higher odd number."
6372 (if org-odd-levels-only
6373 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6374 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6375 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6376 (max 1 (+ level (or change 0)))))
6378 (if (boundp 'define-obsolete-function-alias)
6379 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6380 (define-obsolete-function-alias 'org-get-legal-level
6381 'org-get-valid-level)
6382 (define-obsolete-function-alias 'org-get-legal-level
6383 'org-get-valid-level "23.1")))
6385 (defun org-promote ()
6386 "Promote the current heading higher up the tree.
6387 If the region is active in `transient-mark-mode', promote all headings
6388 in the region."
6389 (org-back-to-heading t)
6390 (let* ((level (save-match-data (funcall outline-level)))
6391 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6392 (diff (abs (- level (length up-head) -1))))
6393 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6394 (replace-match up-head nil t)
6395 ;; Fixup tag positioning
6396 (and org-auto-align-tags (org-set-tags nil t))
6397 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6398 (run-hooks 'org-after-promote-entry-hook)))
6400 (defun org-demote ()
6401 "Demote the current heading lower down the tree.
6402 If the region is active in `transient-mark-mode', demote all headings
6403 in the region."
6404 (org-back-to-heading t)
6405 (let* ((level (save-match-data (funcall outline-level)))
6406 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6407 (diff (abs (- level (length down-head) -1))))
6408 (replace-match down-head nil t)
6409 ;; Fixup tag positioning
6410 (and org-auto-align-tags (org-set-tags nil t))
6411 (if org-adapt-indentation (org-fixup-indentation diff))
6412 (run-hooks 'org-after-demote-entry-hook)))
6414 (defvar org-tab-ind-state nil)
6416 (defun org-cycle-level ()
6417 (let ((org-adapt-indentation nil))
6418 (when (and (looking-at "[ \t]*$")
6419 (org-looking-back
6420 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6421 (setq this-command 'org-cycle-level)
6422 (if (eq last-command 'org-cycle-level)
6423 (condition-case nil
6424 (progn (org-do-promote)
6425 (if (equal org-tab-ind-state (org-current-level))
6426 (org-do-promote)))
6427 (error
6428 (progn
6429 (save-excursion
6430 (beginning-of-line 1)
6431 (and (looking-at "\\*+")
6432 (replace-match
6433 (make-string org-tab-ind-state ?*))))
6434 (setq this-command 'org-cycle))))
6435 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6436 (org-do-demote))
6437 t)))
6439 (defun org-map-tree (fun)
6440 "Call FUN for every heading underneath the current one."
6441 (org-back-to-heading)
6442 (let ((level (funcall outline-level)))
6443 (save-excursion
6444 (funcall fun)
6445 (while (and (progn
6446 (outline-next-heading)
6447 (> (funcall outline-level) level))
6448 (not (eobp)))
6449 (funcall fun)))))
6451 (defun org-map-region (fun beg end)
6452 "Call FUN for every heading between BEG and END."
6453 (let ((org-ignore-region t))
6454 (save-excursion
6455 (setq end (copy-marker end))
6456 (goto-char beg)
6457 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6458 (< (point) end))
6459 (funcall fun))
6460 (while (and (progn
6461 (outline-next-heading)
6462 (< (point) end))
6463 (not (eobp)))
6464 (funcall fun)))))
6466 (defun org-fixup-indentation (diff)
6467 "Change the indentation in the current entry by DIFF
6468 However, if any line in the current entry has no indentation, or if it
6469 would end up with no indentation after the change, nothing at all is done."
6470 (save-excursion
6471 (let ((end (save-excursion (outline-next-heading)
6472 (point-marker)))
6473 (prohibit (if (> diff 0)
6474 "^\\S-"
6475 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6476 col)
6477 (unless (save-excursion (end-of-line 1)
6478 (re-search-forward prohibit end t))
6479 (while (and (< (point) end)
6480 (re-search-forward "^[ \t]+" end t))
6481 (goto-char (match-end 0))
6482 (setq col (current-column))
6483 (if (< diff 0) (replace-match ""))
6484 (org-indent-to-column (+ diff col))))
6485 (move-marker end nil))))
6487 (defun org-convert-to-odd-levels ()
6488 "Convert an org-mode file with all levels allowed to one with odd levels.
6489 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6490 level 5 etc."
6491 (interactive)
6492 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6493 (let ((outline-regexp org-outline-regexp)
6494 (outline-level 'org-outline-level)
6495 (org-odd-levels-only nil) n)
6496 (save-excursion
6497 (goto-char (point-min))
6498 (while (re-search-forward "^\\*\\*+ " nil t)
6499 (setq n (- (length (match-string 0)) 2))
6500 (while (>= (setq n (1- n)) 0)
6501 (org-demote))
6502 (end-of-line 1))))))
6504 (defun org-convert-to-oddeven-levels ()
6505 "Convert an org-mode file with only odd levels to one with odd and even levels.
6506 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6507 section with an even level, conversion would destroy the structure of the file. An error
6508 is signaled in this case."
6509 (interactive)
6510 (goto-char (point-min))
6511 ;; First check if there are no even levels
6512 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6513 (org-show-context t)
6514 (error "Not all levels are odd in this file. Conversion not possible"))
6515 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6516 (let ((outline-regexp org-outline-regexp)
6517 (outline-level 'org-outline-level)
6518 (org-odd-levels-only nil) n)
6519 (save-excursion
6520 (goto-char (point-min))
6521 (while (re-search-forward "^\\*\\*+ " nil t)
6522 (setq n (/ (1- (length (match-string 0))) 2))
6523 (while (>= (setq n (1- n)) 0)
6524 (org-promote))
6525 (end-of-line 1))))))
6527 (defun org-tr-level (n)
6528 "Make N odd if required."
6529 (if org-odd-levels-only (1+ (/ n 2)) n))
6531 ;;; Vertical tree motion, cutting and pasting of subtrees
6533 (defun org-move-subtree-up (&optional arg)
6534 "Move the current subtree up past ARG headlines of the same level."
6535 (interactive "p")
6536 (org-move-subtree-down (- (prefix-numeric-value arg))))
6538 (defun org-move-subtree-down (&optional arg)
6539 "Move the current subtree down past ARG headlines of the same level."
6540 (interactive "p")
6541 (setq arg (prefix-numeric-value arg))
6542 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6543 'org-get-last-sibling))
6544 (ins-point (make-marker))
6545 (cnt (abs arg))
6546 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6547 ;; Select the tree
6548 (org-back-to-heading)
6549 (setq beg0 (point))
6550 (save-excursion
6551 (setq ne-beg (org-back-over-empty-lines))
6552 (setq beg (point)))
6553 (save-match-data
6554 (save-excursion (outline-end-of-heading)
6555 (setq folded (org-invisible-p)))
6556 (outline-end-of-subtree))
6557 (outline-next-heading)
6558 (setq ne-end (org-back-over-empty-lines))
6559 (setq end (point))
6560 (goto-char beg0)
6561 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6562 ;; include less whitespace
6563 (save-excursion
6564 (goto-char beg)
6565 (forward-line (- ne-beg ne-end))
6566 (setq beg (point))))
6567 ;; Find insertion point, with error handling
6568 (while (> cnt 0)
6569 (or (and (funcall movfunc) (looking-at outline-regexp))
6570 (progn (goto-char beg0)
6571 (error "Cannot move past superior level or buffer limit")))
6572 (setq cnt (1- cnt)))
6573 (if (> arg 0)
6574 ;; Moving forward - still need to move over subtree
6575 (progn (org-end-of-subtree t t)
6576 (save-excursion
6577 (org-back-over-empty-lines)
6578 (or (bolp) (newline)))))
6579 (setq ne-ins (org-back-over-empty-lines))
6580 (move-marker ins-point (point))
6581 (setq txt (buffer-substring beg end))
6582 (org-save-markers-in-region beg end)
6583 (delete-region beg end)
6584 (org-remove-empty-overlays-at beg)
6585 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6586 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6587 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6588 (let ((bbb (point)))
6589 (insert-before-markers txt)
6590 (org-reinstall-markers-in-region bbb)
6591 (move-marker ins-point bbb))
6592 (or (bolp) (insert "\n"))
6593 (setq ins-end (point))
6594 (goto-char ins-point)
6595 (org-skip-whitespace)
6596 (when (and (< arg 0)
6597 (org-first-sibling-p)
6598 (> ne-ins ne-beg))
6599 ;; Move whitespace back to beginning
6600 (save-excursion
6601 (goto-char ins-end)
6602 (let ((kill-whole-line t))
6603 (kill-line (- ne-ins ne-beg)) (point)))
6604 (insert (make-string (- ne-ins ne-beg) ?\n)))
6605 (move-marker ins-point nil)
6606 (if folded
6607 (hide-subtree)
6608 (org-show-entry)
6609 (show-children)
6610 (org-cycle-hide-drawers 'children))
6611 (org-clean-visibility-after-subtree-move)))
6613 (defvar org-subtree-clip ""
6614 "Clipboard for cut and paste of subtrees.
6615 This is actually only a copy of the kill, because we use the normal kill
6616 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6618 (defvar org-subtree-clip-folded nil
6619 "Was the last copied subtree folded?
6620 This is used to fold the tree back after pasting.")
6622 (defun org-cut-subtree (&optional n)
6623 "Cut the current subtree into the clipboard.
6624 With prefix arg N, cut this many sequential subtrees.
6625 This is a short-hand for marking the subtree and then cutting it."
6626 (interactive "p")
6627 (org-copy-subtree n 'cut))
6629 (defun org-copy-subtree (&optional n cut force-store-markers)
6630 "Cut the current subtree into the clipboard.
6631 With prefix arg N, cut this many sequential subtrees.
6632 This is a short-hand for marking the subtree and then copying it.
6633 If CUT is non-nil, actually cut the subtree.
6634 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6635 of some markers in the region, even if CUT is non-nil. This is
6636 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6637 (interactive "p")
6638 (let (beg end folded (beg0 (point)))
6639 (if (interactive-p)
6640 (org-back-to-heading nil) ; take what looks like a subtree
6641 (org-back-to-heading t)) ; take what is really there
6642 (org-back-over-empty-lines)
6643 (setq beg (point))
6644 (skip-chars-forward " \t\r\n")
6645 (save-match-data
6646 (save-excursion (outline-end-of-heading)
6647 (setq folded (org-invisible-p)))
6648 (condition-case nil
6649 (org-forward-same-level (1- n) t)
6650 (error nil))
6651 (org-end-of-subtree t t))
6652 (org-back-over-empty-lines)
6653 (setq end (point))
6654 (goto-char beg0)
6655 (when (> end beg)
6656 (setq org-subtree-clip-folded folded)
6657 (when (or cut force-store-markers)
6658 (org-save-markers-in-region beg end))
6659 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6660 (setq org-subtree-clip (current-kill 0))
6661 (message "%s: Subtree(s) with %d characters"
6662 (if cut "Cut" "Copied")
6663 (length org-subtree-clip)))))
6665 (defun org-paste-subtree (&optional level tree for-yank)
6666 "Paste the clipboard as a subtree, with modification of headline level.
6667 The entire subtree is promoted or demoted in order to match a new headline
6668 level.
6670 If the cursor is at the beginning of a headline, the same level as
6671 that headline is used to paste the tree
6673 If not, the new level is derived from the *visible* headings
6674 before and after the insertion point, and taken to be the inferior headline
6675 level of the two. So if the previous visible heading is level 3 and the
6676 next is level 4 (or vice versa), level 4 will be used for insertion.
6677 This makes sure that the subtree remains an independent subtree and does
6678 not swallow low level entries.
6680 You can also force a different level, either by using a numeric prefix
6681 argument, or by inserting the heading marker by hand. For example, if the
6682 cursor is after \"*****\", then the tree will be shifted to level 5.
6684 If optional TREE is given, use this text instead of the kill ring.
6686 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6687 move back over whitespace before inserting, and move point to the end of
6688 the inserted text when done."
6689 (interactive "P")
6690 (setq tree (or tree (and kill-ring (current-kill 0))))
6691 (unless (org-kill-is-subtree-p tree)
6692 (error "%s"
6693 (substitute-command-keys
6694 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6695 (let* ((visp (not (org-invisible-p)))
6696 (txt tree)
6697 (^re (concat "^\\(" outline-regexp "\\)"))
6698 (re (concat "\\(" outline-regexp "\\)"))
6699 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6701 (old-level (if (string-match ^re txt)
6702 (- (match-end 0) (match-beginning 0) 1)
6703 -1))
6704 (force-level (cond (level (prefix-numeric-value level))
6705 ((and (looking-at "[ \t]*$")
6706 (string-match
6707 ^re_ (buffer-substring
6708 (point-at-bol) (point))))
6709 (- (match-end 1) (match-beginning 1)))
6710 ((and (bolp)
6711 (looking-at org-outline-regexp))
6712 (- (match-end 0) (point) 1))
6713 (t nil)))
6714 (previous-level (save-excursion
6715 (condition-case nil
6716 (progn
6717 (outline-previous-visible-heading 1)
6718 (if (looking-at re)
6719 (- (match-end 0) (match-beginning 0) 1)
6721 (error 1))))
6722 (next-level (save-excursion
6723 (condition-case nil
6724 (progn
6725 (or (looking-at outline-regexp)
6726 (outline-next-visible-heading 1))
6727 (if (looking-at re)
6728 (- (match-end 0) (match-beginning 0) 1)
6730 (error 1))))
6731 (new-level (or force-level (max previous-level next-level)))
6732 (shift (if (or (= old-level -1)
6733 (= new-level -1)
6734 (= old-level new-level))
6736 (- new-level old-level)))
6737 (delta (if (> shift 0) -1 1))
6738 (func (if (> shift 0) 'org-demote 'org-promote))
6739 (org-odd-levels-only nil)
6740 beg end newend)
6741 ;; Remove the forced level indicator
6742 (if force-level
6743 (delete-region (point-at-bol) (point)))
6744 ;; Paste
6745 (beginning-of-line 1)
6746 (unless for-yank (org-back-over-empty-lines))
6747 (setq beg (point))
6748 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6749 (insert-before-markers txt)
6750 (unless (string-match "\n\\'" txt) (insert "\n"))
6751 (setq newend (point))
6752 (org-reinstall-markers-in-region beg)
6753 (setq end (point))
6754 (goto-char beg)
6755 (skip-chars-forward " \t\n\r")
6756 (setq beg (point))
6757 (if (and (org-invisible-p) visp)
6758 (save-excursion (outline-show-heading)))
6759 ;; Shift if necessary
6760 (unless (= shift 0)
6761 (save-restriction
6762 (narrow-to-region beg end)
6763 (while (not (= shift 0))
6764 (org-map-region func (point-min) (point-max))
6765 (setq shift (+ delta shift)))
6766 (goto-char (point-min))
6767 (setq newend (point-max))))
6768 (when (or (interactive-p) for-yank)
6769 (message "Clipboard pasted as level %d subtree" new-level))
6770 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6771 kill-ring
6772 (eq org-subtree-clip (current-kill 0))
6773 org-subtree-clip-folded)
6774 ;; The tree was folded before it was killed/copied
6775 (hide-subtree))
6776 (and for-yank (goto-char newend))))
6778 (defun org-kill-is-subtree-p (&optional txt)
6779 "Check if the current kill is an outline subtree, or a set of trees.
6780 Returns nil if kill does not start with a headline, or if the first
6781 headline level is not the largest headline level in the tree.
6782 So this will actually accept several entries of equal levels as well,
6783 which is OK for `org-paste-subtree'.
6784 If optional TXT is given, check this string instead of the current kill."
6785 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6786 (start-level (and kill
6787 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6788 org-outline-regexp "\\)")
6789 kill)
6790 (- (match-end 2) (match-beginning 2) 1)))
6791 (re (concat "^" org-outline-regexp))
6792 (start (1+ (or (match-beginning 2) -1))))
6793 (if (not start-level)
6794 (progn
6795 nil) ;; does not even start with a heading
6796 (catch 'exit
6797 (while (setq start (string-match re kill (1+ start)))
6798 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6799 (throw 'exit nil)))
6800 t))))
6802 (defvar org-markers-to-move nil
6803 "Markers that should be moved with a cut-and-paste operation.
6804 Those markers are stored together with their positions relative to
6805 the start of the region.")
6807 (defun org-save-markers-in-region (beg end)
6808 "Check markers in region.
6809 If these markers are between BEG and END, record their position relative
6810 to BEG, so that after moving the block of text, we can put the markers back
6811 into place.
6812 This function gets called just before an entry or tree gets cut from the
6813 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6814 called immediately, to move the markers with the entries."
6815 (setq org-markers-to-move nil)
6816 (when (featurep 'org-clock)
6817 (org-clock-save-markers-for-cut-and-paste beg end))
6818 (when (featurep 'org-agenda)
6819 (org-agenda-save-markers-for-cut-and-paste beg end)))
6821 (defun org-check-and-save-marker (marker beg end)
6822 "Check if MARKER is between BEG and END.
6823 If yes, remember the marker and the distance to BEG."
6824 (when (and (marker-buffer marker)
6825 (equal (marker-buffer marker) (current-buffer)))
6826 (if (and (>= marker beg) (< marker end))
6827 (push (cons marker (- marker beg)) org-markers-to-move))))
6829 (defun org-reinstall-markers-in-region (beg)
6830 "Move all remembered markers to their position relative to BEG."
6831 (mapc (lambda (x)
6832 (move-marker (car x) (+ beg (cdr x))))
6833 org-markers-to-move)
6834 (setq org-markers-to-move nil))
6836 (defun org-narrow-to-subtree ()
6837 "Narrow buffer to the current subtree."
6838 (interactive)
6839 (save-excursion
6840 (save-match-data
6841 (narrow-to-region
6842 (progn (org-back-to-heading t) (point))
6843 (progn (org-end-of-subtree t t)
6844 (if (org-on-heading-p) (backward-char 1))
6845 (point))))))
6847 (defun org-clone-subtree-with-time-shift (n &optional shift)
6848 "Clone the task (subtree) at point N times.
6849 The clones will be inserted as siblings.
6851 In interactive use, the user will be prompted for the number of clones
6852 to be produced, and for a time SHIFT, which may be a repeater as used
6853 in time stamps, for example `+3d'.
6855 When a valid repeater is given and the entry contains any time stamps,
6856 the clones will become a sequence in time, with time stamps in the
6857 subtree shifted for each clone produced. If SHIFT is nil or the
6858 empty string, time stamps will be left alone.
6860 If the original subtree did contain time stamps with a repeater,
6861 the following will happen:
6862 - the repeater will be removed in each clone
6863 - an additional clone will be produced, with the current, unshifted
6864 date(s) in the entry.
6865 - the original entry will be placed *after* all the clones, with
6866 repeater intact.
6867 - the start days in the repeater in the original entry will be shifted
6868 to past the last clone.
6869 I this way you can spell out a number of instances of a repeating task,
6870 and still retain the repeater to cover future instances of the task."
6871 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6872 (let (beg end template task
6873 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6874 (if (not (and (integerp n) (> n 0)))
6875 (error "Invalid number of replications %s" n))
6876 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6877 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6878 shift)))
6879 (error "Invalid shift specification %s" shift))
6880 (when doshift
6881 (setq shift-n (string-to-number (match-string 1 shift))
6882 shift-what (cdr (assoc (match-string 2 shift)
6883 '(("d" . day) ("w" . week)
6884 ("m" . month) ("y" . year))))))
6885 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6886 (setq nmin 1 nmax n)
6887 (org-back-to-heading t)
6888 (setq beg (point))
6889 (org-end-of-subtree t t)
6890 (or (bolp) (insert "\n"))
6891 (setq end (point))
6892 (setq template (buffer-substring beg end))
6893 (when (and doshift
6894 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6895 (delete-region beg end)
6896 (setq end beg)
6897 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6898 (goto-char end)
6899 (loop for n from nmin to nmax do
6900 (if (not doshift)
6901 (setq task template)
6902 (with-temp-buffer
6903 (insert template)
6904 (org-mode)
6905 (goto-char (point-min))
6906 (while (re-search-forward org-ts-regexp-both nil t)
6907 (org-timestamp-change (* n shift-n) shift-what))
6908 (unless (= n n-no-remove)
6909 (goto-char (point-min))
6910 (while (re-search-forward org-ts-regexp nil t)
6911 (save-excursion
6912 (goto-char (match-beginning 0))
6913 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6914 (delete-region (match-beginning 1) (match-end 1))))))
6915 (setq task (buffer-string))))
6916 (insert task))
6917 (goto-char beg)))
6919 ;;; Outline Sorting
6921 (defun org-sort (with-case)
6922 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6923 Optional argument WITH-CASE means sort case-sensitively.
6924 With a double prefix argument, also remove duplicate entries."
6925 (interactive "P")
6926 (if (org-at-table-p)
6927 (org-call-with-arg 'org-table-sort-lines with-case)
6928 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6930 (defun org-sort-remove-invisible (s)
6931 (remove-text-properties 0 (length s) org-rm-props s)
6932 (while (string-match org-bracket-link-regexp s)
6933 (setq s (replace-match (if (match-end 2)
6934 (match-string 3 s)
6935 (match-string 1 s)) t t s)))
6938 (defvar org-priority-regexp) ; defined later in the file
6940 (defvar org-after-sorting-entries-or-items-hook nil
6941 "Hook that is run after a bunch of entries or items have been sorted.
6942 When children are sorted, the cursor is in the parent line when this
6943 hook gets called. When a region or a plain list is sorted, the cursor
6944 will be in the first entry of the sorted region/list.")
6946 (defun org-sort-entries-or-items
6947 (&optional with-case sorting-type getkey-func compare-func property)
6948 "Sort entries on a certain level of an outline tree, or plain list items.
6949 If there is an active region, the entries in the region are sorted.
6950 Else, if the cursor is before the first entry, sort the top-level items.
6951 Else, the children of the entry at point are sorted.
6952 If the cursor is at the first item in a plain list, the list items will be
6953 sorted.
6955 Sorting can be alphabetically, numerically, by date/time as given by
6956 a time stamp, by a property or by priority.
6958 The command prompts for the sorting type unless it has been given to the
6959 function through the SORTING-TYPE argument, which needs to a character,
6960 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6961 precise meaning of each character:
6963 n Numerically, by converting the beginning of the entry/item to a number.
6964 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6965 t By date/time, either the first active time stamp in the entry, or, if
6966 none exist, by the first inactive one.
6967 In items, only the first line will be checked.
6968 s By the scheduled date/time.
6969 d By deadline date/time.
6970 c By creation time, which is assumed to be the first inactive time stamp
6971 at the beginning of a line.
6972 p By priority according to the cookie.
6973 r By the value of a property.
6975 Capital letters will reverse the sort order.
6977 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6978 called with point at the beginning of the record. It must return either
6979 a string or a number that should serve as the sorting key for that record.
6981 Comparing entries ignores case by default. However, with an optional argument
6982 WITH-CASE, the sorting considers case as well."
6983 (interactive "P")
6984 (let ((case-func (if with-case 'identity 'downcase))
6985 start beg end stars re re2
6986 txt what tmp plain-list-p)
6987 ;; Find beginning and end of region to sort
6988 (cond
6989 ((org-region-active-p)
6990 ;; we will sort the region
6991 (setq end (region-end)
6992 what "region")
6993 (goto-char (region-beginning))
6994 (if (not (org-on-heading-p)) (outline-next-heading))
6995 (setq start (point)))
6996 ((org-at-item-p)
6997 ;; we will sort this plain list
6998 (org-beginning-of-item-list) (setq start (point))
6999 (org-end-of-item-list)
7000 (or (bolp) (insert "\n"))
7001 (setq end (point))
7002 (goto-char start)
7003 (setq plain-list-p t
7004 what "plain list"))
7005 ((or (org-on-heading-p)
7006 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7007 ;; we will sort the children of the current headline
7008 (org-back-to-heading)
7009 (setq start (point)
7010 end (progn (org-end-of-subtree t t)
7011 (or (bolp) (insert "\n"))
7012 (org-back-over-empty-lines)
7013 (point))
7014 what "children")
7015 (goto-char start)
7016 (show-subtree)
7017 (outline-next-heading))
7019 ;; we will sort the top-level entries in this file
7020 (goto-char (point-min))
7021 (or (org-on-heading-p) (outline-next-heading))
7022 (setq start (point))
7023 (goto-char (point-max))
7024 (beginning-of-line 1)
7025 (when (looking-at ".*?\\S-")
7026 ;; File ends in a non-white line
7027 (end-of-line 1)
7028 (insert "\n"))
7029 (setq end (point-max))
7030 (setq what "top-level")
7031 (goto-char start)
7032 (show-all)))
7034 (setq beg (point))
7035 (if (>= beg end) (error "Nothing to sort"))
7037 (unless plain-list-p
7038 (looking-at "\\(\\*+\\)")
7039 (setq stars (match-string 1)
7040 re (concat "^" (regexp-quote stars) " +")
7041 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7042 txt (buffer-substring beg end))
7043 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7044 (if (and (not (equal stars "*")) (string-match re2 txt))
7045 (error "Region to sort contains a level above the first entry")))
7047 (unless sorting-type
7048 (message
7049 (if plain-list-p
7050 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7051 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7052 [t]ime [s]cheduled [d]eadline [c]reated
7053 A/N/T/S/D/C/P/O/F means reversed:")
7054 what)
7055 (setq sorting-type (read-char-exclusive))
7057 (and (= (downcase sorting-type) ?f)
7058 (setq getkey-func
7059 (org-icompleting-read "Sort using function: "
7060 obarray 'fboundp t nil nil))
7061 (setq getkey-func (intern getkey-func)))
7063 (and (= (downcase sorting-type) ?r)
7064 (setq property
7065 (org-icompleting-read "Property: "
7066 (mapcar 'list (org-buffer-property-keys t))
7067 nil t))))
7069 (message "Sorting entries...")
7071 (save-restriction
7072 (narrow-to-region start end)
7074 (let ((dcst (downcase sorting-type))
7075 (case-fold-search nil)
7076 (now (current-time)))
7077 (sort-subr
7078 (/= dcst sorting-type)
7079 ;; This function moves to the beginning character of the "record" to
7080 ;; be sorted.
7081 (if plain-list-p
7082 (lambda nil
7083 (if (org-at-item-p) t (goto-char (point-max))))
7084 (lambda nil
7085 (if (re-search-forward re nil t)
7086 (goto-char (match-beginning 0))
7087 (goto-char (point-max)))))
7088 ;; This function moves to the last character of the "record" being
7089 ;; sorted.
7090 (if plain-list-p
7091 'org-end-of-item
7092 (lambda nil
7093 (save-match-data
7094 (condition-case nil
7095 (outline-forward-same-level 1)
7096 (error
7097 (goto-char (point-max)))))))
7099 ;; This function returns the value that gets sorted against.
7100 (if plain-list-p
7101 (lambda nil
7102 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7103 (cond
7104 ((= dcst ?n)
7105 (string-to-number (buffer-substring (match-end 0)
7106 (point-at-eol))))
7107 ((= dcst ?a)
7108 (buffer-substring (match-end 0) (point-at-eol)))
7109 ((= dcst ?t)
7110 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7111 (re-search-forward org-ts-regexp-both
7112 (point-at-eol) t))
7113 (org-time-string-to-seconds (match-string 0))
7114 (org-float-time now)))
7115 ((= dcst ?f)
7116 (if getkey-func
7117 (progn
7118 (setq tmp (funcall getkey-func))
7119 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7120 tmp)
7121 (error "Invalid key function `%s'" getkey-func)))
7122 (t (error "Invalid sorting type `%c'" sorting-type)))))
7123 (lambda nil
7124 (cond
7125 ((= dcst ?n)
7126 (if (looking-at org-complex-heading-regexp)
7127 (string-to-number (match-string 4))
7128 nil))
7129 ((= dcst ?a)
7130 (if (looking-at org-complex-heading-regexp)
7131 (funcall case-func (match-string 4))
7132 nil))
7133 ((= dcst ?t)
7134 (let ((end (save-excursion (outline-next-heading) (point))))
7135 (if (or (re-search-forward org-ts-regexp end t)
7136 (re-search-forward org-ts-regexp-both end t))
7137 (org-time-string-to-seconds (match-string 0))
7138 (org-float-time now))))
7139 ((= dcst ?c)
7140 (let ((end (save-excursion (outline-next-heading) (point))))
7141 (if (re-search-forward
7142 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7143 end t)
7144 (org-time-string-to-seconds (match-string 0))
7145 (org-float-time now))))
7146 ((= dcst ?s)
7147 (let ((end (save-excursion (outline-next-heading) (point))))
7148 (if (re-search-forward org-scheduled-time-regexp end t)
7149 (org-time-string-to-seconds (match-string 1))
7150 (org-float-time now))))
7151 ((= dcst ?d)
7152 (let ((end (save-excursion (outline-next-heading) (point))))
7153 (if (re-search-forward org-deadline-time-regexp end t)
7154 (org-time-string-to-seconds (match-string 1))
7155 (org-float-time now))))
7156 ((= dcst ?p)
7157 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7158 (string-to-char (match-string 2))
7159 org-default-priority))
7160 ((= dcst ?r)
7161 (or (org-entry-get nil property) ""))
7162 ((= dcst ?o)
7163 (if (looking-at org-complex-heading-regexp)
7164 (- 9999 (length (member (match-string 2)
7165 org-todo-keywords-1)))))
7166 ((= dcst ?f)
7167 (if getkey-func
7168 (progn
7169 (setq tmp (funcall getkey-func))
7170 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7171 tmp)
7172 (error "Invalid key function `%s'" getkey-func)))
7173 (t (error "Invalid sorting type `%c'" sorting-type)))))
7175 (cond
7176 ((= dcst ?a) 'string<)
7177 ((= dcst ?f) compare-func)
7178 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7179 (t nil)))))
7180 (run-hooks 'org-after-sorting-entries-or-items-hook)
7181 (message "Sorting entries...done")))
7183 (defun org-do-sort (table what &optional with-case sorting-type)
7184 "Sort TABLE of WHAT according to SORTING-TYPE.
7185 The user will be prompted for the SORTING-TYPE if the call to this
7186 function does not specify it. WHAT is only for the prompt, to indicate
7187 what is being sorted. The sorting key will be extracted from
7188 the car of the elements of the table.
7189 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7190 (unless sorting-type
7191 (message
7192 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7193 what)
7194 (setq sorting-type (read-char-exclusive)))
7195 (let ((dcst (downcase sorting-type))
7196 extractfun comparefun)
7197 ;; Define the appropriate functions
7198 (cond
7199 ((= dcst ?n)
7200 (setq extractfun 'string-to-number
7201 comparefun (if (= dcst sorting-type) '< '>)))
7202 ((= dcst ?a)
7203 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7204 (lambda(x) (downcase (org-sort-remove-invisible x))))
7205 comparefun (if (= dcst sorting-type)
7206 'string<
7207 (lambda (a b) (and (not (string< a b))
7208 (not (string= a b)))))))
7209 ((= dcst ?t)
7210 (setq extractfun
7211 (lambda (x)
7212 (if (or (string-match org-ts-regexp x)
7213 (string-match org-ts-regexp-both x))
7214 (org-float-time
7215 (org-time-string-to-time (match-string 0 x)))
7217 comparefun (if (= dcst sorting-type) '< '>)))
7218 (t (error "Invalid sorting type `%c'" sorting-type)))
7220 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7221 table)
7222 (lambda (a b) (funcall comparefun (car a) (car b))))))
7225 ;;; The orgstruct minor mode
7227 ;; Define a minor mode which can be used in other modes in order to
7228 ;; integrate the org-mode structure editing commands.
7230 ;; This is really a hack, because the org-mode structure commands use
7231 ;; keys which normally belong to the major mode. Here is how it
7232 ;; works: The minor mode defines all the keys necessary to operate the
7233 ;; structure commands, but wraps the commands into a function which
7234 ;; tests if the cursor is currently at a headline or a plain list
7235 ;; item. If that is the case, the structure command is used,
7236 ;; temporarily setting many Org-mode variables like regular
7237 ;; expressions for filling etc. However, when any of those keys is
7238 ;; used at a different location, function uses `key-binding' to look
7239 ;; up if the key has an associated command in another currently active
7240 ;; keymap (minor modes, major mode, global), and executes that
7241 ;; command. There might be problems if any of the keys is otherwise
7242 ;; used as a prefix key.
7244 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7245 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7246 ;; addresses this by checking explicitly for both bindings.
7248 (defvar orgstruct-mode-map (make-sparse-keymap)
7249 "Keymap for the minor `orgstruct-mode'.")
7251 (defvar org-local-vars nil
7252 "List of local variables, for use by `orgstruct-mode'")
7254 ;;;###autoload
7255 (define-minor-mode orgstruct-mode
7256 "Toggle the minor more `orgstruct-mode'.
7257 This mode is for using Org-mode structure commands in other modes.
7258 The following key behave as if Org-mode was active, if the cursor
7259 is on a headline, or on a plain list item (both in the definition
7260 of Org-mode).
7262 M-up Move entry/item up
7263 M-down Move entry/item down
7264 M-left Promote
7265 M-right Demote
7266 M-S-up Move entry/item up
7267 M-S-down Move entry/item down
7268 M-S-left Promote subtree
7269 M-S-right Demote subtree
7270 M-q Fill paragraph and items like in Org-mode
7271 C-c ^ Sort entries
7272 C-c - Cycle list bullet
7273 TAB Cycle item visibility
7274 M-RET Insert new heading/item
7275 S-M-RET Insert new TODO heading / Checkbox item
7276 C-c C-c Set tags / toggle checkbox"
7277 nil " OrgStruct" nil
7278 (org-load-modules-maybe)
7279 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7281 ;;;###autoload
7282 (defun turn-on-orgstruct ()
7283 "Unconditionally turn on `orgstruct-mode'."
7284 (orgstruct-mode 1))
7286 (defun orgstruct++-mode (&optional arg)
7287 "Toggle `orgstruct-mode', the enhanced version of it.
7288 In addition to setting orgstruct-mode, this also exports all indentation
7289 and autofilling variables from org-mode into the buffer. It will also
7290 recognize item context in multiline items.
7291 Note that turning off orgstruct-mode will *not* remove the
7292 indentation/paragraph settings. This can only be done by refreshing the
7293 major mode, for example with \\[normal-mode]."
7294 (interactive "P")
7295 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7296 (if (< arg 1)
7297 (orgstruct-mode -1)
7298 (orgstruct-mode 1)
7299 (let (var val)
7300 (mapc
7301 (lambda (x)
7302 (when (string-match
7303 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7304 (symbol-name (car x)))
7305 (setq var (car x) val (nth 1 x))
7306 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7307 org-local-vars)
7308 (org-set-local 'orgstruct-is-++ t))))
7310 (defvar orgstruct-is-++ nil
7311 "Is orgstruct-mode in ++ version in the current-buffer?")
7312 (make-variable-buffer-local 'orgstruct-is-++)
7314 ;;;###autoload
7315 (defun turn-on-orgstruct++ ()
7316 "Unconditionally turn on `orgstruct++-mode'."
7317 (orgstruct++-mode 1))
7319 (defun orgstruct-error ()
7320 "Error when there is no default binding for a structure key."
7321 (interactive)
7322 (error "This key has no function outside structure elements"))
7324 (defun orgstruct-setup ()
7325 "Setup orgstruct keymaps."
7326 (let ((nfunc 0)
7327 (bindings
7328 (list
7329 '([(meta up)] org-metaup)
7330 '([(meta down)] org-metadown)
7331 '([(meta left)] org-metaleft)
7332 '([(meta right)] org-metaright)
7333 '([(meta shift up)] org-shiftmetaup)
7334 '([(meta shift down)] org-shiftmetadown)
7335 '([(meta shift left)] org-shiftmetaleft)
7336 '([(meta shift right)] org-shiftmetaright)
7337 '([?\e (up)] org-metaup)
7338 '([?\e (down)] org-metadown)
7339 '([?\e (left)] org-metaleft)
7340 '([?\e (right)] org-metaright)
7341 '([?\e (shift up)] org-shiftmetaup)
7342 '([?\e (shift down)] org-shiftmetadown)
7343 '([?\e (shift left)] org-shiftmetaleft)
7344 '([?\e (shift right)] org-shiftmetaright)
7345 '([(shift up)] org-shiftup)
7346 '([(shift down)] org-shiftdown)
7347 '([(shift left)] org-shiftleft)
7348 '([(shift right)] org-shiftright)
7349 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7350 '("\M-q" fill-paragraph)
7351 '("\C-c^" org-sort)
7352 '("\C-c-" org-cycle-list-bullet)))
7353 elt key fun cmd)
7354 (while (setq elt (pop bindings))
7355 (setq nfunc (1+ nfunc))
7356 (setq key (org-key (car elt))
7357 fun (nth 1 elt)
7358 cmd (orgstruct-make-binding fun nfunc key))
7359 (org-defkey orgstruct-mode-map key cmd))
7361 ;; Special treatment needed for TAB and RET
7362 (org-defkey orgstruct-mode-map [(tab)]
7363 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7364 (org-defkey orgstruct-mode-map "\C-i"
7365 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7367 (org-defkey orgstruct-mode-map "\M-\C-m"
7368 (orgstruct-make-binding 'org-insert-heading 105
7369 "\M-\C-m" [(meta return)]))
7370 (org-defkey orgstruct-mode-map [(meta return)]
7371 (orgstruct-make-binding 'org-insert-heading 106
7372 [(meta return)] "\M-\C-m"))
7374 (org-defkey orgstruct-mode-map [(shift meta return)]
7375 (orgstruct-make-binding 'org-insert-todo-heading 107
7376 [(meta return)] "\M-\C-m"))
7378 (org-defkey orgstruct-mode-map "\e\C-m"
7379 (orgstruct-make-binding 'org-insert-heading 108
7380 "\e\C-m" [?\e (return)]))
7381 (org-defkey orgstruct-mode-map [?\e (return)]
7382 (orgstruct-make-binding 'org-insert-heading 109
7383 [?\e (return)] "\e\C-m"))
7384 (org-defkey orgstruct-mode-map [?\e (shift return)]
7385 (orgstruct-make-binding 'org-insert-todo-heading 110
7386 [?\e (return)] "\e\C-m"))
7388 (unless org-local-vars
7389 (setq org-local-vars (org-get-local-variables)))
7393 (defun orgstruct-make-binding (fun n &rest keys)
7394 "Create a function for binding in the structure minor mode.
7395 FUN is the command to call inside a table. N is used to create a unique
7396 command name. KEYS are keys that should be checked in for a command
7397 to execute outside of tables."
7398 (eval
7399 (list 'defun
7400 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7401 '(arg)
7402 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7403 "Outside of structure, run the binding of `"
7404 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7405 "'.")
7406 '(interactive "p")
7407 (list 'if
7408 `(org-context-p 'headline 'item
7409 (and orgstruct-is-++
7410 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7411 'item-body))
7412 (list 'org-run-like-in-org-mode (list 'quote fun))
7413 (list 'let '(orgstruct-mode)
7414 (list 'call-interactively
7415 (append '(or)
7416 (mapcar (lambda (k)
7417 (list 'key-binding k))
7418 keys)
7419 '('orgstruct-error))))))))
7421 (defun org-context-p (&rest contexts)
7422 "Check if local context is any of CONTEXTS.
7423 Possible values in the list of contexts are `table', `headline', and `item'."
7424 (let ((pos (point)))
7425 (goto-char (point-at-bol))
7426 (prog1 (or (and (memq 'table contexts)
7427 (looking-at "[ \t]*|"))
7428 (and (memq 'headline contexts)
7429 ;;????????? (looking-at "\\*+"))
7430 (looking-at outline-regexp))
7431 (and (memq 'item contexts)
7432 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7433 (and (memq 'item-body contexts)
7434 (org-in-item-p)))
7435 (goto-char pos))))
7437 (defun org-get-local-variables ()
7438 "Return a list of all local variables in an org-mode buffer."
7439 (let (varlist)
7440 (with-current-buffer (get-buffer-create "*Org tmp*")
7441 (erase-buffer)
7442 (org-mode)
7443 (setq varlist (buffer-local-variables)))
7444 (kill-buffer "*Org tmp*")
7445 (delq nil
7446 (mapcar
7447 (lambda (x)
7448 (setq x
7449 (if (symbolp x)
7450 (list x)
7451 (list (car x) (list 'quote (cdr x)))))
7452 (if (string-match
7453 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7454 (symbol-name (car x)))
7455 x nil))
7456 varlist))))
7458 ;;;###autoload
7459 (defun org-run-like-in-org-mode (cmd)
7460 "Run a command, pretending that the current buffer is in Org-mode.
7461 This will temporarily bind local variables that are typically bound in
7462 Org-mode to the values they have in Org-mode, and then interactively
7463 call CMD."
7464 (org-load-modules-maybe)
7465 (unless org-local-vars
7466 (setq org-local-vars (org-get-local-variables)))
7467 (eval (list 'let org-local-vars
7468 (list 'call-interactively (list 'quote cmd)))))
7470 ;;;; Archiving
7472 (defun org-get-category (&optional pos)
7473 "Get the category applying to position POS."
7474 (get-text-property (or pos (point)) 'org-category))
7476 (defun org-refresh-category-properties ()
7477 "Refresh category text properties in the buffer."
7478 (let ((def-cat (cond
7479 ((null org-category)
7480 (if buffer-file-name
7481 (file-name-sans-extension
7482 (file-name-nondirectory buffer-file-name))
7483 "???"))
7484 ((symbolp org-category) (symbol-name org-category))
7485 (t org-category)))
7486 beg end cat pos optionp)
7487 (org-unmodified
7488 (save-excursion
7489 (save-restriction
7490 (widen)
7491 (goto-char (point-min))
7492 (put-text-property (point) (point-max) 'org-category def-cat)
7493 (while (re-search-forward
7494 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7495 (setq pos (match-end 0)
7496 optionp (equal (char-after (match-beginning 0)) ?#)
7497 cat (org-trim (match-string 2)))
7498 (if optionp
7499 (setq beg (point-at-bol) end (point-max))
7500 (org-back-to-heading t)
7501 (setq beg (point) end (org-end-of-subtree t t)))
7502 (put-text-property beg end 'org-category cat)
7503 (goto-char pos)))))))
7506 ;;;; Link Stuff
7508 ;;; Link abbreviations
7510 (defun org-link-expand-abbrev (link)
7511 "Apply replacements as defined in `org-link-abbrev-alist."
7512 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7513 (let* ((key (match-string 1 link))
7514 (as (or (assoc key org-link-abbrev-alist-local)
7515 (assoc key org-link-abbrev-alist)))
7516 (tag (and (match-end 2) (match-string 3 link)))
7517 rpl)
7518 (if (not as)
7519 link
7520 (setq rpl (cdr as))
7521 (cond
7522 ((symbolp rpl) (funcall rpl tag))
7523 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7524 ((string-match "%h" rpl)
7525 (replace-match (url-hexify-string (or tag "")) t t rpl))
7526 (t (concat rpl tag)))))
7527 link))
7529 ;;; Storing and inserting links
7531 (defvar org-insert-link-history nil
7532 "Minibuffer history for links inserted with `org-insert-link'.")
7534 (defvar org-stored-links nil
7535 "Contains the links stored with `org-store-link'.")
7537 (defvar org-store-link-plist nil
7538 "Plist with info about the most recently link created with `org-store-link'.")
7540 (defvar org-link-protocols nil
7541 "Link protocols added to Org-mode using `org-add-link-type'.")
7543 (defvar org-store-link-functions nil
7544 "List of functions that are called to create and store a link.
7545 Each function will be called in turn until one returns a non-nil
7546 value. Each function should check if it is responsible for creating
7547 this link (for example by looking at the major mode).
7548 If not, it must exit and return nil.
7549 If yes, it should return a non-nil value after a calling
7550 `org-store-link-props' with a list of properties and values.
7551 Special properties are:
7553 :type The link prefix. like \"http\". This must be given.
7554 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7555 This is obligatory as well.
7556 :description Optional default description for the second pair
7557 of brackets in an Org-mode link. The user can still change
7558 this when inserting this link into an Org-mode buffer.
7560 In addition to these, any additional properties can be specified
7561 and then used in remember templates.")
7563 (defun org-add-link-type (type &optional follow export)
7564 "Add TYPE to the list of `org-link-types'.
7565 Re-compute all regular expressions depending on `org-link-types'
7567 FOLLOW and EXPORT are two functions.
7569 FOLLOW should take the link path as the single argument and do whatever
7570 is necessary to follow the link, for example find a file or display
7571 a mail message.
7573 EXPORT should format the link path for export to one of the export formats.
7574 It should be a function accepting three arguments:
7576 path the path of the link, the text after the prefix (like \"http:\")
7577 desc the description of the link, if any, nil if there was no description
7578 format the export format, a symbol like `html' or `latex'.
7580 The function may use the FORMAT information to return different values
7581 depending on the format. The return value will be put literally into
7582 the exported file.
7583 Org-mode has a built-in default for exporting links. If you are happy with
7584 this default, there is no need to define an export function for the link
7585 type. For a simple example of an export function, see `org-bbdb.el'."
7586 (add-to-list 'org-link-types type t)
7587 (org-make-link-regexps)
7588 (if (assoc type org-link-protocols)
7589 (setcdr (assoc type org-link-protocols) (list follow export))
7590 (push (list type follow export) org-link-protocols)))
7592 (defvar org-agenda-buffer-name)
7594 ;;;###autoload
7595 (defun org-store-link (arg)
7596 "\\<org-mode-map>Store an org-link to the current location.
7597 This link is added to `org-stored-links' and can later be inserted
7598 into an org-buffer with \\[org-insert-link].
7600 For some link types, a prefix arg is interpreted:
7601 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7602 For file links, arg negates `org-context-in-file-links'."
7603 (interactive "P")
7604 (org-load-modules-maybe)
7605 (setq org-store-link-plist nil) ; reset
7606 (let ((outline-regexp (org-get-limited-outline-regexp))
7607 link cpltxt desc description search txt custom-id)
7608 (cond
7610 ((run-hook-with-args-until-success 'org-store-link-functions)
7611 (setq link (plist-get org-store-link-plist :link)
7612 desc (or (plist-get org-store-link-plist :description) link)))
7614 ((equal (buffer-name) "*Org Edit Src Example*")
7615 (let (label gc)
7616 (while (or (not label)
7617 (save-excursion
7618 (save-restriction
7619 (widen)
7620 (goto-char (point-min))
7621 (re-search-forward
7622 (regexp-quote (format org-coderef-label-format label))
7623 nil t))))
7624 (when label (message "Label exists already") (sit-for 2))
7625 (setq label (read-string "Code line label: " label)))
7626 (end-of-line 1)
7627 (setq link (format org-coderef-label-format label))
7628 (setq gc (- 79 (length link)))
7629 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7630 (insert link)
7631 (setq link (concat "(" label ")") desc nil)))
7633 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7634 ;; We are in the agenda, link to referenced location
7635 (let ((m (or (get-text-property (point) 'org-hd-marker)
7636 (get-text-property (point) 'org-marker))))
7637 (when m
7638 (org-with-point-at m
7639 (call-interactively 'org-store-link)))))
7641 ((eq major-mode 'calendar-mode)
7642 (let ((cd (calendar-cursor-to-date)))
7643 (setq link
7644 (format-time-string
7645 (car org-time-stamp-formats)
7646 (apply 'encode-time
7647 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7648 nil nil nil))))
7649 (org-store-link-props :type "calendar" :date cd)))
7651 ((eq major-mode 'w3-mode)
7652 (setq cpltxt (if (and (buffer-name)
7653 (not (string-match "Untitled" (buffer-name))))
7654 (buffer-name)
7655 (url-view-url t))
7656 link (org-make-link (url-view-url t)))
7657 (org-store-link-props :type "w3" :url (url-view-url t)))
7659 ((eq major-mode 'w3m-mode)
7660 (setq cpltxt (or w3m-current-title w3m-current-url)
7661 link (org-make-link w3m-current-url))
7662 (org-store-link-props :type "w3m" :url (url-view-url t)))
7664 ((setq search (run-hook-with-args-until-success
7665 'org-create-file-search-functions))
7666 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7667 "::" search))
7668 (setq cpltxt (or description link)))
7670 ((eq major-mode 'image-mode)
7671 (setq cpltxt (concat "file:"
7672 (abbreviate-file-name buffer-file-name))
7673 link (org-make-link cpltxt))
7674 (org-store-link-props :type "image" :file buffer-file-name))
7676 ((eq major-mode 'dired-mode)
7677 ;; link to the file in the current line
7678 (let ((file (dired-get-filename nil t)))
7679 (setq file (if file
7680 (abbreviate-file-name
7681 (expand-file-name (dired-get-filename nil t)))
7682 ;; otherwise, no file so use current directory.
7683 default-directory))
7684 (setq cpltxt (concat "file:" file)
7685 link (org-make-link cpltxt))))
7687 ((and buffer-file-name (org-mode-p))
7688 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7689 (cond
7690 ((org-in-regexp "<<\\(.*?\\)>>")
7691 (setq cpltxt
7692 (concat "file:"
7693 (abbreviate-file-name buffer-file-name)
7694 "::" (match-string 1))
7695 link (org-make-link cpltxt)))
7696 ((and (featurep 'org-id)
7697 (or (eq org-link-to-org-use-id t)
7698 (and (eq org-link-to-org-use-id 'create-if-interactive)
7699 (interactive-p))
7700 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7701 (interactive-p)
7702 (not custom-id))
7703 (and org-link-to-org-use-id
7704 (condition-case nil
7705 (org-entry-get nil "ID")
7706 (error nil)))))
7707 ;; We can make a link using the ID.
7708 (setq link (condition-case nil
7709 (prog1 (org-id-store-link)
7710 (setq desc (plist-get org-store-link-plist
7711 :description)))
7712 (error
7713 ;; probably before first headline, link to file only
7714 (concat "file:"
7715 (abbreviate-file-name buffer-file-name))))))
7717 ;; Just link to current headline
7718 (setq cpltxt (concat "file:"
7719 (abbreviate-file-name buffer-file-name)))
7720 ;; Add a context search string
7721 (when (org-xor org-context-in-file-links arg)
7722 (setq txt (cond
7723 ((org-on-heading-p) nil)
7724 ((org-region-active-p)
7725 (buffer-substring (region-beginning) (region-end)))
7726 (t nil)))
7727 (when (or (null txt) (string-match "\\S-" txt))
7728 (setq cpltxt
7729 (concat cpltxt "::"
7730 (condition-case nil
7731 (org-make-org-heading-search-string txt)
7732 (error "")))
7733 desc (or (nth 4 (ignore-errors
7734 (org-heading-components))) "NONE"))))
7735 (if (string-match "::\\'" cpltxt)
7736 (setq cpltxt (substring cpltxt 0 -2)))
7737 (setq link (org-make-link cpltxt)))))
7739 ((buffer-file-name (buffer-base-buffer))
7740 ;; Just link to this file here.
7741 (setq cpltxt (concat "file:"
7742 (abbreviate-file-name
7743 (buffer-file-name (buffer-base-buffer)))))
7744 ;; Add a context string
7745 (when (org-xor org-context-in-file-links arg)
7746 (setq txt (if (org-region-active-p)
7747 (buffer-substring (region-beginning) (region-end))
7748 (buffer-substring (point-at-bol) (point-at-eol))))
7749 ;; Only use search option if there is some text.
7750 (when (string-match "\\S-" txt)
7751 (setq cpltxt
7752 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7753 desc "NONE")))
7754 (setq link (org-make-link cpltxt)))
7756 ((interactive-p)
7757 (error "Cannot link to a buffer which is not visiting a file"))
7759 (t (setq link nil)))
7761 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7762 (setq link (or link cpltxt)
7763 desc (or desc cpltxt))
7764 (if (equal desc "NONE") (setq desc nil))
7766 (if (and (or (interactive-p) executing-kbd-macro) link)
7767 (progn
7768 (setq org-stored-links
7769 (cons (list link desc) org-stored-links))
7770 (message "Stored: %s" (or desc link))
7771 (when custom-id
7772 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7773 "::#" custom-id))
7774 (setq org-stored-links
7775 (cons (list link desc) org-stored-links))))
7776 (and link (org-make-link-string link desc)))))
7778 (defun org-store-link-props (&rest plist)
7779 "Store link properties, extract names and addresses."
7780 (let (x adr)
7781 (when (setq x (plist-get plist :from))
7782 (setq adr (mail-extract-address-components x))
7783 (setq plist (plist-put plist :fromname (car adr)))
7784 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7785 (when (setq x (plist-get plist :to))
7786 (setq adr (mail-extract-address-components x))
7787 (setq plist (plist-put plist :toname (car adr)))
7788 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7789 (let ((from (plist-get plist :from))
7790 (to (plist-get plist :to)))
7791 (when (and from to org-from-is-user-regexp)
7792 (setq plist
7793 (plist-put plist :fromto
7794 (if (string-match org-from-is-user-regexp from)
7795 (concat "to %t")
7796 (concat "from %f"))))))
7797 (setq org-store-link-plist plist))
7799 (defun org-add-link-props (&rest plist)
7800 "Add these properties to the link property list."
7801 (let (key value)
7802 (while plist
7803 (setq key (pop plist) value (pop plist))
7804 (setq org-store-link-plist
7805 (plist-put org-store-link-plist key value)))))
7807 (defun org-email-link-description (&optional fmt)
7808 "Return the description part of an email link.
7809 This takes information from `org-store-link-plist' and formats it
7810 according to FMT (default from `org-email-link-description-format')."
7811 (setq fmt (or fmt org-email-link-description-format))
7812 (let* ((p org-store-link-plist)
7813 (to (plist-get p :toaddress))
7814 (from (plist-get p :fromaddress))
7815 (table
7816 (list
7817 (cons "%c" (plist-get p :fromto))
7818 (cons "%F" (plist-get p :from))
7819 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7820 (cons "%T" (plist-get p :to))
7821 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7822 (cons "%s" (plist-get p :subject))
7823 (cons "%m" (plist-get p :message-id)))))
7824 (when (string-match "%c" fmt)
7825 ;; Check if the user wrote this message
7826 (if (and org-from-is-user-regexp from to
7827 (save-match-data (string-match org-from-is-user-regexp from)))
7828 (setq fmt (replace-match "to %t" t t fmt))
7829 (setq fmt (replace-match "from %f" t t fmt))))
7830 (org-replace-escapes fmt table)))
7832 (defun org-make-org-heading-search-string (&optional string heading)
7833 "Make search string for STRING or current headline."
7834 (interactive)
7835 (let ((s (or string (org-get-heading))))
7836 (unless (and string (not heading))
7837 ;; We are using a headline, clean up garbage in there.
7838 (if (string-match org-todo-regexp s)
7839 (setq s (replace-match "" t t s)))
7840 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7841 (setq s (replace-match "" t t s)))
7842 (setq s (org-trim s))
7843 (if (string-match (concat "^\\(" org-quote-string "\\|"
7844 org-comment-string "\\)") s)
7845 (setq s (replace-match "" t t s)))
7846 (while (string-match org-ts-regexp s)
7847 (setq s (replace-match "" t t s))))
7848 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7849 (setq s (replace-match " " t t s)))
7850 (or string (setq s (concat "*" s))) ; Add * for headlines
7851 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7853 (defun org-make-link (&rest strings)
7854 "Concatenate STRINGS."
7855 (apply 'concat strings))
7857 (defun org-make-link-string (link &optional description)
7858 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7859 (unless (string-match "\\S-" link)
7860 (error "Empty link"))
7861 (when (and description
7862 (stringp description)
7863 (not (string-match "\\S-" description)))
7864 (setq description nil))
7865 (when (stringp description)
7866 ;; Remove brackets from the description, they are fatal.
7867 (while (string-match "\\[" description)
7868 (setq description (replace-match "{" t t description)))
7869 (while (string-match "\\]" description)
7870 (setq description (replace-match "}" t t description))))
7871 (when (equal (org-link-escape link) description)
7872 ;; No description needed, it is identical
7873 (setq description nil))
7874 (when (and (not description)
7875 (not (equal link (org-link-escape link))))
7876 (setq description (org-extract-attributes link)))
7877 (concat "[[" (org-link-escape link) "]"
7878 (if description (concat "[" description "]") "")
7879 "]"))
7881 (defconst org-link-escape-chars
7882 '((?\ . "%20")
7883 (?\[ . "%5B")
7884 (?\] . "%5D")
7885 (?\340 . "%E0") ; `a
7886 (?\342 . "%E2") ; ^a
7887 (?\347 . "%E7") ; ,c
7888 (?\350 . "%E8") ; `e
7889 (?\351 . "%E9") ; 'e
7890 (?\352 . "%EA") ; ^e
7891 (?\356 . "%EE") ; ^i
7892 (?\364 . "%F4") ; ^o
7893 (?\371 . "%F9") ; `u
7894 (?\373 . "%FB") ; ^u
7895 (?\; . "%3B")
7896 (?? . "%3F")
7897 (?= . "%3D")
7898 (?+ . "%2B")
7900 "Association list of escapes for some characters problematic in links.
7901 This is the list that is used for internal purposes.")
7903 (defvar org-url-encoding-use-url-hexify nil)
7905 (defconst org-link-escape-chars-browser
7906 '((?\ . "%20")) ; 32 for the SPC char
7907 "Association list of escapes for some characters problematic in links.
7908 This is the list that is used before handing over to the browser.")
7910 (defun org-link-escape (text &optional table)
7911 "Escape characters in TEXT that are problematic for links."
7912 (if (and org-url-encoding-use-url-hexify (not table))
7913 (url-hexify-string text)
7914 (setq table (or table org-link-escape-chars))
7915 (when text
7916 (let ((re (mapconcat (lambda (x) (regexp-quote
7917 (char-to-string (car x))))
7918 table "\\|")))
7919 (while (string-match re text)
7920 (setq text
7921 (replace-match
7922 (cdr (assoc (string-to-char (match-string 0 text))
7923 table))
7924 t t text)))
7925 text))))
7927 (defun org-link-unescape (text &optional table)
7928 "Reverse the action of `org-link-escape'."
7929 (if (and org-url-encoding-use-url-hexify (not table))
7930 (url-unhex-string text)
7931 (setq table (or table org-link-escape-chars))
7932 (when text
7933 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7934 table "\\|")))
7935 (while (string-match re text)
7936 (setq text
7937 (replace-match
7938 (char-to-string (car (rassoc (match-string 0 text) table)))
7939 t t text)))
7940 text))))
7942 (defun org-xor (a b)
7943 "Exclusive or."
7944 (if a (not b) b))
7946 (defun org-fixup-message-id-for-http (s)
7947 "Replace special characters in a message id, so it can be used in an http query."
7948 (while (string-match "<" s)
7949 (setq s (replace-match "%3C" t t s)))
7950 (while (string-match ">" s)
7951 (setq s (replace-match "%3E" t t s)))
7952 (while (string-match "@" s)
7953 (setq s (replace-match "%40" t t s)))
7956 ;;;###autoload
7957 (defun org-insert-link-global ()
7958 "Insert a link like Org-mode does.
7959 This command can be called in any mode to insert a link in Org-mode syntax."
7960 (interactive)
7961 (org-load-modules-maybe)
7962 (org-run-like-in-org-mode 'org-insert-link))
7964 (defun org-insert-link (&optional complete-file link-location)
7965 "Insert a link. At the prompt, enter the link.
7967 Completion can be used to insert any of the link protocol prefixes like
7968 http or ftp in use.
7970 The history can be used to select a link previously stored with
7971 `org-store-link'. When the empty string is entered (i.e. if you just
7972 press RET at the prompt), the link defaults to the most recently
7973 stored link. As SPC triggers completion in the minibuffer, you need to
7974 use M-SPC or C-q SPC to force the insertion of a space character.
7976 You will also be prompted for a description, and if one is given, it will
7977 be displayed in the buffer instead of the link.
7979 If there is already a link at point, this command will allow you to edit link
7980 and description parts.
7982 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7983 be selected using completion. The path to the file will be relative to the
7984 current directory if the file is in the current directory or a subdirectory.
7985 Otherwise, the link will be the absolute path as completed in the minibuffer
7986 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7987 option `org-link-file-path-type'.
7989 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7990 the current directory or below.
7992 With three \\[universal-argument] prefixes, negate the meaning of
7993 `org-keep-stored-link-after-insertion'.
7995 If `org-make-link-description-function' is non-nil, this function will be
7996 called with the link target, and the result will be the default
7997 link description.
7999 If the LINK-LOCATION parameter is non-nil, this value will be
8000 used as the link location instead of reading one interactively."
8001 (interactive "P")
8002 (let* ((wcf (current-window-configuration))
8003 (region (if (org-region-active-p)
8004 (buffer-substring (region-beginning) (region-end))))
8005 (remove (and region (list (region-beginning) (region-end))))
8006 (desc region)
8007 tmphist ; byte-compile incorrectly complains about this
8008 (link link-location)
8009 entry file all-prefixes)
8010 (cond
8011 (link-location) ; specified by arg, just use it.
8012 ((org-in-regexp org-bracket-link-regexp 1)
8013 ;; We do have a link at point, and we are going to edit it.
8014 (setq remove (list (match-beginning 0) (match-end 0)))
8015 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8016 (setq link (read-string "Link: "
8017 (org-link-unescape
8018 (org-match-string-no-properties 1)))))
8019 ((or (org-in-regexp org-angle-link-re)
8020 (org-in-regexp org-plain-link-re))
8021 ;; Convert to bracket link
8022 (setq remove (list (match-beginning 0) (match-end 0))
8023 link (read-string "Link: "
8024 (org-remove-angle-brackets (match-string 0)))))
8025 ((member complete-file '((4) (16)))
8026 ;; Completing read for file names.
8027 (setq link (org-file-complete-link complete-file)))
8029 ;; Read link, with completion for stored links.
8030 (with-output-to-temp-buffer "*Org Links*"
8031 (princ "Insert a link.
8032 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8033 (when org-stored-links
8034 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8035 (princ (mapconcat
8036 (lambda (x)
8037 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8038 (reverse org-stored-links) "\n"))))
8039 (let ((cw (selected-window)))
8040 (select-window (get-buffer-window "*Org Links*"))
8041 (setq truncate-lines t)
8042 (unless (pos-visible-in-window-p (point-max))
8043 (org-fit-window-to-buffer))
8044 (and (window-live-p cw) (select-window cw)))
8045 ;; Fake a link history, containing the stored links.
8046 (setq tmphist (append (mapcar 'car org-stored-links)
8047 org-insert-link-history))
8048 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8049 (mapcar 'car org-link-abbrev-alist)
8050 org-link-types))
8051 (unwind-protect
8052 (progn
8053 (setq link
8054 (let ((org-completion-use-ido nil)
8055 (org-completion-use-iswitchb nil))
8056 (org-completing-read
8057 "Link: "
8058 (append
8059 (mapcar (lambda (x) (list (concat x ":")))
8060 all-prefixes)
8061 (mapcar 'car org-stored-links))
8062 nil nil nil
8063 'tmphist
8064 (car (car org-stored-links)))))
8065 (if (not (string-match "\\S-" link))
8066 (error "No link selected"))
8067 (if (or (member link all-prefixes)
8068 (and (equal ":" (substring link -1))
8069 (member (substring link 0 -1) all-prefixes)
8070 (setq link (substring link 0 -1))))
8071 (setq link (org-link-try-special-completion link))))
8072 (set-window-configuration wcf)
8073 (kill-buffer "*Org Links*"))
8074 (setq entry (assoc link org-stored-links))
8075 (or entry (push link org-insert-link-history))
8076 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8077 (not org-keep-stored-link-after-insertion))
8078 (setq org-stored-links (delq (assoc link org-stored-links)
8079 org-stored-links)))
8080 (setq desc (or desc (nth 1 entry)))))
8082 (if (string-match org-plain-link-re link)
8083 ;; URL-like link, normalize the use of angular brackets.
8084 (setq link (org-make-link (org-remove-angle-brackets link))))
8086 ;; Check if we are linking to the current file with a search option
8087 ;; If yes, simplify the link by using only the search option.
8088 (when (and buffer-file-name
8089 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8090 (let* ((path (match-string 1 link))
8091 (case-fold-search nil)
8092 (search (match-string 2 link)))
8093 (save-match-data
8094 (if (equal (file-truename buffer-file-name) (file-truename path))
8095 ;; We are linking to this same file, with a search option
8096 (setq link search)))))
8098 ;; Check if we can/should use a relative path. If yes, simplify the link
8099 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8100 (let* ((type (match-string 1 link))
8101 (path (match-string 2 link))
8102 (origpath path)
8103 (case-fold-search nil))
8104 (cond
8105 ((or (eq org-link-file-path-type 'absolute)
8106 (equal complete-file '(16)))
8107 (setq path (abbreviate-file-name (expand-file-name path))))
8108 ((eq org-link-file-path-type 'noabbrev)
8109 (setq path (expand-file-name path)))
8110 ((eq org-link-file-path-type 'relative)
8111 (setq path (file-relative-name path)))
8113 (save-match-data
8114 (if (string-match (concat "^" (regexp-quote
8115 (file-name-as-directory
8116 (expand-file-name "."))))
8117 (expand-file-name path))
8118 ;; We are linking a file with relative path name.
8119 (setq path (substring (expand-file-name path)
8120 (match-end 0)))
8121 (setq path (abbreviate-file-name (expand-file-name path)))))))
8122 (setq link (concat type path))
8123 (if (equal desc origpath)
8124 (setq desc path))))
8126 (if org-make-link-description-function
8127 (setq desc (funcall org-make-link-description-function link desc)))
8129 (setq desc (read-string "Description: " desc))
8130 (unless (string-match "\\S-" desc) (setq desc nil))
8131 (if remove (apply 'delete-region remove))
8132 (insert (org-make-link-string link desc))))
8134 (defun org-link-try-special-completion (type)
8135 "If there is completion support for link type TYPE, offer it."
8136 (let ((fun (intern (concat "org-" type "-complete-link"))))
8137 (if (functionp fun)
8138 (funcall fun)
8139 (read-string "Link (no completion support): " (concat type ":")))))
8141 (defun org-file-complete-link (&optional arg)
8142 "Create a file link using completion."
8143 (let (file link)
8144 (setq file (read-file-name "File: "))
8145 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8146 (pwd1 (file-name-as-directory (abbreviate-file-name
8147 (expand-file-name ".")))))
8148 (cond
8149 ((equal arg '(16))
8150 (setq link (org-make-link
8151 "file:"
8152 (abbreviate-file-name (expand-file-name file)))))
8153 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8154 (setq link (org-make-link "file:" (match-string 1 file))))
8155 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8156 (expand-file-name file))
8157 (setq link (org-make-link
8158 "file:" (match-string 1 (expand-file-name file)))))
8159 (t (setq link (org-make-link "file:" file)))))
8160 link))
8162 (defun org-completing-read (&rest args)
8163 "Completing-read with SPACE being a normal character."
8164 (let ((minibuffer-local-completion-map
8165 (copy-keymap minibuffer-local-completion-map)))
8166 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8167 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8168 (apply 'org-icompleting-read args)))
8170 (defun org-completing-read-no-i (&rest args)
8171 (let (org-completion-use-ido org-completion-use-iswitchb)
8172 (apply 'org-completing-read args)))
8174 (defun org-iswitchb-completing-read (prompt choices &rest args)
8175 "Use iswitch as a completing-read replacement to choose from choices.
8176 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8177 from."
8178 (let* ((iswitchb-use-virtual-buffers nil)
8179 (iswitchb-make-buflist-hook
8180 (lambda ()
8181 (setq iswitchb-temp-buflist choices))))
8182 (iswitchb-read-buffer prompt)))
8184 (defun org-icompleting-read (&rest args)
8185 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8186 (org-without-partial-completion
8187 (if (and org-completion-use-ido
8188 (fboundp 'ido-completing-read)
8189 (boundp 'ido-mode) ido-mode
8190 (listp (second args)))
8191 (let ((ido-enter-matching-directory nil))
8192 (apply 'ido-completing-read (concat (car args))
8193 (if (consp (car (nth 1 args)))
8194 (mapcar (lambda (x) (car x)) (nth 1 args))
8195 (nth 1 args))
8196 (cddr args)))
8197 (if (and org-completion-use-iswitchb
8198 (boundp 'iswitchb-mode) iswitchb-mode
8199 (listp (second args)))
8200 (apply 'org-iswitchb-completing-read (concat (car args))
8201 (if (consp (car (nth 1 args)))
8202 (mapcar (lambda (x) (car x)) (nth 1 args))
8203 (nth 1 args))
8204 (cddr args))
8205 (apply 'completing-read args)))))
8207 (defun org-extract-attributes (s)
8208 "Extract the attributes cookie from a string and set as text property."
8209 (let (a attr (start 0) key value)
8210 (save-match-data
8211 (when (string-match "{{\\([^}]+\\)}}$" s)
8212 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8213 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8214 (setq key (match-string 1 a) value (match-string 2 a)
8215 start (match-end 0)
8216 attr (plist-put attr (intern key) value))))
8217 (org-add-props s nil 'org-attr attr))
8220 (defun org-extract-attributes-from-string (tag)
8221 (let (key value attr)
8222 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8223 (setq key (match-string 1 tag) value (match-string 2 tag)
8224 tag (replace-match "" t t tag)
8225 attr (plist-put attr (intern key) value)))
8226 (cons tag attr)))
8228 (defun org-attributes-to-string (plist)
8229 "Format a property list into an HTML attribute list."
8230 (let ((s "") key value)
8231 (while plist
8232 (setq key (pop plist) value (pop plist))
8233 (and value
8234 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8237 ;;; Opening/following a link
8239 (defvar org-link-search-failed nil)
8241 (defvar org-open-link-functions nil
8242 "Hook for functions finding a plain text link.
8243 These functions must take a single argument, the link content.
8244 They will be called for links that look like [[link text][description]]
8245 when LINK TEXT does not have a protocol like \"http:\" and does not look
8246 like a filename (e.g. \"./blue.png\").
8248 These functions will be called *before* Org attempts to resolve the
8249 link by doing text searches in the current buffer - so if you want a
8250 link \"[[target]]\" to still find \"<<target>>\", your function should
8251 handle this as a special case.
8253 When the function does handle the link, it must return a non-nil value.
8254 If it decides that it is not responsible for this link, it must return
8255 nil to indicate that that Org-mode can continue with other options
8256 like exact and fuzzy text search.")
8258 (defun org-next-link ()
8259 "Move forward to the next link.
8260 If the link is in hidden text, expose it."
8261 (interactive)
8262 (when (and org-link-search-failed (eq this-command last-command))
8263 (goto-char (point-min))
8264 (message "Link search wrapped back to beginning of buffer"))
8265 (setq org-link-search-failed nil)
8266 (let* ((pos (point))
8267 (ct (org-context))
8268 (a (assoc :link ct)))
8269 (if a (goto-char (nth 2 a)))
8270 (if (re-search-forward org-any-link-re nil t)
8271 (progn
8272 (goto-char (match-beginning 0))
8273 (if (org-invisible-p) (org-show-context)))
8274 (goto-char pos)
8275 (setq org-link-search-failed t)
8276 (error "No further link found"))))
8278 (defun org-previous-link ()
8279 "Move backward to the previous link.
8280 If the link is in hidden text, expose it."
8281 (interactive)
8282 (when (and org-link-search-failed (eq this-command last-command))
8283 (goto-char (point-max))
8284 (message "Link search wrapped back to end of buffer"))
8285 (setq org-link-search-failed nil)
8286 (let* ((pos (point))
8287 (ct (org-context))
8288 (a (assoc :link ct)))
8289 (if a (goto-char (nth 1 a)))
8290 (if (re-search-backward org-any-link-re nil t)
8291 (progn
8292 (goto-char (match-beginning 0))
8293 (if (org-invisible-p) (org-show-context)))
8294 (goto-char pos)
8295 (setq org-link-search-failed t)
8296 (error "No further link found"))))
8298 (defun org-translate-link (s)
8299 "Translate a link string if a translation function has been defined."
8300 (if (and org-link-translation-function
8301 (fboundp org-link-translation-function)
8302 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8303 (progn
8304 (setq s (funcall org-link-translation-function
8305 (match-string 1) (match-string 2)))
8306 (concat (car s) ":" (cdr s)))
8309 (defun org-translate-link-from-planner (type path)
8310 "Translate a link from Emacs Planner syntax so that Org can follow it.
8311 This is still an experimental function, your mileage may vary."
8312 (cond
8313 ((member type '("http" "https" "news" "ftp"))
8314 ;; standard Internet links are the same.
8315 nil)
8316 ((and (equal type "irc") (string-match "^//" path))
8317 ;; Planner has two / at the beginning of an irc link, we have 1.
8318 ;; We should have zero, actually....
8319 (setq path (substring path 1)))
8320 ((and (equal type "lisp") (string-match "^/" path))
8321 ;; Planner has a slash, we do not.
8322 (setq type "elisp" path (substring path 1)))
8323 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8324 ;; A typical message link. Planner has the id after the final slash,
8325 ;; we separate it with a hash mark
8326 (setq path (concat (match-string 1 path) "#"
8327 (org-remove-angle-brackets (match-string 2 path)))))
8329 (cons type path))
8331 (defun org-find-file-at-mouse (ev)
8332 "Open file link or URL at mouse."
8333 (interactive "e")
8334 (mouse-set-point ev)
8335 (org-open-at-point 'in-emacs))
8337 (defun org-open-at-mouse (ev)
8338 "Open file link or URL at mouse."
8339 (interactive "e")
8340 (mouse-set-point ev)
8341 (if (eq major-mode 'org-agenda-mode)
8342 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8343 (org-open-at-point))
8345 (defvar org-window-config-before-follow-link nil
8346 "The window configuration before following a link.
8347 This is saved in case the need arises to restore it.")
8349 (defvar org-open-link-marker (make-marker)
8350 "Marker pointing to the location where `org-open-at-point; was called.")
8352 ;;;###autoload
8353 (defun org-open-at-point-global ()
8354 "Follow a link like Org-mode does.
8355 This command can be called in any mode to follow a link that has
8356 Org-mode syntax."
8357 (interactive)
8358 (org-run-like-in-org-mode 'org-open-at-point))
8360 ;;;###autoload
8361 (defun org-open-link-from-string (s &optional arg reference-buffer)
8362 "Open a link in the string S, as if it was in Org-mode."
8363 (interactive "sLink: \nP")
8364 (let ((reference-buffer (or reference-buffer (current-buffer))))
8365 (with-temp-buffer
8366 (let ((org-inhibit-startup t))
8367 (org-mode)
8368 (insert s)
8369 (goto-char (point-min))
8370 (org-open-at-point arg reference-buffer)))))
8372 (defun org-open-at-point (&optional in-emacs reference-buffer)
8373 "Open link at or after point.
8374 If there is no link at point, this function will search forward up to
8375 the end of the current line.
8376 Normally, files will be opened by an appropriate application. If the
8377 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8378 With a double prefix argument, try to open outside of Emacs, in the
8379 application the system uses for this file type."
8380 (interactive "P")
8381 (org-load-modules-maybe)
8382 (move-marker org-open-link-marker (point))
8383 (setq org-window-config-before-follow-link (current-window-configuration))
8384 (org-remove-occur-highlights nil nil t)
8385 (cond
8386 ((and (org-on-heading-p)
8387 (not (org-in-regexp
8388 (concat org-plain-link-re "\\|"
8389 org-bracket-link-regexp "\\|"
8390 org-angle-link-re "\\|"
8391 "[ \t]:[^ \t\n]+:[ \t]*$")))
8392 (not (get-text-property (point) 'org-linked-text)))
8393 (or (org-offer-links-in-entry in-emacs)
8394 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8395 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8396 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8397 (org-footnote-action))
8399 (let (type path link line search (pos (point)))
8400 (catch 'match
8401 (save-excursion
8402 (skip-chars-forward "^]\n\r")
8403 (when (org-in-regexp org-bracket-link-regexp 1)
8404 (setq link (org-extract-attributes
8405 (org-link-unescape (org-match-string-no-properties 1))))
8406 (while (string-match " *\n *" link)
8407 (setq link (replace-match " " t t link)))
8408 (setq link (org-link-expand-abbrev link))
8409 (cond
8410 ((or (file-name-absolute-p link)
8411 (string-match "^\\.\\.?/" link))
8412 (setq type "file" path link))
8413 ((string-match org-link-re-with-space3 link)
8414 (setq type (match-string 1 link) path (match-string 2 link)))
8415 (t (setq type "thisfile" path link)))
8416 (throw 'match t)))
8418 (when (get-text-property (point) 'org-linked-text)
8419 (setq type "thisfile"
8420 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8421 (1+ (point)) (point))
8422 path (buffer-substring
8423 (previous-single-property-change pos 'org-linked-text)
8424 (next-single-property-change pos 'org-linked-text)))
8425 (throw 'match t))
8427 (save-excursion
8428 (when (or (org-in-regexp org-angle-link-re)
8429 (org-in-regexp org-plain-link-re))
8430 (setq type (match-string 1) path (match-string 2))
8431 (throw 'match t)))
8432 (save-excursion
8433 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8434 (setq type "tags"
8435 path (match-string 1))
8436 (while (string-match ":" path)
8437 (setq path (replace-match "+" t t path)))
8438 (throw 'match t)))
8439 (when (org-in-regexp "<\\([^><\n]+\\)>")
8440 (setq type "tree-match"
8441 path (match-string 1))
8442 (throw 'match t)))
8443 (unless path
8444 (error "No link found"))
8446 ;; switch back to reference buffer
8447 ;; needed when if called in a temporary buffer through
8448 ;; org-open-link-from-string
8449 (with-current-buffer (or reference-buffer (current-buffer))
8451 ;; Remove any trailing spaces in path
8452 (if (string-match " +\\'" path)
8453 (setq path (replace-match "" t t path)))
8454 (if (and org-link-translation-function
8455 (fboundp org-link-translation-function))
8456 ;; Check if we need to translate the link
8457 (let ((tmp (funcall org-link-translation-function type path)))
8458 (setq type (car tmp) path (cdr tmp))))
8460 (cond
8462 ((assoc type org-link-protocols)
8463 (funcall (nth 1 (assoc type org-link-protocols)) path))
8465 ((equal type "mailto")
8466 (let ((cmd (car org-link-mailto-program))
8467 (args (cdr org-link-mailto-program)) args1
8468 (address path) (subject "") a)
8469 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8470 (setq address (match-string 1 path)
8471 subject (org-link-escape (match-string 2 path))))
8472 (while args
8473 (cond
8474 ((not (stringp (car args))) (push (pop args) args1))
8475 (t (setq a (pop args))
8476 (if (string-match "%a" a)
8477 (setq a (replace-match address t t a)))
8478 (if (string-match "%s" a)
8479 (setq a (replace-match subject t t a)))
8480 (push a args1))))
8481 (apply cmd (nreverse args1))))
8483 ((member type '("http" "https" "ftp" "news"))
8484 (browse-url (concat type ":" (org-link-escape
8485 path org-link-escape-chars-browser))))
8487 ((member type '("message"))
8488 (browse-url (concat type ":" path)))
8490 ((string= type "tags")
8491 (org-tags-view in-emacs path))
8493 ((string= type "tree-match")
8494 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8496 ((string= type "file")
8497 (if (string-match "::\\([0-9]+\\)\\'" path)
8498 (setq line (string-to-number (match-string 1 path))
8499 path (substring path 0 (match-beginning 0)))
8500 (if (string-match "::\\(.+\\)\\'" path)
8501 (setq search (match-string 1 path)
8502 path (substring path 0 (match-beginning 0)))))
8503 (if (string-match "[*?{]" (file-name-nondirectory path))
8504 (dired path)
8505 (org-open-file path in-emacs line search)))
8507 ((string= type "news")
8508 (require 'org-gnus)
8509 (org-gnus-follow-link path))
8511 ((string= type "shell")
8512 (let ((cmd path))
8513 (if (or (not org-confirm-shell-link-function)
8514 (funcall org-confirm-shell-link-function
8515 (format "Execute \"%s\" in shell? "
8516 (org-add-props cmd nil
8517 'face 'org-warning))))
8518 (progn
8519 (message "Executing %s" cmd)
8520 (shell-command cmd))
8521 (error "Abort"))))
8523 ((string= type "elisp")
8524 (let ((cmd path))
8525 (if (or (not org-confirm-elisp-link-function)
8526 (funcall org-confirm-elisp-link-function
8527 (format "Execute \"%s\" as elisp? "
8528 (org-add-props cmd nil
8529 'face 'org-warning))))
8530 (message "%s => %s" cmd
8531 (if (equal (string-to-char cmd) ?\()
8532 (eval (read cmd))
8533 (call-interactively (read cmd))))
8534 (error "Abort"))))
8536 ((and (string= type "thisfile")
8537 (run-hook-with-args-until-success
8538 'org-open-link-functions path)))
8540 ((string= type "thisfile")
8541 (if in-emacs
8542 (switch-to-buffer-other-window
8543 (org-get-buffer-for-internal-link (current-buffer)))
8544 (org-mark-ring-push))
8545 (let ((cmd `(org-link-search
8546 ,path
8547 ,(cond ((equal in-emacs '(4)) 'occur)
8548 ((equal in-emacs '(16)) 'org-occur)
8549 (t nil))
8550 ,pos)))
8551 (condition-case nil (eval cmd)
8552 (error (progn (widen) (eval cmd))))))
8555 (browse-url-at-point)))))))
8556 (move-marker org-open-link-marker nil)
8557 (run-hook-with-args 'org-follow-link-hook))
8559 (defun org-offer-links-in-entry (&optional nth zero)
8560 "Offer links in the current entry and follow the selected link.
8561 If there is only one link, follow it immediately as well.
8562 If NTH is an integer, immediately pick the NTH link found.
8563 If ZERO is a string, check also this string for a link, and if
8564 there is one, offer it as link number zero."
8565 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8566 "\\(" org-angle-link-re "\\)\\|"
8567 "\\(" org-plain-link-re "\\)"))
8568 (cnt ?0)
8569 (in-emacs (if (integerp nth) nil nth))
8570 have-zero end links link c)
8571 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8572 (push (match-string 0 zero) links)
8573 (setq cnt (1- cnt) have-zero t))
8574 (save-excursion
8575 (org-back-to-heading t)
8576 (setq end (save-excursion (outline-next-heading) (point)))
8577 (while (re-search-forward re end t)
8578 (push (match-string 0) links))
8579 (setq links (org-uniquify (reverse links))))
8581 (cond
8582 ((null links)
8583 (message "No links"))
8584 ((equal (length links) 1)
8585 (setq link (list (car links))))
8586 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8587 (setq link (nth (if have-zero nth (1- nth)) links)))
8588 (t ; we have to select a link
8589 (save-excursion
8590 (save-window-excursion
8591 (delete-other-windows)
8592 (with-output-to-temp-buffer "*Select Link*"
8593 (mapc (lambda (l)
8594 (if (not (string-match org-bracket-link-regexp l))
8595 (princ (format "[%c] %s\n" (incf cnt)
8596 (org-remove-angle-brackets l)))
8597 (if (match-end 3)
8598 (princ (format "[%c] %s (%s)\n" (incf cnt)
8599 (match-string 3 l) (match-string 1 l)))
8600 (princ (format "[%c] %s\n" (incf cnt)
8601 (match-string 1 l))))))
8602 links))
8603 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8604 (message "Select link to open, RET to open all:")
8605 (setq c (read-char-exclusive))
8606 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8607 (when (equal c ?q) (error "Abort"))
8608 (if (equal c ?\C-m)
8609 (setq link links)
8610 (setq nth (- c ?0))
8611 (if have-zero (setq nth (1+ nth)))
8612 (unless (and (integerp nth) (>= (length links) nth))
8613 (error "Invalid link selection"))
8614 (setq link (list (nth (1- nth) links))))))
8615 (if link
8616 (let ((buf (current-buffer)))
8617 (dolist (l link)
8618 (org-open-link-from-string l in-emacs buf))
8620 nil)))
8622 ;; Add special file links that specify the way of opening
8624 (org-add-link-type "file+sys" 'org-open-file-with-system)
8625 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8626 (defun org-open-file-with-system (path)
8627 "Open file at PATH using the system way of opeing it."
8628 (org-open-file path 'system))
8629 (defun org-open-file-with-emacs (path)
8630 "Open file at PATH in emacs."
8631 (org-open-file path 'emacs))
8632 (defun org-remove-file-link-modifiers ()
8633 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8634 (goto-char (point-min))
8635 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8636 (org-if-unprotected
8637 (replace-match "file:" t t))))
8638 (eval-after-load "org-exp"
8639 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8640 'org-remove-file-link-modifiers))
8642 ;;;; Time estimates
8644 (defun org-get-effort (&optional pom)
8645 "Get the effort estimate for the current entry."
8646 (org-entry-get pom org-effort-property))
8648 ;;; File search
8650 (defvar org-create-file-search-functions nil
8651 "List of functions to construct the right search string for a file link.
8652 These functions are called in turn with point at the location to
8653 which the link should point.
8655 A function in the hook should first test if it would like to
8656 handle this file type, for example by checking the major-mode or
8657 the file extension. If it decides not to handle this file, it
8658 should just return nil to give other functions a chance. If it
8659 does handle the file, it must return the search string to be used
8660 when following the link. The search string will be part of the
8661 file link, given after a double colon, and `org-open-at-point'
8662 will automatically search for it. If special measures must be
8663 taken to make the search successful, another function should be
8664 added to the companion hook `org-execute-file-search-functions',
8665 which see.
8667 A function in this hook may also use `setq' to set the variable
8668 `description' to provide a suggestion for the descriptive text to
8669 be used for this link when it gets inserted into an Org-mode
8670 buffer with \\[org-insert-link].")
8672 (defvar org-execute-file-search-functions nil
8673 "List of functions to execute a file search triggered by a link.
8675 Functions added to this hook must accept a single argument, the
8676 search string that was part of the file link, the part after the
8677 double colon. The function must first check if it would like to
8678 handle this search, for example by checking the major-mode or the
8679 file extension. If it decides not to handle this search, it
8680 should just return nil to give other functions a chance. If it
8681 does handle the search, it must return a non-nil value to keep
8682 other functions from trying.
8684 Each function can access the current prefix argument through the
8685 variable `current-prefix-argument'. Note that a single prefix is
8686 used to force opening a link in Emacs, so it may be good to only
8687 use a numeric or double prefix to guide the search function.
8689 In case this is needed, a function in this hook can also restore
8690 the window configuration before `org-open-at-point' was called using:
8692 (set-window-configuration org-window-config-before-follow-link)")
8694 (defun org-link-search (s &optional type avoid-pos)
8695 "Search for a link search option.
8696 If S is surrounded by forward slashes, it is interpreted as a
8697 regular expression. In org-mode files, this will create an `org-occur'
8698 sparse tree. In ordinary files, `occur' will be used to list matches.
8699 If the current buffer is in `dired-mode', grep will be used to search
8700 in all files. If AVOID-POS is given, ignore matches near that position."
8701 (let ((case-fold-search t)
8702 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8703 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8704 (append '(("") (" ") ("\t") ("\n"))
8705 org-emphasis-alist)
8706 "\\|") "\\)"))
8707 (pos (point))
8708 (pre nil) (post nil)
8709 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8710 (cond
8711 ;; First check if there are any special
8712 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8713 ;; Now try the builtin stuff
8714 ((and (equal (string-to-char s0) ?#)
8715 (> (length s0) 1)
8716 (save-excursion
8717 (goto-char (point-min))
8718 (and
8719 (re-search-forward
8720 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8721 (setq type 'dedicated
8722 pos (match-beginning 0))))
8723 ;; There is an exact target for this
8724 (goto-char pos)
8725 (org-back-to-heading t)))
8726 ((save-excursion
8727 (goto-char (point-min))
8728 (and
8729 (re-search-forward
8730 (concat "<<" (regexp-quote s0) ">>") nil t)
8731 (setq type 'dedicated
8732 pos (match-beginning 0))))
8733 ;; There is an exact target for this
8734 (goto-char pos))
8735 ((and (string-match "^(\\(.*\\))$" s0)
8736 (save-excursion
8737 (goto-char (point-min))
8738 (and
8739 (re-search-forward
8740 (concat "[^[]" (regexp-quote
8741 (format org-coderef-label-format
8742 (match-string 1 s0))))
8743 nil t)
8744 (setq type 'dedicated
8745 pos (1+ (match-beginning 0))))))
8746 ;; There is a coderef target for this
8747 (goto-char pos))
8748 ((string-match "^/\\(.*\\)/$" s)
8749 ;; A regular expression
8750 (cond
8751 ((org-mode-p)
8752 (org-occur (match-string 1 s)))
8753 ;;((eq major-mode 'dired-mode)
8754 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8755 (t (org-do-occur (match-string 1 s)))))
8757 ;; A normal search strings
8758 (when (equal (string-to-char s) ?*)
8759 ;; Anchor on headlines, post may include tags.
8760 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8761 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8762 s (substring s 1)))
8763 (remove-text-properties
8764 0 (length s)
8765 '(face nil mouse-face nil keymap nil fontified nil) s)
8766 ;; Make a series of regular expressions to find a match
8767 (setq words (org-split-string s "[ \n\r\t]+")
8769 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8770 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8771 "\\)" markers)
8772 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8773 re2a (concat "[ \t\r\n]" re2a_)
8774 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8775 re4 (concat "[^a-zA-Z_]" re4_)
8777 re1 (concat pre re2 post)
8778 re3 (concat pre (if pre re4_ re4) post)
8779 re5 (concat pre ".*" re4)
8780 re2 (concat pre re2)
8781 re2a (concat pre (if pre re2a_ re2a))
8782 re4 (concat pre (if pre re4_ re4))
8783 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8784 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8785 re5 "\\)"
8787 (cond
8788 ((eq type 'org-occur) (org-occur reall))
8789 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8790 (t (goto-char (point-min))
8791 (setq type 'fuzzy)
8792 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8793 (org-search-not-self 1 re1 nil t)
8794 (org-search-not-self 1 re2 nil t)
8795 (org-search-not-self 1 re2a nil t)
8796 (org-search-not-self 1 re3 nil t)
8797 (org-search-not-self 1 re4 nil t)
8798 (org-search-not-self 1 re5 nil t)
8800 (goto-char (match-beginning 1))
8801 (goto-char pos)
8802 (error "No match")))))
8804 ;; Normal string-search
8805 (goto-char (point-min))
8806 (if (search-forward s nil t)
8807 (goto-char (match-beginning 0))
8808 (error "No match"))))
8809 (and (org-mode-p) (org-show-context 'link-search))
8810 type))
8812 (defun org-search-not-self (group &rest args)
8813 "Execute `re-search-forward', but only accept matches that do not
8814 enclose the position of `org-open-link-marker'."
8815 (let ((m org-open-link-marker))
8816 (catch 'exit
8817 (while (apply 're-search-forward args)
8818 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8819 (goto-char (match-end group))
8820 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8821 (> (match-beginning 0) (marker-position m))
8822 (< (match-end 0) (marker-position m)))
8823 (save-match-data
8824 (or (not (org-in-regexp
8825 org-bracket-link-analytic-regexp 1))
8826 (not (match-end 4)) ; no description
8827 (and (<= (match-beginning 4) (point))
8828 (>= (match-end 4) (point))))))
8829 (throw 'exit (point))))))))
8831 (defun org-get-buffer-for-internal-link (buffer)
8832 "Return a buffer to be used for displaying the link target of internal links."
8833 (cond
8834 ((not org-display-internal-link-with-indirect-buffer)
8835 buffer)
8836 ((string-match "(Clone)$" (buffer-name buffer))
8837 (message "Buffer is already a clone, not making another one")
8838 ;; we also do not modify visibility in this case
8839 buffer)
8840 (t ; make a new indirect buffer for displaying the link
8841 (let* ((bn (buffer-name buffer))
8842 (ibn (concat bn "(Clone)"))
8843 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8844 (with-current-buffer ib (org-overview))
8845 ib))))
8847 (defun org-do-occur (regexp &optional cleanup)
8848 "Call the Emacs command `occur'.
8849 If CLEANUP is non-nil, remove the printout of the regular expression
8850 in the *Occur* buffer. This is useful if the regex is long and not useful
8851 to read."
8852 (occur regexp)
8853 (when cleanup
8854 (let ((cwin (selected-window)) win beg end)
8855 (when (setq win (get-buffer-window "*Occur*"))
8856 (select-window win))
8857 (goto-char (point-min))
8858 (when (re-search-forward "match[a-z]+" nil t)
8859 (setq beg (match-end 0))
8860 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8861 (setq end (1- (match-beginning 0)))))
8862 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8863 (goto-char (point-min))
8864 (select-window cwin))))
8866 ;;; The mark ring for links jumps
8868 (defvar org-mark-ring nil
8869 "Mark ring for positions before jumps in Org-mode.")
8870 (defvar org-mark-ring-last-goto nil
8871 "Last position in the mark ring used to go back.")
8872 ;; Fill and close the ring
8873 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8874 (loop for i from 1 to org-mark-ring-length do
8875 (push (make-marker) org-mark-ring))
8876 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8877 org-mark-ring)
8879 (defun org-mark-ring-push (&optional pos buffer)
8880 "Put the current position or POS into the mark ring and rotate it."
8881 (interactive)
8882 (setq pos (or pos (point)))
8883 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8884 (move-marker (car org-mark-ring)
8885 (or pos (point))
8886 (or buffer (current-buffer)))
8887 (message "%s"
8888 (substitute-command-keys
8889 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8891 (defun org-mark-ring-goto (&optional n)
8892 "Jump to the previous position in the mark ring.
8893 With prefix arg N, jump back that many stored positions. When
8894 called several times in succession, walk through the entire ring.
8895 Org-mode commands jumping to a different position in the current file,
8896 or to another Org-mode file, automatically push the old position
8897 onto the ring."
8898 (interactive "p")
8899 (let (p m)
8900 (if (eq last-command this-command)
8901 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8902 (setq p org-mark-ring))
8903 (setq org-mark-ring-last-goto p)
8904 (setq m (car p))
8905 (switch-to-buffer (marker-buffer m))
8906 (goto-char m)
8907 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8909 (defun org-remove-angle-brackets (s)
8910 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8911 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8913 (defun org-add-angle-brackets (s)
8914 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8915 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8917 (defun org-remove-double-quotes (s)
8918 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8919 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8922 ;;; Following specific links
8924 (defun org-follow-timestamp-link ()
8925 (cond
8926 ((org-at-date-range-p t)
8927 (let ((org-agenda-start-on-weekday)
8928 (t1 (match-string 1))
8929 (t2 (match-string 2)))
8930 (setq t1 (time-to-days (org-time-string-to-time t1))
8931 t2 (time-to-days (org-time-string-to-time t2)))
8932 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8933 ((org-at-timestamp-p t)
8934 (org-agenda-list nil (time-to-days (org-time-string-to-time
8935 (substring (match-string 1) 0 10)))
8937 (t (error "This should not happen"))))
8940 ;;; Following file links
8941 (defvar org-wait nil)
8942 (defun org-open-file (path &optional in-emacs line search)
8943 "Open the file at PATH.
8944 First, this expands any special file name abbreviations. Then the
8945 configuration variable `org-file-apps' is checked if it contains an
8946 entry for this file type, and if yes, the corresponding command is launched.
8948 If no application is found, Emacs simply visits the file.
8950 With optional prefix argument IN-EMACS, Emacs will visit the file.
8951 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8952 and to use an external application to visit the file.
8954 Optional LINE specifies a line to go to, optional SEARCH a string to
8955 search for. If LINE or SEARCH is given, the file will always be
8956 opened in Emacs.
8957 If the file does not exist, an error is thrown."
8958 (setq in-emacs (or in-emacs line search))
8959 (let* ((file (if (equal path "")
8960 buffer-file-name
8961 (substitute-in-file-name (expand-file-name path))))
8962 (apps (append org-file-apps (org-default-apps)))
8963 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8964 (dirp (if remp nil (file-directory-p file)))
8965 (file (if (and dirp org-open-directory-means-index-dot-org)
8966 (concat (file-name-as-directory file) "index.org")
8967 file))
8968 (a-m-a-p (assq 'auto-mode apps))
8969 (dfile (downcase file))
8970 (old-buffer (current-buffer))
8971 (old-pos (point))
8972 (old-mode major-mode)
8973 ext cmd)
8974 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8975 (setq ext (match-string 1 dfile))
8976 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8977 (setq ext (match-string 1 dfile))))
8978 (cond
8979 ((member in-emacs '((16) system))
8980 (setq cmd (cdr (assoc 'system apps))))
8981 (in-emacs (setq cmd 'emacs))
8983 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8984 (and dirp (cdr (assoc 'directory apps)))
8985 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8986 'string-match)
8987 (cdr (assoc ext apps))
8988 (cdr (assoc t apps))))))
8989 (when (eq cmd 'system)
8990 (setq cmd (cdr (assoc 'system apps))))
8991 (when (eq cmd 'default)
8992 (setq cmd (cdr (assoc t apps))))
8993 (when (eq cmd 'mailcap)
8994 (require 'mailcap)
8995 (mailcap-parse-mailcaps)
8996 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8997 (command (mailcap-mime-info mime-type)))
8998 (if (stringp command)
8999 (setq cmd command)
9000 (setq cmd 'emacs))))
9001 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9002 (not (file-exists-p file))
9003 (not org-open-non-existing-files))
9004 (error "No such file: %s" file))
9005 (cond
9006 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9007 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9008 (while (string-match "['\"]%s['\"]" cmd)
9009 (setq cmd (replace-match "%s" t t cmd)))
9010 (while (string-match "%s" cmd)
9011 (setq cmd (replace-match
9012 (save-match-data
9013 (shell-quote-argument
9014 (convert-standard-filename file)))
9015 t t cmd)))
9016 (save-window-excursion
9017 (start-process-shell-command cmd nil cmd)
9018 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9020 ((or (stringp cmd)
9021 (eq cmd 'emacs))
9022 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9023 (widen)
9024 (if line (org-goto-line line)
9025 (if search (org-link-search search))))
9026 ((consp cmd)
9027 (let ((file (convert-standard-filename file)))
9028 (eval cmd)))
9029 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9030 (and (org-mode-p) (eq old-mode 'org-mode)
9031 (or (not (equal old-buffer (current-buffer)))
9032 (not (equal old-pos (point))))
9033 (org-mark-ring-push old-pos old-buffer))))
9035 (defun org-default-apps ()
9036 "Return the default applications for this operating system."
9037 (cond
9038 ((eq system-type 'darwin)
9039 org-file-apps-defaults-macosx)
9040 ((eq system-type 'windows-nt)
9041 org-file-apps-defaults-windowsnt)
9042 (t org-file-apps-defaults-gnu)))
9044 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9045 "Convert extensions to regular expressions in the cars of LIST.
9046 Also, weed out any non-string entries, because the return value is used
9047 only for regexp matching.
9048 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9049 point to the symbol `emacs', indicating that the file should
9050 be opened in Emacs."
9051 (append
9052 (delq nil
9053 (mapcar (lambda (x)
9054 (if (not (stringp (car x)))
9056 (if (string-match "\\W" (car x))
9058 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9059 list))
9060 (if add-auto-mode
9061 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9063 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9064 (defun org-file-remote-p (file)
9065 "Test whether FILE specifies a location on a remote system.
9066 Return non-nil if the location is indeed remote.
9068 For example, the filename \"/user@host:/foo\" specifies a location
9069 on the system \"/user@host:\"."
9070 (cond ((fboundp 'file-remote-p)
9071 (file-remote-p file))
9072 ((fboundp 'tramp-handle-file-remote-p)
9073 (tramp-handle-file-remote-p file))
9074 ((and (boundp 'ange-ftp-name-format)
9075 (string-match (car ange-ftp-name-format) file))
9077 (t nil)))
9080 ;;;; Refiling
9082 (defun org-get-org-file ()
9083 "Read a filename, with default directory `org-directory'."
9084 (let ((default (or org-default-notes-file remember-data-file)))
9085 (read-file-name (format "File name [%s]: " default)
9086 (file-name-as-directory org-directory)
9087 default)))
9089 (defun org-notes-order-reversed-p ()
9090 "Check if the current file should receive notes in reversed order."
9091 (cond
9092 ((not org-reverse-note-order) nil)
9093 ((eq t org-reverse-note-order) t)
9094 ((not (listp org-reverse-note-order)) nil)
9095 (t (catch 'exit
9096 (let ((all org-reverse-note-order)
9097 entry)
9098 (while (setq entry (pop all))
9099 (if (string-match (car entry) buffer-file-name)
9100 (throw 'exit (cdr entry))))
9101 nil)))))
9103 (defvar org-refile-target-table nil
9104 "The list of refile targets, created by `org-refile'.")
9106 (defvar org-agenda-new-buffers nil
9107 "Buffers created to visit agenda files.")
9109 (defun org-get-refile-targets (&optional default-buffer)
9110 "Produce a table with refile targets."
9111 (let ((case-fold-search nil)
9112 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9113 (entries (or org-refile-targets '((nil . (:level . 1)))))
9114 targets txt re files f desc descre fast-path-p level pos0)
9115 (message "Getting targets...")
9116 (with-current-buffer (or default-buffer (current-buffer))
9117 (while (setq entry (pop entries))
9118 (setq files (car entry) desc (cdr entry))
9119 (setq fast-path-p nil)
9120 (cond
9121 ((null files) (setq files (list (current-buffer))))
9122 ((eq files 'org-agenda-files)
9123 (setq files (org-agenda-files 'unrestricted)))
9124 ((and (symbolp files) (fboundp files))
9125 (setq files (funcall files)))
9126 ((and (symbolp files) (boundp files))
9127 (setq files (symbol-value files))))
9128 (if (stringp files) (setq files (list files)))
9129 (cond
9130 ((eq (car desc) :tag)
9131 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9132 ((eq (car desc) :todo)
9133 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9134 ((eq (car desc) :regexp)
9135 (setq descre (cdr desc)))
9136 ((eq (car desc) :level)
9137 (setq descre (concat "^\\*\\{" (number-to-string
9138 (if org-odd-levels-only
9139 (1- (* 2 (cdr desc)))
9140 (cdr desc)))
9141 "\\}[ \t]")))
9142 ((eq (car desc) :maxlevel)
9143 (setq fast-path-p t)
9144 (setq descre (concat "^\\*\\{1," (number-to-string
9145 (if org-odd-levels-only
9146 (1- (* 2 (cdr desc)))
9147 (cdr desc)))
9148 "\\}[ \t]")))
9149 (t (error "Bad refiling target description %s" desc)))
9150 (while (setq f (pop files))
9151 (with-current-buffer
9152 (if (bufferp f) f (org-get-agenda-file-buffer f))
9153 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9154 (setq f (and f (expand-file-name f)))
9155 (if (eq org-refile-use-outline-path 'file)
9156 (push (list (file-name-nondirectory f) f nil nil) targets))
9157 (save-excursion
9158 (save-restriction
9159 (widen)
9160 (goto-char (point-min))
9161 (while (re-search-forward descre nil t)
9162 (goto-char (setq pos0 (point-at-bol)))
9163 (catch 'next
9164 (when org-refile-target-verify-function
9165 (save-match-data
9166 (or (funcall org-refile-target-verify-function)
9167 (throw 'next t))))
9168 (when (looking-at org-complex-heading-regexp)
9169 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9170 txt (org-link-display-format (match-string 4))
9171 re (concat "^" (regexp-quote
9172 (buffer-substring (match-beginning 1)
9173 (match-end 4)))))
9174 (if (match-end 5) (setq re (concat re "[ \t]+"
9175 (regexp-quote
9176 (match-string 5)))))
9177 (setq re (concat re "[ \t]*$"))
9178 (when org-refile-use-outline-path
9179 (setq txt (mapconcat 'org-protect-slash
9180 (append
9181 (if (eq org-refile-use-outline-path 'file)
9182 (list (file-name-nondirectory
9183 (buffer-file-name (buffer-base-buffer))))
9184 (if (eq org-refile-use-outline-path 'full-file-path)
9185 (list (buffer-file-name (buffer-base-buffer)))))
9186 (org-get-outline-path fast-path-p level txt)
9187 (list txt))
9188 "/")))
9189 (push (list txt f re (point)) targets)))
9190 (when (= (point) pos0)
9191 ;; verification function has not moved point
9192 (goto-char (point-at-eol))))))))))
9193 (message "Getting targets...done")
9194 (nreverse targets)))
9196 (defun org-protect-slash (s)
9197 (while (string-match "/" s)
9198 (setq s (replace-match "\\" t t s)))
9201 (defvar org-olpa (make-vector 20 nil))
9203 (defun org-get-outline-path (&optional fastp level heading)
9204 "Return the outline path to the current entry, as a list.
9205 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9206 routine which makes outline path derivations for an entire file,
9207 avoiding backtracing."
9208 (if fastp
9209 (progn
9210 (if (> level 19)
9211 (error "Outline path failure, more than 19 levels."))
9212 (loop for i from level upto 19 do
9213 (aset org-olpa i nil))
9214 (prog1
9215 (delq nil (append org-olpa nil))
9216 (aset org-olpa level heading)))
9217 (let (rtn case-fold-search)
9218 (save-excursion
9219 (save-restriction
9220 (widen)
9221 (while (org-up-heading-safe)
9222 (when (looking-at org-complex-heading-regexp)
9223 (push (org-match-string-no-properties 4) rtn)))
9224 rtn)))))
9226 (defun org-format-outline-path (path &optional width prefix)
9227 "Format the outlie path PATH for display.
9228 Width is the maximum number of characters that is available.
9229 Prefix is a prefix to be included in the returned string,
9230 such as the file name."
9231 (setq width (or width 79))
9232 (if prefix (setq width (- width (length prefix))))
9233 (if (not path)
9234 (or prefix "")
9235 (let* ((nsteps (length path))
9236 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9237 (maxwidth (if (<= total-width width)
9238 10000 ;; everything fits
9239 ;; we need to shorten the level headings
9240 (/ (- width nsteps) nsteps)))
9241 (org-odd-levels-only nil)
9242 (n 0)
9243 (total (1+ (length prefix))))
9244 (setq maxwidth (max maxwidth 10))
9245 (concat prefix
9246 (mapconcat
9247 (lambda (h)
9248 (setq n (1+ n))
9249 (if (and (= n nsteps) (< maxwidth 10000))
9250 (setq maxwidth (- total-width total)))
9251 (if (< (length h) maxwidth)
9252 (progn (setq total (+ total (length h) 1)) h)
9253 (setq h (substring h 0 (- maxwidth 2))
9254 total (+ total maxwidth 1))
9255 (if (string-match "[ \t]+\\'" h)
9256 (setq h (substring h 0 (match-beginning 0))))
9257 (setq h (concat h "..")))
9258 (org-add-props h nil 'face
9259 (nth (% (1- n) org-n-level-faces)
9260 org-level-faces))
9262 path "/")))))
9264 (defun org-display-outline-path (&optional file current)
9265 "Display the current outline path in the echo area."
9266 (interactive "P")
9267 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9268 (case-fold-search nil)
9269 (path (and (org-mode-p) (org-get-outline-path))))
9270 (if current (setq path (append path
9271 (save-excursion
9272 (org-back-to-heading t)
9273 (if (looking-at org-complex-heading-regexp)
9274 (list (match-string 4)))))))
9275 (message "%s"
9276 (org-format-outline-path
9277 path
9278 (1- (frame-width))
9279 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9281 (defvar org-refile-history nil
9282 "History for refiling operations.")
9284 (defvar org-after-refile-insert-hook nil
9285 "Hook run after `org-refile' has inserted its stuff at the new location.
9286 Note that this is still *before* the stuff will be removed from
9287 the *old* location.")
9289 (defun org-refile (&optional goto default-buffer rfloc)
9290 "Move the entry at point to another heading.
9291 The list of target headings is compiled using the information in
9292 `org-refile-targets', which see. This list is created before each use
9293 and will therefore always be up-to-date.
9295 At the target location, the entry is filed as a subitem of the target heading.
9296 Depending on `org-reverse-note-order', the new subitem will either be the
9297 first or the last subitem.
9299 If there is an active region, all entries in that region will be moved.
9300 However, the region must fulfil the requirement that the first heading
9301 is the first one sets the top-level of the moved text - at most siblings
9302 below it are allowed.
9304 With prefix arg GOTO, the command will only visit the target location,
9305 not actually move anything.
9306 With a double prefix `C-u C-u', go to the location where the last refiling
9307 operation has put the subtree.
9308 With a prefix argument of `2', refile to the running clock.
9310 RFLOC can be a refile location obtained in a different way.
9312 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9313 (interactive "P")
9314 (let* ((cbuf (current-buffer))
9315 (regionp (org-region-active-p))
9316 (region-start (and regionp (region-beginning)))
9317 (region-end (and regionp (region-end)))
9318 (region-length (and regionp (- region-end region-start)))
9319 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9320 pos it nbuf file re level reversed)
9321 (setq last-command nil)
9322 (when regionp
9323 (goto-char region-start)
9324 (or (bolp) (goto-char (point-at-bol)))
9325 (setq region-start (point))
9326 (unless (org-kill-is-subtree-p
9327 (buffer-substring region-start region-end))
9328 (error "The region is not a (sequence of) subtree(s)")))
9329 (if (equal goto '(16))
9330 (org-refile-goto-last-stored)
9331 (when (or
9332 (and (equal goto 2)
9333 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9334 (prog1
9335 (setq it (list (or org-clock-heading "running clock")
9336 (buffer-file-name
9337 (marker-buffer org-clock-hd-marker))
9339 (marker-position org-clock-hd-marker)))
9340 (setq goto nil)))
9341 (setq it (or rfloc
9342 (save-excursion
9343 (org-refile-get-location
9344 (if goto "Goto: " "Refile to: ") default-buffer
9345 org-refile-allow-creating-parent-nodes)))))
9346 (setq file (nth 1 it)
9347 re (nth 2 it)
9348 pos (nth 3 it))
9349 (if (and (not goto)
9351 (equal (buffer-file-name) file)
9352 (if regionp
9353 (and (>= pos region-start)
9354 (<= pos region-end))
9355 (and (>= pos (point))
9356 (< pos (save-excursion
9357 (org-end-of-subtree t t))))))
9358 (error "Cannot refile to position inside the tree or region"))
9360 (setq nbuf (or (find-buffer-visiting file)
9361 (find-file-noselect file)))
9362 (if goto
9363 (progn
9364 (switch-to-buffer nbuf)
9365 (goto-char pos)
9366 (org-show-context 'org-goto))
9367 (if regionp
9368 (progn
9369 (org-kill-new (buffer-substring region-start region-end))
9370 (org-save-markers-in-region region-start region-end))
9371 (org-copy-subtree 1 nil t))
9372 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9373 (find-file-noselect file)))
9374 (setq reversed (org-notes-order-reversed-p))
9375 (save-excursion
9376 (save-restriction
9377 (widen)
9378 (if pos
9379 (progn
9380 (goto-char pos)
9381 (looking-at outline-regexp)
9382 (setq level (org-get-valid-level (funcall outline-level) 1))
9383 (goto-char
9384 (if reversed
9385 (or (outline-next-heading) (point-max))
9386 (or (save-excursion (org-get-next-sibling))
9387 (org-end-of-subtree t t)
9388 (point-max)))))
9389 (setq level 1)
9390 (if (not reversed)
9391 (goto-char (point-max))
9392 (goto-char (point-min))
9393 (or (outline-next-heading) (goto-char (point-max)))))
9394 (if (not (bolp)) (newline))
9395 (bookmark-set "org-refile-last-stored")
9396 (org-paste-subtree level)
9397 (if (fboundp 'deactivate-mark) (deactivate-mark))
9398 (run-hooks 'org-after-refile-insert-hook))))
9399 (if regionp
9400 (delete-region (point) (+ (point) region-length))
9401 (org-cut-subtree))
9402 (when (featurep 'org-inlinetask)
9403 (org-inlinetask-remove-END-maybe))
9404 (setq org-markers-to-move nil)
9405 (message "Refiled to \"%s\"" (car it))))))
9406 (org-reveal))
9408 (defun org-refile-goto-last-stored ()
9409 "Go to the location where the last refile was stored."
9410 (interactive)
9411 (bookmark-jump "org-refile-last-stored")
9412 (message "This is the location of the last refile"))
9414 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9415 "Prompt the user for a refile location, using PROMPT."
9416 (let ((org-refile-targets org-refile-targets)
9417 (org-refile-use-outline-path org-refile-use-outline-path))
9418 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9419 (unless org-refile-target-table
9420 (error "No refile targets"))
9421 (let* ((cbuf (current-buffer))
9422 (partial-completion-mode nil)
9423 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9424 (cfunc (if (and org-refile-use-outline-path
9425 org-outline-path-complete-in-steps)
9426 'org-olpath-completing-read
9427 'org-icompleting-read))
9428 (extra (if org-refile-use-outline-path "/" ""))
9429 (filename (and cfn (expand-file-name cfn)))
9430 (tbl (mapcar
9431 (lambda (x)
9432 (if (and (not (member org-refile-use-outline-path
9433 '(file full-file-path)))
9434 (not (equal filename (nth 1 x))))
9435 (cons (concat (car x) extra " ("
9436 (file-name-nondirectory (nth 1 x)) ")")
9437 (cdr x))
9438 (cons (concat (car x) extra) (cdr x))))
9439 org-refile-target-table))
9440 (completion-ignore-case t)
9441 pa answ parent-target child parent old-hist)
9442 (setq old-hist org-refile-history)
9443 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9444 nil 'org-refile-history))
9445 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9446 (if pa
9447 (progn
9448 (when (or (not org-refile-history)
9449 (not (eq old-hist org-refile-history))
9450 (not (equal (car pa) (car org-refile-history))))
9451 (setq org-refile-history
9452 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9453 org-refile-history
9454 (cdr org-refile-history))))
9455 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9456 (pop org-refile-history)))
9458 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9459 (setq parent (match-string 1 answ)
9460 child (match-string 2 answ))
9461 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9462 (when (and parent-target
9463 (or (eq new-nodes t)
9464 (and (eq new-nodes 'confirm)
9465 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9466 (org-refile-new-child parent-target child))))))
9468 (defun org-refile-new-child (parent-target child)
9469 "Use refile target PARENT-TARGET to add new CHILD below it."
9470 (unless parent-target
9471 (error "Cannot find parent for new node"))
9472 (let ((file (nth 1 parent-target))
9473 (pos (nth 3 parent-target))
9474 level)
9475 (with-current-buffer (or (find-buffer-visiting file)
9476 (find-file-noselect file))
9477 (save-excursion
9478 (save-restriction
9479 (widen)
9480 (if pos
9481 (goto-char pos)
9482 (goto-char (point-max))
9483 (if (not (bolp)) (newline)))
9484 (when (looking-at outline-regexp)
9485 (setq level (funcall outline-level))
9486 (org-end-of-subtree t t))
9487 (org-back-over-empty-lines)
9488 (insert "\n" (make-string
9489 (if pos (org-get-valid-level level 1) 1) ?*)
9490 " " child "\n")
9491 (beginning-of-line 0)
9492 (list (concat (car parent-target) "/" child) file "" (point)))))))
9494 (defun org-olpath-completing-read (prompt collection &rest args)
9495 "Read an outline path like a file name."
9496 (let ((thetable collection)
9497 (org-completion-use-ido nil) ; does not work with ido.
9498 (org-completion-use-iswitchb nil)) ; or iswitchb
9499 (apply
9500 'org-icompleting-read prompt
9501 (lambda (string predicate &optional flag)
9502 (let (rtn r f (l (length string)))
9503 (cond
9504 ((eq flag nil)
9505 ;; try completion
9506 (try-completion string thetable))
9507 ((eq flag t)
9508 ;; all-completions
9509 (setq rtn (all-completions string thetable predicate))
9510 (mapcar
9511 (lambda (x)
9512 (setq r (substring x l))
9513 (if (string-match " ([^)]*)$" x)
9514 (setq f (match-string 0 x))
9515 (setq f ""))
9516 (if (string-match "/" r)
9517 (concat string (substring r 0 (match-end 0)) f)
9519 rtn))
9520 ((eq flag 'lambda)
9521 ;; exact match?
9522 (assoc string thetable)))
9524 args)))
9526 ;;;; Dynamic blocks
9528 (defun org-find-dblock (name)
9529 "Find the first dynamic block with name NAME in the buffer.
9530 If not found, stay at current position and return nil."
9531 (let (pos)
9532 (save-excursion
9533 (goto-char (point-min))
9534 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9535 nil t)
9536 (match-beginning 0))))
9537 (if pos (goto-char pos))
9538 pos))
9540 (defconst org-dblock-start-re
9541 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9542 "Matches the start line of a dynamic block, with parameters.")
9544 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9545 "Matches the end of a dynamic block.")
9547 (defun org-create-dblock (plist)
9548 "Create a dynamic block section, with parameters taken from PLIST.
9549 PLIST must contain a :name entry which is used as name of the block."
9550 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9551 (end-of-line 1)
9552 (newline))
9553 (let ((col (current-column))
9554 (name (plist-get plist :name)))
9555 (insert "#+BEGIN: " name)
9556 (while plist
9557 (if (eq (car plist) :name)
9558 (setq plist (cddr plist))
9559 (insert " " (prin1-to-string (pop plist)))))
9560 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9561 (beginning-of-line -2)))
9563 (defun org-prepare-dblock ()
9564 "Prepare dynamic block for refresh.
9565 This empties the block, puts the cursor at the insert position and returns
9566 the property list including an extra property :name with the block name."
9567 (unless (looking-at org-dblock-start-re)
9568 (error "Not at a dynamic block"))
9569 (let* ((begdel (1+ (match-end 0)))
9570 (name (org-no-properties (match-string 1)))
9571 (params (append (list :name name)
9572 (read (concat "(" (match-string 3) ")")))))
9573 (save-excursion
9574 (beginning-of-line 1)
9575 (skip-chars-forward " \t")
9576 (setq params (plist-put params :indentation-column (current-column))))
9577 (unless (re-search-forward org-dblock-end-re nil t)
9578 (error "Dynamic block not terminated"))
9579 (setq params
9580 (append params
9581 (list :content (buffer-substring
9582 begdel (match-beginning 0)))))
9583 (delete-region begdel (match-beginning 0))
9584 (goto-char begdel)
9585 (open-line 1)
9586 params))
9588 (defun org-map-dblocks (&optional command)
9589 "Apply COMMAND to all dynamic blocks in the current buffer.
9590 If COMMAND is not given, use `org-update-dblock'."
9591 (let ((cmd (or command 'org-update-dblock))
9592 pos)
9593 (save-excursion
9594 (goto-char (point-min))
9595 (while (re-search-forward org-dblock-start-re nil t)
9596 (goto-char (setq pos (match-beginning 0)))
9597 (condition-case nil
9598 (funcall cmd)
9599 (error (message "Error during update of dynamic block")))
9600 (goto-char pos)
9601 (unless (re-search-forward org-dblock-end-re nil t)
9602 (error "Dynamic block not terminated"))))))
9604 (defun org-dblock-update (&optional arg)
9605 "User command for updating dynamic blocks.
9606 Update the dynamic block at point. With prefix ARG, update all dynamic
9607 blocks in the buffer."
9608 (interactive "P")
9609 (if arg
9610 (org-update-all-dblocks)
9611 (or (looking-at org-dblock-start-re)
9612 (org-beginning-of-dblock))
9613 (org-update-dblock)))
9615 (defun org-update-dblock ()
9616 "Update the dynamic block at point
9617 This means to empty the block, parse for parameters and then call
9618 the correct writing function."
9619 (save-window-excursion
9620 (let* ((pos (point))
9621 (line (org-current-line))
9622 (params (org-prepare-dblock))
9623 (name (plist-get params :name))
9624 (indent (plist-get params :indentation-column))
9625 (cmd (intern (concat "org-dblock-write:" name))))
9626 (message "Updating dynamic block `%s' at line %d..." name line)
9627 (funcall cmd params)
9628 (message "Updating dynamic block `%s' at line %d...done" name line)
9629 (goto-char pos)
9630 (when (and indent (> indent 0))
9631 (setq indent (make-string indent ?\ ))
9632 (save-excursion
9633 (org-beginning-of-dblock)
9634 (forward-line 1)
9635 (while (not (looking-at org-dblock-end-re))
9636 (insert indent)
9637 (beginning-of-line 2))
9638 (when (looking-at org-dblock-end-re)
9639 (and (looking-at "[ \t]+")
9640 (replace-match ""))
9641 (insert indent)))))))
9643 (defun org-beginning-of-dblock ()
9644 "Find the beginning of the dynamic block at point.
9645 Error if there is no such block at point."
9646 (let ((pos (point))
9647 beg)
9648 (end-of-line 1)
9649 (if (and (re-search-backward org-dblock-start-re nil t)
9650 (setq beg (match-beginning 0))
9651 (re-search-forward org-dblock-end-re nil t)
9652 (> (match-end 0) pos))
9653 (goto-char beg)
9654 (goto-char pos)
9655 (error "Not in a dynamic block"))))
9657 (defun org-update-all-dblocks ()
9658 "Update all dynamic blocks in the buffer.
9659 This function can be used in a hook."
9660 (when (org-mode-p)
9661 (org-map-dblocks 'org-update-dblock)))
9664 ;;;; Completion
9666 (defconst org-additional-option-like-keywords
9667 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9668 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9669 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9670 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9671 "BEGIN:" "END:"
9672 "ORGTBL" "TBLFM:" "TBLNAME:"
9673 "BEGIN_EXAMPLE" "END_EXAMPLE"
9674 "BEGIN_QUOTE" "END_QUOTE"
9675 "BEGIN_VERSE" "END_VERSE"
9676 "BEGIN_CENTER" "END_CENTER"
9677 "BEGIN_SRC" "END_SRC"
9678 "CATEGORY" "COLUMNS"
9679 "CAPTION" "LABEL"
9680 "SETUPFILE"
9681 "BIND"
9682 "MACRO"))
9684 (defcustom org-structure-template-alist
9686 ("s" "#+begin_src ?\n\n#+end_src"
9687 "<src lang=\"?\">\n\n</src>")
9688 ("e" "#+begin_example\n?\n#+end_example"
9689 "<example>\n?\n</example>")
9690 ("q" "#+begin_quote\n?\n#+end_quote"
9691 "<quote>\n?\n</quote>")
9692 ("v" "#+begin_verse\n?\n#+end_verse"
9693 "<verse>\n?\n/verse>")
9694 ("c" "#+begin_center\n?\n#+end_center"
9695 "<center>\n?\n/center>")
9696 ("l" "#+begin_latex\n?\n#+end_latex"
9697 "<literal style=\"latex\">\n?\n</literal>")
9698 ("L" "#+latex: "
9699 "<literal style=\"latex\">?</literal>")
9700 ("h" "#+begin_html\n?\n#+end_html"
9701 "<literal style=\"html\">\n?\n</literal>")
9702 ("H" "#+html: "
9703 "<literal style=\"html\">?</literal>")
9704 ("a" "#+begin_ascii\n?\n#+end_ascii")
9705 ("A" "#+ascii: ")
9706 ("i" "#+include %file ?"
9707 "<include file=%file markup=\"?\">")
9709 "Structure completion elements.
9710 This is a list of abbreviation keys and values. The value gets inserted
9711 it you type @samp{.} followed by the key and then the completion key,
9712 usually `M-TAB'. %file will be replaced by a file name after prompting
9713 for the file using completion.
9714 There are two templates for each key, the first uses the original Org syntax,
9715 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9716 the default when the /org-mtags.el/ module has been loaded. See also the
9717 variable `org-mtags-prefer-muse-templates'.
9718 This is an experimental feature, it is undecided if it is going to stay in."
9719 :group 'org-completion
9720 :type '(repeat
9721 (string :tag "Key")
9722 (string :tag "Template")
9723 (string :tag "Muse Template")))
9725 (defun org-try-structure-completion ()
9726 "Try to complete a structure template before point.
9727 This looks for strings like \"<e\" on an otherwise empty line and
9728 expands them."
9729 (let ((l (buffer-substring (point-at-bol) (point)))
9731 (when (and (looking-at "[ \t]*$")
9732 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9733 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9734 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9735 (match-beginning 1)) a)
9736 t)))
9738 (defun org-complete-expand-structure-template (start cell)
9739 "Expand a structure template."
9740 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9741 (rpl (nth (if musep 2 1) cell))
9742 (ind ""))
9743 (delete-region start (point))
9744 (when (string-match "\\`#\\+" rpl)
9745 (cond
9746 ((bolp))
9747 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9748 (setq ind (buffer-substring (point-at-bol) (point))))
9749 (t (newline))))
9750 (setq start (point))
9751 (if (string-match "%file" rpl)
9752 (setq rpl (replace-match
9753 (concat
9754 "\""
9755 (save-match-data
9756 (abbreviate-file-name (read-file-name "Include file: ")))
9757 "\"")
9758 t t rpl)))
9759 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9760 (concat "\n" ind)))
9761 (insert rpl)
9762 (if (re-search-backward "\\?" start t) (delete-char 1))))
9765 (defun org-complete (&optional arg)
9766 "Perform completion on word at point.
9767 At the beginning of a headline, this completes TODO keywords as given in
9768 `org-todo-keywords'.
9769 If the current word is preceded by a backslash, completes the TeX symbols
9770 that are supported for HTML support.
9771 If the current word is preceded by \"#+\", completes special words for
9772 setting file options.
9773 In the line after \"#+STARTUP:, complete valid keywords.\"
9774 At all other locations, this simply calls the value of
9775 `org-completion-fallback-command'."
9776 (interactive "P")
9777 (org-without-partial-completion
9778 (catch 'exit
9779 (let* ((a nil)
9780 (end (point))
9781 (beg1 (save-excursion
9782 (skip-chars-backward (org-re "[:alnum:]_@"))
9783 (point)))
9784 (beg (save-excursion
9785 (skip-chars-backward "a-zA-Z0-9_:$")
9786 (point)))
9787 (confirm (lambda (x) (stringp (car x))))
9788 (searchhead (equal (char-before beg) ?*))
9789 (struct
9790 (when (and (member (char-before beg1) '(?. ?<))
9791 (setq a (assoc (buffer-substring beg1 (point))
9792 org-structure-template-alist)))
9793 (org-complete-expand-structure-template (1- beg1) a)
9794 (throw 'exit t)))
9795 (tag (and (equal (char-before beg1) ?:)
9796 (equal (char-after (point-at-bol)) ?*)))
9797 (prop (and (equal (char-before beg1) ?:)
9798 (not (equal (char-after (point-at-bol)) ?*))))
9799 (texp (equal (char-before beg) ?\\))
9800 (link (equal (char-before beg) ?\[))
9801 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9802 beg)
9803 "#+"))
9804 (startup (string-match "^#\\+STARTUP:.*"
9805 (buffer-substring (point-at-bol) (point))))
9806 (completion-ignore-case opt)
9807 (type nil)
9808 (tbl nil)
9809 (table (cond
9810 (opt
9811 (setq type :opt)
9812 (require 'org-exp)
9813 (append
9814 (delq nil
9815 (mapcar
9816 (lambda (x)
9817 (if (string-match
9818 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9819 (cons (match-string 2 x)
9820 (match-string 1 x))))
9821 (org-split-string (org-get-current-options) "\n")))
9822 (mapcar 'list org-additional-option-like-keywords)))
9823 (startup
9824 (setq type :startup)
9825 org-startup-options)
9826 (link (append org-link-abbrev-alist-local
9827 org-link-abbrev-alist))
9828 (texp
9829 (setq type :tex)
9830 org-html-entities)
9831 ((string-match "\\`\\*+[ \t]+\\'"
9832 (buffer-substring (point-at-bol) beg))
9833 (setq type :todo)
9834 (mapcar 'list org-todo-keywords-1))
9835 (searchhead
9836 (setq type :searchhead)
9837 (save-excursion
9838 (goto-char (point-min))
9839 (while (re-search-forward org-todo-line-regexp nil t)
9840 (push (list
9841 (org-make-org-heading-search-string
9842 (match-string 3) t))
9843 tbl)))
9844 tbl)
9845 (tag (setq type :tag beg beg1)
9846 (or org-tag-alist (org-get-buffer-tags)))
9847 (prop (setq type :prop beg beg1)
9848 (mapcar 'list (org-buffer-property-keys nil t t)))
9849 (t (progn
9850 (call-interactively org-completion-fallback-command)
9851 (throw 'exit nil)))))
9852 (pattern (buffer-substring-no-properties beg end))
9853 (completion (try-completion pattern table confirm)))
9854 (cond ((eq completion t)
9855 (if (not (assoc (upcase pattern) table))
9856 (message "Already complete")
9857 (if (and (equal type :opt)
9858 (not (member (car (assoc (upcase pattern) table))
9859 org-additional-option-like-keywords)))
9860 (insert (substring (cdr (assoc (upcase pattern) table))
9861 (length pattern)))
9862 (if (memq type '(:tag :prop)) (insert ":")))))
9863 ((null completion)
9864 (message "Can't find completion for \"%s\"" pattern)
9865 (ding))
9866 ((not (string= pattern completion))
9867 (delete-region beg end)
9868 (if (string-match " +$" completion)
9869 (setq completion (replace-match "" t t completion)))
9870 (insert completion)
9871 (if (get-buffer-window "*Completions*")
9872 (delete-window (get-buffer-window "*Completions*")))
9873 (if (assoc completion table)
9874 (if (eq type :todo) (insert " ")
9875 (if (memq type '(:tag :prop)) (insert ":"))))
9876 (if (and (equal type :opt) (assoc completion table))
9877 (message "%s" (substitute-command-keys
9878 "Press \\[org-complete] again to insert example settings"))))
9880 (message "Making completion list...")
9881 (let ((list (sort (all-completions pattern table confirm)
9882 'string<)))
9883 (with-output-to-temp-buffer "*Completions*"
9884 (condition-case nil
9885 ;; Protection needed for XEmacs and emacs 21
9886 (display-completion-list list pattern)
9887 (error (display-completion-list list)))))
9888 (message "Making completion list...%s" "done")))))))
9890 ;;;; TODO, DEADLINE, Comments
9892 (defun org-toggle-comment ()
9893 "Change the COMMENT state of an entry."
9894 (interactive)
9895 (save-excursion
9896 (org-back-to-heading)
9897 (let (case-fold-search)
9898 (if (looking-at (concat outline-regexp
9899 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9900 (replace-match "" t t nil 1)
9901 (if (looking-at outline-regexp)
9902 (progn
9903 (goto-char (match-end 0))
9904 (insert org-comment-string " ")))))))
9906 (defvar org-last-todo-state-is-todo nil
9907 "This is non-nil when the last TODO state change led to a TODO state.
9908 If the last change removed the TODO tag or switched to DONE, then
9909 this is nil.")
9911 (defvar org-setting-tags nil) ; dynamically skipped
9913 (defun org-parse-local-options (string var)
9914 "Parse STRING for startup setting relevant for variable VAR."
9915 (let ((rtn (symbol-value var))
9916 e opts)
9917 (save-match-data
9918 (if (or (not string) (not (string-match "\\S-" string)))
9920 (setq opts (delq nil (mapcar (lambda (x)
9921 (setq e (assoc x org-startup-options))
9922 (if (eq (nth 1 e) var) e nil))
9923 (org-split-string string "[ \t]+"))))
9924 (if (not opts)
9926 (setq rtn nil)
9927 (while (setq e (pop opts))
9928 (if (not (nth 3 e))
9929 (setq rtn (nth 2 e))
9930 (if (not (listp rtn)) (setq rtn nil))
9931 (push (nth 2 e) rtn)))
9932 rtn)))))
9934 (defvar org-todo-setup-filter-hook nil
9935 "Hook for functions that pre-filter todo specs.
9937 Each function takes a todo spec and returns either `nil' or the spec
9938 transformed into canonical form." )
9940 (defvar org-todo-get-default-hook nil
9941 "Hook for functions that get a default item for todo.
9943 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9944 `nil' or a string to be used for the todo mark." )
9946 (defvar org-agenda-headline-snapshot-before-repeat)
9948 (defun org-todo (&optional arg)
9949 "Change the TODO state of an item.
9950 The state of an item is given by a keyword at the start of the heading,
9951 like
9952 *** TODO Write paper
9953 *** DONE Call mom
9955 The different keywords are specified in the variable `org-todo-keywords'.
9956 By default the available states are \"TODO\" and \"DONE\".
9957 So for this example: when the item starts with TODO, it is changed to DONE.
9958 When it starts with DONE, the DONE is removed. And when neither TODO nor
9959 DONE are present, add TODO at the beginning of the heading.
9961 With C-u prefix arg, use completion to determine the new state.
9962 With numeric prefix arg, switch to that state.
9963 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9964 With a triple C-u prefix, circumvent any state blocking.
9966 For calling through lisp, arg is also interpreted in the following way:
9967 'none -> empty state
9968 \"\"(empty string) -> switch to empty state
9969 'done -> switch to DONE
9970 'nextset -> switch to the next set of keywords
9971 'previousset -> switch to the previous set of keywords
9972 \"WAITING\" -> switch to the specified keyword, but only if it
9973 really is a member of `org-todo-keywords'."
9974 (interactive "P")
9975 (if (equal arg '(16)) (setq arg 'nextset))
9976 (let ((org-blocker-hook org-blocker-hook)
9977 (case-fold-search nil))
9978 (when (equal arg '(64))
9979 (setq arg nil org-blocker-hook nil))
9980 (when (and org-blocker-hook
9981 (or org-inhibit-blocking
9982 (org-entry-get nil "NOBLOCKING")))
9983 (setq org-blocker-hook nil))
9984 (save-excursion
9985 (catch 'exit
9986 (org-back-to-heading t)
9987 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9988 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9989 (looking-at " *"))
9990 (let* ((match-data (match-data))
9991 (startpos (point-at-bol))
9992 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9993 (org-log-done org-log-done)
9994 (org-log-repeat org-log-repeat)
9995 (org-todo-log-states org-todo-log-states)
9996 (this (match-string 1))
9997 (hl-pos (match-beginning 0))
9998 (head (org-get-todo-sequence-head this))
9999 (ass (assoc head org-todo-kwd-alist))
10000 (interpret (nth 1 ass))
10001 (done-word (nth 3 ass))
10002 (final-done-word (nth 4 ass))
10003 (last-state (or this ""))
10004 (completion-ignore-case t)
10005 (member (member this org-todo-keywords-1))
10006 (tail (cdr member))
10007 (state (cond
10008 ((and org-todo-key-trigger
10009 (or (and (equal arg '(4))
10010 (eq org-use-fast-todo-selection 'prefix))
10011 (and (not arg) org-use-fast-todo-selection
10012 (not (eq org-use-fast-todo-selection
10013 'prefix)))))
10014 ;; Use fast selection
10015 (org-fast-todo-selection))
10016 ((and (equal arg '(4))
10017 (or (not org-use-fast-todo-selection)
10018 (not org-todo-key-trigger)))
10019 ;; Read a state with completion
10020 (org-icompleting-read
10021 "State: " (mapcar (lambda(x) (list x))
10022 org-todo-keywords-1)
10023 nil t))
10024 ((eq arg 'right)
10025 (if this
10026 (if tail (car tail) nil)
10027 (car org-todo-keywords-1)))
10028 ((eq arg 'left)
10029 (if (equal member org-todo-keywords-1)
10031 (if this
10032 (nth (- (length org-todo-keywords-1)
10033 (length tail) 2)
10034 org-todo-keywords-1)
10035 (org-last org-todo-keywords-1))))
10036 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10037 (setq arg nil))) ; hack to fall back to cycling
10038 (arg
10039 ;; user or caller requests a specific state
10040 (cond
10041 ((equal arg "") nil)
10042 ((eq arg 'none) nil)
10043 ((eq arg 'done) (or done-word (car org-done-keywords)))
10044 ((eq arg 'nextset)
10045 (or (car (cdr (member head org-todo-heads)))
10046 (car org-todo-heads)))
10047 ((eq arg 'previousset)
10048 (let ((org-todo-heads (reverse org-todo-heads)))
10049 (or (car (cdr (member head org-todo-heads)))
10050 (car org-todo-heads))))
10051 ((car (member arg org-todo-keywords-1)))
10052 ((stringp arg)
10053 (error "State `%s' not valid in this file" arg))
10054 ((nth (1- (prefix-numeric-value arg))
10055 org-todo-keywords-1))))
10056 ((null member) (or head (car org-todo-keywords-1)))
10057 ((equal this final-done-word) nil) ;; -> make empty
10058 ((null tail) nil) ;; -> first entry
10059 ((memq interpret '(type priority))
10060 (if (eq this-command last-command)
10061 (car tail)
10062 (if (> (length tail) 0)
10063 (or done-word (car org-done-keywords))
10064 nil)))
10066 (car tail))))
10067 (state (or
10068 (run-hook-with-args-until-success
10069 'org-todo-get-default-hook state last-state)
10070 state))
10071 (next (if state (concat " " state " ") " "))
10072 (change-plist (list :type 'todo-state-change :from this :to state
10073 :position startpos))
10074 dolog now-done-p)
10075 (when org-blocker-hook
10076 (setq org-last-todo-state-is-todo
10077 (not (member this org-done-keywords)))
10078 (unless (save-excursion
10079 (save-match-data
10080 (run-hook-with-args-until-failure
10081 'org-blocker-hook change-plist)))
10082 (if (interactive-p)
10083 (error "TODO state change from %s to %s blocked" this state)
10084 ;; fail silently
10085 (message "TODO state change from %s to %s blocked" this state)
10086 (throw 'exit nil))))
10087 (store-match-data match-data)
10088 (replace-match next t t)
10089 (unless (pos-visible-in-window-p hl-pos)
10090 (message "TODO state changed to %s" (org-trim next)))
10091 (unless head
10092 (setq head (org-get-todo-sequence-head state)
10093 ass (assoc head org-todo-kwd-alist)
10094 interpret (nth 1 ass)
10095 done-word (nth 3 ass)
10096 final-done-word (nth 4 ass)))
10097 (when (memq arg '(nextset previousset))
10098 (message "Keyword-Set %d/%d: %s"
10099 (- (length org-todo-sets) -1
10100 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10101 (length org-todo-sets)
10102 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10103 (setq org-last-todo-state-is-todo
10104 (not (member state org-done-keywords)))
10105 (setq now-done-p (and (member state org-done-keywords)
10106 (not (member this org-done-keywords))))
10107 (and logging (org-local-logging logging))
10108 (when (and (or org-todo-log-states org-log-done)
10109 (not (eq org-inhibit-logging t))
10110 (not (memq arg '(nextset previousset))))
10111 ;; we need to look at recording a time and note
10112 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10113 (nth 2 (assoc this org-todo-log-states))))
10114 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10115 (setq dolog 'time))
10116 (when (and state
10117 (member state org-not-done-keywords)
10118 (not (member this org-not-done-keywords)))
10119 ;; This is now a todo state and was not one before
10120 ;; If there was a CLOSED time stamp, get rid of it.
10121 (org-add-planning-info nil nil 'closed))
10122 (when (and now-done-p org-log-done)
10123 ;; It is now done, and it was not done before
10124 (org-add-planning-info 'closed (org-current-time))
10125 (if (and (not dolog) (eq 'note org-log-done))
10126 (org-add-log-setup 'done state this 'findpos 'note)))
10127 (when (and state dolog)
10128 ;; This is a non-nil state, and we need to log it
10129 (org-add-log-setup 'state state this 'findpos dolog)))
10130 ;; Fixup tag positioning
10131 (org-todo-trigger-tag-changes state)
10132 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10133 (when org-provide-todo-statistics
10134 (org-update-parent-todo-statistics))
10135 (run-hooks 'org-after-todo-state-change-hook)
10136 (if (and arg (not (member state org-done-keywords)))
10137 (setq head (org-get-todo-sequence-head state)))
10138 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10139 ;; Do we need to trigger a repeat?
10140 (when now-done-p
10141 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10142 ;; This is for the agenda, take a snapshot of the headline.
10143 (save-match-data
10144 (setq org-agenda-headline-snapshot-before-repeat
10145 (org-get-heading))))
10146 (org-auto-repeat-maybe state))
10147 ;; Fixup cursor location if close to the keyword
10148 (if (and (outline-on-heading-p)
10149 (not (bolp))
10150 (save-excursion (beginning-of-line 1)
10151 (looking-at org-todo-line-regexp))
10152 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10153 (progn
10154 (goto-char (or (match-end 2) (match-end 1)))
10155 (and (looking-at " ") (just-one-space))))
10156 (when org-trigger-hook
10157 (save-excursion
10158 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10160 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10161 "Block turning an entry into a TODO, using the hierarchy.
10162 This checks whether the current task should be blocked from state
10163 changes. Such blocking occurs when:
10165 1. The task has children which are not all in a completed state.
10167 2. A task has a parent with the property :ORDERED:, and there
10168 are siblings prior to the current task with incomplete
10169 status.
10171 3. The parent of the task is blocked because it has siblings that should
10172 be done first, or is child of a block grandparent TODO entry."
10174 (if (not org-enforce-todo-dependencies)
10175 t ; if locally turned off don't block
10176 (catch 'dont-block
10177 ;; If this is not a todo state change, or if this entry is already DONE,
10178 ;; do not block
10179 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10180 (member (plist-get change-plist :from)
10181 (cons 'done org-done-keywords))
10182 (member (plist-get change-plist :to)
10183 (cons 'todo org-not-done-keywords))
10184 (not (plist-get change-plist :to)))
10185 (throw 'dont-block t))
10186 ;; If this task has children, and any are undone, it's blocked
10187 (save-excursion
10188 (org-back-to-heading t)
10189 (let ((this-level (funcall outline-level)))
10190 (outline-next-heading)
10191 (let ((child-level (funcall outline-level)))
10192 (while (and (not (eobp))
10193 (> child-level this-level))
10194 ;; this todo has children, check whether they are all
10195 ;; completed
10196 (if (and (not (org-entry-is-done-p))
10197 (org-entry-is-todo-p))
10198 (throw 'dont-block nil))
10199 (outline-next-heading)
10200 (setq child-level (funcall outline-level))))))
10201 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10202 ;; any previous siblings are undone, it's blocked
10203 (save-excursion
10204 (org-back-to-heading t)
10205 (let* ((pos (point))
10206 (parent-pos (and (org-up-heading-safe) (point))))
10207 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10208 (when (and (org-entry-get (point) "ORDERED")
10209 (forward-line 1)
10210 (re-search-forward org-not-done-heading-regexp pos t))
10211 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10212 ;; Search further up the hierarchy, to see if an anchestor is blocked
10213 (while t
10214 (goto-char parent-pos)
10215 (if (not (looking-at org-not-done-heading-regexp))
10216 (throw 'dont-block t)) ; do not block, parent is not a TODO
10217 (setq pos (point))
10218 (setq parent-pos (and (org-up-heading-safe) (point)))
10219 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10220 (when (and (org-entry-get (point) "ORDERED")
10221 (forward-line 1)
10222 (re-search-forward org-not-done-heading-regexp pos t))
10223 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10225 (defcustom org-track-ordered-property-with-tag nil
10226 "Should the ORDERED property also be shown as a tag?
10227 The ORDERED property decides if an entry should require subtasks to be
10228 completed in sequence. Since a property is not very visible, setting
10229 this option means that toggling the ORDERED property with the command
10230 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10231 not relevant for the behavior, but it makes things more visible.
10233 Note that toggling the tag with tags commands will not change the property
10234 and therefore not influence behavior!
10236 This can be t, meaning the tag ORDERED should be used, It can also be a
10237 string to select a different tag for this task."
10238 :group 'org-todo
10239 :type '(choice
10240 (const :tag "No tracking" nil)
10241 (const :tag "Track with ORDERED tag" t)
10242 (string :tag "Use other tag")))
10244 (defun org-toggle-ordered-property ()
10245 "Toggle the ORDERED property of the current entry.
10246 For better visibility, you can track the value of this property with a tag.
10247 See variable `org-track-ordered-property-with-tag'."
10248 (interactive)
10249 (let* ((t1 org-track-ordered-property-with-tag)
10250 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10251 (save-excursion
10252 (org-back-to-heading)
10253 (if (org-entry-get nil "ORDERED")
10254 (progn
10255 (org-delete-property "ORDERED")
10256 (and tag (org-toggle-tag tag 'off))
10257 (message "Subtasks can be completed in arbitrary order"))
10258 (org-entry-put nil "ORDERED" "t")
10259 (and tag (org-toggle-tag tag 'on))
10260 (message "Subtasks must be completed in sequence")))))
10262 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10263 (defun org-block-todo-from-checkboxes (change-plist)
10264 "Block turning an entry into a TODO, using checkboxes.
10265 This checks whether the current task should be blocked from state
10266 changes because there are unchecked boxes in this entry."
10267 (if (not org-enforce-todo-checkbox-dependencies)
10268 t ; if locally turned off don't block
10269 (catch 'dont-block
10270 ;; If this is not a todo state change, or if this entry is already DONE,
10271 ;; do not block
10272 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10273 (member (plist-get change-plist :from)
10274 (cons 'done org-done-keywords))
10275 (member (plist-get change-plist :to)
10276 (cons 'todo org-not-done-keywords))
10277 (not (plist-get change-plist :to)))
10278 (throw 'dont-block t))
10279 ;; If this task has checkboxes that are not checked, it's blocked
10280 (save-excursion
10281 (org-back-to-heading t)
10282 (let ((beg (point)) end)
10283 (outline-next-heading)
10284 (setq end (point))
10285 (goto-char beg)
10286 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10287 end t)
10288 (progn
10289 (if (boundp 'org-blocked-by-checkboxes)
10290 (setq org-blocked-by-checkboxes t))
10291 (throw 'dont-block nil)))))
10292 t))) ; do not block
10294 (defun org-entry-blocked-p ()
10295 "Is the current entry blocked?"
10296 (if (org-entry-get nil "NOBLOCKING")
10297 nil ;; Never block this entry
10298 (not
10299 (run-hook-with-args-until-failure
10300 'org-blocker-hook
10301 (list :type 'todo-state-change
10302 :position (point)
10303 :from 'todo
10304 :to 'done)))))
10306 (defun org-update-statistics-cookies (all)
10307 "Update the statistics cookie, either from TODO or from checkboxes.
10308 This should be called with the cursor in a line with a statistics cookie."
10309 (interactive "P")
10310 (if all
10311 (progn
10312 (org-update-checkbox-count 'all)
10313 (org-map-entries 'org-update-parent-todo-statistics))
10314 (if (not (org-on-heading-p))
10315 (org-update-checkbox-count)
10316 (let ((pos (move-marker (make-marker) (point)))
10317 end l1 l2)
10318 (ignore-errors (org-back-to-heading t))
10319 (if (not (org-on-heading-p))
10320 (org-update-checkbox-count)
10321 (setq l1 (org-outline-level))
10322 (setq end (save-excursion
10323 (outline-next-heading)
10324 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10325 (point)))
10326 (if (and (save-excursion
10327 (re-search-forward
10328 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10329 (not (save-excursion (re-search-forward
10330 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10331 (org-update-checkbox-count)
10332 (if (and l2 (> l2 l1))
10333 (progn
10334 (goto-char end)
10335 (org-update-parent-todo-statistics))
10336 (goto-char pos)
10337 (beginning-of-line 1)
10338 (while (re-search-forward
10339 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10340 (point-at-eol) t)
10341 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10342 (goto-char pos)
10343 (move-marker pos nil)))))
10345 (defvar org-entry-property-inherited-from) ;; defined below
10346 (defun org-update-parent-todo-statistics ()
10347 "Update any statistics cookie in the parent of the current headline.
10348 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10349 the entire subtree and this will travel up the hierarchy and update
10350 statistics everywhere."
10351 (interactive)
10352 (let* ((lim 0) prop
10353 (recursive (or (not org-hierarchical-todo-statistics)
10354 (string-match
10355 "\\<recursive\\>"
10356 (or (setq prop (org-entry-get
10357 nil "COOKIE_DATA" 'inherit)) ""))))
10358 (lim (or (and prop (marker-position
10359 org-entry-property-inherited-from))
10360 lim))
10361 (first t)
10362 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10363 level ltoggle l1 new ndel
10364 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10365 (catch 'exit
10366 (save-excursion
10367 (beginning-of-line 1)
10368 (if (org-at-heading-p)
10369 (setq ltoggle (funcall outline-level))
10370 (error "This should not happen"))
10371 (while (and (setq level (org-up-heading-safe))
10372 (or recursive first)
10373 (>= (point) lim))
10374 (setq first nil cookie-present nil)
10375 (unless (and level
10376 (not (string-match
10377 "\\<checkbox\\>"
10378 (downcase
10379 (or (org-entry-get
10380 nil "COOKIE_DATA")
10381 "")))))
10382 (throw 'exit nil))
10383 (while (re-search-forward box-re (point-at-eol) t)
10384 (setq cnt-all 0 cnt-done 0 cookie-present t)
10385 (setq is-percent (match-end 2))
10386 (save-match-data
10387 (unless (outline-next-heading) (throw 'exit nil))
10388 (while (and (looking-at org-complex-heading-regexp)
10389 (> (setq l1 (length (match-string 1))) level))
10390 (setq kwd (and (or recursive (= l1 ltoggle))
10391 (match-string 2)))
10392 (if (or (eq org-provide-todo-statistics 'all-headlines)
10393 (and (listp org-provide-todo-statistics)
10394 (or (member kwd org-provide-todo-statistics)
10395 (member kwd org-done-keywords))))
10396 (setq cnt-all (1+ cnt-all))
10397 (if (eq org-provide-todo-statistics t)
10398 (and kwd (setq cnt-all (1+ cnt-all)))))
10399 (and (member kwd org-done-keywords)
10400 (setq cnt-done (1+ cnt-done)))
10401 (outline-next-heading)))
10402 (setq new
10403 (if is-percent
10404 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10405 (format "[%d/%d]" cnt-done cnt-all))
10406 ndel (- (match-end 0) (match-beginning 0)))
10407 (goto-char (match-beginning 0))
10408 (insert new)
10409 (delete-region (point) (+ (point) ndel)))
10410 (when cookie-present
10411 (run-hook-with-args 'org-after-todo-statistics-hook
10412 cnt-done (- cnt-all cnt-done))))))
10413 (run-hooks 'org-todo-statistics-hook)))
10415 (defvar org-after-todo-statistics-hook nil
10416 "Hook that is called after a TODO statistics cookie has been updated.
10417 Each function is called with two arguments: the number of not-done entries
10418 and the number of done entries.
10420 For example, the following function, when added to this hook, will switch
10421 an entry to DONE when all children are done, and back to TODO when new
10422 entries are set to a TODO status. Note that this hook is only called
10423 when there is a statistics cookie in the headline!
10425 (defun org-summary-todo (n-done n-not-done)
10426 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10427 (let (org-log-done org-log-states) ; turn off logging
10428 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10431 (defvar org-todo-statistics-hook nil
10432 "Hook that is run whenever Org thinks TODO statistics should be updated.
10433 This hook runs even if there is no statistics cookie present, in which case
10434 `org-after-todo-statistics-hook' would not run.")
10436 (defun org-todo-trigger-tag-changes (state)
10437 "Apply the changes defined in `org-todo-state-tags-triggers'."
10438 (let ((l org-todo-state-tags-triggers)
10439 changes)
10440 (when (or (not state) (equal state ""))
10441 (setq changes (append changes (cdr (assoc "" l)))))
10442 (when (and (stringp state) (> (length state) 0))
10443 (setq changes (append changes (cdr (assoc state l)))))
10444 (when (member state org-not-done-keywords)
10445 (setq changes (append changes (cdr (assoc 'todo l)))))
10446 (when (member state org-done-keywords)
10447 (setq changes (append changes (cdr (assoc 'done l)))))
10448 (dolist (c changes)
10449 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10451 (defun org-local-logging (value)
10452 "Get logging settings from a property VALUE."
10453 (let* (words w a)
10454 ;; directly set the variables, they are already local.
10455 (setq org-log-done nil
10456 org-log-repeat nil
10457 org-todo-log-states nil)
10458 (setq words (org-split-string value))
10459 (while (setq w (pop words))
10460 (cond
10461 ((setq a (assoc w org-startup-options))
10462 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10463 (set (nth 1 a) (nth 2 a))))
10464 ((setq a (org-extract-log-state-settings w))
10465 (and (member (car a) org-todo-keywords-1)
10466 (push a org-todo-log-states)))))))
10468 (defun org-get-todo-sequence-head (kwd)
10469 "Return the head of the TODO sequence to which KWD belongs.
10470 If KWD is not set, check if there is a text property remembering the
10471 right sequence."
10472 (let (p)
10473 (cond
10474 ((not kwd)
10475 (or (get-text-property (point-at-bol) 'org-todo-head)
10476 (progn
10477 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10478 nil (point-at-eol)))
10479 (get-text-property p 'org-todo-head))))
10480 ((not (member kwd org-todo-keywords-1))
10481 (car org-todo-keywords-1))
10482 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10484 (defun org-fast-todo-selection ()
10485 "Fast TODO keyword selection with single keys.
10486 Returns the new TODO keyword, or nil if no state change should occur."
10487 (let* ((fulltable org-todo-key-alist)
10488 (done-keywords org-done-keywords) ;; needed for the faces.
10489 (maxlen (apply 'max (mapcar
10490 (lambda (x)
10491 (if (stringp (car x)) (string-width (car x)) 0))
10492 fulltable)))
10493 (expert nil)
10494 (fwidth (+ maxlen 3 1 3))
10495 (ncol (/ (- (window-width) 4) fwidth))
10496 tg cnt e c tbl
10497 groups ingroup)
10498 (save-excursion
10499 (save-window-excursion
10500 (if expert
10501 (set-buffer (get-buffer-create " *Org todo*"))
10502 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10503 (erase-buffer)
10504 (org-set-local 'org-done-keywords done-keywords)
10505 (setq tbl fulltable cnt 0)
10506 (while (setq e (pop tbl))
10507 (cond
10508 ((equal e '(:startgroup))
10509 (push '() groups) (setq ingroup t)
10510 (when (not (= cnt 0))
10511 (setq cnt 0)
10512 (insert "\n"))
10513 (insert "{ "))
10514 ((equal e '(:endgroup))
10515 (setq ingroup nil cnt 0)
10516 (insert "}\n"))
10517 ((equal e '(:newline))
10518 (when (not (= cnt 0))
10519 (setq cnt 0)
10520 (insert "\n")
10521 (setq e (car tbl))
10522 (while (equal (car tbl) '(:newline))
10523 (insert "\n")
10524 (setq tbl (cdr tbl)))))
10526 (setq tg (car e) c (cdr e))
10527 (if ingroup (push tg (car groups)))
10528 (setq tg (org-add-props tg nil 'face
10529 (org-get-todo-face tg)))
10530 (if (and (= cnt 0) (not ingroup)) (insert " "))
10531 (insert "[" c "] " tg (make-string
10532 (- fwidth 4 (length tg)) ?\ ))
10533 (when (= (setq cnt (1+ cnt)) ncol)
10534 (insert "\n")
10535 (if ingroup (insert " "))
10536 (setq cnt 0)))))
10537 (insert "\n")
10538 (goto-char (point-min))
10539 (if (not expert) (org-fit-window-to-buffer))
10540 (message "[a-z..]:Set [SPC]:clear")
10541 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10542 (cond
10543 ((or (= c ?\C-g)
10544 (and (= c ?q) (not (rassoc c fulltable))))
10545 (setq quit-flag t))
10546 ((= c ?\ ) nil)
10547 ((setq e (rassoc c fulltable) tg (car e))
10549 (t (setq quit-flag t)))))))
10551 (defun org-entry-is-todo-p ()
10552 (member (org-get-todo-state) org-not-done-keywords))
10554 (defun org-entry-is-done-p ()
10555 (member (org-get-todo-state) org-done-keywords))
10557 (defun org-get-todo-state ()
10558 (save-excursion
10559 (org-back-to-heading t)
10560 (and (looking-at org-todo-line-regexp)
10561 (match-end 2)
10562 (match-string 2))))
10564 (defun org-at-date-range-p (&optional inactive-ok)
10565 "Is the cursor inside a date range?"
10566 (interactive)
10567 (save-excursion
10568 (catch 'exit
10569 (let ((pos (point)))
10570 (skip-chars-backward "^[<\r\n")
10571 (skip-chars-backward "<[")
10572 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10573 (>= (match-end 0) pos)
10574 (throw 'exit t))
10575 (skip-chars-backward "^<[\r\n")
10576 (skip-chars-backward "<[")
10577 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10578 (>= (match-end 0) pos)
10579 (throw 'exit t)))
10580 nil)))
10582 (defun org-get-repeat (&optional tagline)
10583 "Check if there is a deadline/schedule with repeater in this entry."
10584 (save-match-data
10585 (save-excursion
10586 (org-back-to-heading t)
10587 (and (re-search-forward (if tagline
10588 (concat tagline "\\s-*" org-repeat-re)
10589 org-repeat-re)
10590 (org-entry-end-position) t)
10591 (match-string-no-properties 1)))))
10593 (defvar org-last-changed-timestamp)
10594 (defvar org-last-inserted-timestamp)
10595 (defvar org-log-post-message)
10596 (defvar org-log-note-purpose)
10597 (defvar org-log-note-how)
10598 (defvar org-log-note-extra)
10599 (defun org-auto-repeat-maybe (done-word)
10600 "Check if the current headline contains a repeated deadline/schedule.
10601 If yes, set TODO state back to what it was and change the base date
10602 of repeating deadline/scheduled time stamps to new date.
10603 This function is run automatically after each state change to a DONE state."
10604 ;; last-state is dynamically scoped into this function
10605 (let* ((repeat (org-get-repeat))
10606 (aa (assoc last-state org-todo-kwd-alist))
10607 (interpret (nth 1 aa))
10608 (head (nth 2 aa))
10609 (whata '(("d" . day) ("m" . month) ("y" . year)))
10610 (msg "Entry repeats: ")
10611 (org-log-done nil)
10612 (org-todo-log-states nil)
10613 (nshiftmax 10) (nshift 0)
10614 re type n what ts time)
10615 (when repeat
10616 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10617 (org-todo (if (eq interpret 'type) last-state head))
10618 (org-entry-put nil "LAST_REPEAT" (format-time-string
10619 (org-time-stamp-format t t)))
10620 (when org-log-repeat
10621 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10622 (memq 'org-add-log-note post-command-hook))
10623 ;; OK, we are already setup for some record
10624 (if (eq org-log-repeat 'note)
10625 ;; make sure we take a note, not only a time stamp
10626 (setq org-log-note-how 'note))
10627 ;; Set up for taking a record
10628 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10629 last-state
10630 'findpos org-log-repeat)))
10631 (org-back-to-heading t)
10632 (org-add-planning-info nil nil 'closed)
10633 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10634 org-deadline-time-regexp "\\)\\|\\("
10635 org-ts-regexp "\\)"))
10636 (while (re-search-forward
10637 re (save-excursion (outline-next-heading) (point)) t)
10638 (setq type (if (match-end 1) org-scheduled-string
10639 (if (match-end 3) org-deadline-string "Plain:"))
10640 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10641 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10642 (setq n (string-to-number (match-string 2 ts))
10643 what (match-string 3 ts))
10644 (if (equal what "w") (setq n (* n 7) what "d"))
10645 ;; Preparation, see if we need to modify the start date for the change
10646 (when (match-end 1)
10647 (setq time (save-match-data (org-time-string-to-time ts)))
10648 (cond
10649 ((equal (match-string 1 ts) ".")
10650 ;; Shift starting date to today
10651 (org-timestamp-change
10652 (- (time-to-days (current-time)) (time-to-days time))
10653 'day))
10654 ((equal (match-string 1 ts) "+")
10655 (while (or (= nshift 0)
10656 (<= (time-to-days time) (time-to-days (current-time))))
10657 (when (= (incf nshift) nshiftmax)
10658 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10659 (error "Abort")))
10660 (org-timestamp-change n (cdr (assoc what whata)))
10661 (org-at-timestamp-p t)
10662 (setq ts (match-string 1))
10663 (setq time (save-match-data (org-time-string-to-time ts))))
10664 (org-timestamp-change (- n) (cdr (assoc what whata)))
10665 ;; rematch, so that we have everything in place for the real shift
10666 (org-at-timestamp-p t)
10667 (setq ts (match-string 1))
10668 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10669 (org-timestamp-change n (cdr (assoc what whata)))
10670 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10671 (setq org-log-post-message msg)
10672 (message "%s" msg))))
10674 (defun org-show-todo-tree (arg)
10675 "Make a compact tree which shows all headlines marked with TODO.
10676 The tree will show the lines where the regexp matches, and all higher
10677 headlines above the match.
10678 With a \\[universal-argument] prefix, prompt for a regexp to match.
10679 With a numeric prefix N, construct a sparse tree for the Nth element
10680 of `org-todo-keywords-1'."
10681 (interactive "P")
10682 (let ((case-fold-search nil)
10683 (kwd-re
10684 (cond ((null arg) org-not-done-regexp)
10685 ((equal arg '(4))
10686 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10687 (mapcar 'list org-todo-keywords-1))))
10688 (concat "\\("
10689 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10690 "\\)\\>")))
10691 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10692 (regexp-quote (nth (1- (prefix-numeric-value arg))
10693 org-todo-keywords-1)))
10694 (t (error "Invalid prefix argument: %s" arg)))))
10695 (message "%d TODO entries found"
10696 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10698 (defun org-deadline (&optional remove time)
10699 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10700 With argument REMOVE, remove any deadline from the item.
10701 When TIME is set, it should be an internal time specification, and the
10702 scheduling will use the corresponding date."
10703 (interactive "P")
10704 (let ((old-date (org-entry-get nil "DEADLINE")))
10705 (if remove
10706 (progn
10707 (when (and old-date org-log-redeadline)
10708 (org-add-log-setup 'deldeadline nil old-date 'findpos
10709 org-log-redeadline))
10710 (org-remove-timestamp-with-keyword org-deadline-string)
10711 (message "Item no longer has a deadline."))
10712 (if (org-get-repeat)
10713 (error "Cannot change deadline on task with repeater, please do that by hand")
10714 (org-add-planning-info 'deadline time 'closed)
10715 (when (and old-date org-log-redeadline
10716 (not (equal old-date
10717 (substring org-last-inserted-timestamp 1 -1))))
10718 (org-add-log-setup 'redeadline nil old-date 'findpos
10719 org-log-redeadline))
10720 (message "Deadline on %s" org-last-inserted-timestamp)))))
10722 (defun org-schedule (&optional remove time)
10723 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10724 With argument REMOVE, remove any scheduling date from the item.
10725 When TIME is set, it should be an internal time specification, and the
10726 scheduling will use the corresponding date."
10727 (interactive "P")
10728 (let ((old-date (org-entry-get nil "SCHEDULED")))
10729 (if remove
10730 (progn
10731 (when (and old-date org-log-reschedule)
10732 (org-add-log-setup 'delschedule nil old-date 'findpos
10733 org-log-reschedule))
10734 (org-remove-timestamp-with-keyword org-scheduled-string)
10735 (message "Item is no longer scheduled."))
10736 (if (org-get-repeat)
10737 (error "Cannot reschedule task with repeater, please do that by hand")
10738 (org-add-planning-info 'scheduled time 'closed)
10739 (when (and old-date org-log-reschedule
10740 (not (equal old-date
10741 (substring org-last-inserted-timestamp 1 -1))))
10742 (org-add-log-setup 'reschedule nil old-date 'findpos
10743 org-log-reschedule))
10744 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10746 (defun org-get-scheduled-time (pom &optional inherit)
10747 "Get the scheduled time as a time tuple, of a format suitable
10748 for calling org-schedule with, or if there is no scheduling,
10749 returns nil."
10750 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10751 (when time
10752 (apply 'encode-time (org-parse-time-string time)))))
10754 (defun org-get-deadline-time (pom &optional inherit)
10755 "Get the deadine as a time tuple, of a format suitable for
10756 calling org-deadline with, or if there is no scheduling, returns
10757 nil."
10758 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10759 (when time
10760 (apply 'encode-time (org-parse-time-string time)))))
10762 (defun org-remove-timestamp-with-keyword (keyword)
10763 "Remove all time stamps with KEYWORD in the current entry."
10764 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10765 beg)
10766 (save-excursion
10767 (org-back-to-heading t)
10768 (setq beg (point))
10769 (outline-next-heading)
10770 (while (re-search-backward re beg t)
10771 (replace-match "")
10772 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10773 (equal (char-before) ?\ ))
10774 (backward-delete-char 1)
10775 (if (string-match "^[ \t]*$" (buffer-substring
10776 (point-at-bol) (point-at-eol)))
10777 (delete-region (point-at-bol)
10778 (min (point-max) (1+ (point-at-eol))))))))))
10780 (defun org-add-planning-info (what &optional time &rest remove)
10781 "Insert new timestamp with keyword in the line directly after the headline.
10782 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10783 If non is given, the user is prompted for a date.
10784 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10785 be removed."
10786 (interactive)
10787 (let (org-time-was-given org-end-time-was-given ts
10788 end default-time default-input)
10790 (catch 'exit
10791 (when (and (not time) (memq what '(scheduled deadline)))
10792 ;; Try to get a default date/time from existing timestamp
10793 (save-excursion
10794 (org-back-to-heading t)
10795 (setq end (save-excursion (outline-next-heading) (point)))
10796 (when (re-search-forward (if (eq what 'scheduled)
10797 org-scheduled-time-regexp
10798 org-deadline-time-regexp)
10799 end t)
10800 (setq ts (match-string 1)
10801 default-time
10802 (apply 'encode-time (org-parse-time-string ts))
10803 default-input (and ts (org-get-compact-tod ts))))))
10804 (when what
10805 ;; If necessary, get the time from the user
10806 (setq time (or time (org-read-date nil 'to-time nil nil
10807 default-time default-input))))
10809 (when (and org-insert-labeled-timestamps-at-point
10810 (member what '(scheduled deadline)))
10811 (insert
10812 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10813 (org-insert-time-stamp time org-time-was-given
10814 nil nil nil (list org-end-time-was-given))
10815 (setq what nil))
10816 (save-excursion
10817 (save-restriction
10818 (let (col list elt ts buffer-invisibility-spec)
10819 (org-back-to-heading t)
10820 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10821 (goto-char (match-end 1))
10822 (setq col (current-column))
10823 (goto-char (match-end 0))
10824 (if (eobp) (insert "\n") (forward-char 1))
10825 (when (and (not what)
10826 (not (looking-at
10827 (concat "[ \t]*"
10828 org-keyword-time-not-clock-regexp))))
10829 ;; Nothing to add, nothing to remove...... :-)
10830 (throw 'exit nil))
10831 (if (and (not (looking-at outline-regexp))
10832 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10833 "[^\r\n]*"))
10834 (not (equal (match-string 1) org-clock-string)))
10835 (narrow-to-region (match-beginning 0) (match-end 0))
10836 (insert-before-markers "\n")
10837 (backward-char 1)
10838 (narrow-to-region (point) (point))
10839 (and org-adapt-indentation (org-indent-to-column col)))
10840 ;; Check if we have to remove something.
10841 (setq list (cons what remove))
10842 (while list
10843 (setq elt (pop list))
10844 (goto-char (point-min))
10845 (when (or (and (eq elt 'scheduled)
10846 (re-search-forward org-scheduled-time-regexp nil t))
10847 (and (eq elt 'deadline)
10848 (re-search-forward org-deadline-time-regexp nil t))
10849 (and (eq elt 'closed)
10850 (re-search-forward org-closed-time-regexp nil t)))
10851 (replace-match "")
10852 (if (looking-at "--+<[^>]+>") (replace-match ""))
10853 (skip-chars-backward " ")
10854 (if (looking-at " +") (replace-match ""))))
10855 (goto-char (point-max))
10856 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10857 (when what
10858 (insert
10859 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10860 (cond ((eq what 'scheduled) org-scheduled-string)
10861 ((eq what 'deadline) org-deadline-string)
10862 ((eq what 'closed) org-closed-string))
10863 " ")
10864 (setq ts (org-insert-time-stamp
10865 time
10866 (or org-time-was-given
10867 (and (eq what 'closed) org-log-done-with-time))
10868 (eq what 'closed)
10869 nil nil (list org-end-time-was-given)))
10870 (end-of-line 1))
10871 (goto-char (point-min))
10872 (widen)
10873 (if (and (looking-at "[ \t]+\n")
10874 (equal (char-before) ?\n))
10875 (delete-region (1- (point)) (point-at-eol)))
10876 ts))))))
10878 (defvar org-log-note-marker (make-marker))
10879 (defvar org-log-note-purpose nil)
10880 (defvar org-log-note-state nil)
10881 (defvar org-log-note-previous-state nil)
10882 (defvar org-log-note-how nil)
10883 (defvar org-log-note-extra nil)
10884 (defvar org-log-note-window-configuration nil)
10885 (defvar org-log-note-return-to (make-marker))
10886 (defvar org-log-post-message nil
10887 "Message to be displayed after a log note has been stored.
10888 The auto-repeater uses this.")
10890 (defun org-add-note ()
10891 "Add a note to the current entry.
10892 This is done in the same way as adding a state change note."
10893 (interactive)
10894 (org-add-log-setup 'note nil nil 'findpos nil))
10896 (defvar org-property-end-re)
10897 (defun org-add-log-setup (&optional purpose state prev-state
10898 findpos how &optional extra)
10899 "Set up the post command hook to take a note.
10900 If this is about to TODO state change, the new state is expected in STATE.
10901 When FINDPOS is non-nil, find the correct position for the note in
10902 the current entry. If not, assume that it can be inserted at point.
10903 HOW is an indicator what kind of note should be created.
10904 EXTRA is additional text that will be inserted into the notes buffer."
10905 (let* ((org-log-into-drawer (org-log-into-drawer))
10906 (drawer (cond ((stringp org-log-into-drawer)
10907 org-log-into-drawer)
10908 (org-log-into-drawer "LOGBOOK")
10909 (t nil))))
10910 (save-restriction
10911 (save-excursion
10912 (when findpos
10913 (org-back-to-heading t)
10914 (narrow-to-region (point) (save-excursion
10915 (outline-next-heading) (point)))
10916 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10917 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10918 "[^\r\n]*\\)?"))
10919 (goto-char (match-end 0))
10920 (cond
10921 (drawer
10922 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10923 nil t)
10924 (progn
10925 (goto-char (match-end 0))
10926 (or org-log-states-order-reversed
10927 (and (re-search-forward org-property-end-re nil t)
10928 (goto-char (1- (match-beginning 0))))))
10929 (insert "\n:" drawer ":\n:END:")
10930 (beginning-of-line 0)
10931 (org-indent-line-function)
10932 (beginning-of-line 2)
10933 (org-indent-line-function)
10934 (end-of-line 0)))
10935 ((and org-log-state-notes-insert-after-drawers
10936 (save-excursion
10937 (forward-line) (looking-at org-drawer-regexp)))
10938 (forward-line)
10939 (while (looking-at org-drawer-regexp)
10940 (goto-char (match-end 0))
10941 (re-search-forward org-property-end-re (point-max) t)
10942 (forward-line))
10943 (forward-line -1)))
10944 (unless org-log-states-order-reversed
10945 (and (= (char-after) ?\n) (forward-char 1))
10946 (org-skip-over-state-notes)
10947 (skip-chars-backward " \t\n\r")))
10948 (move-marker org-log-note-marker (point))
10949 (setq org-log-note-purpose purpose
10950 org-log-note-state state
10951 org-log-note-previous-state prev-state
10952 org-log-note-how how
10953 org-log-note-extra extra)
10954 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10956 (defun org-skip-over-state-notes ()
10957 "Skip past the list of State notes in an entry."
10958 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10959 (while (looking-at "[ \t]*- State")
10960 (condition-case nil
10961 (org-next-item)
10962 (error (org-end-of-item)))))
10964 (defun org-add-log-note (&optional purpose)
10965 "Pop up a window for taking a note, and add this note later at point."
10966 (remove-hook 'post-command-hook 'org-add-log-note)
10967 (setq org-log-note-window-configuration (current-window-configuration))
10968 (delete-other-windows)
10969 (move-marker org-log-note-return-to (point))
10970 (switch-to-buffer (marker-buffer org-log-note-marker))
10971 (goto-char org-log-note-marker)
10972 (org-switch-to-buffer-other-window "*Org Note*")
10973 (erase-buffer)
10974 (if (memq org-log-note-how '(time state))
10975 (let (current-prefix-arg) (org-store-log-note))
10976 (let ((org-inhibit-startup t)) (org-mode))
10977 (insert (format "# Insert note for %s.
10978 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10979 (cond
10980 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10981 ((eq org-log-note-purpose 'done) "closed todo item")
10982 ((eq org-log-note-purpose 'state)
10983 (format "state change from \"%s\" to \"%s\""
10984 (or org-log-note-previous-state "")
10985 (or org-log-note-state "")))
10986 ((eq org-log-note-purpose 'reschedule)
10987 "rescheduling")
10988 ((eq org-log-note-purpose 'delschedule)
10989 "no longer scheduled")
10990 ((eq org-log-note-purpose 'redeadline)
10991 "changing deadline")
10992 ((eq org-log-note-purpose 'deldeadline)
10993 "removing deadline")
10994 ((eq org-log-note-purpose 'note)
10995 "this entry")
10996 (t (error "This should not happen")))))
10997 (if org-log-note-extra (insert org-log-note-extra))
10998 (org-set-local 'org-finish-function 'org-store-log-note)))
11000 (defvar org-note-abort nil) ; dynamically scoped
11001 (defun org-store-log-note ()
11002 "Finish taking a log note, and insert it to where it belongs."
11003 (let ((txt (buffer-string))
11004 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11005 lines ind)
11006 (kill-buffer (current-buffer))
11007 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11008 (setq txt (replace-match "" t t txt)))
11009 (if (string-match "\\s-+\\'" txt)
11010 (setq txt (replace-match "" t t txt)))
11011 (setq lines (org-split-string txt "\n"))
11012 (when (and note (string-match "\\S-" note))
11013 (setq note
11014 (org-replace-escapes
11015 note
11016 (list (cons "%u" (user-login-name))
11017 (cons "%U" user-full-name)
11018 (cons "%t" (format-time-string
11019 (org-time-stamp-format 'long 'inactive)
11020 (current-time)))
11021 (cons "%s" (if org-log-note-state
11022 (concat "\"" org-log-note-state "\"")
11023 ""))
11024 (cons "%S" (if org-log-note-previous-state
11025 (concat "\"" org-log-note-previous-state "\"")
11026 "\"\"")))))
11027 (if lines (setq note (concat note " \\\\")))
11028 (push note lines))
11029 (when (or current-prefix-arg org-note-abort)
11030 (when org-log-into-drawer
11031 (org-remove-empty-drawer-at
11032 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11033 org-log-note-marker))
11034 (setq lines nil))
11035 (when lines
11036 (with-current-buffer (marker-buffer org-log-note-marker)
11037 (save-excursion
11038 (goto-char org-log-note-marker)
11039 (move-marker org-log-note-marker nil)
11040 (end-of-line 1)
11041 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11042 (insert "- " (pop lines))
11043 (org-indent-line-function)
11044 (beginning-of-line 1)
11045 (looking-at "[ \t]*")
11046 (setq ind (concat (match-string 0) " "))
11047 (end-of-line 1)
11048 (while lines (insert "\n" ind (pop lines)))
11049 (message "Note stored")
11050 (org-back-to-heading t)
11051 (org-cycle-hide-drawers 'children)))))
11052 (set-window-configuration org-log-note-window-configuration)
11053 (with-current-buffer (marker-buffer org-log-note-return-to)
11054 (goto-char org-log-note-return-to))
11055 (move-marker org-log-note-return-to nil)
11056 (and org-log-post-message (message "%s" org-log-post-message)))
11058 (defun org-remove-empty-drawer-at (drawer pos)
11059 "Remove an empty drawer DRAWER at position POS.
11060 POS may also be a marker."
11061 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11062 (save-excursion
11063 (save-restriction
11064 (widen)
11065 (goto-char pos)
11066 (if (org-in-regexp
11067 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11068 (replace-match ""))))))
11070 (defun org-sparse-tree (&optional arg)
11071 "Create a sparse tree, prompt for the details.
11072 This command can create sparse trees. You first need to select the type
11073 of match used to create the tree:
11075 t Show entries with a specific TODO keyword.
11076 m Show entries selected by a tags/property match.
11077 p Enter a property name and its value (both with completion on existing
11078 names/values) and show entries with that property.
11079 / Show entries matching a regular expression (`r' can be used as well)
11080 d Show deadlines due within `org-deadline-warning-days'.
11081 b Show deadlines and scheduled items before a date.
11082 a Show deadlines and scheduled items after a date."
11083 (interactive "P")
11084 (let (ans kwd value)
11085 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11086 (setq ans (read-char-exclusive))
11087 (cond
11088 ((equal ans ?d)
11089 (call-interactively 'org-check-deadlines))
11090 ((equal ans ?b)
11091 (call-interactively 'org-check-before-date))
11092 ((equal ans ?a)
11093 (call-interactively 'org-check-after-date))
11094 ((equal ans ?t)
11095 (org-show-todo-tree '(4)))
11096 ((member ans '(?T ?m))
11097 (call-interactively 'org-match-sparse-tree))
11098 ((member ans '(?p ?P))
11099 (setq kwd (org-icompleting-read "Property: "
11100 (mapcar 'list (org-buffer-property-keys))))
11101 (setq value (org-icompleting-read "Value: "
11102 (mapcar 'list (org-property-values kwd))))
11103 (unless (string-match "\\`{.*}\\'" value)
11104 (setq value (concat "\"" value "\"")))
11105 (org-match-sparse-tree arg (concat kwd "=" value)))
11106 ((member ans '(?r ?R ?/))
11107 (call-interactively 'org-occur))
11108 (t (error "No such sparse tree command \"%c\"" ans)))))
11110 (defvar org-occur-highlights nil
11111 "List of overlays used for occur matches.")
11112 (make-variable-buffer-local 'org-occur-highlights)
11113 (defvar org-occur-parameters nil
11114 "Parameters of the active org-occur calls.
11115 This is a list, each call to org-occur pushes as cons cell,
11116 containing the regular expression and the callback, onto the list.
11117 The list can contain several entries if `org-occur' has been called
11118 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11119 will only contain one set of parameters. When the highlights are
11120 removed (for example with `C-c C-c', or with the next edit (depending
11121 on `org-remove-highlights-with-change'), this variable is emptied
11122 as well.")
11123 (make-variable-buffer-local 'org-occur-parameters)
11125 (defun org-occur (regexp &optional keep-previous callback)
11126 "Make a compact tree which shows all matches of REGEXP.
11127 The tree will show the lines where the regexp matches, and all higher
11128 headlines above the match. It will also show the heading after the match,
11129 to make sure editing the matching entry is easy.
11130 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11131 call to `org-occur' will be kept, to allow stacking of calls to this
11132 command.
11133 If CALLBACK is non-nil, it is a function which is called to confirm
11134 that the match should indeed be shown."
11135 (interactive "sRegexp: \nP")
11136 (when (equal regexp "")
11137 (error "Regexp cannot be empty"))
11138 (unless keep-previous
11139 (org-remove-occur-highlights nil nil t))
11140 (push (cons regexp callback) org-occur-parameters)
11141 (let ((cnt 0))
11142 (save-excursion
11143 (goto-char (point-min))
11144 (if (or (not keep-previous) ; do not want to keep
11145 (not org-occur-highlights)) ; no previous matches
11146 ;; hide everything
11147 (org-overview))
11148 (while (re-search-forward regexp nil t)
11149 (when (or (not callback)
11150 (save-match-data (funcall callback)))
11151 (setq cnt (1+ cnt))
11152 (when org-highlight-sparse-tree-matches
11153 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11154 (org-show-context 'occur-tree))))
11155 (when org-remove-highlights-with-change
11156 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11157 nil 'local))
11158 (unless org-sparse-tree-open-archived-trees
11159 (org-hide-archived-subtrees (point-min) (point-max)))
11160 (run-hooks 'org-occur-hook)
11161 (if (interactive-p)
11162 (message "%d match(es) for regexp %s" cnt regexp))
11163 cnt))
11165 (defun org-show-context (&optional key)
11166 "Make sure point and context and visible.
11167 How much context is shown depends upon the variables
11168 `org-show-hierarchy-above', `org-show-following-heading'. and
11169 `org-show-siblings'."
11170 (let ((heading-p (org-on-heading-p t))
11171 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11172 (following-p (org-get-alist-option org-show-following-heading key))
11173 (entry-p (org-get-alist-option org-show-entry-below key))
11174 (siblings-p (org-get-alist-option org-show-siblings key)))
11175 (catch 'exit
11176 ;; Show heading or entry text
11177 (if (and heading-p (not entry-p))
11178 (org-flag-heading nil) ; only show the heading
11179 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11180 (org-show-hidden-entry))) ; show entire entry
11181 (when following-p
11182 ;; Show next sibling, or heading below text
11183 (save-excursion
11184 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11185 (org-flag-heading nil))))
11186 (when siblings-p (org-show-siblings))
11187 (when hierarchy-p
11188 ;; show all higher headings, possibly with siblings
11189 (save-excursion
11190 (while (and (condition-case nil
11191 (progn (org-up-heading-all 1) t)
11192 (error nil))
11193 (not (bobp)))
11194 (org-flag-heading nil)
11195 (when siblings-p (org-show-siblings))))))))
11197 (defun org-reveal (&optional siblings)
11198 "Show current entry, hierarchy above it, and the following headline.
11199 This can be used to show a consistent set of context around locations
11200 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11201 not t for the search context.
11203 With optional argument SIBLINGS, on each level of the hierarchy all
11204 siblings are shown. This repairs the tree structure to what it would
11205 look like when opened with hierarchical calls to `org-cycle'."
11206 (interactive "P")
11207 (let ((org-show-hierarchy-above t)
11208 (org-show-following-heading t)
11209 (org-show-siblings (if siblings t org-show-siblings)))
11210 (org-show-context nil)))
11212 (defun org-highlight-new-match (beg end)
11213 "Highlight from BEG to END and mark the highlight is an occur headline."
11214 (let ((ov (org-make-overlay beg end)))
11215 (org-overlay-put ov 'face 'secondary-selection)
11216 (push ov org-occur-highlights)))
11218 (defun org-remove-occur-highlights (&optional beg end noremove)
11219 "Remove the occur highlights from the buffer.
11220 BEG and END are ignored. If NOREMOVE is nil, remove this function
11221 from the `before-change-functions' in the current buffer."
11222 (interactive)
11223 (unless org-inhibit-highlight-removal
11224 (mapc 'org-delete-overlay org-occur-highlights)
11225 (setq org-occur-highlights nil)
11226 (setq org-occur-parameters nil)
11227 (unless noremove
11228 (remove-hook 'before-change-functions
11229 'org-remove-occur-highlights 'local))))
11231 ;;;; Priorities
11233 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11234 "Regular expression matching the priority indicator.")
11236 (defvar org-remove-priority-next-time nil)
11238 (defun org-priority-up ()
11239 "Increase the priority of the current item."
11240 (interactive)
11241 (org-priority 'up))
11243 (defun org-priority-down ()
11244 "Decrease the priority of the current item."
11245 (interactive)
11246 (org-priority 'down))
11248 (defun org-priority (&optional action)
11249 "Change the priority of an item by ARG.
11250 ACTION can be `set', `up', `down', or a character."
11251 (interactive)
11252 (unless org-enable-priority-commands
11253 (error "Priority commands are disabled"))
11254 (setq action (or action 'set))
11255 (let (current new news have remove)
11256 (save-excursion
11257 (org-back-to-heading t)
11258 (if (looking-at org-priority-regexp)
11259 (setq current (string-to-char (match-string 2))
11260 have t)
11261 (setq current org-default-priority))
11262 (cond
11263 ((eq action 'remove)
11264 (setq remove t new ?\ ))
11265 ((or (eq action 'set)
11266 (if (featurep 'xemacs) (characterp action) (integerp action)))
11267 (if (not (eq action 'set))
11268 (setq new action)
11269 (message "Priority %c-%c, SPC to remove: "
11270 org-highest-priority org-lowest-priority)
11271 (setq new (read-char-exclusive)))
11272 (if (and (= (upcase org-highest-priority) org-highest-priority)
11273 (= (upcase org-lowest-priority) org-lowest-priority))
11274 (setq new (upcase new)))
11275 (cond ((equal new ?\ ) (setq remove t))
11276 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11277 (error "Priority must be between `%c' and `%c'"
11278 org-highest-priority org-lowest-priority))))
11279 ((eq action 'up)
11280 (if (and (not have) (eq last-command this-command))
11281 (setq new org-lowest-priority)
11282 (setq new (if (and org-priority-start-cycle-with-default (not have))
11283 org-default-priority (1- current)))))
11284 ((eq action 'down)
11285 (if (and (not have) (eq last-command this-command))
11286 (setq new org-highest-priority)
11287 (setq new (if (and org-priority-start-cycle-with-default (not have))
11288 org-default-priority (1+ current)))))
11289 (t (error "Invalid action")))
11290 (if (or (< (upcase new) org-highest-priority)
11291 (> (upcase new) org-lowest-priority))
11292 (setq remove t))
11293 (setq news (format "%c" new))
11294 (if have
11295 (if remove
11296 (replace-match "" t t nil 1)
11297 (replace-match news t t nil 2))
11298 (if remove
11299 (error "No priority cookie found in line")
11300 (let ((case-fold-search nil))
11301 (looking-at org-todo-line-regexp))
11302 (if (match-end 2)
11303 (progn
11304 (goto-char (match-end 2))
11305 (insert " [#" news "]"))
11306 (goto-char (match-beginning 3))
11307 (insert "[#" news "] "))))
11308 (org-preserve-lc (org-set-tags nil 'align)))
11309 (if remove
11310 (message "Priority removed")
11311 (message "Priority of current item set to %s" news))))
11313 (defun org-get-priority (s)
11314 "Find priority cookie and return priority."
11315 (save-match-data
11316 (if (not (string-match org-priority-regexp s))
11317 (* 1000 (- org-lowest-priority org-default-priority))
11318 (* 1000 (- org-lowest-priority
11319 (string-to-char (match-string 2 s)))))))
11321 ;;;; Tags
11323 (defvar org-agenda-archives-mode)
11324 (defvar org-map-continue-from nil
11325 "Position from where mapping should continue.
11326 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11328 (defvar org-scanner-tags nil
11329 "The current tag list while the tags scanner is running.")
11330 (defvar org-trust-scanner-tags nil
11331 "Should `org-get-tags-at' use the tags fro the scanner.
11332 This is for internal dynamical scoping only.
11333 When this is non-nil, the function `org-get-tags-at' will return the value
11334 of `org-scanner-tags' instead of building the list by itself. This
11335 can lead to large speed-ups when the tags scanner is used in a file with
11336 many entries, and when the list of tags is retrieved, for example to
11337 obtain a list of properties. Building the tags list for each entry in such
11338 a file becomes an N^2 operation - but with this variable set, it scales
11339 as N.")
11341 (defun org-scan-tags (action matcher &optional todo-only)
11342 "Scan headline tags with inheritance and produce output ACTION.
11344 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11345 or `agenda' to produce an entry list for an agenda view. It can also be
11346 a Lisp form or a function that should be called at each matched headline, in
11347 this case the return value is a list of all return values from these calls.
11349 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11350 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11351 only lines with a TODO keyword are included in the output."
11352 (require 'org-agenda)
11353 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11354 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11355 (org-re
11356 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11357 (props (list 'face 'default
11358 'done-face 'org-agenda-done
11359 'undone-face 'default
11360 'mouse-face 'highlight
11361 'org-not-done-regexp org-not-done-regexp
11362 'org-todo-regexp org-todo-regexp
11363 'help-echo
11364 (format "mouse-2 or RET jump to org file %s"
11365 (abbreviate-file-name
11366 (or (buffer-file-name (buffer-base-buffer))
11367 (buffer-name (buffer-base-buffer)))))))
11368 (case-fold-search nil)
11369 (org-map-continue-from nil)
11370 lspos tags tags-list
11371 (tags-alist (list (cons 0 org-file-tags)))
11372 (llast 0) rtn rtn1 level category i txt
11373 todo marker entry priority)
11374 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11375 (setq action (list 'lambda nil action)))
11376 (save-excursion
11377 (goto-char (point-min))
11378 (when (eq action 'sparse-tree)
11379 (org-overview)
11380 (org-remove-occur-highlights))
11381 (while (re-search-forward re nil t)
11382 (catch :skip
11383 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11384 tags (if (match-end 4) (org-match-string-no-properties 4)))
11385 (goto-char (setq lspos (match-beginning 0)))
11386 (setq level (org-reduced-level (funcall outline-level))
11387 category (org-get-category))
11388 (setq i llast llast level)
11389 ;; remove tag lists from same and sublevels
11390 (while (>= i level)
11391 (when (setq entry (assoc i tags-alist))
11392 (setq tags-alist (delete entry tags-alist)))
11393 (setq i (1- i)))
11394 ;; add the next tags
11395 (when tags
11396 (setq tags (org-split-string tags ":")
11397 tags-alist
11398 (cons (cons level tags) tags-alist)))
11399 ;; compile tags for current headline
11400 (setq tags-list
11401 (if org-use-tag-inheritance
11402 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11403 tags)
11404 org-scanner-tags tags-list)
11405 (when org-use-tag-inheritance
11406 (setcdr (car tags-alist)
11407 (mapcar (lambda (x)
11408 (setq x (copy-sequence x))
11409 (org-add-prop-inherited x))
11410 (cdar tags-alist))))
11411 (when (and tags org-use-tag-inheritance
11412 (or (not (eq t org-use-tag-inheritance))
11413 org-tags-exclude-from-inheritance))
11414 ;; selective inheritance, remove uninherited ones
11415 (setcdr (car tags-alist)
11416 (org-remove-uniherited-tags (cdar tags-alist))))
11417 (when (and (or (not todo-only)
11418 (and (member todo org-not-done-keywords)
11419 (or (not org-agenda-tags-todo-honor-ignore-options)
11420 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11421 (let ((case-fold-search t)) (eval matcher))
11423 (not (member org-archive-tag tags-list))
11424 ;; we have an archive tag, should we use this anyway?
11425 (or (not org-agenda-skip-archived-trees)
11426 (and (eq action 'agenda) org-agenda-archives-mode))))
11427 (unless (eq action 'sparse-tree) (org-agenda-skip))
11429 ;; select this headline
11431 (cond
11432 ((eq action 'sparse-tree)
11433 (and org-highlight-sparse-tree-matches
11434 (org-get-heading) (match-end 0)
11435 (org-highlight-new-match
11436 (match-beginning 0) (match-beginning 1)))
11437 (org-show-context 'tags-tree))
11438 ((eq action 'agenda)
11439 (setq txt (org-format-agenda-item
11441 (concat
11442 (if (eq org-tags-match-list-sublevels 'indented)
11443 (make-string (1- level) ?.) "")
11444 (org-get-heading))
11445 category
11446 tags-list
11448 priority (org-get-priority txt))
11449 (goto-char lspos)
11450 (setq marker (org-agenda-new-marker))
11451 (org-add-props txt props
11452 'org-marker marker 'org-hd-marker marker 'org-category category
11453 'todo-state todo
11454 'priority priority 'type "tagsmatch")
11455 (push txt rtn))
11456 ((functionp action)
11457 (setq org-map-continue-from nil)
11458 (save-excursion
11459 (setq rtn1 (funcall action))
11460 (push rtn1 rtn)))
11461 (t (error "Invalid action")))
11463 ;; if we are to skip sublevels, jump to end of subtree
11464 (unless org-tags-match-list-sublevels
11465 (org-end-of-subtree t)
11466 (backward-char 1))))
11467 ;; Get the correct position from where to continue
11468 (if org-map-continue-from
11469 (goto-char org-map-continue-from)
11470 (and (= (point) lspos) (end-of-line 1)))))
11471 (when (and (eq action 'sparse-tree)
11472 (not org-sparse-tree-open-archived-trees))
11473 (org-hide-archived-subtrees (point-min) (point-max)))
11474 (nreverse rtn)))
11476 (defun org-remove-uniherited-tags (tags)
11477 "Remove all tags that are not inherited from the list TAGS."
11478 (cond
11479 ((eq org-use-tag-inheritance t)
11480 (if org-tags-exclude-from-inheritance
11481 (org-delete-all org-tags-exclude-from-inheritance tags)
11482 tags))
11483 ((not org-use-tag-inheritance) nil)
11484 ((stringp org-use-tag-inheritance)
11485 (delq nil (mapcar
11486 (lambda (x)
11487 (if (and (string-match org-use-tag-inheritance x)
11488 (not (member x org-tags-exclude-from-inheritance)))
11489 x nil))
11490 tags)))
11491 ((listp org-use-tag-inheritance)
11492 (delq nil (mapcar
11493 (lambda (x)
11494 (if (member x org-use-tag-inheritance) x nil))
11495 tags)))))
11497 (defvar todo-only) ;; dynamically scoped
11499 (defun org-match-sparse-tree (&optional todo-only match)
11500 "Create a sparse tree according to tags string MATCH.
11501 MATCH can contain positive and negative selection of tags, like
11502 \"+WORK+URGENT-WITHBOSS\".
11503 If optional argument TODO-ONLY is non-nil, only select lines that are
11504 also TODO lines."
11505 (interactive "P")
11506 (org-prepare-agenda-buffers (list (current-buffer)))
11507 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11509 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11511 (defvar org-cached-props nil)
11512 (defun org-cached-entry-get (pom property)
11513 (if (or (eq t org-use-property-inheritance)
11514 (and (stringp org-use-property-inheritance)
11515 (string-match org-use-property-inheritance property))
11516 (and (listp org-use-property-inheritance)
11517 (member property org-use-property-inheritance)))
11518 ;; Caching is not possible, check it directly
11519 (org-entry-get pom property 'inherit)
11520 ;; Get all properties, so that we can do complicated checks easily
11521 (cdr (assoc property (or org-cached-props
11522 (setq org-cached-props
11523 (org-entry-properties pom)))))))
11525 (defun org-global-tags-completion-table (&optional files)
11526 "Return the list of all tags in all agenda buffer/files."
11527 (save-excursion
11528 (org-uniquify
11529 (delq nil
11530 (apply 'append
11531 (mapcar
11532 (lambda (file)
11533 (set-buffer (find-file-noselect file))
11534 (append (org-get-buffer-tags)
11535 (mapcar (lambda (x) (if (stringp (car-safe x))
11536 (list (car-safe x)) nil))
11537 org-tag-alist)))
11538 (if (and files (car files))
11539 files
11540 (org-agenda-files))))))))
11542 (defun org-make-tags-matcher (match)
11543 "Create the TAGS//TODO matcher form for the selection string MATCH."
11544 ;; todo-only is scoped dynamically into this function, and the function
11545 ;; may change it if the matcher asks for it.
11546 (unless match
11547 ;; Get a new match request, with completion
11548 (let ((org-last-tags-completion-table
11549 (org-global-tags-completion-table)))
11550 (setq match (org-completing-read-no-i
11551 "Match: " 'org-tags-completion-function nil nil nil
11552 'org-tags-history))))
11554 ;; Parse the string and create a lisp form
11555 (let ((match0 match)
11556 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11557 minus tag mm
11558 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11559 orterms term orlist re-p str-p level-p level-op time-p
11560 prop-p pn pv po cat-p gv rest)
11561 (if (string-match "/+" match)
11562 ;; match contains also a todo-matching request
11563 (progn
11564 (setq tagsmatch (substring match 0 (match-beginning 0))
11565 todomatch (substring match (match-end 0)))
11566 (if (string-match "^!" todomatch)
11567 (setq todo-only t todomatch (substring todomatch 1)))
11568 (if (string-match "^\\s-*$" todomatch)
11569 (setq todomatch nil)))
11570 ;; only matching tags
11571 (setq tagsmatch match todomatch nil))
11573 ;; Make the tags matcher
11574 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11575 (setq tagsmatcher t)
11576 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11577 (while (setq term (pop orterms))
11578 (while (and (equal (substring term -1) "\\") orterms)
11579 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11580 (while (string-match re term)
11581 (setq rest (substring term (match-end 0))
11582 minus (and (match-end 1)
11583 (equal (match-string 1 term) "-"))
11584 tag (match-string 2 term)
11585 re-p (equal (string-to-char tag) ?{)
11586 level-p (match-end 4)
11587 prop-p (match-end 5)
11588 mm (cond
11589 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11590 (level-p
11591 (setq level-op (org-op-to-function (match-string 3 term)))
11592 `(,level-op level ,(string-to-number
11593 (match-string 4 term))))
11594 (prop-p
11595 (setq pn (match-string 5 term)
11596 po (match-string 6 term)
11597 pv (match-string 7 term)
11598 cat-p (equal pn "CATEGORY")
11599 re-p (equal (string-to-char pv) ?{)
11600 str-p (equal (string-to-char pv) ?\")
11601 time-p (save-match-data
11602 (string-match "^\"[[<].*[]>]\"$" pv))
11603 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11604 (if time-p (setq pv (org-matcher-time pv)))
11605 (setq po (org-op-to-function po (if time-p 'time str-p)))
11606 (cond
11607 ((equal pn "CATEGORY")
11608 (setq gv '(get-text-property (point) 'org-category)))
11609 ((equal pn "TODO")
11610 (setq gv 'todo))
11612 (setq gv `(org-cached-entry-get nil ,pn))))
11613 (if re-p
11614 (if (eq po 'org<>)
11615 `(not (string-match ,pv (or ,gv "")))
11616 `(string-match ,pv (or ,gv "")))
11617 (if str-p
11618 `(,po (or ,gv "") ,pv)
11619 `(,po (string-to-number (or ,gv ""))
11620 ,(string-to-number pv) ))))
11621 (t `(member ,tag tags-list)))
11622 mm (if minus (list 'not mm) mm)
11623 term rest)
11624 (push mm tagsmatcher))
11625 (push (if (> (length tagsmatcher) 1)
11626 (cons 'and tagsmatcher)
11627 (car tagsmatcher))
11628 orlist)
11629 (setq tagsmatcher nil))
11630 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11631 (setq tagsmatcher
11632 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11633 ;; Make the todo matcher
11634 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11635 (setq todomatcher t)
11636 (setq orterms (org-split-string todomatch "|") orlist nil)
11637 (while (setq term (pop orterms))
11638 (while (string-match re term)
11639 (setq minus (and (match-end 1)
11640 (equal (match-string 1 term) "-"))
11641 kwd (match-string 2 term)
11642 re-p (equal (string-to-char kwd) ?{)
11643 term (substring term (match-end 0))
11644 mm (if re-p
11645 `(string-match ,(substring kwd 1 -1) todo)
11646 (list 'equal 'todo kwd))
11647 mm (if minus (list 'not mm) mm))
11648 (push mm todomatcher))
11649 (push (if (> (length todomatcher) 1)
11650 (cons 'and todomatcher)
11651 (car todomatcher))
11652 orlist)
11653 (setq todomatcher nil))
11654 (setq todomatcher (if (> (length orlist) 1)
11655 (cons 'or orlist) (car orlist))))
11657 ;; Return the string and lisp forms of the matcher
11658 (setq matcher (if todomatcher
11659 (list 'and tagsmatcher todomatcher)
11660 tagsmatcher))
11661 (cons match0 matcher)))
11663 (defun org-op-to-function (op &optional stringp)
11664 "Turn an operator into the appropriate function."
11665 (setq op
11666 (cond
11667 ((equal op "<" ) '(< string< org-time<))
11668 ((equal op ">" ) '(> org-string> org-time>))
11669 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11670 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11671 ((member op '("=" "==")) '(= string= org-time=))
11672 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11673 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11675 (defun org<> (a b) (not (= a b)))
11676 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11677 (defun org-string>= (a b) (not (string< a b)))
11678 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11679 (defun org-string<> (a b) (not (string= a b)))
11680 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11681 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11682 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11683 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11684 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11685 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11686 (defun org-2ft (s)
11687 "Convert S to a floating point time.
11688 If S is already a number, just return it. If it is a string, parse
11689 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11690 (cond
11691 ((numberp s) s)
11692 ((stringp s)
11693 (condition-case nil
11694 (float-time (apply 'encode-time (org-parse-time-string s)))
11695 (error 0.)))
11696 (t 0.)))
11698 (defun org-time-today ()
11699 "Time in seconds today at 0:00.
11700 Returns the float number of seconds since the beginning of the
11701 epoch to the beginning of today (00:00)."
11702 (float-time (apply 'encode-time
11703 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11705 (defun org-matcher-time (s)
11706 "Interpret a time comparison value."
11707 (save-match-data
11708 (cond
11709 ((string= s "<now>") (float-time))
11710 ((string= s "<today>") (org-time-today))
11711 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11712 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11713 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11714 (+ (org-time-today)
11715 (* (string-to-number (match-string 1 s))
11716 (cdr (assoc (match-string 2 s)
11717 '(("d" . 86400.0) ("w" . 604800.0)
11718 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11719 (t (org-2ft s)))))
11721 (defun org-match-any-p (re list)
11722 "Does re match any element of list?"
11723 (setq list (mapcar (lambda (x) (string-match re x)) list))
11724 (delq nil list))
11726 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11727 (defvar org-tags-overlay (org-make-overlay 1 1))
11728 (org-detach-overlay org-tags-overlay)
11730 (defun org-get-local-tags-at (&optional pos)
11731 "Get a list of tags defined in the current headline."
11732 (org-get-tags-at pos 'local))
11734 (defun org-get-local-tags ()
11735 "Get a list of tags defined in the current headline."
11736 (org-get-tags-at nil 'local))
11738 (defun org-get-tags-at (&optional pos local)
11739 "Get a list of all headline tags applicable at POS.
11740 POS defaults to point. If tags are inherited, the list contains
11741 the targets in the same sequence as the headlines appear, i.e.
11742 the tags of the current headline come last.
11743 When LOCAL is non-nil, only return tags from the current headline,
11744 ignore inherited ones."
11745 (interactive)
11746 (if (and org-trust-scanner-tags
11747 (or (not pos) (equal pos (point)))
11748 (not local))
11749 org-scanner-tags
11750 (let (tags ltags lastpos parent)
11751 (save-excursion
11752 (save-restriction
11753 (widen)
11754 (goto-char (or pos (point)))
11755 (save-match-data
11756 (catch 'done
11757 (condition-case nil
11758 (progn
11759 (org-back-to-heading t)
11760 (while (not (equal lastpos (point)))
11761 (setq lastpos (point))
11762 (when (looking-at
11763 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11764 (setq ltags (org-split-string
11765 (org-match-string-no-properties 1) ":"))
11766 (when parent
11767 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11768 (setq tags (append
11769 (if parent
11770 (org-remove-uniherited-tags ltags)
11771 ltags)
11772 tags)))
11773 (or org-use-tag-inheritance (throw 'done t))
11774 (if local (throw 'done t))
11775 (or (org-up-heading-safe) (error nil))
11776 (setq parent t)))
11777 (error nil)))))
11778 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11780 (defun org-add-prop-inherited (s)
11781 (add-text-properties 0 (length s) '(inherited t) s)
11784 (defun org-toggle-tag (tag &optional onoff)
11785 "Toggle the tag TAG for the current line.
11786 If ONOFF is `on' or `off', don't toggle but set to this state."
11787 (let (res current)
11788 (save-excursion
11789 (org-back-to-heading t)
11790 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11791 (point-at-eol) t)
11792 (progn
11793 (setq current (match-string 1))
11794 (replace-match ""))
11795 (setq current ""))
11796 (setq current (nreverse (org-split-string current ":")))
11797 (cond
11798 ((eq onoff 'on)
11799 (setq res t)
11800 (or (member tag current) (push tag current)))
11801 ((eq onoff 'off)
11802 (or (not (member tag current)) (setq current (delete tag current))))
11803 (t (if (member tag current)
11804 (setq current (delete tag current))
11805 (setq res t)
11806 (push tag current))))
11807 (end-of-line 1)
11808 (if current
11809 (progn
11810 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11811 (org-set-tags nil t))
11812 (delete-horizontal-space))
11813 (run-hooks 'org-after-tags-change-hook))
11814 res))
11816 (defun org-align-tags-here (to-col)
11817 ;; Assumes that this is a headline
11818 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11819 (beginning-of-line 1)
11820 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11821 (< pos (match-beginning 2)))
11822 (progn
11823 (setq tags-l (- (match-end 2) (match-beginning 2)))
11824 (goto-char (match-beginning 1))
11825 (insert " ")
11826 (delete-region (point) (1+ (match-beginning 2)))
11827 (setq ncol (max (1+ (current-column))
11828 (1+ col)
11829 (if (> to-col 0)
11830 to-col
11831 (- (abs to-col) tags-l))))
11832 (setq p (point))
11833 (insert (make-string (- ncol (current-column)) ?\ ))
11834 (setq ncol (current-column))
11835 (when indent-tabs-mode (tabify p (point-at-eol)))
11836 (org-move-to-column (min ncol col) t))
11837 (goto-char pos))))
11839 (defun org-set-tags-command (&optional arg just-align)
11840 "Call the set-tags command for the current entry."
11841 (interactive "P")
11842 (if (org-on-heading-p)
11843 (org-set-tags arg just-align)
11844 (save-excursion
11845 (org-back-to-heading t)
11846 (org-set-tags arg just-align))))
11848 (defun org-set-tags-to (data)
11849 "Set the tags of the current entry to DATA, replacing the current tags.
11850 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11851 If DATA is nil or the empty string, any tags will be removed."
11852 (interactive "sTags: ")
11853 (setq data
11854 (cond
11855 ((eq data nil) "")
11856 ((equal data "") "")
11857 ((stringp data)
11858 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11859 ":"))
11860 ((listp data)
11861 (concat ":" (mapconcat 'identity data ":") ":"))
11862 (t nil)))
11863 (when data
11864 (save-excursion
11865 (org-back-to-heading t)
11866 (when (looking-at org-complex-heading-regexp)
11867 (if (match-end 5)
11868 (progn
11869 (goto-char (match-beginning 5))
11870 (insert data)
11871 (delete-region (point) (point-at-eol))
11872 (org-set-tags nil 'align))
11873 (goto-char (point-at-eol))
11874 (insert " " data)
11875 (org-set-tags nil 'align)))
11876 (beginning-of-line 1)
11877 (if (looking-at ".*?\\([ \t]+\\)$")
11878 (delete-region (match-beginning 1) (match-end 1))))))
11880 (defun org-set-tags (&optional arg just-align)
11881 "Set the tags for the current headline.
11882 With prefix ARG, realign all tags in headings in the current buffer."
11883 (interactive "P")
11884 (let* ((re (concat "^" outline-regexp))
11885 (current (org-get-tags-string))
11886 (col (current-column))
11887 (org-setting-tags t)
11888 table current-tags inherited-tags ; computed below when needed
11889 tags p0 c0 c1 rpl)
11890 (if arg
11891 (save-excursion
11892 (goto-char (point-min))
11893 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11894 (while (re-search-forward re nil t)
11895 (org-set-tags nil t)
11896 (end-of-line 1)))
11897 (message "All tags realigned to column %d" org-tags-column))
11898 (if just-align
11899 (setq tags current)
11900 ;; Get a new set of tags from the user
11901 (save-excursion
11902 (setq table (append org-tag-persistent-alist
11903 (or org-tag-alist (org-get-buffer-tags))
11904 (and org-complete-tags-always-offer-all-agenda-tags
11905 (org-global-tags-completion-table (org-agenda-files))))
11906 org-last-tags-completion-table table
11907 current-tags (org-split-string current ":")
11908 inherited-tags (nreverse
11909 (nthcdr (length current-tags)
11910 (nreverse (org-get-tags-at))))
11911 tags
11912 (if (or (eq t org-use-fast-tag-selection)
11913 (and org-use-fast-tag-selection
11914 (delq nil (mapcar 'cdr table))))
11915 (org-fast-tag-selection
11916 current-tags inherited-tags table
11917 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11918 (let ((org-add-colon-after-tag-completion t))
11919 (org-trim
11920 (org-without-partial-completion
11921 (org-icompleting-read "Tags: " 'org-tags-completion-function
11922 nil nil current 'org-tags-history)))))))
11923 (while (string-match "[-+&]+" tags)
11924 ;; No boolean logic, just a list
11925 (setq tags (replace-match ":" t t tags))))
11927 (if org-tags-sort-function
11928 (setq tags (mapconcat 'identity
11929 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11930 org-tags-sort-function) ":")))
11932 (if (string-match "\\`[\t ]*\\'" tags)
11933 (setq tags "")
11934 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11935 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11937 ;; Insert new tags at the correct column
11938 (beginning-of-line 1)
11939 (cond
11940 ((and (equal current "") (equal tags "")))
11941 ((re-search-forward
11942 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11943 (point-at-eol) t)
11944 (if (equal tags "")
11945 (setq rpl "")
11946 (goto-char (match-beginning 0))
11947 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11948 (1+ (point)) (point))
11949 c1 (max (1+ c0) (if (> org-tags-column 0)
11950 org-tags-column
11951 (- (- org-tags-column) (length tags))))
11952 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11953 (replace-match rpl t t)
11954 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11955 tags)
11956 (t (error "Tags alignment failed")))
11957 (org-move-to-column col)
11958 (unless just-align
11959 (run-hooks 'org-after-tags-change-hook)))))
11961 (defun org-change-tag-in-region (beg end tag off)
11962 "Add or remove TAG for each entry in the region.
11963 This works in the agenda, and also in an org-mode buffer."
11964 (interactive
11965 (list (region-beginning) (region-end)
11966 (let ((org-last-tags-completion-table
11967 (if (org-mode-p)
11968 (org-get-buffer-tags)
11969 (org-global-tags-completion-table))))
11970 (org-icompleting-read
11971 "Tag: " 'org-tags-completion-function nil nil nil
11972 'org-tags-history))
11973 (progn
11974 (message "[s]et or [r]emove? ")
11975 (equal (read-char-exclusive) ?r))))
11976 (if (fboundp 'deactivate-mark) (deactivate-mark))
11977 (let ((agendap (equal major-mode 'org-agenda-mode))
11978 l1 l2 m buf pos newhead (cnt 0))
11979 (goto-char end)
11980 (setq l2 (1- (org-current-line)))
11981 (goto-char beg)
11982 (setq l1 (org-current-line))
11983 (loop for l from l1 to l2 do
11984 (org-goto-line l)
11985 (setq m (get-text-property (point) 'org-hd-marker))
11986 (when (or (and (org-mode-p) (org-on-heading-p))
11987 (and agendap m))
11988 (setq buf (if agendap (marker-buffer m) (current-buffer))
11989 pos (if agendap m (point)))
11990 (with-current-buffer buf
11991 (save-excursion
11992 (save-restriction
11993 (goto-char pos)
11994 (setq cnt (1+ cnt))
11995 (org-toggle-tag tag (if off 'off 'on))
11996 (setq newhead (org-get-heading)))))
11997 (and agendap (org-agenda-change-all-lines newhead m))))
11998 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12000 (defun org-tags-completion-function (string predicate &optional flag)
12001 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12002 (confirm (lambda (x) (stringp (car x)))))
12003 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12004 (setq s1 (match-string 1 string)
12005 s2 (match-string 2 string))
12006 (setq s1 "" s2 string))
12007 (cond
12008 ((eq flag nil)
12009 ;; try completion
12010 (setq rtn (try-completion s2 ctable confirm))
12011 (if (stringp rtn)
12012 (setq rtn
12013 (concat s1 s2 (substring rtn (length s2))
12014 (if (and org-add-colon-after-tag-completion
12015 (assoc rtn ctable))
12016 ":" ""))))
12017 rtn)
12018 ((eq flag t)
12019 ;; all-completions
12020 (all-completions s2 ctable confirm)
12022 ((eq flag 'lambda)
12023 ;; exact match?
12024 (assoc s2 ctable)))
12027 (defun org-fast-tag-insert (kwd tags face &optional end)
12028 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12029 (insert (format "%-12s" (concat kwd ":"))
12030 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12031 (or end "")))
12033 (defun org-fast-tag-show-exit (flag)
12034 (save-excursion
12035 (org-goto-line 3)
12036 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12037 (replace-match ""))
12038 (when flag
12039 (end-of-line 1)
12040 (org-move-to-column (- (window-width) 19) t)
12041 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12043 (defun org-set-current-tags-overlay (current prefix)
12044 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12045 (if (featurep 'xemacs)
12046 (org-overlay-display org-tags-overlay (concat prefix s)
12047 'secondary-selection)
12048 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12049 (org-overlay-display org-tags-overlay (concat prefix s)))))
12051 (defvar org-last-tag-selection-key nil)
12052 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12053 "Fast tag selection with single keys.
12054 CURRENT is the current list of tags in the headline, INHERITED is the
12055 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12056 possibly with grouping information. TODO-TABLE is a similar table with
12057 TODO keywords, should these have keys assigned to them.
12058 If the keys are nil, a-z are automatically assigned.
12059 Returns the new tags string, or nil to not change the current settings."
12060 (let* ((fulltable (append table todo-table))
12061 (maxlen (apply 'max (mapcar
12062 (lambda (x)
12063 (if (stringp (car x)) (string-width (car x)) 0))
12064 fulltable)))
12065 (buf (current-buffer))
12066 (expert (eq org-fast-tag-selection-single-key 'expert))
12067 (buffer-tags nil)
12068 (fwidth (+ maxlen 3 1 3))
12069 (ncol (/ (- (window-width) 4) fwidth))
12070 (i-face 'org-done)
12071 (c-face 'org-todo)
12072 tg cnt e c char c1 c2 ntable tbl rtn
12073 ov-start ov-end ov-prefix
12074 (exit-after-next org-fast-tag-selection-single-key)
12075 (done-keywords org-done-keywords)
12076 groups ingroup)
12077 (save-excursion
12078 (beginning-of-line 1)
12079 (if (looking-at
12080 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12081 (setq ov-start (match-beginning 1)
12082 ov-end (match-end 1)
12083 ov-prefix "")
12084 (setq ov-start (1- (point-at-eol))
12085 ov-end (1+ ov-start))
12086 (skip-chars-forward "^\n\r")
12087 (setq ov-prefix
12088 (concat
12089 (buffer-substring (1- (point)) (point))
12090 (if (> (current-column) org-tags-column)
12092 (make-string (- org-tags-column (current-column)) ?\ ))))))
12093 (org-move-overlay org-tags-overlay ov-start ov-end)
12094 (save-window-excursion
12095 (if expert
12096 (set-buffer (get-buffer-create " *Org tags*"))
12097 (delete-other-windows)
12098 (split-window-vertically)
12099 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12100 (erase-buffer)
12101 (org-set-local 'org-done-keywords done-keywords)
12102 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12103 (org-fast-tag-insert "Current" current c-face "\n\n")
12104 (org-fast-tag-show-exit exit-after-next)
12105 (org-set-current-tags-overlay current ov-prefix)
12106 (setq tbl fulltable char ?a cnt 0)
12107 (while (setq e (pop tbl))
12108 (cond
12109 ((equal (car e) :startgroup)
12110 (push '() groups) (setq ingroup t)
12111 (when (not (= cnt 0))
12112 (setq cnt 0)
12113 (insert "\n"))
12114 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12115 ((equal (car e) :endgroup)
12116 (setq ingroup nil cnt 0)
12117 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12118 ((equal e '(:newline))
12119 (when (not (= cnt 0))
12120 (setq cnt 0)
12121 (insert "\n")
12122 (setq e (car tbl))
12123 (while (equal (car tbl) '(:newline))
12124 (insert "\n")
12125 (setq tbl (cdr tbl)))))
12127 (setq tg (copy-sequence (car e)) c2 nil)
12128 (if (cdr e)
12129 (setq c (cdr e))
12130 ;; automatically assign a character.
12131 (setq c1 (string-to-char
12132 (downcase (substring
12133 tg (if (= (string-to-char tg) ?@) 1 0)))))
12134 (if (or (rassoc c1 ntable) (rassoc c1 table))
12135 (while (or (rassoc char ntable) (rassoc char table))
12136 (setq char (1+ char)))
12137 (setq c2 c1))
12138 (setq c (or c2 char)))
12139 (if ingroup (push tg (car groups)))
12140 (setq tg (org-add-props tg nil 'face
12141 (cond
12142 ((not (assoc tg table))
12143 (org-get-todo-face tg))
12144 ((member tg current) c-face)
12145 ((member tg inherited) i-face)
12146 (t nil))))
12147 (if (and (= cnt 0) (not ingroup)) (insert " "))
12148 (insert "[" c "] " tg (make-string
12149 (- fwidth 4 (length tg)) ?\ ))
12150 (push (cons tg c) ntable)
12151 (when (= (setq cnt (1+ cnt)) ncol)
12152 (insert "\n")
12153 (if ingroup (insert " "))
12154 (setq cnt 0)))))
12155 (setq ntable (nreverse ntable))
12156 (insert "\n")
12157 (goto-char (point-min))
12158 (if (not expert) (org-fit-window-to-buffer))
12159 (setq rtn
12160 (catch 'exit
12161 (while t
12162 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12163 (if (not groups) "no " "")
12164 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12165 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12166 (setq org-last-tag-selection-key c)
12167 (cond
12168 ((= c ?\r) (throw 'exit t))
12169 ((= c ?!)
12170 (setq groups (not groups))
12171 (goto-char (point-min))
12172 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12173 ((= c ?\C-c)
12174 (if (not expert)
12175 (org-fast-tag-show-exit
12176 (setq exit-after-next (not exit-after-next)))
12177 (setq expert nil)
12178 (delete-other-windows)
12179 (split-window-vertically)
12180 (org-switch-to-buffer-other-window " *Org tags*")
12181 (org-fit-window-to-buffer)))
12182 ((or (= c ?\C-g)
12183 (and (= c ?q) (not (rassoc c ntable))))
12184 (org-detach-overlay org-tags-overlay)
12185 (setq quit-flag t))
12186 ((= c ?\ )
12187 (setq current nil)
12188 (if exit-after-next (setq exit-after-next 'now)))
12189 ((= c ?\t)
12190 (condition-case nil
12191 (setq tg (org-icompleting-read
12192 "Tag: "
12193 (or buffer-tags
12194 (with-current-buffer buf
12195 (org-get-buffer-tags)))))
12196 (quit (setq tg "")))
12197 (when (string-match "\\S-" tg)
12198 (add-to-list 'buffer-tags (list tg))
12199 (if (member tg current)
12200 (setq current (delete tg current))
12201 (push tg current)))
12202 (if exit-after-next (setq exit-after-next 'now)))
12203 ((setq e (rassoc c todo-table) tg (car e))
12204 (with-current-buffer buf
12205 (save-excursion (org-todo tg)))
12206 (if exit-after-next (setq exit-after-next 'now)))
12207 ((setq e (rassoc c ntable) tg (car e))
12208 (if (member tg current)
12209 (setq current (delete tg current))
12210 (loop for g in groups do
12211 (if (member tg g)
12212 (mapc (lambda (x)
12213 (setq current (delete x current)))
12214 g)))
12215 (push tg current))
12216 (if exit-after-next (setq exit-after-next 'now))))
12218 ;; Create a sorted list
12219 (setq current
12220 (sort current
12221 (lambda (a b)
12222 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12223 (if (eq exit-after-next 'now) (throw 'exit t))
12224 (goto-char (point-min))
12225 (beginning-of-line 2)
12226 (delete-region (point) (point-at-eol))
12227 (org-fast-tag-insert "Current" current c-face)
12228 (org-set-current-tags-overlay current ov-prefix)
12229 (while (re-search-forward
12230 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12231 (setq tg (match-string 1))
12232 (add-text-properties
12233 (match-beginning 1) (match-end 1)
12234 (list 'face
12235 (cond
12236 ((member tg current) c-face)
12237 ((member tg inherited) i-face)
12238 (t (get-text-property (match-beginning 1) 'face))))))
12239 (goto-char (point-min)))))
12240 (org-detach-overlay org-tags-overlay)
12241 (if rtn
12242 (mapconcat 'identity current ":")
12243 nil))))
12245 (defun org-get-tags-string ()
12246 "Get the TAGS string in the current headline."
12247 (unless (org-on-heading-p t)
12248 (error "Not on a heading"))
12249 (save-excursion
12250 (beginning-of-line 1)
12251 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12252 (org-match-string-no-properties 1)
12253 "")))
12255 (defun org-get-tags ()
12256 "Get the list of tags specified in the current headline."
12257 (org-split-string (org-get-tags-string) ":"))
12259 (defun org-get-buffer-tags ()
12260 "Get a table of all tags used in the buffer, for completion."
12261 (let (tags)
12262 (save-excursion
12263 (goto-char (point-min))
12264 (while (re-search-forward
12265 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12266 (when (equal (char-after (point-at-bol 0)) ?*)
12267 (mapc (lambda (x) (add-to-list 'tags x))
12268 (org-split-string (org-match-string-no-properties 1) ":")))))
12269 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12270 (mapcar 'list tags)))
12272 ;;;; The mapping API
12274 ;;;###autoload
12275 (defun org-map-entries (func &optional match scope &rest skip)
12276 "Call FUNC at each headline selected by MATCH in SCOPE.
12278 FUNC is a function or a lisp form. The function will be called without
12279 arguments, with the cursor positioned at the beginning of the headline.
12280 The return values of all calls to the function will be collected and
12281 returned as a list.
12283 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12284 does not need to preserve point. After evaluation, the cursor will be
12285 moved to the end of the line (presumably of the headline of the
12286 processed entry) and search continues from there. Under some
12287 circumstances, this may not produce the wanted results. For example,
12288 if you have removed (e.g. archived) the current (sub)tree it could
12289 mean that the next entry will be skipped entirely. In such cases, you
12290 can specify the position from where search should continue by making
12291 FUNC set the variable `org-map-continue-from' to the desired buffer
12292 position.
12294 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12295 Only headlines that are matched by this query will be considered during
12296 the iteration. When MATCH is nil or t, all headlines will be
12297 visited by the iteration.
12299 SCOPE determines the scope of this command. It can be any of:
12301 nil The current buffer, respecting the restriction if any
12302 tree The subtree started with the entry at point
12303 file The current buffer, without restriction
12304 file-with-archives
12305 The current buffer, and any archives associated with it
12306 agenda All agenda files
12307 agenda-with-archives
12308 All agenda files with any archive files associated with them
12309 \(file1 file2 ...)
12310 If this is a list, all files in the list will be scanned
12312 The remaining args are treated as settings for the skipping facilities of
12313 the scanner. The following items can be given here:
12315 archive skip trees with the archive tag.
12316 comment skip trees with the COMMENT keyword
12317 function or Emacs Lisp form:
12318 will be used as value for `org-agenda-skip-function', so whenever
12319 the function returns t, FUNC will not be called for that
12320 entry and search will continue from the point where the
12321 function leaves it.
12323 If your function needs to retrieve the tags including inherited tags
12324 at the *current* entry, you can use the value of the variable
12325 `org-scanner-tags' which will be much faster than getting the value
12326 with `org-get-tags-at'. If your function gets properties with
12327 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12328 to t around the call to `org-entry-properties' to get the same speedup.
12329 Note that if your function moves around to retrieve tags and properties at
12330 a *different* entry, you cannot use these techniques."
12331 (let* ((org-agenda-archives-mode nil) ; just to make sure
12332 (org-agenda-skip-archived-trees (memq 'archive skip))
12333 (org-agenda-skip-comment-trees (memq 'comment skip))
12334 (org-agenda-skip-function
12335 (car (org-delete-all '(comment archive) skip)))
12336 (org-tags-match-list-sublevels t)
12337 matcher file res
12338 org-todo-keywords-for-agenda
12339 org-done-keywords-for-agenda
12340 org-todo-keyword-alist-for-agenda
12341 org-drawers-for-agenda
12342 org-tag-alist-for-agenda)
12344 (cond
12345 ((eq match t) (setq matcher t))
12346 ((eq match nil) (setq matcher t))
12347 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12349 (save-excursion
12350 (save-restriction
12351 (when (eq scope 'tree)
12352 (org-back-to-heading t)
12353 (org-narrow-to-subtree)
12354 (setq scope nil))
12356 (if (not scope)
12357 (progn
12358 (org-prepare-agenda-buffers
12359 (list (buffer-file-name (current-buffer))))
12360 (setq res (org-scan-tags func matcher)))
12361 ;; Get the right scope
12362 (cond
12363 ((and scope (listp scope) (symbolp (car scope)))
12364 (setq scope (eval scope)))
12365 ((eq scope 'agenda)
12366 (setq scope (org-agenda-files t)))
12367 ((eq scope 'agenda-with-archives)
12368 (setq scope (org-agenda-files t))
12369 (setq scope (org-add-archive-files scope)))
12370 ((eq scope 'file)
12371 (setq scope (list (buffer-file-name))))
12372 ((eq scope 'file-with-archives)
12373 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12374 (org-prepare-agenda-buffers scope)
12375 (while (setq file (pop scope))
12376 (with-current-buffer (org-find-base-buffer-visiting file)
12377 (save-excursion
12378 (save-restriction
12379 (widen)
12380 (goto-char (point-min))
12381 (setq res (append res (org-scan-tags func matcher))))))))))
12382 res))
12384 ;;;; Properties
12386 ;;; Setting and retrieving properties
12388 (defconst org-special-properties
12389 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12390 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12391 "The special properties valid in Org-mode.
12393 These are properties that are not defined in the property drawer,
12394 but in some other way.")
12396 (defconst org-default-properties
12397 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12398 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12399 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12400 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12401 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12402 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12403 "Some properties that are used by Org-mode for various purposes.
12404 Being in this list makes sure that they are offered for completion.")
12406 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12407 "Regular expression matching the first line of a property drawer.")
12409 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12410 "Regular expression matching the first line of a property drawer.")
12412 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12413 "Regular expression matching the first line of a property drawer.")
12415 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12416 "Regular expression matching the first line of a property drawer.")
12418 (defconst org-property-drawer-re
12419 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12420 org-property-end-re "\\)\n?")
12421 "Matches an entire property drawer.")
12423 (defconst org-clock-drawer-re
12424 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12425 org-property-end-re "\\)\n?")
12426 "Matches an entire clock drawer.")
12428 (defun org-property-action ()
12429 "Do an action on properties."
12430 (interactive)
12431 (let (c)
12432 (org-at-property-p)
12433 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12434 (setq c (read-char-exclusive))
12435 (cond
12436 ((equal c ?s)
12437 (call-interactively 'org-set-property))
12438 ((equal c ?d)
12439 (call-interactively 'org-delete-property))
12440 ((equal c ?D)
12441 (call-interactively 'org-delete-property-globally))
12442 ((equal c ?c)
12443 (call-interactively 'org-compute-property-at-point))
12444 (t (error "No such property action %c" c)))))
12446 (defun org-set-effort (&optional value)
12447 "Set the effort property of the current entry.
12448 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12449 allowed value."
12450 (interactive "P")
12451 (if (equal value 0) (setq value 10))
12452 (let* ((completion-ignore-case t)
12453 (prop org-effort-property)
12454 (cur (org-entry-get nil prop))
12455 (allowed (org-property-get-allowed-values nil prop 'table))
12456 (existing (mapcar 'list (org-property-values prop)))
12458 (val (cond
12459 ((stringp value) value)
12460 ((and allowed (integerp value))
12461 (or (car (nth (1- value) allowed))
12462 (car (org-last allowed))))
12463 (allowed
12464 (message "Select 1-9,0, [RET%s]: %s"
12465 (if cur (concat "=" cur) "")
12466 (mapconcat 'car allowed " "))
12467 (setq rpl (read-char-exclusive))
12468 (if (equal rpl ?\r)
12470 (setq rpl (- rpl ?0))
12471 (if (equal rpl 0) (setq rpl 10))
12472 (if (and (> rpl 0) (<= rpl (length allowed)))
12473 (car (nth (1- rpl) allowed))
12474 (org-completing-read "Effort: " allowed nil))))
12476 (let (org-completion-use-ido org-completion-use-iswitchb)
12477 (org-completing-read
12478 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12479 (concat "[" cur "]") "")
12480 ": ")
12481 existing nil nil "" nil cur))))))
12482 (unless (equal (org-entry-get nil prop) val)
12483 (org-entry-put nil prop val))
12484 (message "%s is now %s" prop val)))
12486 (defun org-at-property-p ()
12487 "Is the cursor in a property line?"
12488 ;; FIXME: Does not check if we are actually in the drawer.
12489 ;; FIXME: also returns true on any drawers.....
12490 ;; This is used by C-c C-c for property action.
12491 (save-excursion
12492 (beginning-of-line 1)
12493 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12495 (defun org-get-property-block (&optional beg end force)
12496 "Return the (beg . end) range of the body of the property drawer.
12497 BEG and END can be beginning and end of subtree, if not given
12498 they will be found.
12499 If the drawer does not exist and FORCE is non-nil, create the drawer."
12500 (catch 'exit
12501 (save-excursion
12502 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12503 (end (or end (progn (outline-next-heading) (point)))))
12504 (goto-char beg)
12505 (if (re-search-forward org-property-start-re end t)
12506 (setq beg (1+ (match-end 0)))
12507 (if force
12508 (save-excursion
12509 (org-insert-property-drawer)
12510 (setq end (progn (outline-next-heading) (point))))
12511 (throw 'exit nil))
12512 (goto-char beg)
12513 (if (re-search-forward org-property-start-re end t)
12514 (setq beg (1+ (match-end 0)))))
12515 (if (re-search-forward org-property-end-re end t)
12516 (setq end (match-beginning 0))
12517 (or force (throw 'exit nil))
12518 (goto-char beg)
12519 (setq end beg)
12520 (org-indent-line-function)
12521 (insert ":END:\n"))
12522 (cons beg end)))))
12524 (defun org-entry-properties (&optional pom which specific)
12525 "Get all properties of the entry at point-or-marker POM.
12526 This includes the TODO keyword, the tags, time strings for deadline,
12527 scheduled, and clocking, and any additional properties defined in the
12528 entry. The return value is an alist, keys may occur multiple times
12529 if the property key was used several times.
12530 POM may also be nil, in which case the current entry is used.
12531 If WHICH is nil or `all', get all properties. If WHICH is
12532 `special' or `standard', only get that subclass. If WHICH
12533 is a string only get exactly this property. Specific can be a string, the
12534 specific property we are interested in. Specifying it can speed
12535 things up because then unnecessary parsing is avoided."
12536 (setq which (or which 'all))
12537 (org-with-point-at pom
12538 (let ((clockstr (substring org-clock-string 0 -1))
12539 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12540 (case-fold-search nil)
12541 beg end range props sum-props key value string clocksum)
12542 (save-excursion
12543 (when (condition-case nil
12544 (and (org-mode-p) (org-back-to-heading t))
12545 (error nil))
12546 (setq beg (point))
12547 (setq sum-props (get-text-property (point) 'org-summaries))
12548 (setq clocksum (get-text-property (point) :org-clock-minutes))
12549 (outline-next-heading)
12550 (setq end (point))
12551 (when (memq which '(all special))
12552 ;; Get the special properties, like TODO and tags
12553 (goto-char beg)
12554 (when (and (or (not specific) (string= specific "TODO"))
12555 (looking-at org-todo-line-regexp) (match-end 2))
12556 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12557 (when (and (or (not specific) (string= specific "PRIORITY"))
12558 (looking-at org-priority-regexp))
12559 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12560 (when (and (or (not specific) (string= specific "TAGS"))
12561 (setq value (org-get-tags-string))
12562 (string-match "\\S-" value))
12563 (push (cons "TAGS" value) props))
12564 (when (and (or (not specific) (string= specific "ALLTAGS"))
12565 (setq value (org-get-tags-at)))
12566 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12567 ":"))
12568 props))
12569 (when (or (not specific) (string= specific "BLOCKED"))
12570 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12571 (when (or (not specific)
12572 (member specific org-all-time-keywords)
12573 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12574 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12575 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12576 string (if (equal key clockstr)
12577 (org-no-properties
12578 (org-trim
12579 (buffer-substring
12580 (match-beginning 3) (goto-char (point-at-eol)))))
12581 (substring (org-match-string-no-properties 3) 1 -1)))
12582 (unless key
12583 (if (= (char-after (match-beginning 3)) ?\[)
12584 (setq key "TIMESTAMP_IA")
12585 (setq key "TIMESTAMP")))
12586 (when (or (equal key clockstr) (not (assoc key props)))
12587 (push (cons key string) props))))
12591 (when (memq which '(all standard))
12592 ;; Get the standard properties, like :PROP: ...
12593 (setq range (org-get-property-block beg end))
12594 (when range
12595 (goto-char (car range))
12596 (while (re-search-forward
12597 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12598 (cdr range) t)
12599 (setq key (org-match-string-no-properties 1)
12600 value (org-trim (or (org-match-string-no-properties 2) "")))
12601 (unless (member key excluded)
12602 (push (cons key (or value "")) props)))))
12603 (if clocksum
12604 (push (cons "CLOCKSUM"
12605 (org-columns-number-to-string (/ (float clocksum) 60.)
12606 'add_times))
12607 props))
12608 (unless (assoc "CATEGORY" props)
12609 (setq value (or (org-get-category)
12610 (progn (org-refresh-category-properties)
12611 (org-get-category))))
12612 (push (cons "CATEGORY" value) props))
12613 (append sum-props (nreverse props)))))))
12615 (defun org-entry-get (pom property &optional inherit)
12616 "Get value of PROPERTY for entry at point-or-marker POM.
12617 If INHERIT is non-nil and the entry does not have the property,
12618 then also check higher levels of the hierarchy.
12619 If INHERIT is the symbol `selective', use inheritance only if the setting
12620 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12621 If the property is present but empty, the return value is the empty string.
12622 If the property is not present at all, nil is returned."
12623 (org-with-point-at pom
12624 (if (and inherit (if (eq inherit 'selective)
12625 (org-property-inherit-p property)
12627 (org-entry-get-with-inheritance property)
12628 (if (member property org-special-properties)
12629 ;; We need a special property. Use `org-entry-properties' to
12630 ;; retrieve it, but specify the wanted property
12631 (cdr (assoc property (org-entry-properties nil 'special property)))
12632 (let ((range (org-get-property-block)))
12633 (if (and range
12634 (goto-char (car range))
12635 (re-search-forward
12636 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12637 (cdr range) t))
12638 ;; Found the property, return it.
12639 (if (match-end 1)
12640 (org-match-string-no-properties 1)
12641 "")))))))
12643 (defun org-property-or-variable-value (var &optional inherit)
12644 "Check if there is a property fixing the value of VAR.
12645 If yes, return this value. If not, return the current value of the variable."
12646 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12647 (if (and prop (stringp prop) (string-match "\\S-" prop))
12648 (read prop)
12649 (symbol-value var))))
12651 (defun org-entry-delete (pom property)
12652 "Delete the property PROPERTY from entry at point-or-marker POM."
12653 (org-with-point-at pom
12654 (if (member property org-special-properties)
12655 nil ; cannot delete these properties.
12656 (let ((range (org-get-property-block)))
12657 (if (and range
12658 (goto-char (car range))
12659 (re-search-forward
12660 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12661 (cdr range) t))
12662 (progn
12663 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12665 nil)))))
12667 ;; Multi-values properties are properties that contain multiple values
12668 ;; These values are assumed to be single words, separated by whitespace.
12669 (defun org-entry-add-to-multivalued-property (pom property value)
12670 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12671 (let* ((old (org-entry-get pom property))
12672 (values (and old (org-split-string old "[ \t]"))))
12673 (setq value (org-entry-protect-space value))
12674 (unless (member value values)
12675 (setq values (cons value values))
12676 (org-entry-put pom property
12677 (mapconcat 'identity values " ")))))
12679 (defun org-entry-remove-from-multivalued-property (pom property value)
12680 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12681 (let* ((old (org-entry-get pom property))
12682 (values (and old (org-split-string old "[ \t]"))))
12683 (setq value (org-entry-protect-space value))
12684 (when (member value values)
12685 (setq values (delete value values))
12686 (org-entry-put pom property
12687 (mapconcat 'identity values " ")))))
12689 (defun org-entry-member-in-multivalued-property (pom property value)
12690 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12691 (let* ((old (org-entry-get pom property))
12692 (values (and old (org-split-string old "[ \t]"))))
12693 (setq value (org-entry-protect-space value))
12694 (member value values)))
12696 (defun org-entry-get-multivalued-property (pom property)
12697 "Return a list of values in a multivalued property."
12698 (let* ((value (org-entry-get pom property))
12699 (values (and value (org-split-string value "[ \t]"))))
12700 (mapcar 'org-entry-restore-space values)))
12702 (defun org-entry-put-multivalued-property (pom property &rest values)
12703 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12704 VALUES should be a list of strings. Spaces will be protected."
12705 (org-entry-put pom property
12706 (mapconcat 'org-entry-protect-space values " "))
12707 (let* ((value (org-entry-get pom property))
12708 (values (and value (org-split-string value "[ \t]"))))
12709 (mapcar 'org-entry-restore-space values)))
12711 (defun org-entry-protect-space (s)
12712 "Protect spaces and newline in string S."
12713 (while (string-match " " s)
12714 (setq s (replace-match "%20" t t s)))
12715 (while (string-match "\n" s)
12716 (setq s (replace-match "%0A" t t s)))
12719 (defun org-entry-restore-space (s)
12720 "Restore spaces and newline in string S."
12721 (while (string-match "%20" s)
12722 (setq s (replace-match " " t t s)))
12723 (while (string-match "%0A" s)
12724 (setq s (replace-match "\n" t t s)))
12727 (defvar org-entry-property-inherited-from (make-marker)
12728 "Marker pointing to the entry from where a property was inherited.
12729 Each call to `org-entry-get-with-inheritance' will set this marker to the
12730 location of the entry where the inheritance search matched. If there was
12731 no match, the marker will point nowhere.
12732 Note that also `org-entry-get' calls this function, if the INHERIT flag
12733 is set.")
12735 (defun org-entry-get-with-inheritance (property)
12736 "Get entry property, and search higher levels if not present."
12737 (move-marker org-entry-property-inherited-from nil)
12738 (let (tmp)
12739 (save-excursion
12740 (save-restriction
12741 (widen)
12742 (catch 'ex
12743 (while t
12744 (when (setq tmp (org-entry-get nil property))
12745 (org-back-to-heading t)
12746 (move-marker org-entry-property-inherited-from (point))
12747 (throw 'ex tmp))
12748 (or (org-up-heading-safe) (throw 'ex nil)))))
12749 (or tmp
12750 (cdr (assoc property org-file-properties))
12751 (cdr (assoc property org-global-properties))
12752 (cdr (assoc property org-global-properties-fixed))))))
12754 (defvar org-property-changed-functions nil
12755 "Hook called when the value of a property has changed.
12756 Each hook function should accept two arguments, the name of the property
12757 and the new value.")
12759 (defun org-entry-put (pom property value)
12760 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12761 (org-with-point-at pom
12762 (org-back-to-heading t)
12763 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12764 range)
12765 (cond
12766 ((equal property "TODO")
12767 (when (and (stringp value) (string-match "\\S-" value)
12768 (not (member value org-todo-keywords-1)))
12769 (error "\"%s\" is not a valid TODO state" value))
12770 (if (or (not value)
12771 (not (string-match "\\S-" value)))
12772 (setq value 'none))
12773 (org-todo value)
12774 (org-set-tags nil 'align))
12775 ((equal property "PRIORITY")
12776 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12777 (string-to-char value) ?\ ))
12778 (org-set-tags nil 'align))
12779 ((equal property "SCHEDULED")
12780 (if (re-search-forward org-scheduled-time-regexp end t)
12781 (cond
12782 ((eq value 'earlier) (org-timestamp-change -1 'day))
12783 ((eq value 'later) (org-timestamp-change 1 'day))
12784 (t (call-interactively 'org-schedule)))
12785 (call-interactively 'org-schedule)))
12786 ((equal property "DEADLINE")
12787 (if (re-search-forward org-deadline-time-regexp end t)
12788 (cond
12789 ((eq value 'earlier) (org-timestamp-change -1 'day))
12790 ((eq value 'later) (org-timestamp-change 1 'day))
12791 (t (call-interactively 'org-deadline)))
12792 (call-interactively 'org-deadline)))
12793 ((member property org-special-properties)
12794 (error "The %s property can not yet be set with `org-entry-put'"
12795 property))
12796 (t ; a non-special property
12797 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12798 (setq range (org-get-property-block beg end 'force))
12799 (goto-char (car range))
12800 (if (re-search-forward
12801 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12802 (progn
12803 (delete-region (match-beginning 1) (match-end 1))
12804 (goto-char (match-beginning 1)))
12805 (goto-char (cdr range))
12806 (insert "\n")
12807 (backward-char 1)
12808 (org-indent-line-function)
12809 (insert ":" property ":"))
12810 (and value (insert " " value))
12811 (org-indent-line-function)))))
12812 (run-hook-with-args 'org-property-changed-functions property value)))
12814 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12815 "Get all property keys in the current buffer.
12816 With INCLUDE-SPECIALS, also list the special properties that reflect things
12817 like tags and TODO state.
12818 With INCLUDE-DEFAULTS, also include properties that has special meaning
12819 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12820 With INCLUDE-COLUMNS, also include property names given in COLUMN
12821 formats in the current buffer."
12822 (let (rtn range cfmt s p)
12823 (save-excursion
12824 (save-restriction
12825 (widen)
12826 (goto-char (point-min))
12827 (while (re-search-forward org-property-start-re nil t)
12828 (setq range (org-get-property-block))
12829 (goto-char (car range))
12830 (while (re-search-forward
12831 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12832 (cdr range) t)
12833 (add-to-list 'rtn (org-match-string-no-properties 1)))
12834 (outline-next-heading))))
12836 (when include-specials
12837 (setq rtn (append org-special-properties rtn)))
12839 (when include-defaults
12840 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12841 (add-to-list 'rtn org-effort-property))
12843 (when include-columns
12844 (save-excursion
12845 (save-restriction
12846 (widen)
12847 (goto-char (point-min))
12848 (while (re-search-forward
12849 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12850 nil t)
12851 (setq cfmt (match-string 2) s 0)
12852 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12853 cfmt s)
12854 (setq s (match-end 0)
12855 p (match-string 1 cfmt))
12856 (unless (or (equal p "ITEM")
12857 (member p org-special-properties))
12858 (add-to-list 'rtn (match-string 1 cfmt))))))))
12860 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12862 (defun org-property-values (key)
12863 "Return a list of all values of property KEY."
12864 (save-excursion
12865 (save-restriction
12866 (widen)
12867 (goto-char (point-min))
12868 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12869 values)
12870 (while (re-search-forward re nil t)
12871 (add-to-list 'values (org-trim (match-string 1))))
12872 (delete "" values)))))
12874 (defun org-insert-property-drawer ()
12875 "Insert a property drawer into the current entry."
12876 (interactive)
12877 (org-back-to-heading t)
12878 (looking-at outline-regexp)
12879 (let ((indent (if org-adapt-indentation
12880 (- (match-end 0)(match-beginning 0))
12882 (beg (point))
12883 (re (concat "^[ \t]*" org-keyword-time-regexp))
12884 end hiddenp)
12885 (outline-next-heading)
12886 (setq end (point))
12887 (goto-char beg)
12888 (while (re-search-forward re end t))
12889 (setq hiddenp (org-invisible-p))
12890 (end-of-line 1)
12891 (and (equal (char-after) ?\n) (forward-char 1))
12892 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12893 (if (member (match-string 1) '("CLOCK:" ":END:"))
12894 ;; just skip this line
12895 (beginning-of-line 2)
12896 ;; Drawer start, find the end
12897 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12898 (beginning-of-line 1)))
12899 (org-skip-over-state-notes)
12900 (skip-chars-backward " \t\n\r")
12901 (if (eq (char-before) ?*) (forward-char 1))
12902 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12903 (beginning-of-line 0)
12904 (org-indent-to-column indent)
12905 (beginning-of-line 2)
12906 (org-indent-to-column indent)
12907 (beginning-of-line 0)
12908 (if hiddenp
12909 (save-excursion
12910 (org-back-to-heading t)
12911 (hide-entry))
12912 (org-flag-drawer t))))
12914 (defun org-set-property (property value)
12915 "In the current entry, set PROPERTY to VALUE.
12916 When called interactively, this will prompt for a property name, offering
12917 completion on existing and default properties. And then it will prompt
12918 for a value, offering completion either on allowed values (via an inherited
12919 xxx_ALL property) or on existing values in other instances of this property
12920 in the current file."
12921 (interactive
12922 (let* ((completion-ignore-case t)
12923 (keys (org-buffer-property-keys nil t t))
12924 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12925 (prop (if (member prop0 keys)
12926 prop0
12927 (or (cdr (assoc (downcase prop0)
12928 (mapcar (lambda (x) (cons (downcase x) x))
12929 keys)))
12930 prop0)))
12931 (cur (org-entry-get nil prop))
12932 (allowed (org-property-get-allowed-values nil prop 'table))
12933 (existing (mapcar 'list (org-property-values prop)))
12934 (val (if allowed
12935 (org-completing-read "Value: " allowed nil
12936 (not (get-text-property 0 'org-unrestricted
12937 (caar allowed))))
12938 (let (org-completion-use-ido org-completion-use-iswitchb)
12939 (org-completing-read
12940 (concat "Value " (if (and cur (string-match "\\S-" cur))
12941 (concat "[" cur "]") "")
12942 ": ")
12943 existing nil nil "" nil cur)))))
12944 (list prop (if (equal val "") cur val))))
12945 (unless (equal (org-entry-get nil property) value)
12946 (org-entry-put nil property value)))
12948 (defun org-delete-property (property)
12949 "In the current entry, delete PROPERTY."
12950 (interactive
12951 (let* ((completion-ignore-case t)
12952 (prop (org-icompleting-read
12953 "Property: " (org-entry-properties nil 'standard))))
12954 (list prop)))
12955 (message "Property %s %s" property
12956 (if (org-entry-delete nil property)
12957 "deleted"
12958 "was not present in the entry")))
12960 (defun org-delete-property-globally (property)
12961 "Remove PROPERTY globally, from all entries."
12962 (interactive
12963 (let* ((completion-ignore-case t)
12964 (prop (org-icompleting-read
12965 "Globally remove property: "
12966 (mapcar 'list (org-buffer-property-keys)))))
12967 (list prop)))
12968 (save-excursion
12969 (save-restriction
12970 (widen)
12971 (goto-char (point-min))
12972 (let ((cnt 0))
12973 (while (re-search-forward
12974 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12975 nil t)
12976 (setq cnt (1+ cnt))
12977 (replace-match ""))
12978 (message "Property \"%s\" removed from %d entries" property cnt)))))
12980 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12982 (defun org-compute-property-at-point ()
12983 "Compute the property at point.
12984 This looks for an enclosing column format, extracts the operator and
12985 then applies it to the property in the column format's scope."
12986 (interactive)
12987 (unless (org-at-property-p)
12988 (error "Not at a property"))
12989 (let ((prop (org-match-string-no-properties 2)))
12990 (org-columns-get-format-and-top-level)
12991 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12992 (error "No operator defined for property %s" prop))
12993 (org-columns-compute prop)))
12995 (defvar org-property-allowed-value-functions nil
12996 "Hook for functions supplying allowed values for a specific property.
12997 The functions must take a single argument, the name of the property, and
12998 return a flat list of allowed values. If \":ETC\" is one of
12999 the values, this means that these values are intended as defaults for
13000 completion, but that other values should be allowed too.
13001 The functions must return nil if they are not responsible for this
13002 property.")
13004 (defun org-property-get-allowed-values (pom property &optional table)
13005 "Get allowed values for the property PROPERTY.
13006 When TABLE is non-nil, return an alist that can directly be used for
13007 completion."
13008 (let (vals)
13009 (cond
13010 ((equal property "TODO")
13011 (setq vals (org-with-point-at pom
13012 (append org-todo-keywords-1 '("")))))
13013 ((equal property "PRIORITY")
13014 (let ((n org-lowest-priority))
13015 (while (>= n org-highest-priority)
13016 (push (char-to-string n) vals)
13017 (setq n (1- n)))))
13018 ((member property org-special-properties))
13019 ((setq vals (run-hook-with-args-until-success
13020 'org-property-allowed-value-functions property)))
13022 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13023 (when (and vals (string-match "\\S-" vals))
13024 (setq vals (car (read-from-string (concat "(" vals ")"))))
13025 (setq vals (mapcar (lambda (x)
13026 (cond ((stringp x) x)
13027 ((numberp x) (number-to-string x))
13028 ((symbolp x) (symbol-name x))
13029 (t "???")))
13030 vals)))))
13031 (when (member ":ETC" vals)
13032 (setq vals (remove ":ETC" vals))
13033 (org-add-props (car vals) '(org-unrestricted t)))
13034 (if table (mapcar 'list vals) vals)))
13036 (defun org-property-previous-allowed-value (&optional previous)
13037 "Switch to the next allowed value for this property."
13038 (interactive)
13039 (org-property-next-allowed-value t))
13041 (defun org-property-next-allowed-value (&optional previous)
13042 "Switch to the next allowed value for this property."
13043 (interactive)
13044 (unless (org-at-property-p)
13045 (error "Not at a property"))
13046 (let* ((key (match-string 2))
13047 (value (match-string 3))
13048 (allowed (or (org-property-get-allowed-values (point) key)
13049 (and (member value '("[ ]" "[-]" "[X]"))
13050 '("[ ]" "[X]"))))
13051 nval)
13052 (unless allowed
13053 (error "Allowed values for this property have not been defined"))
13054 (if previous (setq allowed (reverse allowed)))
13055 (if (member value allowed)
13056 (setq nval (car (cdr (member value allowed)))))
13057 (setq nval (or nval (car allowed)))
13058 (if (equal nval value)
13059 (error "Only one allowed value for this property"))
13060 (org-at-property-p)
13061 (replace-match (concat " :" key ": " nval) t t)
13062 (org-indent-line-function)
13063 (beginning-of-line 1)
13064 (skip-chars-forward " \t")
13065 (run-hook-with-args 'org-property-changed-functions key nval)))
13067 (defun org-find-entry-with-id (ident)
13068 "Locate the entry that contains the ID property with exact value IDENT.
13069 IDENT can be a string, a symbol or a number, this function will search for
13070 the string representation of it.
13071 Return the position where this entry starts, or nil if there is no such entry."
13072 (interactive "sID: ")
13073 (let ((id (cond
13074 ((stringp ident) ident)
13075 ((symbol-name ident) (symbol-name ident))
13076 ((numberp ident) (number-to-string ident))
13077 (t (error "IDENT %s must be a string, symbol or number" ident))))
13078 (case-fold-search nil))
13079 (save-excursion
13080 (save-restriction
13081 (widen)
13082 (goto-char (point-min))
13083 (when (re-search-forward
13084 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13085 nil t)
13086 (org-back-to-heading t)
13087 (point))))))
13089 ;;;; Timestamps
13091 (defvar org-last-changed-timestamp nil)
13092 (defvar org-last-inserted-timestamp nil
13093 "The last time stamp inserted with `org-insert-time-stamp'.")
13094 (defvar org-time-was-given) ; dynamically scoped parameter
13095 (defvar org-end-time-was-given) ; dynamically scoped parameter
13096 (defvar org-ts-what) ; dynamically scoped parameter
13098 (defun org-time-stamp (arg &optional inactive)
13099 "Prompt for a date/time and insert a time stamp.
13100 If the user specifies a time like HH:MM, or if this command is called
13101 with a prefix argument, the time stamp will contain date and time.
13102 Otherwise, only the date will be included. All parts of a date not
13103 specified by the user will be filled in from the current date/time.
13104 So if you press just return without typing anything, the time stamp
13105 will represent the current date/time. If there is already a timestamp
13106 at the cursor, it will be modified."
13107 (interactive "P")
13108 (let* ((ts nil)
13109 (default-time
13110 ;; Default time is either today, or, when entering a range,
13111 ;; the range start.
13112 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13113 (save-excursion
13114 (re-search-backward
13115 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13116 (- (point) 20) t)))
13117 (apply 'encode-time (org-parse-time-string (match-string 1)))
13118 (current-time)))
13119 (default-input (and ts (org-get-compact-tod ts)))
13120 org-time-was-given org-end-time-was-given time)
13121 (cond
13122 ((and (org-at-timestamp-p t)
13123 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13124 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13125 (insert "--")
13126 (setq time (let ((this-command this-command))
13127 (org-read-date arg 'totime nil nil
13128 default-time default-input)))
13129 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13130 ((org-at-timestamp-p t)
13131 (setq time (let ((this-command this-command))
13132 (org-read-date arg 'totime nil nil default-time default-input)))
13133 (when (org-at-timestamp-p t) ; just to get the match data
13134 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13135 (replace-match "")
13136 (setq org-last-changed-timestamp
13137 (org-insert-time-stamp
13138 time (or org-time-was-given arg)
13139 inactive nil nil (list org-end-time-was-given))))
13140 (message "Timestamp updated"))
13142 (setq time (let ((this-command this-command))
13143 (org-read-date arg 'totime nil nil default-time default-input)))
13144 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13145 nil nil (list org-end-time-was-given))))))
13147 ;; FIXME: can we use this for something else, like computing time differences?
13148 (defun org-get-compact-tod (s)
13149 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13150 (let* ((t1 (match-string 1 s))
13151 (h1 (string-to-number (match-string 2 s)))
13152 (m1 (string-to-number (match-string 3 s)))
13153 (t2 (and (match-end 4) (match-string 5 s)))
13154 (h2 (and t2 (string-to-number (match-string 6 s))))
13155 (m2 (and t2 (string-to-number (match-string 7 s))))
13156 dh dm)
13157 (if (not t2)
13159 (setq dh (- h2 h1) dm (- m2 m1))
13160 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13161 (concat t1 "+" (number-to-string dh)
13162 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13164 (defun org-time-stamp-inactive (&optional arg)
13165 "Insert an inactive time stamp.
13166 An inactive time stamp is enclosed in square brackets instead of angle
13167 brackets. It is inactive in the sense that it does not trigger agenda entries,
13168 does not link to the calendar and cannot be changed with the S-cursor keys.
13169 So these are more for recording a certain time/date."
13170 (interactive "P")
13171 (org-time-stamp arg 'inactive))
13173 (defvar org-date-ovl (org-make-overlay 1 1))
13174 (org-overlay-put org-date-ovl 'face 'org-warning)
13175 (org-detach-overlay org-date-ovl)
13177 (defvar org-ans1) ; dynamically scoped parameter
13178 (defvar org-ans2) ; dynamically scoped parameter
13180 (defvar org-plain-time-of-day-regexp) ; defined below
13182 (defvar org-overriding-default-time nil) ; dynamically scoped
13183 (defvar org-read-date-overlay nil)
13184 (defvar org-dcst nil) ; dynamically scoped
13185 (defvar org-read-date-history nil)
13186 (defvar org-read-date-final-answer nil)
13188 (defun org-read-date (&optional with-time to-time from-string prompt
13189 default-time default-input)
13190 "Read a date, possibly a time, and make things smooth for the user.
13191 The prompt will suggest to enter an ISO date, but you can also enter anything
13192 which will at least partially be understood by `parse-time-string'.
13193 Unrecognized parts of the date will default to the current day, month, year,
13194 hour and minute. If this command is called to replace a timestamp at point,
13195 of to enter the second timestamp of a range, the default time is taken from the
13196 existing stamp. For example,
13197 3-2-5 --> 2003-02-05
13198 feb 15 --> currentyear-02-15
13199 sep 12 9 --> 2009-09-12
13200 12:45 --> today 12:45
13201 22 sept 0:34 --> currentyear-09-22 0:34
13202 12 --> currentyear-currentmonth-12
13203 Fri --> nearest Friday (today or later)
13204 etc.
13206 Furthermore you can specify a relative date by giving, as the *first* thing
13207 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13208 change in days weeks, months, years.
13209 With a single plus or minus, the date is relative to today. With a double
13210 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13211 +4d --> four days from today
13212 +4 --> same as above
13213 +2w --> two weeks from today
13214 ++5 --> five days from default date
13216 The function understands only English month and weekday abbreviations,
13217 but this can be configured with the variables `parse-time-months' and
13218 `parse-time-weekdays'.
13220 While prompting, a calendar is popped up - you can also select the
13221 date with the mouse (button 1). The calendar shows a period of three
13222 months. To scroll it to other months, use the keys `>' and `<'.
13223 If you don't like the calendar, turn it off with
13224 \(setq org-read-date-popup-calendar nil)
13226 With optional argument TO-TIME, the date will immediately be converted
13227 to an internal time.
13228 With an optional argument WITH-TIME, the prompt will suggest to also
13229 insert a time. Note that when WITH-TIME is not set, you can still
13230 enter a time, and this function will inform the calling routine about
13231 this change. The calling routine may then choose to change the format
13232 used to insert the time stamp into the buffer to include the time.
13233 With optional argument FROM-STRING, read from this string instead from
13234 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13235 the time/date that is used for everything that is not specified by the
13236 user."
13237 (require 'parse-time)
13238 (let* ((org-time-stamp-rounding-minutes
13239 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13240 (org-dcst org-display-custom-times)
13241 (ct (org-current-time))
13242 (def (or org-overriding-default-time default-time ct))
13243 (defdecode (decode-time def))
13244 (dummy (progn
13245 (when (< (nth 2 defdecode) org-extend-today-until)
13246 (setcar (nthcdr 2 defdecode) -1)
13247 (setcar (nthcdr 1 defdecode) 59)
13248 (setq def (apply 'encode-time defdecode)
13249 defdecode (decode-time def)))))
13250 (calendar-frame-setup nil)
13251 (calendar-move-hook nil)
13252 (calendar-view-diary-initially-flag nil)
13253 (view-diary-entries-initially nil)
13254 (calendar-view-holidays-initially-flag nil)
13255 (view-calendar-holidays-initially nil)
13256 (timestr (format-time-string
13257 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13258 (prompt (concat (if prompt (concat prompt " ") "")
13259 (format "Date+time [%s]: " timestr)))
13260 ans (org-ans0 "") org-ans1 org-ans2 final)
13262 (cond
13263 (from-string (setq ans from-string))
13264 (org-read-date-popup-calendar
13265 (save-excursion
13266 (save-window-excursion
13267 (calendar)
13268 (calendar-forward-day (- (time-to-days def)
13269 (calendar-absolute-from-gregorian
13270 (calendar-current-date))))
13271 (org-eval-in-calendar nil t)
13272 (let* ((old-map (current-local-map))
13273 (map (copy-keymap calendar-mode-map))
13274 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13275 (org-defkey map (kbd "RET") 'org-calendar-select)
13276 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13277 'org-calendar-select-mouse)
13278 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13279 'org-calendar-select-mouse)
13280 (org-defkey minibuffer-local-map [(meta shift left)]
13281 (lambda () (interactive)
13282 (org-eval-in-calendar '(calendar-backward-month 1))))
13283 (org-defkey minibuffer-local-map [(meta shift right)]
13284 (lambda () (interactive)
13285 (org-eval-in-calendar '(calendar-forward-month 1))))
13286 (org-defkey minibuffer-local-map [(meta shift up)]
13287 (lambda () (interactive)
13288 (org-eval-in-calendar '(calendar-backward-year 1))))
13289 (org-defkey minibuffer-local-map [(meta shift down)]
13290 (lambda () (interactive)
13291 (org-eval-in-calendar '(calendar-forward-year 1))))
13292 (org-defkey minibuffer-local-map [?\e (shift left)]
13293 (lambda () (interactive)
13294 (org-eval-in-calendar '(calendar-backward-month 1))))
13295 (org-defkey minibuffer-local-map [?\e (shift right)]
13296 (lambda () (interactive)
13297 (org-eval-in-calendar '(calendar-forward-month 1))))
13298 (org-defkey minibuffer-local-map [?\e (shift up)]
13299 (lambda () (interactive)
13300 (org-eval-in-calendar '(calendar-backward-year 1))))
13301 (org-defkey minibuffer-local-map [?\e (shift down)]
13302 (lambda () (interactive)
13303 (org-eval-in-calendar '(calendar-forward-year 1))))
13304 (org-defkey minibuffer-local-map [(shift up)]
13305 (lambda () (interactive)
13306 (org-eval-in-calendar '(calendar-backward-week 1))))
13307 (org-defkey minibuffer-local-map [(shift down)]
13308 (lambda () (interactive)
13309 (org-eval-in-calendar '(calendar-forward-week 1))))
13310 (org-defkey minibuffer-local-map [(shift left)]
13311 (lambda () (interactive)
13312 (org-eval-in-calendar '(calendar-backward-day 1))))
13313 (org-defkey minibuffer-local-map [(shift right)]
13314 (lambda () (interactive)
13315 (org-eval-in-calendar '(calendar-forward-day 1))))
13316 (org-defkey minibuffer-local-map ">"
13317 (lambda () (interactive)
13318 (org-eval-in-calendar '(scroll-calendar-left 1))))
13319 (org-defkey minibuffer-local-map "<"
13320 (lambda () (interactive)
13321 (org-eval-in-calendar '(scroll-calendar-right 1))))
13322 (run-hooks 'org-read-date-minibuffer-setup-hook)
13323 (unwind-protect
13324 (progn
13325 (use-local-map map)
13326 (add-hook 'post-command-hook 'org-read-date-display)
13327 (setq org-ans0 (read-string prompt default-input
13328 'org-read-date-history nil))
13329 ;; org-ans0: from prompt
13330 ;; org-ans1: from mouse click
13331 ;; org-ans2: from calendar motion
13332 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13333 (remove-hook 'post-command-hook 'org-read-date-display)
13334 (use-local-map old-map)
13335 (when org-read-date-overlay
13336 (org-delete-overlay org-read-date-overlay)
13337 (setq org-read-date-overlay nil)))))))
13339 (t ; Naked prompt only
13340 (unwind-protect
13341 (setq ans (read-string prompt default-input
13342 'org-read-date-history timestr))
13343 (when org-read-date-overlay
13344 (org-delete-overlay org-read-date-overlay)
13345 (setq org-read-date-overlay nil)))))
13347 (setq final (org-read-date-analyze ans def defdecode))
13348 (setq org-read-date-final-answer ans)
13350 (if to-time
13351 (apply 'encode-time final)
13352 (if (and (boundp 'org-time-was-given) org-time-was-given)
13353 (format "%04d-%02d-%02d %02d:%02d"
13354 (nth 5 final) (nth 4 final) (nth 3 final)
13355 (nth 2 final) (nth 1 final))
13356 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13358 (defvar def)
13359 (defvar defdecode)
13360 (defvar with-time)
13361 (defvar org-read-date-analyze-futurep nil)
13362 (defun org-read-date-display ()
13363 "Display the current date prompt interpretation in the minibuffer."
13364 (when org-read-date-display-live
13365 (when org-read-date-overlay
13366 (org-delete-overlay org-read-date-overlay))
13367 (let ((p (point)))
13368 (end-of-line 1)
13369 (while (not (equal (buffer-substring
13370 (max (point-min) (- (point) 4)) (point))
13371 " "))
13372 (insert " "))
13373 (goto-char p))
13374 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13375 " " (or org-ans1 org-ans2)))
13376 (org-end-time-was-given nil)
13377 (f (org-read-date-analyze ans def defdecode))
13378 (fmts (if org-dcst
13379 org-time-stamp-custom-formats
13380 org-time-stamp-formats))
13381 (fmt (if (or with-time
13382 (and (boundp 'org-time-was-given) org-time-was-given))
13383 (cdr fmts)
13384 (car fmts)))
13385 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13386 (when (and org-end-time-was-given
13387 (string-match org-plain-time-of-day-regexp txt))
13388 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13389 org-end-time-was-given
13390 (substring txt (match-end 0)))))
13391 (when org-read-date-analyze-futurep
13392 (setq txt (concat txt " (=>F)")))
13393 (setq org-read-date-overlay
13394 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13395 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13397 (defun org-read-date-analyze (ans def defdecode)
13398 "Analyse the combined answer of the date prompt."
13399 ;; FIXME: cleanup and comment
13400 (let ((nowdecode (decode-time (current-time)))
13401 delta deltan deltaw deltadef year month day
13402 hour minute second wday pm h2 m2 tl wday1
13403 iso-year iso-weekday iso-week iso-year iso-date futurep)
13404 (setq org-read-date-analyze-futurep nil)
13405 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13406 (setq ans "+0"))
13408 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13409 (setq ans (replace-match "" t t ans)
13410 deltan (car delta)
13411 deltaw (nth 1 delta)
13412 deltadef (nth 2 delta)))
13414 ;; Check if there is an iso week date in there
13415 ;; If yes, store the info and postpone interpreting it until the rest
13416 ;; of the parsing is done
13417 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13418 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13419 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13420 iso-week (string-to-number (match-string 2 ans)))
13421 (setq ans (replace-match "" t t ans)))
13423 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13424 (when (string-match
13425 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13426 (setq year (if (match-end 2)
13427 (string-to-number (match-string 2 ans))
13428 (string-to-number (format-time-string "%Y")))
13429 month (string-to-number (match-string 3 ans))
13430 day (string-to-number (match-string 4 ans)))
13431 (if (< year 100) (setq year (+ 2000 year)))
13432 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13433 t nil ans)))
13434 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13435 ;; If there is a time with am/pm, and *no* time without it, we convert
13436 ;; so that matching will be successful.
13437 (loop for i from 1 to 2 do ; twice, for end time as well
13438 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13439 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13440 (setq hour (string-to-number (match-string 1 ans))
13441 minute (if (match-end 3)
13442 (string-to-number (match-string 3 ans))
13444 pm (equal ?p
13445 (string-to-char (downcase (match-string 4 ans)))))
13446 (if (and (= hour 12) (not pm))
13447 (setq hour 0)
13448 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13449 (setq ans (replace-match (format "%02d:%02d" hour minute)
13450 t t ans))))
13452 ;; Check if a time range is given as a duration
13453 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13454 (setq hour (string-to-number (match-string 1 ans))
13455 h2 (+ hour (string-to-number (match-string 3 ans)))
13456 minute (string-to-number (match-string 2 ans))
13457 m2 (+ minute (if (match-end 5) (string-to-number
13458 (match-string 5 ans))0)))
13459 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13460 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13461 t t ans)))
13463 ;; Check if there is a time range
13464 (when (boundp 'org-end-time-was-given)
13465 (setq org-time-was-given nil)
13466 (when (and (string-match org-plain-time-of-day-regexp ans)
13467 (match-end 8))
13468 (setq org-end-time-was-given (match-string 8 ans))
13469 (setq ans (concat (substring ans 0 (match-beginning 7))
13470 (substring ans (match-end 7))))))
13472 (setq tl (parse-time-string ans)
13473 day (or (nth 3 tl) (nth 3 defdecode))
13474 month (or (nth 4 tl)
13475 (if (and org-read-date-prefer-future
13476 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13477 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13478 (nth 4 defdecode)))
13479 year (or (nth 5 tl)
13480 (if (and org-read-date-prefer-future
13481 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13482 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13483 (nth 5 defdecode)))
13484 hour (or (nth 2 tl) (nth 2 defdecode))
13485 minute (or (nth 1 tl) (nth 1 defdecode))
13486 second (or (nth 0 tl) 0)
13487 wday (nth 6 tl))
13489 (when (and (eq org-read-date-prefer-future 'time)
13490 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13491 (equal day (nth 3 nowdecode))
13492 (equal month (nth 4 nowdecode))
13493 (equal year (nth 5 nowdecode))
13494 (nth 2 tl)
13495 (or (< (nth 2 tl) (nth 2 nowdecode))
13496 (and (= (nth 2 tl) (nth 2 nowdecode))
13497 (nth 1 tl)
13498 (< (nth 1 tl) (nth 1 nowdecode)))))
13499 (setq day (1+ day)
13500 futurep t))
13502 ;; Special date definitions below
13503 (cond
13504 (iso-week
13505 ;; There was an iso week
13506 (setq futurep nil)
13507 (setq year (or iso-year year)
13508 day (or iso-weekday wday 1)
13509 wday nil ; to make sure that the trigger below does not match
13510 iso-date (calendar-gregorian-from-absolute
13511 (calendar-absolute-from-iso
13512 (list iso-week day year))))
13513 ; FIXME: Should we also push ISO weeks into the future?
13514 ; (when (and org-read-date-prefer-future
13515 ; (not iso-year)
13516 ; (< (calendar-absolute-from-gregorian iso-date)
13517 ; (time-to-days (current-time))))
13518 ; (setq year (1+ year)
13519 ; iso-date (calendar-gregorian-from-absolute
13520 ; (calendar-absolute-from-iso
13521 ; (list iso-week day year)))))
13522 (setq month (car iso-date)
13523 year (nth 2 iso-date)
13524 day (nth 1 iso-date)))
13525 (deltan
13526 (setq futurep nil)
13527 (unless deltadef
13528 (let ((now (decode-time (current-time))))
13529 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13530 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13531 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13532 ((equal deltaw "m") (setq month (+ month deltan)))
13533 ((equal deltaw "y") (setq year (+ year deltan)))))
13534 ((and wday (not (nth 3 tl)))
13535 (setq futurep nil)
13536 ;; Weekday was given, but no day, so pick that day in the week
13537 ;; on or after the derived date.
13538 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13539 (unless (equal wday wday1)
13540 (setq day (+ day (% (- wday wday1 -7) 7))))))
13541 (if (and (boundp 'org-time-was-given)
13542 (nth 2 tl))
13543 (setq org-time-was-given t))
13544 (if (< year 100) (setq year (+ 2000 year)))
13545 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13546 (setq org-read-date-analyze-futurep futurep)
13547 (list second minute hour day month year)))
13549 (defvar parse-time-weekdays)
13551 (defun org-read-date-get-relative (s today default)
13552 "Check string S for special relative date string.
13553 TODAY and DEFAULT are internal times, for today and for a default.
13554 Return shift list (N what def-flag)
13555 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13556 N is the number of WHATs to shift.
13557 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13558 the DEFAULT date rather than TODAY."
13559 (when (and
13560 (string-match
13561 (concat
13562 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13563 "\\([0-9]+\\)?"
13564 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13565 "\\([ \t]\\|$\\)") s)
13566 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13567 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13568 (string-to-char (substring (match-string 1 s) -1))
13569 ?+))
13570 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13571 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13572 (what (if (match-end 3) (match-string 3 s) "d"))
13573 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13574 (date (if rel default today))
13575 (wday (nth 6 (decode-time date)))
13576 delta)
13577 (if wday1
13578 (progn
13579 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13580 (if (= dir ?-) (setq delta (- delta 7)))
13581 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13582 (list delta "d" rel))
13583 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13585 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13586 "Turn a user-specified date into the internal representation.
13587 The internal representation needed by the calendar is (month day year).
13588 This is a wrapper to handle the brain-dead convention in calendar that
13589 user function argument order change dependent on argument order."
13590 (if (boundp 'calendar-date-style)
13591 (cond
13592 ((eq calendar-date-style 'american)
13593 (list arg1 arg2 arg3))
13594 ((eq calendar-date-style 'european)
13595 (list arg2 arg1 arg3))
13596 ((eq calendar-date-style 'iso)
13597 (list arg2 arg3 arg1)))
13598 (if (org-bound-and-true-p european-calendar-style)
13599 (list arg2 arg1 arg3)
13600 (list arg1 arg2 arg3))))
13602 (defun org-eval-in-calendar (form &optional keepdate)
13603 "Eval FORM in the calendar window and return to current window.
13604 Also, store the cursor date in variable org-ans2."
13605 (let ((sf (selected-frame))
13606 (sw (selected-window)))
13607 (select-window (get-buffer-window "*Calendar*" t))
13608 (eval form)
13609 (when (and (not keepdate) (calendar-cursor-to-date))
13610 (let* ((date (calendar-cursor-to-date))
13611 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13612 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13613 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13614 (select-window sw)
13615 (org-select-frame-set-input-focus sf)))
13617 (defun org-calendar-select ()
13618 "Return to `org-read-date' with the date currently selected.
13619 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13620 (interactive)
13621 (when (calendar-cursor-to-date)
13622 (let* ((date (calendar-cursor-to-date))
13623 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13624 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13625 (if (active-minibuffer-window) (exit-minibuffer))))
13627 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13628 "Insert a date stamp for the date given by the internal TIME.
13629 WITH-HM means use the stamp format that includes the time of the day.
13630 INACTIVE means use square brackets instead of angular ones, so that the
13631 stamp will not contribute to the agenda.
13632 PRE and POST are optional strings to be inserted before and after the
13633 stamp.
13634 The command returns the inserted time stamp."
13635 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13636 stamp)
13637 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13638 (insert-before-markers (or pre ""))
13639 (insert-before-markers (setq stamp (format-time-string fmt time)))
13640 (when (listp extra)
13641 (setq extra (car extra))
13642 (if (and (stringp extra)
13643 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13644 (setq extra (format "-%02d:%02d"
13645 (string-to-number (match-string 1 extra))
13646 (string-to-number (match-string 2 extra))))
13647 (setq extra nil)))
13648 (when extra
13649 (backward-char 1)
13650 (insert-before-markers extra)
13651 (forward-char 1))
13652 (insert-before-markers (or post ""))
13653 (setq org-last-inserted-timestamp stamp)))
13655 (defun org-toggle-time-stamp-overlays ()
13656 "Toggle the use of custom time stamp formats."
13657 (interactive)
13658 (setq org-display-custom-times (not org-display-custom-times))
13659 (unless org-display-custom-times
13660 (let ((p (point-min)) (bmp (buffer-modified-p)))
13661 (while (setq p (next-single-property-change p 'display))
13662 (if (and (get-text-property p 'display)
13663 (eq (get-text-property p 'face) 'org-date))
13664 (remove-text-properties
13665 p (setq p (next-single-property-change p 'display))
13666 '(display t))))
13667 (set-buffer-modified-p bmp)))
13668 (if (featurep 'xemacs)
13669 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13670 (org-restart-font-lock)
13671 (setq org-table-may-need-update t)
13672 (if org-display-custom-times
13673 (message "Time stamps are overlayed with custom format")
13674 (message "Time stamp overlays removed")))
13676 (defun org-display-custom-time (beg end)
13677 "Overlay modified time stamp format over timestamp between BEG and END."
13678 (let* ((ts (buffer-substring beg end))
13679 t1 w1 with-hm tf time str w2 (off 0))
13680 (save-match-data
13681 (setq t1 (org-parse-time-string ts t))
13682 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13683 (setq off (- (match-end 0) (match-beginning 0)))))
13684 (setq end (- end off))
13685 (setq w1 (- end beg)
13686 with-hm (and (nth 1 t1) (nth 2 t1))
13687 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13688 time (org-fix-decoded-time t1)
13689 str (org-add-props
13690 (format-time-string
13691 (substring tf 1 -1) (apply 'encode-time time))
13692 nil 'mouse-face 'highlight)
13693 w2 (length str))
13694 (if (not (= w2 w1))
13695 (add-text-properties (1+ beg) (+ 2 beg)
13696 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13697 (if (featurep 'xemacs)
13698 (progn
13699 (put-text-property beg end 'invisible t)
13700 (put-text-property beg end 'end-glyph (make-glyph str)))
13701 (put-text-property beg end 'display str))))
13703 (defun org-translate-time (string)
13704 "Translate all timestamps in STRING to custom format.
13705 But do this only if the variable `org-display-custom-times' is set."
13706 (when org-display-custom-times
13707 (save-match-data
13708 (let* ((start 0)
13709 (re org-ts-regexp-both)
13710 t1 with-hm inactive tf time str beg end)
13711 (while (setq start (string-match re string start))
13712 (setq beg (match-beginning 0)
13713 end (match-end 0)
13714 t1 (save-match-data
13715 (org-parse-time-string (substring string beg end) t))
13716 with-hm (and (nth 1 t1) (nth 2 t1))
13717 inactive (equal (substring string beg (1+ beg)) "[")
13718 tf (funcall (if with-hm 'cdr 'car)
13719 org-time-stamp-custom-formats)
13720 time (org-fix-decoded-time t1)
13721 str (format-time-string
13722 (concat
13723 (if inactive "[" "<") (substring tf 1 -1)
13724 (if inactive "]" ">"))
13725 (apply 'encode-time time))
13726 string (replace-match str t t string)
13727 start (+ start (length str)))))))
13728 string)
13730 (defun org-fix-decoded-time (time)
13731 "Set 0 instead of nil for the first 6 elements of time.
13732 Don't touch the rest."
13733 (let ((n 0))
13734 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13736 (defun org-days-to-time (timestamp-string)
13737 "Difference between TIMESTAMP-STRING and now in days."
13738 (- (time-to-days (org-time-string-to-time timestamp-string))
13739 (time-to-days (current-time))))
13741 (defun org-deadline-close (timestamp-string &optional ndays)
13742 "Is the time in TIMESTAMP-STRING close to the current date?"
13743 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13744 (and (< (org-days-to-time timestamp-string) ndays)
13745 (not (org-entry-is-done-p))))
13747 (defun org-get-wdays (ts)
13748 "Get the deadline lead time appropriate for timestring TS."
13749 (cond
13750 ((<= org-deadline-warning-days 0)
13751 ;; 0 or negative, enforce this value no matter what
13752 (- org-deadline-warning-days))
13753 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13754 ;; lead time is specified.
13755 (floor (* (string-to-number (match-string 1 ts))
13756 (cdr (assoc (match-string 2 ts)
13757 '(("d" . 1) ("w" . 7)
13758 ("m" . 30.4) ("y" . 365.25)))))))
13759 ;; go for the default.
13760 (t org-deadline-warning-days)))
13762 (defun org-calendar-select-mouse (ev)
13763 "Return to `org-read-date' with the date currently selected.
13764 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13765 (interactive "e")
13766 (mouse-set-point ev)
13767 (when (calendar-cursor-to-date)
13768 (let* ((date (calendar-cursor-to-date))
13769 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13770 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13771 (if (active-minibuffer-window) (exit-minibuffer))))
13773 (defun org-check-deadlines (ndays)
13774 "Check if there are any deadlines due or past due.
13775 A deadline is considered due if it happens within `org-deadline-warning-days'
13776 days from today's date. If the deadline appears in an entry marked DONE,
13777 it is not shown. The prefix arg NDAYS can be used to test that many
13778 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13779 (interactive "P")
13780 (let* ((org-warn-days
13781 (cond
13782 ((equal ndays '(4)) 100000)
13783 (ndays (prefix-numeric-value ndays))
13784 (t (abs org-deadline-warning-days))))
13785 (case-fold-search nil)
13786 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13787 (callback
13788 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13790 (message "%d deadlines past-due or due within %d days"
13791 (org-occur regexp nil callback)
13792 org-warn-days)))
13794 (defun org-check-before-date (date)
13795 "Check if there are deadlines or scheduled entries before DATE."
13796 (interactive (list (org-read-date)))
13797 (let ((case-fold-search nil)
13798 (regexp (concat "\\<\\(" org-deadline-string
13799 "\\|" org-scheduled-string
13800 "\\) *<\\([^>]+\\)>"))
13801 (callback
13802 (lambda () (time-less-p
13803 (org-time-string-to-time (match-string 2))
13804 (org-time-string-to-time date)))))
13805 (message "%d entries before %s"
13806 (org-occur regexp nil callback) date)))
13808 (defun org-check-after-date (date)
13809 "Check if there are deadlines or scheduled entries after DATE."
13810 (interactive (list (org-read-date)))
13811 (let ((case-fold-search nil)
13812 (regexp (concat "\\<\\(" org-deadline-string
13813 "\\|" org-scheduled-string
13814 "\\) *<\\([^>]+\\)>"))
13815 (callback
13816 (lambda () (not
13817 (time-less-p
13818 (org-time-string-to-time (match-string 2))
13819 (org-time-string-to-time date))))))
13820 (message "%d entries after %s"
13821 (org-occur regexp nil callback) date)))
13823 (defun org-evaluate-time-range (&optional to-buffer)
13824 "Evaluate a time range by computing the difference between start and end.
13825 Normally the result is just printed in the echo area, but with prefix arg
13826 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13827 If the time range is actually in a table, the result is inserted into the
13828 next column.
13829 For time difference computation, a year is assumed to be exactly 365
13830 days in order to avoid rounding problems."
13831 (interactive "P")
13833 (org-clock-update-time-maybe)
13834 (save-excursion
13835 (unless (org-at-date-range-p t)
13836 (goto-char (point-at-bol))
13837 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13838 (if (not (org-at-date-range-p t))
13839 (error "Not at a time-stamp range, and none found in current line")))
13840 (let* ((ts1 (match-string 1))
13841 (ts2 (match-string 2))
13842 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13843 (match-end (match-end 0))
13844 (time1 (org-time-string-to-time ts1))
13845 (time2 (org-time-string-to-time ts2))
13846 (t1 (org-float-time time1))
13847 (t2 (org-float-time time2))
13848 (diff (abs (- t2 t1)))
13849 (negative (< (- t2 t1) 0))
13850 ;; (ys (floor (* 365 24 60 60)))
13851 (ds (* 24 60 60))
13852 (hs (* 60 60))
13853 (fy "%dy %dd %02d:%02d")
13854 (fy1 "%dy %dd")
13855 (fd "%dd %02d:%02d")
13856 (fd1 "%dd")
13857 (fh "%02d:%02d")
13858 y d h m align)
13859 (if havetime
13860 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13862 d (floor (/ diff ds)) diff (mod diff ds)
13863 h (floor (/ diff hs)) diff (mod diff hs)
13864 m (floor (/ diff 60)))
13865 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13867 d (floor (+ (/ diff ds) 0.5))
13868 h 0 m 0))
13869 (if (not to-buffer)
13870 (message "%s" (org-make-tdiff-string y d h m))
13871 (if (org-at-table-p)
13872 (progn
13873 (goto-char match-end)
13874 (setq align t)
13875 (and (looking-at " *|") (goto-char (match-end 0))))
13876 (goto-char match-end))
13877 (if (looking-at
13878 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13879 (replace-match ""))
13880 (if negative (insert " -"))
13881 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13882 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13883 (insert " " (format fh h m))))
13884 (if align (org-table-align))
13885 (message "Time difference inserted")))))
13887 (defun org-make-tdiff-string (y d h m)
13888 (let ((fmt "")
13889 (l nil))
13890 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13891 l (push y l)))
13892 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13893 l (push d l)))
13894 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13895 l (push h l)))
13896 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13897 l (push m l)))
13898 (apply 'format fmt (nreverse l))))
13900 (defun org-time-string-to-time (s)
13901 (apply 'encode-time (org-parse-time-string s)))
13902 (defun org-time-string-to-seconds (s)
13903 (org-float-time (org-time-string-to-time s)))
13905 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13906 "Convert a time stamp to an absolute day number.
13907 If there is a specifyer for a cyclic time stamp, get the closest date to
13908 DAYNR.
13909 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13910 the variable date is bound by the calendar when this is called."
13911 (cond
13912 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13913 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13914 daynr
13915 (+ daynr 1000)))
13916 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13917 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13918 (time-to-days (current-time))) (match-string 0 s)
13919 prefer show-all))
13920 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13922 (defun org-days-to-iso-week (days)
13923 "Return the iso week number."
13924 (require 'cal-iso)
13925 (car (calendar-iso-from-absolute days)))
13927 (defun org-small-year-to-year (year)
13928 "Convert 2-digit years into 4-digit years.
13929 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13930 The year 2000 cannot be abbreviated. Any year larger than 99
13931 is returned unchanged."
13932 (if (< year 38)
13933 (setq year (+ 2000 year))
13934 (if (< year 100)
13935 (setq year (+ 1900 year))))
13936 year)
13938 (defun org-time-from-absolute (d)
13939 "Return the time corresponding to date D.
13940 D may be an absolute day number, or a calendar-type list (month day year)."
13941 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13942 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13944 (defun org-calendar-holiday ()
13945 "List of holidays, for Diary display in Org-mode."
13946 (require 'holidays)
13947 (let ((hl (funcall
13948 (if (fboundp 'calendar-check-holidays)
13949 'calendar-check-holidays 'check-calendar-holidays) date)))
13950 (if hl (mapconcat 'identity hl "; "))))
13952 (defun org-diary-sexp-entry (sexp entry date)
13953 "Process a SEXP diary ENTRY for DATE."
13954 (require 'diary-lib)
13955 (let ((result (if calendar-debug-sexp
13956 (let ((stack-trace-on-error t))
13957 (eval (car (read-from-string sexp))))
13958 (condition-case nil
13959 (eval (car (read-from-string sexp)))
13960 (error
13961 (beep)
13962 (message "Bad sexp at line %d in %s: %s"
13963 (org-current-line)
13964 (buffer-file-name) sexp)
13965 (sleep-for 2))))))
13966 (cond ((stringp result) result)
13967 ((and (consp result)
13968 (stringp (cdr result))) (cdr result))
13969 (result entry)
13970 (t nil))))
13972 (defun org-diary-to-ical-string (frombuf)
13973 "Get iCalendar entries from diary entries in buffer FROMBUF.
13974 This uses the icalendar.el library."
13975 (let* ((tmpdir (if (featurep 'xemacs)
13976 (temp-directory)
13977 temporary-file-directory))
13978 (tmpfile (make-temp-name
13979 (expand-file-name "orgics" tmpdir)))
13980 buf rtn b e)
13981 (with-current-buffer frombuf
13982 (icalendar-export-region (point-min) (point-max) tmpfile)
13983 (setq buf (find-buffer-visiting tmpfile))
13984 (set-buffer buf)
13985 (goto-char (point-min))
13986 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13987 (setq b (match-beginning 0)))
13988 (goto-char (point-max))
13989 (if (re-search-backward "^END:VEVENT" nil t)
13990 (setq e (match-end 0)))
13991 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13992 (kill-buffer buf)
13993 (delete-file tmpfile)
13994 rtn))
13996 (defun org-closest-date (start current change prefer show-all)
13997 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13998 When PREFER is `past' return a date that is either CURRENT or past.
13999 When PREFER is `future', return a date that is either CURRENT or future.
14000 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14001 ;; Make the proper lists from the dates
14002 (catch 'exit
14003 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14004 dn dw sday cday n1 n2 n0
14005 d m y y1 y2 date1 date2 nmonths nm ny m2)
14007 (setq start (org-date-to-gregorian start)
14008 current (org-date-to-gregorian
14009 (if show-all
14010 current
14011 (time-to-days (current-time))))
14012 sday (calendar-absolute-from-gregorian start)
14013 cday (calendar-absolute-from-gregorian current))
14015 (if (<= cday sday) (throw 'exit sday))
14017 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14018 (setq dn (string-to-number (match-string 1 change))
14019 dw (cdr (assoc (match-string 2 change) a1)))
14020 (error "Invalid change specifyer: %s" change))
14021 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14022 (cond
14023 ((eq dw 'day)
14024 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14025 n2 (+ n1 dn)))
14026 ((eq dw 'year)
14027 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14028 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14029 (setq date1 (list m d y1)
14030 n1 (calendar-absolute-from-gregorian date1)
14031 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14032 n2 (calendar-absolute-from-gregorian date2)))
14033 ((eq dw 'month)
14034 ;; approx number of month between the two dates
14035 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14036 ;; How often does dn fit in there?
14037 (setq d (nth 1 start) m (car start) y (nth 2 start)
14038 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14039 m (+ m nm)
14040 ny (floor (/ m 12))
14041 y (+ y ny)
14042 m (- m (* ny 12)))
14043 (while (> m 12) (setq m (- m 12) y (1+ y)))
14044 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14045 (setq m2 (+ m dn) y2 y)
14046 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14047 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14048 (while (<= n2 cday)
14049 (setq n1 n2 m m2 y y2)
14050 (setq m2 (+ m dn) y2 y)
14051 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14052 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14053 ;; Make sure n1 is the earlier date
14054 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14055 (if show-all
14056 (cond
14057 ((eq prefer 'past) (if (= cday n2) n2 n1))
14058 ((eq prefer 'future) (if (= cday n1) n1 n2))
14059 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14060 (cond
14061 ((eq prefer 'past) (if (= cday n2) n2 n1))
14062 ((eq prefer 'future) (if (= cday n1) n1 n2))
14063 (t (if (= cday n1) n1 n2)))))))
14065 (defun org-date-to-gregorian (date)
14066 "Turn any specification of DATE into a gregorian date for the calendar."
14067 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14068 ((and (listp date) (= (length date) 3)) date)
14069 ((stringp date)
14070 (setq date (org-parse-time-string date))
14071 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14072 ((listp date)
14073 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14075 (defun org-parse-time-string (s &optional nodefault)
14076 "Parse the standard Org-mode time string.
14077 This should be a lot faster than the normal `parse-time-string'.
14078 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14079 hour and minute fields will be nil if not given."
14080 (if (string-match org-ts-regexp0 s)
14081 (list 0
14082 (if (or (match-beginning 8) (not nodefault))
14083 (string-to-number (or (match-string 8 s) "0")))
14084 (if (or (match-beginning 7) (not nodefault))
14085 (string-to-number (or (match-string 7 s) "0")))
14086 (string-to-number (match-string 4 s))
14087 (string-to-number (match-string 3 s))
14088 (string-to-number (match-string 2 s))
14089 nil nil nil)
14090 (error "Not a standard Org-mode time string: %s" s)))
14092 (defun org-timestamp-up (&optional arg)
14093 "Increase the date item at the cursor by one.
14094 If the cursor is on the year, change the year. If it is on the month or
14095 the day, change that.
14096 With prefix ARG, change by that many units."
14097 (interactive "p")
14098 (org-timestamp-change (prefix-numeric-value arg)))
14100 (defun org-timestamp-down (&optional arg)
14101 "Decrease the date item at the cursor by one.
14102 If the cursor is on the year, change the year. If it is on the month or
14103 the day, change that.
14104 With prefix ARG, change by that many units."
14105 (interactive "p")
14106 (org-timestamp-change (- (prefix-numeric-value arg))))
14108 (defun org-timestamp-up-day (&optional arg)
14109 "Increase the date in the time stamp by one day.
14110 With prefix ARG, change that many days."
14111 (interactive "p")
14112 (if (and (not (org-at-timestamp-p t))
14113 (org-on-heading-p))
14114 (org-todo 'up)
14115 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14117 (defun org-timestamp-down-day (&optional arg)
14118 "Decrease the date in the time stamp by one day.
14119 With prefix ARG, change that many days."
14120 (interactive "p")
14121 (if (and (not (org-at-timestamp-p t))
14122 (org-on-heading-p))
14123 (org-todo 'down)
14124 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14126 (defun org-at-timestamp-p (&optional inactive-ok)
14127 "Determine if the cursor is in or at a timestamp."
14128 (interactive)
14129 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14130 (pos (point))
14131 (ans (or (looking-at tsr)
14132 (save-excursion
14133 (skip-chars-backward "^[<\n\r\t")
14134 (if (> (point) (point-min)) (backward-char 1))
14135 (and (looking-at tsr)
14136 (> (- (match-end 0) pos) -1))))))
14137 (and ans
14138 (boundp 'org-ts-what)
14139 (setq org-ts-what
14140 (cond
14141 ((= pos (match-beginning 0)) 'bracket)
14142 ((= pos (1- (match-end 0))) 'bracket)
14143 ((org-pos-in-match-range pos 2) 'year)
14144 ((org-pos-in-match-range pos 3) 'month)
14145 ((org-pos-in-match-range pos 7) 'hour)
14146 ((org-pos-in-match-range pos 8) 'minute)
14147 ((or (org-pos-in-match-range pos 4)
14148 (org-pos-in-match-range pos 5)) 'day)
14149 ((and (> pos (or (match-end 8) (match-end 5)))
14150 (< pos (match-end 0)))
14151 (- pos (or (match-end 8) (match-end 5))))
14152 (t 'day))))
14153 ans))
14155 (defun org-toggle-timestamp-type ()
14156 "Toggle the type (<active> or [inactive]) of a time stamp."
14157 (interactive)
14158 (when (org-at-timestamp-p t)
14159 (let ((beg (match-beginning 0)) (end (match-end 0))
14160 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14161 (save-excursion
14162 (goto-char beg)
14163 (while (re-search-forward "[][<>]" end t)
14164 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14165 t t)))
14166 (message "Timestamp is now %sactive"
14167 (if (equal (char-after beg) ?<) "" "in")))))
14169 (defun org-timestamp-change (n &optional what)
14170 "Change the date in the time stamp at point.
14171 The date will be changed by N times WHAT. WHAT can be `day', `month',
14172 `year', `minute', `second'. If WHAT is not given, the cursor position
14173 in the timestamp determines what will be changed."
14174 (let ((pos (point))
14175 with-hm inactive
14176 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14177 org-ts-what
14178 extra rem
14179 ts time time0)
14180 (if (not (org-at-timestamp-p t))
14181 (error "Not at a timestamp"))
14182 (if (and (not what) (eq org-ts-what 'bracket))
14183 (org-toggle-timestamp-type)
14184 (if (and (not what) (not (eq org-ts-what 'day))
14185 org-display-custom-times
14186 (get-text-property (point) 'display)
14187 (not (get-text-property (1- (point)) 'display)))
14188 (setq org-ts-what 'day))
14189 (setq org-ts-what (or what org-ts-what)
14190 inactive (= (char-after (match-beginning 0)) ?\[)
14191 ts (match-string 0))
14192 (replace-match "")
14193 (if (string-match
14194 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14196 (setq extra (match-string 1 ts)))
14197 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14198 (setq with-hm t))
14199 (setq time0 (org-parse-time-string ts))
14200 (when (and (eq org-ts-what 'minute)
14201 (eq current-prefix-arg nil))
14202 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14203 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14204 (setcar (cdr time0) (+ (nth 1 time0)
14205 (if (> n 0) (- rem) (- dm rem))))))
14206 (setq time
14207 (encode-time (or (car time0) 0)
14208 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14209 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14210 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14211 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14212 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14213 (nthcdr 6 time0)))
14214 (when (and (member org-ts-what '(hour minute))
14215 extra
14216 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14217 (setq extra (org-modify-ts-extra
14218 extra
14219 (if (eq org-ts-what 'hour) 2 5)
14220 n dm)))
14221 (when (integerp org-ts-what)
14222 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14223 (if (eq what 'calendar)
14224 (let ((cal-date (org-get-date-from-calendar)))
14225 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14226 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14227 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14228 (setcar time0 (or (car time0) 0))
14229 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14230 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14231 (setq time (apply 'encode-time time0))))
14232 (setq org-last-changed-timestamp
14233 (org-insert-time-stamp time with-hm inactive nil nil extra))
14234 (org-clock-update-time-maybe)
14235 (goto-char pos)
14236 ;; Try to recenter the calendar window, if any
14237 (if (and org-calendar-follow-timestamp-change
14238 (get-buffer-window "*Calendar*" t)
14239 (memq org-ts-what '(day month year)))
14240 (org-recenter-calendar (time-to-days time))))))
14242 (defun org-modify-ts-extra (s pos n dm)
14243 "Change the different parts of the lead-time and repeat fields in timestamp."
14244 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14245 ng h m new rem)
14246 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14247 (cond
14248 ((or (org-pos-in-match-range pos 2)
14249 (org-pos-in-match-range pos 3))
14250 (setq m (string-to-number (match-string 3 s))
14251 h (string-to-number (match-string 2 s)))
14252 (if (org-pos-in-match-range pos 2)
14253 (setq h (+ h n))
14254 (setq n (* dm (org-no-warnings (signum n))))
14255 (when (not (= 0 (setq rem (% m dm))))
14256 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14257 (setq m (+ m n)))
14258 (if (< m 0) (setq m (+ m 60) h (1- h)))
14259 (if (> m 59) (setq m (- m 60) h (1+ h)))
14260 (setq h (min 24 (max 0 h)))
14261 (setq ng 1 new (format "-%02d:%02d" h m)))
14262 ((org-pos-in-match-range pos 6)
14263 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14264 ((org-pos-in-match-range pos 5)
14265 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14267 ((org-pos-in-match-range pos 9)
14268 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14269 ((org-pos-in-match-range pos 8)
14270 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14272 (when ng
14273 (setq s (concat
14274 (substring s 0 (match-beginning ng))
14276 (substring s (match-end ng))))))
14279 (defun org-recenter-calendar (date)
14280 "If the calendar is visible, recenter it to DATE."
14281 (let* ((win (selected-window))
14282 (cwin (get-buffer-window "*Calendar*" t))
14283 (calendar-move-hook nil))
14284 (when cwin
14285 (select-window cwin)
14286 (calendar-goto-date (if (listp date) date
14287 (calendar-gregorian-from-absolute date)))
14288 (select-window win))))
14290 (defun org-goto-calendar (&optional arg)
14291 "Go to the Emacs calendar at the current date.
14292 If there is a time stamp in the current line, go to that date.
14293 A prefix ARG can be used to force the current date."
14294 (interactive "P")
14295 (let ((tsr org-ts-regexp) diff
14296 (calendar-move-hook nil)
14297 (calendar-view-holidays-initially-flag nil)
14298 (view-calendar-holidays-initially nil)
14299 (calendar-view-diary-initially-flag nil)
14300 (view-diary-entries-initially nil))
14301 (if (or (org-at-timestamp-p)
14302 (save-excursion
14303 (beginning-of-line 1)
14304 (looking-at (concat ".*" tsr))))
14305 (let ((d1 (time-to-days (current-time)))
14306 (d2 (time-to-days
14307 (org-time-string-to-time (match-string 1)))))
14308 (setq diff (- d2 d1))))
14309 (calendar)
14310 (calendar-goto-today)
14311 (if (and diff (not arg)) (calendar-forward-day diff))))
14313 (defun org-get-date-from-calendar ()
14314 "Return a list (month day year) of date at point in calendar."
14315 (with-current-buffer "*Calendar*"
14316 (save-match-data
14317 (calendar-cursor-to-date))))
14319 (defun org-date-from-calendar ()
14320 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14321 If there is already a time stamp at the cursor position, update it."
14322 (interactive)
14323 (if (org-at-timestamp-p t)
14324 (org-timestamp-change 0 'calendar)
14325 (let ((cal-date (org-get-date-from-calendar)))
14326 (org-insert-time-stamp
14327 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14329 (defun org-minutes-to-hh:mm-string (m)
14330 "Compute H:MM from a number of minutes."
14331 (let ((h (/ m 60)))
14332 (setq m (- m (* 60 h)))
14333 (format org-time-clocksum-format h m)))
14335 (defun org-hh:mm-string-to-minutes (s)
14336 "Convert a string H:MM to a number of minutes.
14337 If the string is just a number, interpret it as minutes.
14338 In fact, the first hh:mm or number in the string will be taken,
14339 there can be extra stuff in the string.
14340 If no number is found, the return value is 0."
14341 (cond
14342 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14343 (+ (* (string-to-number (match-string 1 s)) 60)
14344 (string-to-number (match-string 2 s))))
14345 ((string-match "\\([0-9]+\\)" s)
14346 (string-to-number (match-string 1 s)))
14347 (t 0)))
14349 ;;;; Files
14351 (defun org-save-all-org-buffers ()
14352 "Save all Org-mode buffers without user confirmation."
14353 (interactive)
14354 (message "Saving all Org-mode buffers...")
14355 (save-some-buffers t 'org-mode-p)
14356 (when (featurep 'org-id) (org-id-locations-save))
14357 (message "Saving all Org-mode buffers... done"))
14359 (defun org-revert-all-org-buffers ()
14360 "Revert all Org-mode buffers.
14361 Prompt for confirmation when there are unsaved changes.
14362 Be sure you know what you are doing before letting this function
14363 overwrite your changes.
14365 This function is useful in a setup where one tracks org files
14366 with a version control system, to revert on one machine after pulling
14367 changes from another. I believe the procedure must be like this:
14369 1. M-x org-save-all-org-buffers
14370 2. Pull changes from the other machine, resolve conflicts
14371 3. M-x org-revert-all-org-buffers"
14372 (interactive)
14373 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14374 (error "Abort"))
14375 (save-excursion
14376 (save-window-excursion
14377 (mapc
14378 (lambda (b)
14379 (when (and (with-current-buffer b (org-mode-p))
14380 (with-current-buffer b buffer-file-name))
14381 (switch-to-buffer b)
14382 (revert-buffer t 'no-confirm)))
14383 (buffer-list))
14384 (when (and (featurep 'org-id) org-id-track-globally)
14385 (org-id-locations-load)))))
14387 ;;;; Agenda files
14389 ;;;###autoload
14390 (defun org-iswitchb (&optional arg)
14391 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14392 With a prefix argument, restrict available to files.
14393 With two prefix arguments, restrict available buffers to agenda files."
14394 (interactive "P")
14395 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14396 ((equal arg '(16)) (org-buffer-list 'agenda))
14397 (t (org-buffer-list)))))
14398 (switch-to-buffer
14399 (org-icompleting-read "Org buffer: "
14400 (mapcar 'list (mapcar 'buffer-name blist))
14401 nil t))))
14403 ;;;###autoload
14404 (defalias 'org-ido-switchb 'org-iswitchb)
14406 (defun org-buffer-list (&optional predicate exclude-tmp)
14407 "Return a list of Org buffers.
14408 PREDICATE can be `export', `files' or `agenda'.
14410 export restrict the list to Export buffers.
14411 files restrict the list to buffers visiting Org files.
14412 agenda restrict the list to buffers visiting agenda files.
14414 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14415 (let* ((bfn nil)
14416 (agenda-files (and (eq predicate 'agenda)
14417 (mapcar 'file-truename (org-agenda-files t))))
14418 (filter
14419 (cond
14420 ((eq predicate 'files)
14421 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14422 ((eq predicate 'export)
14423 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14424 ((eq predicate 'agenda)
14425 (lambda (b)
14426 (with-current-buffer b
14427 (and (eq major-mode 'org-mode)
14428 (setq bfn (buffer-file-name b))
14429 (member (file-truename bfn) agenda-files)))))
14430 (t (lambda (b) (with-current-buffer b
14431 (or (eq major-mode 'org-mode)
14432 (string-match "\*Org .*Export"
14433 (buffer-name b)))))))))
14434 (delq nil
14435 (mapcar
14436 (lambda(b)
14437 (if (and (funcall filter b)
14438 (or (not exclude-tmp)
14439 (not (string-match "tmp" (buffer-name b)))))
14441 nil))
14442 (buffer-list)))))
14444 (defun org-agenda-files (&optional unrestricted archives)
14445 "Get the list of agenda files.
14446 Optional UNRESTRICTED means return the full list even if a restriction
14447 is currently in place.
14448 When ARCHIVES is t, include all archive files hat are really being
14449 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14450 `org-agenda-archives-mode' is t."
14451 (let ((files
14452 (cond
14453 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14454 ((stringp org-agenda-files) (org-read-agenda-file-list))
14455 ((listp org-agenda-files) org-agenda-files)
14456 (t (error "Invalid value of `org-agenda-files'")))))
14457 (setq files (apply 'append
14458 (mapcar (lambda (f)
14459 (if (file-directory-p f)
14460 (directory-files
14461 f t org-agenda-file-regexp)
14462 (list f)))
14463 files)))
14464 (when org-agenda-skip-unavailable-files
14465 (setq files (delq nil
14466 (mapcar (function
14467 (lambda (file)
14468 (and (file-readable-p file) file)))
14469 files))))
14470 (when (or (eq archives t)
14471 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14472 (setq files (org-add-archive-files files)))
14473 files))
14475 (defun org-edit-agenda-file-list ()
14476 "Edit the list of agenda files.
14477 Depending on setup, this either uses customize to edit the variable
14478 `org-agenda-files', or it visits the file that is holding the list. In the
14479 latter case, the buffer is set up in a way that saving it automatically kills
14480 the buffer and restores the previous window configuration."
14481 (interactive)
14482 (if (stringp org-agenda-files)
14483 (let ((cw (current-window-configuration)))
14484 (find-file org-agenda-files)
14485 (org-set-local 'org-window-configuration cw)
14486 (org-add-hook 'after-save-hook
14487 (lambda ()
14488 (set-window-configuration
14489 (prog1 org-window-configuration
14490 (kill-buffer (current-buffer))))
14491 (org-install-agenda-files-menu)
14492 (message "New agenda file list installed"))
14493 nil 'local)
14494 (message "%s" (substitute-command-keys
14495 "Edit list and finish with \\[save-buffer]")))
14496 (customize-variable 'org-agenda-files)))
14498 (defun org-store-new-agenda-file-list (list)
14499 "Set new value for the agenda file list and save it correctly."
14500 (if (stringp org-agenda-files)
14501 (let ((f org-agenda-files) b)
14502 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14503 (with-temp-file f
14504 (insert (mapconcat 'identity list "\n") "\n")))
14505 (let ((org-mode-hook nil) (org-inhibit-startup t)
14506 (org-insert-mode-line-in-empty-file nil))
14507 (setq org-agenda-files list)
14508 (customize-save-variable 'org-agenda-files org-agenda-files))))
14510 (defun org-read-agenda-file-list ()
14511 "Read the list of agenda files from a file."
14512 (when (file-directory-p org-agenda-files)
14513 (error "`org-agenda-files' cannot be a single directory"))
14514 (when (stringp org-agenda-files)
14515 (with-temp-buffer
14516 (insert-file-contents org-agenda-files)
14517 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14520 ;;;###autoload
14521 (defun org-cycle-agenda-files ()
14522 "Cycle through the files in `org-agenda-files'.
14523 If the current buffer visits an agenda file, find the next one in the list.
14524 If the current buffer does not, find the first agenda file."
14525 (interactive)
14526 (let* ((fs (org-agenda-files t))
14527 (files (append fs (list (car fs))))
14528 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14529 file)
14530 (unless files (error "No agenda files"))
14531 (catch 'exit
14532 (while (setq file (pop files))
14533 (if (equal (file-truename file) tcf)
14534 (when (car files)
14535 (find-file (car files))
14536 (throw 'exit t))))
14537 (find-file (car fs)))
14538 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14540 (defun org-agenda-file-to-front (&optional to-end)
14541 "Move/add the current file to the top of the agenda file list.
14542 If the file is not present in the list, it is added to the front. If it is
14543 present, it is moved there. With optional argument TO-END, add/move to the
14544 end of the list."
14545 (interactive "P")
14546 (let ((org-agenda-skip-unavailable-files nil)
14547 (file-alist (mapcar (lambda (x)
14548 (cons (file-truename x) x))
14549 (org-agenda-files t)))
14550 (ctf (file-truename buffer-file-name))
14551 x had)
14552 (setq x (assoc ctf file-alist) had x)
14554 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14555 (if to-end
14556 (setq file-alist (append (delq x file-alist) (list x)))
14557 (setq file-alist (cons x (delq x file-alist))))
14558 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14559 (org-install-agenda-files-menu)
14560 (message "File %s to %s of agenda file list"
14561 (if had "moved" "added") (if to-end "end" "front"))))
14563 (defun org-remove-file (&optional file)
14564 "Remove current file from the list of files in variable `org-agenda-files'.
14565 These are the files which are being checked for agenda entries.
14566 Optional argument FILE means use this file instead of the current."
14567 (interactive)
14568 (let* ((org-agenda-skip-unavailable-files nil)
14569 (file (or file buffer-file-name))
14570 (true-file (file-truename file))
14571 (afile (abbreviate-file-name file))
14572 (files (delq nil (mapcar
14573 (lambda (x)
14574 (if (equal true-file
14575 (file-truename x))
14576 nil x))
14577 (org-agenda-files t)))))
14578 (if (not (= (length files) (length (org-agenda-files t))))
14579 (progn
14580 (org-store-new-agenda-file-list files)
14581 (org-install-agenda-files-menu)
14582 (message "Removed file: %s" afile))
14583 (message "File was not in list: %s (not removed)" afile))))
14585 (defun org-file-menu-entry (file)
14586 (vector file (list 'find-file file) t))
14588 (defun org-check-agenda-file (file)
14589 "Make sure FILE exists. If not, ask user what to do."
14590 (when (not (file-exists-p file))
14591 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14592 (abbreviate-file-name file))
14593 (let ((r (downcase (read-char-exclusive))))
14594 (cond
14595 ((equal r ?r)
14596 (org-remove-file file)
14597 (throw 'nextfile t))
14598 (t (error "Abort"))))))
14600 (defun org-get-agenda-file-buffer (file)
14601 "Get a buffer visiting FILE. If the buffer needs to be created, add
14602 it to the list of buffers which might be released later."
14603 (let ((buf (org-find-base-buffer-visiting file)))
14604 (if buf
14605 buf ; just return it
14606 ;; Make a new buffer and remember it
14607 (setq buf (find-file-noselect file))
14608 (if buf (push buf org-agenda-new-buffers))
14609 buf)))
14611 (defun org-release-buffers (blist)
14612 "Release all buffers in list, asking the user for confirmation when needed.
14613 When a buffer is unmodified, it is just killed. When modified, it is saved
14614 \(if the user agrees) and then killed."
14615 (let (buf file)
14616 (while (setq buf (pop blist))
14617 (setq file (buffer-file-name buf))
14618 (when (and (buffer-modified-p buf)
14619 file
14620 (y-or-n-p (format "Save file %s? " file)))
14621 (with-current-buffer buf (save-buffer)))
14622 (kill-buffer buf))))
14624 (defun org-prepare-agenda-buffers (files)
14625 "Create buffers for all agenda files, protect archived trees and comments."
14626 (interactive)
14627 (let ((pa '(:org-archived t))
14628 (pc '(:org-comment t))
14629 (pall '(:org-archived t :org-comment t))
14630 (inhibit-read-only t)
14631 (rea (concat ":" org-archive-tag ":"))
14632 bmp file re)
14633 (save-excursion
14634 (save-restriction
14635 (while (setq file (pop files))
14636 (catch 'nextfile
14637 (if (bufferp file)
14638 (set-buffer file)
14639 (org-check-agenda-file file)
14640 (set-buffer (org-get-agenda-file-buffer file)))
14641 (widen)
14642 (setq bmp (buffer-modified-p))
14643 (org-refresh-category-properties)
14644 (setq org-todo-keywords-for-agenda
14645 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14646 (setq org-done-keywords-for-agenda
14647 (append org-done-keywords-for-agenda org-done-keywords))
14648 (setq org-todo-keyword-alist-for-agenda
14649 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14650 (setq org-drawers-for-agenda
14651 (append org-drawers-for-agenda org-drawers))
14652 (setq org-tag-alist-for-agenda
14653 (append org-tag-alist-for-agenda org-tag-alist))
14655 (save-excursion
14656 (remove-text-properties (point-min) (point-max) pall)
14657 (when org-agenda-skip-archived-trees
14658 (goto-char (point-min))
14659 (while (re-search-forward rea nil t)
14660 (if (org-on-heading-p t)
14661 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14662 (goto-char (point-min))
14663 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14664 (while (re-search-forward re nil t)
14665 (add-text-properties
14666 (match-beginning 0) (org-end-of-subtree t) pc)))
14667 (set-buffer-modified-p bmp)))))
14668 (setq org-todo-keyword-alist-for-agenda
14669 (org-uniquify org-todo-keyword-alist-for-agenda)
14670 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14672 ;;;; Embedded LaTeX
14674 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14675 "Keymap for the minor `org-cdlatex-mode'.")
14677 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14678 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14679 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14680 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14681 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14683 (defvar org-cdlatex-texmathp-advice-is-done nil
14684 "Flag remembering if we have applied the advice to texmathp already.")
14686 (define-minor-mode org-cdlatex-mode
14687 "Toggle the minor `org-cdlatex-mode'.
14688 This mode supports entering LaTeX environment and math in LaTeX fragments
14689 in Org-mode.
14690 \\{org-cdlatex-mode-map}"
14691 nil " OCDL" nil
14692 (when org-cdlatex-mode (require 'cdlatex))
14693 (unless org-cdlatex-texmathp-advice-is-done
14694 (setq org-cdlatex-texmathp-advice-is-done t)
14695 (defadvice texmathp (around org-math-always-on activate)
14696 "Always return t in org-mode buffers.
14697 This is because we want to insert math symbols without dollars even outside
14698 the LaTeX math segments. If Orgmode thinks that point is actually inside
14699 an embedded LaTeX fragment, let texmathp do its job.
14700 \\[org-cdlatex-mode-map]"
14701 (interactive)
14702 (let (p)
14703 (cond
14704 ((not (org-mode-p)) ad-do-it)
14705 ((eq this-command 'cdlatex-math-symbol)
14706 (setq ad-return-value t
14707 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14709 (let ((p (org-inside-LaTeX-fragment-p)))
14710 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14711 (setq ad-return-value t
14712 texmathp-why '("Org-mode embedded math" . 0))
14713 (if p ad-do-it)))))))))
14715 (defun turn-on-org-cdlatex ()
14716 "Unconditionally turn on `org-cdlatex-mode'."
14717 (org-cdlatex-mode 1))
14719 (defun org-inside-LaTeX-fragment-p ()
14720 "Test if point is inside a LaTeX fragment.
14721 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14722 sequence appearing also before point.
14723 Even though the matchers for math are configurable, this function assumes
14724 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14725 delimiters are skipped when they have been removed by customization.
14726 The return value is nil, or a cons cell with the delimiter and
14727 and the position of this delimiter.
14729 This function does a reasonably good job, but can locally be fooled by
14730 for example currency specifications. For example it will assume being in
14731 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14732 fragments that are properly closed, but during editing, we have to live
14733 with the uncertainty caused by missing closing delimiters. This function
14734 looks only before point, not after."
14735 (catch 'exit
14736 (let ((pos (point))
14737 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14738 (lim (progn
14739 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14740 (point)))
14741 dd-on str (start 0) m re)
14742 (goto-char pos)
14743 (when dodollar
14744 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14745 re (nth 1 (assoc "$" org-latex-regexps)))
14746 (while (string-match re str start)
14747 (cond
14748 ((= (match-end 0) (length str))
14749 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14750 ((= (match-end 0) (- (length str) 5))
14751 (throw 'exit nil))
14752 (t (setq start (match-end 0))))))
14753 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14754 (goto-char pos)
14755 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14756 (and (match-beginning 2) (throw 'exit nil))
14757 ;; count $$
14758 (while (re-search-backward "\\$\\$" lim t)
14759 (setq dd-on (not dd-on)))
14760 (goto-char pos)
14761 (if dd-on (cons "$$" m))))))
14763 (defun org-inside-latex-macro-p ()
14764 "Is point inside a LaTeX macro or its arguments?"
14765 (save-match-data
14766 (org-in-regexp
14767 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14769 (defun org-try-cdlatex-tab ()
14770 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14771 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14772 - inside a LaTeX fragment, or
14773 - after the first word in a line, where an abbreviation expansion could
14774 insert a LaTeX environment."
14775 (when org-cdlatex-mode
14776 (cond
14777 ((save-excursion
14778 (skip-chars-backward "a-zA-Z0-9*")
14779 (skip-chars-backward " \t")
14780 (bolp))
14781 (cdlatex-tab) t)
14782 ((org-inside-LaTeX-fragment-p)
14783 (cdlatex-tab) t)
14784 (t nil))))
14786 (defun org-cdlatex-underscore-caret (&optional arg)
14787 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14788 Revert to the normal definition outside of these fragments."
14789 (interactive "P")
14790 (if (org-inside-LaTeX-fragment-p)
14791 (call-interactively 'cdlatex-sub-superscript)
14792 (let (org-cdlatex-mode)
14793 (call-interactively (key-binding (vector last-input-event))))))
14795 (defun org-cdlatex-math-modify (&optional arg)
14796 "Execute `cdlatex-math-modify' in LaTeX fragments.
14797 Revert to the normal definition outside of these fragments."
14798 (interactive "P")
14799 (if (org-inside-LaTeX-fragment-p)
14800 (call-interactively 'cdlatex-math-modify)
14801 (let (org-cdlatex-mode)
14802 (call-interactively (key-binding (vector last-input-event))))))
14804 (defvar org-latex-fragment-image-overlays nil
14805 "List of overlays carrying the images of latex fragments.")
14806 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14808 (defun org-remove-latex-fragment-image-overlays ()
14809 "Remove all overlays with LaTeX fragment images in current buffer."
14810 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14811 (setq org-latex-fragment-image-overlays nil))
14813 (defun org-preview-latex-fragment (&optional subtree)
14814 "Preview the LaTeX fragment at point, or all locally or globally.
14815 If the cursor is in a LaTeX fragment, create the image and overlay
14816 it over the source code. If there is no fragment at point, display
14817 all fragments in the current text, from one headline to the next. With
14818 prefix SUBTREE, display all fragments in the current subtree. With a
14819 double prefix `C-u C-u', or when the cursor is before the first headline,
14820 display all fragments in the buffer.
14821 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14822 (interactive "P")
14823 (org-remove-latex-fragment-image-overlays)
14824 (save-excursion
14825 (save-restriction
14826 (let (beg end at msg)
14827 (cond
14828 ((or (equal subtree '(16))
14829 (not (save-excursion
14830 (re-search-backward (concat "^" outline-regexp) nil t))))
14831 (setq beg (point-min) end (point-max)
14832 msg "Creating images for buffer...%s"))
14833 ((equal subtree '(4))
14834 (org-back-to-heading)
14835 (setq beg (point) end (org-end-of-subtree t)
14836 msg "Creating images for subtree...%s"))
14838 (if (setq at (org-inside-LaTeX-fragment-p))
14839 (goto-char (max (point-min) (- (cdr at) 2)))
14840 (org-back-to-heading))
14841 (setq beg (point) end (progn (outline-next-heading) (point))
14842 msg (if at "Creating image...%s"
14843 "Creating images for entry...%s"))))
14844 (message msg "")
14845 (narrow-to-region beg end)
14846 (goto-char beg)
14847 (org-format-latex
14848 (concat "ltxpng/" (file-name-sans-extension
14849 (file-name-nondirectory
14850 buffer-file-name)))
14851 default-directory 'overlays msg at 'forbuffer)
14852 (message msg "done. Use `C-c C-c' to remove images.")))))
14854 (defvar org-latex-regexps
14855 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14856 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14857 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14858 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14859 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14860 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14861 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14862 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14863 "Regular expressions for matching embedded LaTeX.")
14865 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14866 "Replace LaTeX fragments with links to an image, and produce images.
14867 Some of the options can be changed using the variable
14868 `org-format-latex-options'."
14869 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14870 (let* ((prefixnodir (file-name-nondirectory prefix))
14871 (absprefix (expand-file-name prefix dir))
14872 (todir (file-name-directory absprefix))
14873 (opt org-format-latex-options)
14874 (matchers (plist-get opt :matchers))
14875 (re-list org-latex-regexps)
14876 (org-format-latex-header-extra
14877 (plist-get (org-infile-export-plist) :latex-header-extra))
14878 (cnt 0) txt hash link beg end re e checkdir
14879 executables-checked
14880 m n block linkfile movefile ov)
14881 ;; Check the different regular expressions
14882 (while (setq e (pop re-list))
14883 (setq m (car e) re (nth 1 e) n (nth 2 e)
14884 block (if (nth 3 e) "\n\n" ""))
14885 (when (member m matchers)
14886 (goto-char (point-min))
14887 (while (re-search-forward re nil t)
14888 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14889 (not (get-text-property (match-beginning n)
14890 'org-protected))
14891 (or (not overlays)
14892 (not (eq (get-char-property (match-beginning n)
14893 'org-overlay-type)
14894 'org-latex-overlay))))
14895 (setq txt (match-string n)
14896 beg (match-beginning n) end (match-end n)
14897 cnt (1+ cnt))
14898 (let (print-length print-level) ; make sure full list is printed
14899 (setq hash (sha1 (prin1-to-string
14900 (list org-format-latex-header
14901 org-format-latex-header-extra
14902 org-export-latex-packages-alist
14903 org-format-latex-options
14904 forbuffer txt)))
14905 linkfile (format "%s_%s.png" prefix hash)
14906 movefile (format "%s_%s.png" absprefix hash)))
14907 (setq link (concat block "[[file:" linkfile "]]" block))
14908 (if msg (message msg cnt))
14909 (goto-char beg)
14910 (unless checkdir ; make sure the directory exists
14911 (setq checkdir t)
14912 (or (file-directory-p todir) (make-directory todir)))
14914 (unless executables-checked
14915 (org-check-external-command
14916 "latex" "needed to convert LaTeX fragments to images")
14917 (org-check-external-command
14918 "dvipng" "needed to convert LaTeX fragments to images")
14919 (setq executables-checked t))
14921 (unless (file-exists-p movefile)
14922 (org-create-formula-image
14923 txt movefile opt forbuffer))
14924 (if overlays
14925 (progn
14926 (mapc (lambda (o)
14927 (if (eq (org-overlay-get o 'org-overlay-type)
14928 'org-latex-overlay)
14929 (org-delete-overlay o)))
14930 (org-overlays-in beg end))
14931 (setq ov (org-make-overlay beg end))
14932 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14933 (if (featurep 'xemacs)
14934 (progn
14935 (org-overlay-put ov 'invisible t)
14936 (org-overlay-put
14937 ov 'end-glyph
14938 (make-glyph (vector 'png :file movefile))))
14939 (org-overlay-put
14940 ov 'display
14941 (list 'image :type 'png :file movefile :ascent 'center)))
14942 (push ov org-latex-fragment-image-overlays)
14943 (goto-char end))
14944 (delete-region beg end)
14945 (insert link))))))))
14947 ;; This function borrows from Ganesh Swami's latex2png.el
14948 (defun org-create-formula-image (string tofile options buffer)
14949 "This calls dvipng."
14950 (require 'org-latex)
14951 (let* ((tmpdir (if (featurep 'xemacs)
14952 (temp-directory)
14953 temporary-file-directory))
14954 (texfilebase (make-temp-name
14955 (expand-file-name "orgtex" tmpdir)))
14956 (texfile (concat texfilebase ".tex"))
14957 (dvifile (concat texfilebase ".dvi"))
14958 (pngfile (concat texfilebase ".png"))
14959 (fnh (if (featurep 'xemacs)
14960 (font-height (get-face-font 'default))
14961 (face-attribute 'default :height nil)))
14962 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14963 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14964 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14965 "Black"))
14966 (bg (or (plist-get options (if buffer :background :html-background))
14967 "Transparent")))
14968 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14969 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14970 (with-temp-file texfile
14971 (insert org-format-latex-header
14972 (if org-export-latex-packages-alist
14973 (concat "\n"
14974 (mapconcat (lambda(p)
14975 (if (equal "" (car p))
14976 (format "\\usepackage{%s}" (cadr p))
14977 (format "\\usepackage[%s]{%s}"
14978 (car p) (cadr p))))
14979 org-export-latex-packages-alist "\n"))
14981 (if org-format-latex-header-extra
14982 (concat "\n" org-format-latex-header-extra)
14984 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14985 (let ((dir default-directory))
14986 (condition-case nil
14987 (progn
14988 (cd tmpdir)
14989 (call-process "latex" nil nil nil texfile))
14990 (error nil))
14991 (cd dir))
14992 (if (not (file-exists-p dvifile))
14993 (progn (message "Failed to create dvi file from %s" texfile) nil)
14994 (condition-case nil
14995 (call-process "dvipng" nil nil nil
14996 "-fg" fg "-bg" bg
14997 "-D" dpi
14998 ;;"-x" scale "-y" scale
14999 "-T" "tight"
15000 "-o" pngfile
15001 dvifile)
15002 (error nil))
15003 (if (not (file-exists-p pngfile))
15004 (if org-format-latex-signal-error
15005 (error "Failed to create png file from %s" texfile)
15006 (message "Failed to create png file from %s" texfile)
15007 nil)
15008 ;; Use the requested file name and clean up
15009 (copy-file pngfile tofile 'replace)
15010 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15011 (delete-file (concat texfilebase e)))
15012 pngfile))))
15014 (defun org-dvipng-color (attr)
15015 "Return an rgb color specification for dvipng."
15016 (apply 'format "rgb %s %s %s"
15017 (mapcar 'org-normalize-color
15018 (color-values (face-attribute 'default attr nil)))))
15020 (defun org-normalize-color (value)
15021 "Return string to be used as color value for an RGB component."
15022 (format "%g" (/ value 65535.0)))
15024 ;;;; Key bindings
15026 ;; Make `C-c C-x' a prefix key
15027 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15029 ;; TAB key with modifiers
15030 (org-defkey org-mode-map "\C-i" 'org-cycle)
15031 (org-defkey org-mode-map [(tab)] 'org-cycle)
15032 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15033 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15034 (org-defkey org-mode-map "\M-\t" 'org-complete)
15035 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15036 ;; The following line is necessary under Suse GNU/Linux
15037 (unless (featurep 'xemacs)
15038 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15039 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15040 (define-key org-mode-map [backtab] 'org-shifttab)
15042 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15043 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15044 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15046 ;; Cursor keys with modifiers
15047 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15048 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15049 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15050 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15052 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15053 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15054 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15055 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15057 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15058 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15059 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15060 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15062 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15063 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15065 ;;; Extra keys for tty access.
15066 ;; We only set them when really needed because otherwise the
15067 ;; menus don't show the simple keys
15069 (when (or org-use-extra-keys
15070 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15071 (not window-system))
15072 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15073 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15074 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15075 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15076 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15077 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15078 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15079 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15080 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15081 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15082 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15083 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15084 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15085 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15086 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15087 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15088 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15089 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15090 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15091 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15092 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15093 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15094 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15095 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15096 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15097 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15098 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15099 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15101 ;; All the other keys
15103 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15104 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15105 (if (boundp 'narrow-map)
15106 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15107 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15108 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15109 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15110 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15111 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15112 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15113 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15114 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15115 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15116 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15117 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15118 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15119 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15120 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15121 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15122 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15123 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15124 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15125 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15126 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15127 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15128 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15129 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15130 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15131 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15132 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15133 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15134 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15135 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15136 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15137 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15138 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15139 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15140 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15141 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15142 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15143 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15144 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15145 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15146 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15147 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15148 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15149 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15150 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15151 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15152 (org-defkey org-mode-map "\C-c^" 'org-sort)
15153 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15154 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15155 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15156 (org-defkey org-mode-map "\C-m" 'org-return)
15157 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15158 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15159 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15160 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15161 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15162 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15163 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15164 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15165 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15166 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15167 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15168 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15169 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15170 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15171 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15172 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15173 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15174 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15175 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15176 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15177 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15179 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15180 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15181 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15182 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15184 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15185 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15186 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15187 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15188 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15189 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15190 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15191 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15192 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15193 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15194 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15195 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15196 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15197 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15198 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15200 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15201 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15202 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15203 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15205 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15207 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15209 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15210 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15212 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15215 (when (featurep 'xemacs)
15216 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15219 (defconst org-speed-commands-default
15221 ("Outline Navigation")
15222 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15223 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15224 ("f" . (org-speed-move-safe 'org-forward-same-level))
15225 ("b" . (org-speed-move-safe 'org-backward-same-level))
15226 ("u" . (org-speed-move-safe 'outline-up-heading))
15227 ("j" . org-goto)
15228 ("g" . (org-refile t))
15229 ("Outline Visibility")
15230 ("c" . org-cycle)
15231 ("C" . org-shifttab)
15232 (" " . org-display-outline-path)
15233 ("Outline Structure Editing")
15234 ("U" . org-shiftmetaup)
15235 ("D" . org-shiftmetadown)
15236 ("r" . org-metaright)
15237 ("l" . org-metaleft)
15238 ("R" . org-shiftmetaright)
15239 ("L" . org-shiftmetaleft)
15240 ("i" . (progn (forward-char 1) (call-interactively
15241 'org-insert-heading-respect-content)))
15242 ("^" . org-sort)
15243 ("w" . org-refile)
15244 ("a" . org-archive-subtree-default-with-confirmation)
15245 ("." . outline-mark-subtree)
15246 ("Clock Commands")
15247 ("I" . org-clock-in)
15248 ("O" . org-clock-out)
15249 ("Meta Data Editing")
15250 ("t" . org-todo)
15251 ("0" . (org-priority ?\ ))
15252 ("1" . (org-priority ?A))
15253 ("2" . (org-priority ?B))
15254 ("3" . (org-priority ?C))
15255 (";" . org-set-tags-command)
15256 ("e" . org-set-effort)
15257 ("Agenda Views etc")
15258 ("v" . org-agenda)
15259 ("/" . org-sparse-tree)
15260 ("Misc")
15261 ("o" . org-open-at-point)
15262 ("?" . org-speed-command-help)
15264 "The default speed commands.")
15266 (defun org-print-speed-command (e)
15267 (if (> (length (car e)) 1)
15268 (progn
15269 (princ "\n")
15270 (princ (car e))
15271 (princ "\n")
15272 (princ (make-string (length (car e)) ?-))
15273 (princ "\n"))
15274 (princ (car e))
15275 (princ " ")
15276 (if (symbolp (cdr e))
15277 (princ (symbol-name (cdr e)))
15278 (prin1 (cdr e)))
15279 (princ "\n")))
15281 (defun org-speed-command-help ()
15282 "Show the available speed commands."
15283 (interactive)
15284 (if (not org-use-speed-commands)
15285 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15286 (with-output-to-temp-buffer "*Help*"
15287 (princ "User-defined Speed commands\n===========================\n")
15288 (mapc 'org-print-speed-command org-speed-commands-user)
15289 (princ "\n")
15290 (princ "Built-in Speed commands\n=======================\n")
15291 (mapc 'org-print-speed-command org-speed-commands-default))
15292 (with-current-buffer "*Help*"
15293 (setq truncate-lines t))))
15295 (defun org-speed-move-safe (cmd)
15296 "Execute CMD, but make sure that the cursor always ends up in a headline.
15297 If not, return to the original position and throw an error."
15298 (interactive)
15299 (let ((pos (point)))
15300 (call-interactively cmd)
15301 (unless (and (bolp) (org-on-heading-p))
15302 (goto-char pos)
15303 (error "Boundary reached while executing %s" cmd))))
15305 (defvar org-self-insert-command-undo-counter 0)
15307 (defvar org-table-auto-blank-field) ; defined in org-table.el
15308 (defvar org-speed-command nil)
15309 (defun org-self-insert-command (N)
15310 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15311 If the cursor is in a table looking at whitespace, the whitespace is
15312 overwritten, and the table is not marked as requiring realignment."
15313 (interactive "p")
15314 (cond
15315 ((and org-use-speed-commands
15316 (or (and (bolp) (looking-at outline-regexp))
15317 (and (functionp org-use-speed-commands)
15318 (funcall org-use-speed-commands)))
15319 (setq
15320 org-speed-command
15321 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15322 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15323 (cond
15324 ((commandp org-speed-command)
15325 (setq this-command org-speed-command)
15326 (call-interactively org-speed-command))
15327 ((functionp org-speed-command)
15328 (funcall org-speed-command))
15329 ((and org-speed-command (listp org-speed-command))
15330 (eval org-speed-command))
15331 (t (let (org-use-speed-commands)
15332 (call-interactively 'org-self-insert-command)))))
15333 ((and
15334 (org-table-p)
15335 (progn
15336 ;; check if we blank the field, and if that triggers align
15337 (and (featurep 'org-table) org-table-auto-blank-field
15338 (member last-command
15339 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15340 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15341 ;; got extra space, this field does not determine column width
15342 (let (org-table-may-need-update) (org-table-blank-field))
15343 ;; no extra space, this field may determine column width
15344 (org-table-blank-field)))
15346 (eq N 1)
15347 (looking-at "[^|\n]* |"))
15348 (let (org-table-may-need-update)
15349 (goto-char (1- (match-end 0)))
15350 (delete-backward-char 1)
15351 (goto-char (match-beginning 0))
15352 (self-insert-command N)))
15354 (setq org-table-may-need-update t)
15355 (self-insert-command N)
15356 (org-fix-tags-on-the-fly)
15357 (if org-self-insert-cluster-for-undo
15358 (if (not (eq last-command 'org-self-insert-command))
15359 (setq org-self-insert-command-undo-counter 1)
15360 (if (>= org-self-insert-command-undo-counter 20)
15361 (setq org-self-insert-command-undo-counter 1)
15362 (and (> org-self-insert-command-undo-counter 0)
15363 buffer-undo-list
15364 (not (cadr buffer-undo-list)) ; remove nil entry
15365 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15366 (setq org-self-insert-command-undo-counter
15367 (1+ org-self-insert-command-undo-counter))))))))
15369 (defun org-fix-tags-on-the-fly ()
15370 (when (and (equal (char-after (point-at-bol)) ?*)
15371 (org-on-heading-p))
15372 (org-align-tags-here org-tags-column)))
15374 (defun org-delete-backward-char (N)
15375 "Like `delete-backward-char', insert whitespace at field end in tables.
15376 When deleting backwards, in tables this function will insert whitespace in
15377 front of the next \"|\" separator, to keep the table aligned. The table will
15378 still be marked for re-alignment if the field did fill the entire column,
15379 because, in this case the deletion might narrow the column."
15380 (interactive "p")
15381 (if (and (org-table-p)
15382 (eq N 1)
15383 (string-match "|" (buffer-substring (point-at-bol) (point)))
15384 (looking-at ".*?|"))
15385 (let ((pos (point))
15386 (noalign (looking-at "[^|\n\r]* |"))
15387 (c org-table-may-need-update))
15388 (backward-delete-char N)
15389 (skip-chars-forward "^|")
15390 (insert " ")
15391 (goto-char (1- pos))
15392 ;; noalign: if there were two spaces at the end, this field
15393 ;; does not determine the width of the column.
15394 (if noalign (setq org-table-may-need-update c)))
15395 (backward-delete-char N)
15396 (org-fix-tags-on-the-fly)))
15398 (defun org-delete-char (N)
15399 "Like `delete-char', but insert whitespace at field end in tables.
15400 When deleting characters, in tables this function will insert whitespace in
15401 front of the next \"|\" separator, to keep the table aligned. The table will
15402 still be marked for re-alignment if the field did fill the entire column,
15403 because, in this case the deletion might narrow the column."
15404 (interactive "p")
15405 (if (and (org-table-p)
15406 (not (bolp))
15407 (not (= (char-after) ?|))
15408 (eq N 1))
15409 (if (looking-at ".*?|")
15410 (let ((pos (point))
15411 (noalign (looking-at "[^|\n\r]* |"))
15412 (c org-table-may-need-update))
15413 (replace-match (concat
15414 (substring (match-string 0) 1 -1)
15415 " |"))
15416 (goto-char pos)
15417 ;; noalign: if there were two spaces at the end, this field
15418 ;; does not determine the width of the column.
15419 (if noalign (setq org-table-may-need-update c)))
15420 (delete-char N))
15421 (delete-char N)
15422 (org-fix-tags-on-the-fly)))
15424 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15425 (put 'org-self-insert-command 'delete-selection t)
15426 (put 'orgtbl-self-insert-command 'delete-selection t)
15427 (put 'org-delete-char 'delete-selection 'supersede)
15428 (put 'org-delete-backward-char 'delete-selection 'supersede)
15429 (put 'org-yank 'delete-selection 'yank)
15431 ;; Make `flyspell-mode' delay after some commands
15432 (put 'org-self-insert-command 'flyspell-delayed t)
15433 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15434 (put 'org-delete-char 'flyspell-delayed t)
15435 (put 'org-delete-backward-char 'flyspell-delayed t)
15437 ;; Make pabbrev-mode expand after org-mode commands
15438 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15439 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15441 ;; How to do this: Measure non-white length of current string
15442 ;; If equal to column width, we should realign.
15444 (defun org-remap (map &rest commands)
15445 "In MAP, remap the functions given in COMMANDS.
15446 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15447 (let (new old)
15448 (while commands
15449 (setq old (pop commands) new (pop commands))
15450 (if (fboundp 'command-remapping)
15451 (org-defkey map (vector 'remap old) new)
15452 (substitute-key-definition old new map global-map)))))
15454 (when (eq org-enable-table-editor 'optimized)
15455 ;; If the user wants maximum table support, we need to hijack
15456 ;; some standard editing functions
15457 (org-remap org-mode-map
15458 'self-insert-command 'org-self-insert-command
15459 'delete-char 'org-delete-char
15460 'delete-backward-char 'org-delete-backward-char)
15461 (org-defkey org-mode-map "|" 'org-force-self-insert))
15463 (defvar org-ctrl-c-ctrl-c-hook nil
15464 "Hook for functions attaching themselves to `C-c C-c'.
15465 This can be used to add additional functionality to the C-c C-c key which
15466 executes context-dependent commands.
15467 Each function will be called with no arguments. The function must check
15468 if the context is appropriate for it to act. If yes, it should do its
15469 thing and then return a non-nil value. If the context is wrong,
15470 just do nothing and return nil.")
15472 (defvar org-tab-first-hook nil
15473 "Hook for functions to attach themselves to TAB.
15474 See `org-ctrl-c-ctrl-c-hook' for more information.
15475 This hook runs as the first action when TAB is pressed, even before
15476 `org-cycle' messes around with the `outline-regexp' to cater for
15477 inline tasks and plain list item folding.
15478 If any function in this hook returns t, not other actions like table
15479 field motion visibility cycling will be done.")
15481 (defvar org-tab-after-check-for-table-hook nil
15482 "Hook for functions to attach themselves to TAB.
15483 See `org-ctrl-c-ctrl-c-hook' for more information.
15484 This hook runs after it has been established that the cursor is not in a
15485 table, but before checking if the cursor is in a headline or if global cycling
15486 should be done.
15487 If any function in this hook returns t, not other actions like visibility
15488 cycling will be done.")
15490 (defvar org-tab-after-check-for-cycling-hook nil
15491 "Hook for functions to attach themselves to TAB.
15492 See `org-ctrl-c-ctrl-c-hook' for more information.
15493 This hook runs after it has been established that not table field motion and
15494 not visibility should be done because of current context. This is probably
15495 the place where a package like yasnippets can hook in.")
15497 (defvar org-tab-before-tab-emulation-hook nil
15498 "Hook for functions to attach themselves to TAB.
15499 See `org-ctrl-c-ctrl-c-hook' for more information.
15500 This hook runs after every other options for TAB have been exhausted, but
15501 before indentation and \t insertion takes place.")
15503 (defvar org-metaleft-hook nil
15504 "Hook for functions attaching themselves to `M-left'.
15505 See `org-ctrl-c-ctrl-c-hook' for more information.")
15506 (defvar org-metaright-hook nil
15507 "Hook for functions attaching themselves to `M-right'.
15508 See `org-ctrl-c-ctrl-c-hook' for more information.")
15509 (defvar org-metaup-hook nil
15510 "Hook for functions attaching themselves to `M-up'.
15511 See `org-ctrl-c-ctrl-c-hook' for more information.")
15512 (defvar org-metadown-hook nil
15513 "Hook for functions attaching themselves to `M-down'.
15514 See `org-ctrl-c-ctrl-c-hook' for more information.")
15515 (defvar org-shiftmetaleft-hook nil
15516 "Hook for functions attaching themselves to `M-S-left'.
15517 See `org-ctrl-c-ctrl-c-hook' for more information.")
15518 (defvar org-shiftmetaright-hook nil
15519 "Hook for functions attaching themselves to `M-S-right'.
15520 See `org-ctrl-c-ctrl-c-hook' for more information.")
15521 (defvar org-shiftmetaup-hook nil
15522 "Hook for functions attaching themselves to `M-S-up'.
15523 See `org-ctrl-c-ctrl-c-hook' for more information.")
15524 (defvar org-shiftmetadown-hook nil
15525 "Hook for functions attaching themselves to `M-S-down'.
15526 See `org-ctrl-c-ctrl-c-hook' for more information.")
15527 (defvar org-metareturn-hook nil
15528 "Hook for functions attaching themselves to `M-RET'.
15529 See `org-ctrl-c-ctrl-c-hook' for more information.")
15531 (defun org-modifier-cursor-error ()
15532 "Throw an error, a modified cursor command was applied in wrong context."
15533 (error "This command is active in special context like tables, headlines or items"))
15535 (defun org-shiftselect-error ()
15536 "Throw an error because Shift-Cursor command was applied in wrong context."
15537 (if (and (boundp 'shift-select-mode) shift-select-mode)
15538 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15539 (error "This command works only in special context like headlines or timestamps")))
15541 (defun org-call-for-shift-select (cmd)
15542 (let ((this-command-keys-shift-translated t))
15543 (call-interactively cmd)))
15545 (defun org-shifttab (&optional arg)
15546 "Global visibility cycling or move to previous table field.
15547 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15548 on context.
15549 See the individual commands for more information."
15550 (interactive "P")
15551 (cond
15552 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15553 ((integerp arg)
15554 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15555 (message "Content view to level: %d" arg)
15556 (org-content (prefix-numeric-value arg2))
15557 (setq org-cycle-global-status 'overview)))
15558 (t (call-interactively 'org-global-cycle))))
15560 (defun org-shiftmetaleft ()
15561 "Promote subtree or delete table column.
15562 Calls `org-promote-subtree', `org-outdent-item',
15563 or `org-table-delete-column', depending on context.
15564 See the individual commands for more information."
15565 (interactive)
15566 (cond
15567 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15568 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15569 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15570 ((org-at-item-p) (call-interactively 'org-outdent-item))
15571 (t (org-modifier-cursor-error))))
15573 (defun org-shiftmetaright ()
15574 "Demote subtree or insert table column.
15575 Calls `org-demote-subtree', `org-indent-item',
15576 or `org-table-insert-column', depending on context.
15577 See the individual commands for more information."
15578 (interactive)
15579 (cond
15580 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15581 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15582 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15583 ((org-at-item-p) (call-interactively 'org-indent-item))
15584 (t (org-modifier-cursor-error))))
15586 (defun org-shiftmetaup (&optional arg)
15587 "Move subtree up or kill table row.
15588 Calls `org-move-subtree-up' or `org-table-kill-row' or
15589 `org-move-item-up' depending on context. See the individual commands
15590 for more information."
15591 (interactive "P")
15592 (cond
15593 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15594 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15595 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15596 ((org-at-item-p) (call-interactively 'org-move-item-up))
15597 (t (org-modifier-cursor-error))))
15599 (defun org-shiftmetadown (&optional arg)
15600 "Move subtree down or insert table row.
15601 Calls `org-move-subtree-down' or `org-table-insert-row' or
15602 `org-move-item-down', depending on context. See the individual
15603 commands for more information."
15604 (interactive "P")
15605 (cond
15606 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15607 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15608 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15609 ((org-at-item-p) (call-interactively 'org-move-item-down))
15610 (t (org-modifier-cursor-error))))
15612 (defun org-metaleft (&optional arg)
15613 "Promote heading or move table column to left.
15614 Calls `org-do-promote' or `org-table-move-column', depending on context.
15615 With no specific context, calls the Emacs default `backward-word'.
15616 See the individual commands for more information."
15617 (interactive "P")
15618 (cond
15619 ((run-hook-with-args-until-success 'org-metaleft-hook))
15620 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15621 ((or (org-on-heading-p)
15622 (and (org-region-active-p)
15623 (save-excursion
15624 (goto-char (region-beginning))
15625 (org-on-heading-p))))
15626 (call-interactively 'org-do-promote))
15627 ((or (org-at-item-p)
15628 (and (org-region-active-p)
15629 (save-excursion
15630 (goto-char (region-beginning))
15631 (org-at-item-p))))
15632 (call-interactively 'org-outdent-item))
15633 (t (call-interactively 'backward-word))))
15635 (defun org-metaright (&optional arg)
15636 "Demote subtree or move table column to right.
15637 Calls `org-do-demote' or `org-table-move-column', depending on context.
15638 With no specific context, calls the Emacs default `forward-word'.
15639 See the individual commands for more information."
15640 (interactive "P")
15641 (cond
15642 ((run-hook-with-args-until-success 'org-metaright-hook))
15643 ((org-at-table-p) (call-interactively 'org-table-move-column))
15644 ((or (org-on-heading-p)
15645 (and (org-region-active-p)
15646 (save-excursion
15647 (goto-char (region-beginning))
15648 (org-on-heading-p))))
15649 (call-interactively 'org-do-demote))
15650 ((or (org-at-item-p)
15651 (and (org-region-active-p)
15652 (save-excursion
15653 (goto-char (region-beginning))
15654 (org-at-item-p))))
15655 (call-interactively 'org-indent-item))
15656 (t (call-interactively 'forward-word))))
15658 (defun org-metaup (&optional arg)
15659 "Move subtree up or move table row up.
15660 Calls `org-move-subtree-up' or `org-table-move-row' or
15661 `org-move-item-up', depending on context. See the individual commands
15662 for more information."
15663 (interactive "P")
15664 (cond
15665 ((run-hook-with-args-until-success 'org-metaup-hook))
15666 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15667 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15668 ((org-at-item-p) (call-interactively 'org-move-item-up))
15669 (t (transpose-lines 1) (beginning-of-line -1))))
15671 (defun org-metadown (&optional arg)
15672 "Move subtree down or move table row down.
15673 Calls `org-move-subtree-down' or `org-table-move-row' or
15674 `org-move-item-down', depending on context. See the individual
15675 commands for more information."
15676 (interactive "P")
15677 (cond
15678 ((run-hook-with-args-until-success 'org-metadown-hook))
15679 ((org-at-table-p) (call-interactively 'org-table-move-row))
15680 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15681 ((org-at-item-p) (call-interactively 'org-move-item-down))
15682 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15684 (defun org-shiftup (&optional arg)
15685 "Increase item in timestamp or increase priority of current headline.
15686 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15687 depending on context. See the individual commands for more information."
15688 (interactive "P")
15689 (cond
15690 ((and org-support-shift-select (org-region-active-p))
15691 (org-call-for-shift-select 'previous-line))
15692 ((org-at-timestamp-p t)
15693 (call-interactively (if org-edit-timestamp-down-means-later
15694 'org-timestamp-down 'org-timestamp-up)))
15695 ((and (not (eq org-support-shift-select 'always))
15696 org-enable-priority-commands
15697 (org-on-heading-p))
15698 (call-interactively 'org-priority-up))
15699 ((and (not org-support-shift-select) (org-at-item-p))
15700 (call-interactively 'org-previous-item))
15701 ((org-clocktable-try-shift 'up arg))
15702 (org-support-shift-select
15703 (org-call-for-shift-select 'previous-line))
15704 (t (org-shiftselect-error))))
15706 (defun org-shiftdown (&optional arg)
15707 "Decrease item in timestamp or decrease priority of current headline.
15708 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15709 depending on context. See the individual commands for more information."
15710 (interactive "P")
15711 (cond
15712 ((and org-support-shift-select (org-region-active-p))
15713 (org-call-for-shift-select 'next-line))
15714 ((org-at-timestamp-p t)
15715 (call-interactively (if org-edit-timestamp-down-means-later
15716 'org-timestamp-up 'org-timestamp-down)))
15717 ((and (not (eq org-support-shift-select 'always))
15718 org-enable-priority-commands
15719 (org-on-heading-p))
15720 (call-interactively 'org-priority-down))
15721 ((and (not org-support-shift-select) (org-at-item-p))
15722 (call-interactively 'org-next-item))
15723 ((org-clocktable-try-shift 'down arg))
15724 (org-support-shift-select
15725 (org-call-for-shift-select 'next-line))
15726 (t (org-shiftselect-error))))
15728 (defun org-shiftright (&optional arg)
15729 "Cycle the thing at point or in the current line, depending on context.
15730 Depending on context, this does one of the following:
15732 - switch a timestamp at point one day into the future
15733 - on a headline, switch to the next TODO keyword.
15734 - on an item, switch entire list to the next bullet type
15735 - on a property line, switch to the next allowed value
15736 - on a clocktable definition line, move time block into the future"
15737 (interactive "P")
15738 (cond
15739 ((and org-support-shift-select (org-region-active-p))
15740 (org-call-for-shift-select 'forward-char))
15741 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15742 ((and (not (eq org-support-shift-select 'always))
15743 (org-on-heading-p))
15744 (let ((org-inhibit-logging
15745 (not org-treat-S-cursor-todo-selection-as-state-change))
15746 (org-inhibit-blocking
15747 (not org-treat-S-cursor-todo-selection-as-state-change)))
15748 (org-call-with-arg 'org-todo 'right)))
15749 ((or (and org-support-shift-select
15750 (not (eq org-support-shift-select 'always))
15751 (org-at-item-bullet-p))
15752 (and (not org-support-shift-select) (org-at-item-p)))
15753 (org-call-with-arg 'org-cycle-list-bullet nil))
15754 ((and (not (eq org-support-shift-select 'always))
15755 (org-at-property-p))
15756 (call-interactively 'org-property-next-allowed-value))
15757 ((org-clocktable-try-shift 'right arg))
15758 (org-support-shift-select
15759 (org-call-for-shift-select 'forward-char))
15760 (t (org-shiftselect-error))))
15762 (defun org-shiftleft (&optional arg)
15763 "Cycle the thing at point or in the current line, depending on context.
15764 Depending on context, this does one of the following:
15766 - switch a timestamp at point one day into the past
15767 - on a headline, switch to the previous TODO keyword.
15768 - on an item, switch entire list to the previous bullet type
15769 - on a property line, switch to the previous allowed value
15770 - on a clocktable definition line, move time block into the past"
15771 (interactive "P")
15772 (cond
15773 ((and org-support-shift-select (org-region-active-p))
15774 (org-call-for-shift-select 'backward-char))
15775 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15776 ((and (not (eq org-support-shift-select 'always))
15777 (org-on-heading-p))
15778 (let ((org-inhibit-logging
15779 (not org-treat-S-cursor-todo-selection-as-state-change))
15780 (org-inhibit-blocking
15781 (not org-treat-S-cursor-todo-selection-as-state-change)))
15782 (org-call-with-arg 'org-todo 'left)))
15783 ((or (and org-support-shift-select
15784 (not (eq org-support-shift-select 'always))
15785 (org-at-item-bullet-p))
15786 (and (not org-support-shift-select) (org-at-item-p)))
15787 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15788 ((and (not (eq org-support-shift-select 'always))
15789 (org-at-property-p))
15790 (call-interactively 'org-property-previous-allowed-value))
15791 ((org-clocktable-try-shift 'left arg))
15792 (org-support-shift-select
15793 (org-call-for-shift-select 'backward-char))
15794 (t (org-shiftselect-error))))
15796 (defun org-shiftcontrolright ()
15797 "Switch to next TODO set."
15798 (interactive)
15799 (cond
15800 ((and org-support-shift-select (org-region-active-p))
15801 (org-call-for-shift-select 'forward-word))
15802 ((and (not (eq org-support-shift-select 'always))
15803 (org-on-heading-p))
15804 (org-call-with-arg 'org-todo 'nextset))
15805 (org-support-shift-select
15806 (org-call-for-shift-select 'forward-word))
15807 (t (org-shiftselect-error))))
15809 (defun org-shiftcontrolleft ()
15810 "Switch to previous TODO set."
15811 (interactive)
15812 (cond
15813 ((and org-support-shift-select (org-region-active-p))
15814 (org-call-for-shift-select 'backward-word))
15815 ((and (not (eq org-support-shift-select 'always))
15816 (org-on-heading-p))
15817 (org-call-with-arg 'org-todo 'previousset))
15818 (org-support-shift-select
15819 (org-call-for-shift-select 'backward-word))
15820 (t (org-shiftselect-error))))
15822 (defun org-ctrl-c-ret ()
15823 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15824 (interactive)
15825 (cond
15826 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15827 (t (call-interactively 'org-insert-heading))))
15829 (defun org-copy-special ()
15830 "Copy region in table or copy current subtree.
15831 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15832 See the individual commands for more information."
15833 (interactive)
15834 (call-interactively
15835 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15837 (defun org-cut-special ()
15838 "Cut region in table or cut current subtree.
15839 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15840 See the individual commands for more information."
15841 (interactive)
15842 (call-interactively
15843 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15845 (defun org-paste-special (arg)
15846 "Paste rectangular region into table, or past subtree relative to level.
15847 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15848 See the individual commands for more information."
15849 (interactive "P")
15850 (if (org-at-table-p)
15851 (org-table-paste-rectangle)
15852 (org-paste-subtree arg)))
15854 (defun org-edit-special ()
15855 "Call a special editor for the stuff at point.
15856 When at a table, call the formula editor with `org-table-edit-formulas'.
15857 When at the first line of an src example, call `org-edit-src-code'.
15858 When in an #+include line, visit the include file. Otherwise call
15859 `ffap' to visit the file at point."
15860 (interactive)
15861 (cond
15862 ((org-at-table-p)
15863 (call-interactively 'org-table-edit-formulas))
15864 ((save-excursion
15865 (beginning-of-line 1)
15866 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15867 (find-file (org-trim (match-string 1))))
15868 ((org-edit-src-code))
15869 ((org-edit-fixed-width-region))
15870 (t (call-interactively 'ffap))))
15873 (defun org-ctrl-c-ctrl-c (&optional arg)
15874 "Set tags in headline, or update according to changed information at point.
15876 This command does many different things, depending on context:
15878 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15879 this is what we do.
15881 - If the cursor is on a statistics cookie, update it.
15883 - If the cursor is in a headline, prompt for tags and insert them
15884 into the current line, aligned to `org-tags-column'. When called
15885 with prefix arg, realign all tags in the current buffer.
15887 - If the cursor is in one of the special #+KEYWORD lines, this
15888 triggers scanning the buffer for these lines and updating the
15889 information.
15891 - If the cursor is inside a table, realign the table. This command
15892 works even if the automatic table editor has been turned off.
15894 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15895 the entire table.
15897 - If the cursor is at a footnote reference or definition, jump to
15898 the corresponding definition or references, respectively.
15900 - If the cursor is a the beginning of a dynamic block, update it.
15902 - If the cursor is inside a table created by the table.el package,
15903 activate that table.
15905 - If the current buffer is a remember buffer, close note and file
15906 it. A prefix argument of 1 files to the default location
15907 without further interaction. A prefix argument of 2 files to
15908 the currently clocking task.
15910 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15911 links in this buffer.
15913 - If the cursor is on a numbered item in a plain list, renumber the
15914 ordered list.
15916 - If the cursor is on a checkbox, toggle it."
15917 (interactive "P")
15918 (let ((org-enable-table-editor t))
15919 (cond
15920 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15921 org-occur-highlights
15922 org-latex-fragment-image-overlays)
15923 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15924 (org-remove-occur-highlights)
15925 (org-remove-latex-fragment-image-overlays)
15926 (message "Temporary highlights/overlays removed from current buffer"))
15927 ((and (local-variable-p 'org-finish-function (current-buffer))
15928 (fboundp org-finish-function))
15929 (funcall org-finish-function))
15930 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15931 ((org-at-property-p)
15932 (call-interactively 'org-property-action))
15933 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15934 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15935 (or (org-on-heading-p) (org-at-item-p)))
15936 (call-interactively 'org-update-statistics-cookies))
15937 ((org-on-heading-p) (call-interactively 'org-set-tags))
15938 ((org-at-table.el-p)
15939 (require 'table)
15940 (beginning-of-line 1)
15941 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15942 (call-interactively 'table-recognize-table))
15943 ((org-at-table-p)
15944 (org-table-maybe-eval-formula)
15945 (if arg
15946 (call-interactively 'org-table-recalculate)
15947 (org-table-maybe-recalculate-line))
15948 (call-interactively 'org-table-align))
15949 ((or (org-footnote-at-reference-p)
15950 (org-footnote-at-definition-p))
15951 (call-interactively 'org-footnote-action))
15952 ((org-at-item-checkbox-p)
15953 (call-interactively 'org-toggle-checkbox))
15954 ((org-at-item-p)
15955 (if arg
15956 (call-interactively 'org-toggle-checkbox)
15957 (call-interactively 'org-maybe-renumber-ordered-list)))
15958 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15959 ;; Dynamic block
15960 (beginning-of-line 1)
15961 (save-excursion (org-update-dblock)))
15962 ((save-excursion
15963 (beginning-of-line 1)
15964 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15965 (cond
15966 ((equal (match-string 1) "TBLFM")
15967 ;; Recalculate the table before this line
15968 (save-excursion
15969 (beginning-of-line 1)
15970 (skip-chars-backward " \r\n\t")
15971 (if (org-at-table-p)
15972 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15974 (let ((org-inhibit-startup-visibility-stuff t)
15975 (org-startup-align-all-tables nil))
15976 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15977 (message "Local setup has been refreshed"))))
15978 ((org-clock-update-time-maybe))
15979 (t (error "C-c C-c can do nothing useful at this location")))))
15981 (defun org-mode-restart ()
15982 "Restart Org-mode, to scan again for special lines.
15983 Also updates the keyword regular expressions."
15984 (interactive)
15985 (org-mode)
15986 (message "Org-mode restarted"))
15988 (defun org-kill-note-or-show-branches ()
15989 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15990 (interactive)
15991 (if (not org-finish-function)
15992 (call-interactively 'show-branches)
15993 (let ((org-note-abort t))
15994 (funcall org-finish-function))))
15996 (defun org-return (&optional indent)
15997 "Goto next table row or insert a newline.
15998 Calls `org-table-next-row' or `newline', depending on context.
15999 See the individual commands for more information."
16000 (interactive)
16001 (cond
16002 ((bobp) (if indent (newline-and-indent) (newline)))
16003 ((org-at-table-p)
16004 (org-table-justify-field-maybe)
16005 (call-interactively 'org-table-next-row))
16006 ((and org-return-follows-link
16007 (eq (get-text-property (point) 'face) 'org-link))
16008 (call-interactively 'org-open-at-point))
16009 ((and (org-at-heading-p)
16010 (looking-at
16011 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16012 (org-show-entry)
16013 (end-of-line 1)
16014 (newline))
16015 (t (if indent (newline-and-indent) (newline)))))
16017 (defun org-return-indent ()
16018 "Goto next table row or insert a newline and indent.
16019 Calls `org-table-next-row' or `newline-and-indent', depending on
16020 context. See the individual commands for more information."
16021 (interactive)
16022 (org-return t))
16024 (defun org-ctrl-c-star ()
16025 "Compute table, or change heading status of lines.
16026 Calls `org-table-recalculate' or `org-toggle-heading',
16027 depending on context."
16028 (interactive)
16029 (cond
16030 ((org-at-table-p)
16031 (call-interactively 'org-table-recalculate))
16033 ;; Convert all lines in region to list items
16034 (call-interactively 'org-toggle-heading))))
16036 (defun org-ctrl-c-minus ()
16037 "Insert separator line in table or modify bullet status of line.
16038 Also turns a plain line or a region of lines into list items.
16039 Calls `org-table-insert-hline', `org-toggle-item', or
16040 `org-cycle-list-bullet', depending on context."
16041 (interactive)
16042 (cond
16043 ((org-at-table-p)
16044 (call-interactively 'org-table-insert-hline))
16045 ((org-region-active-p)
16046 (call-interactively 'org-toggle-item))
16047 ((org-in-item-p)
16048 (call-interactively 'org-cycle-list-bullet))
16050 (call-interactively 'org-toggle-item))))
16052 (defun org-toggle-item ()
16053 "Convert headings or normal lines to items, items to normal lines.
16054 If there is no active region, only the current line is considered.
16056 If the first line in the region is a headline, convert all headlines to items.
16058 If the first line in the region is an item, convert all items to normal lines.
16060 If the first line is normal text, add an item bullet to each line."
16061 (interactive)
16062 (let (l2 l beg end)
16063 (if (org-region-active-p)
16064 (setq beg (region-beginning) end (region-end))
16065 (setq beg (point-at-bol)
16066 end (min (1+ (point-at-eol)) (point-max))))
16067 (save-excursion
16068 (goto-char end)
16069 (setq l2 (org-current-line))
16070 (goto-char beg)
16071 (beginning-of-line 1)
16072 (setq l (1- (org-current-line)))
16073 (if (org-at-item-p)
16074 ;; We already have items, de-itemize
16075 (while (< (setq l (1+ l)) l2)
16076 (when (org-at-item-p)
16077 (goto-char (match-beginning 2))
16078 (delete-region (match-beginning 2) (match-end 2))
16079 (and (looking-at "[ \t]+") (replace-match "")))
16080 (beginning-of-line 2))
16081 (if (org-on-heading-p)
16082 ;; Headings, convert to items
16083 (while (< (setq l (1+ l)) l2)
16084 (if (looking-at org-outline-regexp)
16085 (replace-match "- " t t))
16086 (beginning-of-line 2))
16087 ;; normal lines, turn them into items
16088 (while (< (setq l (1+ l)) l2)
16089 (unless (org-at-item-p)
16090 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16091 (replace-match "\\1- \\2")))
16092 (beginning-of-line 2)))))))
16094 (defun org-toggle-heading (&optional nstars)
16095 "Convert headings to normal text, or items or text to headings.
16096 If there is no active region, only the current line is considered.
16098 If the first line is a heading, remove the stars from all headlines
16099 in the region.
16101 If the first line is a plain list item, turn all plain list items
16102 into headings.
16104 If the first line is a normal line, turn each and every line in the
16105 region into a heading.
16107 When converting a line into a heading, the number of stars is chosen
16108 such that the lines become children of the current entry. However,
16109 when a prefix argument is given, its value determines the number of
16110 stars to add."
16111 (interactive "P")
16112 (let (l2 l itemp beg end)
16113 (if (org-region-active-p)
16114 (setq beg (region-beginning) end (region-end))
16115 (setq beg (point-at-bol)
16116 end (min (1+ (point-at-eol)) (point-max))))
16117 (save-excursion
16118 (goto-char end)
16119 (setq l2 (org-current-line))
16120 (goto-char beg)
16121 (beginning-of-line 1)
16122 (setq l (1- (org-current-line)))
16123 (if (org-on-heading-p)
16124 ;; We already have headlines, de-star them
16125 (while (< (setq l (1+ l)) l2)
16126 (when (org-on-heading-p t)
16127 (and (looking-at outline-regexp) (replace-match "")))
16128 (beginning-of-line 2))
16129 (setq itemp (org-at-item-p))
16130 (let* ((stars
16131 (if nstars
16132 (make-string (prefix-numeric-value current-prefix-arg)
16134 (save-excursion
16135 (if (re-search-backward org-complex-heading-regexp nil t)
16136 (match-string 1) ""))))
16137 (add-stars (cond (nstars "")
16138 ((equal stars "") "*")
16139 (org-odd-levels-only "**")
16140 (t "*")))
16141 (rpl (concat stars add-stars " ")))
16142 (while (< (setq l (1+ l)) l2)
16143 (if itemp
16144 (and (org-at-item-p) (replace-match rpl t t))
16145 (unless (org-on-heading-p)
16146 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16147 (replace-match (concat rpl (match-string 2))))))
16148 (beginning-of-line 2)))))))
16150 (defun org-meta-return (&optional arg)
16151 "Insert a new heading or wrap a region in a table.
16152 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16153 See the individual commands for more information."
16154 (interactive "P")
16155 (cond
16156 ((run-hook-with-args-until-success 'org-metareturn-hook))
16157 ((org-at-table-p)
16158 (call-interactively 'org-table-wrap-region))
16159 (t (call-interactively 'org-insert-heading))))
16161 ;;; Menu entries
16163 ;; Define the Org-mode menus
16164 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16165 '("Tbl"
16166 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16167 ["Next Field" org-cycle (org-at-table-p)]
16168 ["Previous Field" org-shifttab (org-at-table-p)]
16169 ["Next Row" org-return (org-at-table-p)]
16170 "--"
16171 ["Blank Field" org-table-blank-field (org-at-table-p)]
16172 ["Edit Field" org-table-edit-field (org-at-table-p)]
16173 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16174 "--"
16175 ("Column"
16176 ["Move Column Left" org-metaleft (org-at-table-p)]
16177 ["Move Column Right" org-metaright (org-at-table-p)]
16178 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16179 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16180 ("Row"
16181 ["Move Row Up" org-metaup (org-at-table-p)]
16182 ["Move Row Down" org-metadown (org-at-table-p)]
16183 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16184 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16185 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16186 "--"
16187 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16188 ("Rectangle"
16189 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16190 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16191 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16192 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16193 "--"
16194 ("Calculate"
16195 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16196 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16197 ["Edit Formulas" org-edit-special (org-at-table-p)]
16198 "--"
16199 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16200 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16201 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16202 "--"
16203 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16204 "--"
16205 ["Sum Column/Rectangle" org-table-sum
16206 (or (org-at-table-p) (org-region-active-p))]
16207 ["Which Column?" org-table-current-column (org-at-table-p)])
16208 ["Debug Formulas"
16209 org-table-toggle-formula-debugger
16210 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16211 ["Show Col/Row Numbers"
16212 org-table-toggle-coordinate-overlays
16213 :style toggle
16214 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16215 "--"
16216 ["Create" org-table-create (and (not (org-at-table-p))
16217 org-enable-table-editor)]
16218 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16219 ["Import from File" org-table-import (not (org-at-table-p))]
16220 ["Export to File" org-table-export (org-at-table-p)]
16221 "--"
16222 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16224 (easy-menu-define org-org-menu org-mode-map "Org menu"
16225 '("Org"
16226 ("Show/Hide"
16227 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16228 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16229 ["Sparse Tree..." org-sparse-tree t]
16230 ["Reveal Context" org-reveal t]
16231 ["Show All" show-all t]
16232 "--"
16233 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16234 "--"
16235 ["New Heading" org-insert-heading t]
16236 ("Navigate Headings"
16237 ["Up" outline-up-heading t]
16238 ["Next" outline-next-visible-heading t]
16239 ["Previous" outline-previous-visible-heading t]
16240 ["Next Same Level" outline-forward-same-level t]
16241 ["Previous Same Level" outline-backward-same-level t]
16242 "--"
16243 ["Jump" org-goto t])
16244 ("Edit Structure"
16245 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16246 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16247 "--"
16248 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16249 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16250 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16251 "--"
16252 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16253 "--"
16254 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16255 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16256 ["Demote Heading" org-metaright (not (org-at-table-p))]
16257 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16258 "--"
16259 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16260 "--"
16261 ["Convert to odd levels" org-convert-to-odd-levels t]
16262 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16263 ("Editing"
16264 ["Emphasis..." org-emphasize t]
16265 ["Edit Source Example" org-edit-special t]
16266 "--"
16267 ["Footnote new/jump" org-footnote-action t]
16268 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16269 ("Archive"
16270 ["Archive (default method)" org-archive-subtree-default t]
16271 "--"
16272 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16273 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16274 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16276 "--"
16277 ("Hyperlinks"
16278 ["Store Link (Global)" org-store-link t]
16279 ["Find existing link to here" org-occur-link-in-agenda-files t]
16280 ["Insert Link" org-insert-link t]
16281 ["Follow Link" org-open-at-point t]
16282 "--"
16283 ["Next link" org-next-link t]
16284 ["Previous link" org-previous-link t]
16285 "--"
16286 ["Descriptive Links"
16287 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16288 :style radio
16289 :selected (member '(org-link) buffer-invisibility-spec)]
16290 ["Literal Links"
16291 (progn
16292 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16293 :style radio
16294 :selected (not (member '(org-link) buffer-invisibility-spec))])
16295 "--"
16296 ("TODO Lists"
16297 ["TODO/DONE/-" org-todo t]
16298 ("Select keyword"
16299 ["Next keyword" org-shiftright (org-on-heading-p)]
16300 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16301 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16302 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16303 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16304 ["Show TODO Tree" org-show-todo-tree t]
16305 ["Global TODO list" org-todo-list t]
16306 "--"
16307 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16308 :selected org-enforce-todo-dependencies :style toggle :active t]
16309 "Settings for tree at point"
16310 ["Do Children sequentially" org-toggle-ordered-property :style radio
16311 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16312 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16313 ["Do Children parallel" org-toggle-ordered-property :style radio
16314 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16315 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16316 "--"
16317 ["Set Priority" org-priority t]
16318 ["Priority Up" org-shiftup t]
16319 ["Priority Down" org-shiftdown t]
16320 "--"
16321 ["Get news from all feeds" org-feed-update-all t]
16322 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16323 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16324 ("TAGS and Properties"
16325 ["Set Tags" org-set-tags-command t]
16326 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16327 "--"
16328 ["Set property" org-set-property t]
16329 ["Column view of properties" org-columns t]
16330 ["Insert Column View DBlock" org-insert-columns-dblock t])
16331 ("Dates and Scheduling"
16332 ["Timestamp" org-time-stamp t]
16333 ["Timestamp (inactive)" org-time-stamp-inactive t]
16334 ("Change Date"
16335 ["1 Day Later" org-shiftright t]
16336 ["1 Day Earlier" org-shiftleft t]
16337 ["1 ... Later" org-shiftup t]
16338 ["1 ... Earlier" org-shiftdown t])
16339 ["Compute Time Range" org-evaluate-time-range t]
16340 ["Schedule Item" org-schedule t]
16341 ["Deadline" org-deadline t]
16342 "--"
16343 ["Custom time format" org-toggle-time-stamp-overlays
16344 :style radio :selected org-display-custom-times]
16345 "--"
16346 ["Goto Calendar" org-goto-calendar t]
16347 ["Date from Calendar" org-date-from-calendar t]
16348 "--"
16349 ["Start/Restart Timer" org-timer-start t]
16350 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16351 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16352 ["Insert Timer String" org-timer t]
16353 ["Insert Timer Item" org-timer-item t])
16354 ("Logging work"
16355 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16356 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16357 ["Clock out" org-clock-out t]
16358 ["Clock cancel" org-clock-cancel t]
16359 "--"
16360 ["Mark as default task" org-clock-mark-default-task t]
16361 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16362 ["Goto running clock" org-clock-goto t]
16363 "--"
16364 ["Display times" org-clock-display t]
16365 ["Create clock table" org-clock-report t]
16366 "--"
16367 ["Record DONE time"
16368 (progn (setq org-log-done (not org-log-done))
16369 (message "Switching to %s will %s record a timestamp"
16370 (car org-done-keywords)
16371 (if org-log-done "automatically" "not")))
16372 :style toggle :selected org-log-done])
16373 "--"
16374 ["Agenda Command..." org-agenda t]
16375 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16376 ("File List for Agenda")
16377 ("Special views current file"
16378 ["TODO Tree" org-show-todo-tree t]
16379 ["Check Deadlines" org-check-deadlines t]
16380 ["Timeline" org-timeline t]
16381 ["Tags/Property tree" org-match-sparse-tree t])
16382 "--"
16383 ["Export/Publish..." org-export t]
16384 ("LaTeX"
16385 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16386 :selected org-cdlatex-mode]
16387 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16388 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16389 ["Modify math symbol" org-cdlatex-math-modify
16390 (org-inside-LaTeX-fragment-p)]
16391 ["Insert citation" org-reftex-citation t]
16392 "--"
16393 ["Export LaTeX fragments as images"
16394 (if (featurep 'org-exp)
16395 (setq org-export-with-LaTeX-fragments
16396 (not org-export-with-LaTeX-fragments))
16397 (require 'org-exp))
16398 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16399 org-export-with-LaTeX-fragments)]
16400 "--"
16401 ["Template for BEAMER" org-beamer-settings-template t])
16402 "--"
16403 ("MobileOrg"
16404 ["Push Files and Views" org-mobile-push t]
16405 ["Get Captured and Flagged" org-mobile-pull t]
16406 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16407 "--"
16408 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16409 "--"
16410 ("Documentation"
16411 ["Show Version" org-version t]
16412 ["Info Documentation" org-info t])
16413 ("Customize"
16414 ["Browse Org Group" org-customize t]
16415 "--"
16416 ["Expand This Menu" org-create-customize-menu
16417 (fboundp 'customize-menu-create)])
16418 ["Send bug report" org-submit-bug-report t]
16419 "--"
16420 ("Refresh/Reload"
16421 ["Refresh setup current buffer" org-mode-restart t]
16422 ["Reload Org (after update)" org-reload t]
16423 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16426 (defun org-info (&optional node)
16427 "Read documentation for Org-mode in the info system.
16428 With optional NODE, go directly to that node."
16429 (interactive)
16430 (info (format "(org)%s" (or node ""))))
16432 ;;;###autoload
16433 (defun org-submit-bug-report ()
16434 "Submit a bug report on Org-mode via mail.
16436 Don't hesitate to report any problems or inaccurate documentation.
16438 If you don't have setup sending mail from (X)Emacs, please copy the
16439 output buffer into your mail program, as it gives us important
16440 information about your Org-mode version and configuration."
16441 (interactive)
16442 (require 'reporter)
16443 (org-load-modules-maybe)
16444 (org-require-autoloaded-modules)
16445 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16446 (reporter-submit-bug-report
16447 "emacs-orgmode@gnu.org"
16448 (org-version)
16449 (let (list)
16450 (save-window-excursion
16451 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16452 (delete-other-windows)
16453 (erase-buffer)
16454 (insert "You are about to submit a bug report to the Org-mode mailing list.
16456 We would like to add your full Org-mode and Outline configuration to the
16457 bug report. This greatly simplifies the work of the maintainer and
16458 other experts on the mailing list.
16460 HOWEVER, some variables you have customized may contain private
16461 information. The names of customers, colleagues, or friends, might
16462 appear in the form of file names, tags, todo states, or search strings.
16463 If you answer yes to the prompt, you might want to check and remove
16464 such private information before sending the email.")
16465 (add-text-properties (point-min) (point-max) '(face org-warning))
16466 (when (yes-or-no-p "Include your Org-mode configuration ")
16467 (mapatoms
16468 (lambda (v)
16469 (and (boundp v)
16470 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16471 (or (and (symbol-value v)
16472 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16473 (and
16474 (get v 'custom-type) (get v 'standard-value)
16475 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16476 (push v list)))))
16477 (kill-buffer (get-buffer "*Warn about privacy*"))
16478 list))
16479 nil nil
16480 "Remember to cover the basics, that is, what you expected to happen and
16481 what in fact did happen. You don't know how to make a good report? See
16483 http://orgmode.org/manual/Feedback.html#Feedback
16485 Your bug report will be posted to the Org-mode mailing list.
16486 ------------------------------------------------------------------------")
16487 (save-excursion
16488 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16489 (replace-match "\\1Bug: \\3 [\\2]")))))
16492 (defun org-install-agenda-files-menu ()
16493 (let ((bl (buffer-list)))
16494 (save-excursion
16495 (while bl
16496 (set-buffer (pop bl))
16497 (if (org-mode-p) (setq bl nil)))
16498 (when (org-mode-p)
16499 (easy-menu-change
16500 '("Org") "File List for Agenda"
16501 (append
16502 (list
16503 ["Edit File List" (org-edit-agenda-file-list) t]
16504 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16505 ["Remove Current File from List" org-remove-file t]
16506 ["Cycle through agenda files" org-cycle-agenda-files t]
16507 ["Occur in all agenda files" org-occur-in-agenda-files t]
16508 "--")
16509 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16511 ;;;; Documentation
16513 ;;;###autoload
16514 (defun org-require-autoloaded-modules ()
16515 (interactive)
16516 (mapc 'require
16517 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16518 org-docbook org-exp org-html org-icalendar
16519 org-id org-latex
16520 org-publish org-remember org-table
16521 org-timer org-xoxo)))
16523 ;;;###autoload
16524 (defun org-reload (&optional uncompiled)
16525 "Reload all org lisp files.
16526 With prefix arg UNCOMPILED, load the uncompiled versions."
16527 (interactive "P")
16528 (require 'find-func)
16529 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16530 (dir-org (file-name-directory (org-find-library-name "org")))
16531 (dir-org-contrib (ignore-errors
16532 (file-name-directory
16533 (org-find-library-name "org-contribdir"))))
16534 (files
16535 (append (directory-files dir-org t file-re)
16536 (and dir-org-contrib
16537 (directory-files dir-org-contrib t file-re))))
16538 (remove-re (concat (if (featurep 'xemacs)
16539 "org-colview" "org-colview-xemacs")
16540 "\\'")))
16541 (setq files (mapcar 'file-name-sans-extension files))
16542 (setq files (mapcar
16543 (lambda (x) (if (string-match remove-re x) nil x))
16544 files))
16545 (setq files (delq nil files))
16546 (mapc
16547 (lambda (f)
16548 (when (featurep (intern (file-name-nondirectory f)))
16549 (if (and (not uncompiled)
16550 (file-exists-p (concat f ".elc")))
16551 (load (concat f ".elc") nil nil t)
16552 (load (concat f ".el") nil nil t))))
16553 files))
16554 (org-version))
16556 ;;;###autoload
16557 (defun org-customize ()
16558 "Call the customize function with org as argument."
16559 (interactive)
16560 (org-load-modules-maybe)
16561 (org-require-autoloaded-modules)
16562 (customize-browse 'org))
16564 (defun org-create-customize-menu ()
16565 "Create a full customization menu for Org-mode, insert it into the menu."
16566 (interactive)
16567 (org-load-modules-maybe)
16568 (org-require-autoloaded-modules)
16569 (if (fboundp 'customize-menu-create)
16570 (progn
16571 (easy-menu-change
16572 '("Org") "Customize"
16573 `(["Browse Org group" org-customize t]
16574 "--"
16575 ,(customize-menu-create 'org)
16576 ["Set" Custom-set t]
16577 ["Save" Custom-save t]
16578 ["Reset to Current" Custom-reset-current t]
16579 ["Reset to Saved" Custom-reset-saved t]
16580 ["Reset to Standard Settings" Custom-reset-standard t]))
16581 (message "\"Org\"-menu now contains full customization menu"))
16582 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16584 ;;;; Miscellaneous stuff
16586 ;;; Generally useful functions
16588 (defun org-get-at-bol (property)
16589 "Get text property PROPERTY at beginning of line."
16590 (get-text-property (point-at-bol) property))
16592 (defun org-find-text-property-in-string (prop s)
16593 "Return the first non-nil value of property PROP in string S."
16594 (or (get-text-property 0 prop s)
16595 (get-text-property (or (next-single-property-change 0 prop s) 0)
16596 prop s)))
16598 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16599 "Display the given MESSAGE as a warning."
16600 (if (fboundp 'display-warning)
16601 (display-warning 'org message
16602 (if (featurep 'xemacs)
16603 'warning
16604 :warning))
16605 (let ((buf (get-buffer-create "*Org warnings*")))
16606 (with-current-buffer buf
16607 (goto-char (point-max))
16608 (insert "Warning (Org): " message)
16609 (unless (bolp)
16610 (newline)))
16611 (display-buffer buf)
16612 (sit-for 0))))
16614 (defun org-in-commented-line ()
16615 "Is point in a line starting with `#'?"
16616 (equal (char-after (point-at-bol)) ?#))
16618 (defun org-in-verbatim-emphasis ()
16619 (save-match-data
16620 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16622 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16623 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16624 (if (and marker (marker-buffer marker)
16625 (buffer-live-p (marker-buffer marker)))
16626 (progn
16627 (switch-to-buffer (marker-buffer marker))
16628 (if (or (> marker (point-max)) (< marker (point-min)))
16629 (widen))
16630 (goto-char marker)
16631 (org-show-context 'org-goto))
16632 (if bookmark
16633 (bookmark-jump bookmark)
16634 (error "Cannot find location"))))
16636 (defun org-quote-csv-field (s)
16637 "Quote field for inclusion in CSV material."
16638 (if (string-match "[\",]" s)
16639 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16642 (defun org-plist-delete (plist property)
16643 "Delete PROPERTY from PLIST.
16644 This is in contrast to merely setting it to 0."
16645 (let (p)
16646 (while plist
16647 (if (not (eq property (car plist)))
16648 (setq p (plist-put p (car plist) (nth 1 plist))))
16649 (setq plist (cddr plist)))
16652 (defun org-force-self-insert (N)
16653 "Needed to enforce self-insert under remapping."
16654 (interactive "p")
16655 (self-insert-command N))
16657 (defun org-string-width (s)
16658 "Compute width of string, ignoring invisible characters.
16659 This ignores character with invisibility property `org-link', and also
16660 characters with property `org-cwidth', because these will become invisible
16661 upon the next fontification round."
16662 (let (b l)
16663 (when (or (eq t buffer-invisibility-spec)
16664 (assq 'org-link buffer-invisibility-spec))
16665 (while (setq b (text-property-any 0 (length s)
16666 'invisible 'org-link s))
16667 (setq s (concat (substring s 0 b)
16668 (substring s (or (next-single-property-change
16669 b 'invisible s) (length s)))))))
16670 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16671 (setq s (concat (substring s 0 b)
16672 (substring s (or (next-single-property-change
16673 b 'org-cwidth s) (length s))))))
16674 (setq l (string-width s) b -1)
16675 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16676 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16679 (defun org-get-indentation (&optional line)
16680 "Get the indentation of the current line, interpreting tabs.
16681 When LINE is given, assume it represents a line and compute its indentation."
16682 (if line
16683 (if (string-match "^ *" (org-remove-tabs line))
16684 (match-end 0))
16685 (save-excursion
16686 (beginning-of-line 1)
16687 (skip-chars-forward " \t")
16688 (current-column))))
16690 (defun org-remove-tabs (s &optional width)
16691 "Replace tabulators in S with spaces.
16692 Assumes that s is a single line, starting in column 0."
16693 (setq width (or width tab-width))
16694 (while (string-match "\t" s)
16695 (setq s (replace-match
16696 (make-string
16697 (- (* width (/ (+ (match-beginning 0) width) width))
16698 (match-beginning 0)) ?\ )
16699 t t s)))
16702 (defun org-fix-indentation (line ind)
16703 "Fix indentation in LINE.
16704 IND is a cons cell with target and minimum indentation.
16705 If the current indentation in LINE is smaller than the minimum,
16706 leave it alone. If it is larger than ind, set it to the target."
16707 (let* ((l (org-remove-tabs line))
16708 (i (org-get-indentation l))
16709 (i1 (car ind)) (i2 (cdr ind)))
16710 (if (>= i i2) (setq l (substring line i2)))
16711 (if (> i1 0)
16712 (concat (make-string i1 ?\ ) l)
16713 l)))
16715 (defun org-remove-indentation (code &optional n)
16716 "Remove the maximum common indentation from the lines in CODE.
16717 N may optionally be the number of spaces to remove."
16718 (with-temp-buffer
16719 (insert code)
16720 (org-do-remove-indentation n)
16721 (buffer-string)))
16723 (defun org-do-remove-indentation (&optional n)
16724 "Remove the maximum common indentation from the buffer."
16725 (untabify (point-min) (point-max))
16726 (let ((min 10000) re)
16727 (if n
16728 (setq min n)
16729 (goto-char (point-min))
16730 (while (re-search-forward "^ *[^ \n]" nil t)
16731 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16732 (unless (or (= min 0) (= min 10000))
16733 (setq re (format "^ \\{%d\\}" min))
16734 (goto-char (point-min))
16735 (while (re-search-forward re nil t)
16736 (replace-match "")
16737 (end-of-line 1))
16738 min)))
16740 (defun org-fill-template (template alist)
16741 "Find each %key of ALIST in TEMPLATE and replace it."
16742 (let ((case-fold-search nil)
16743 entry key value)
16744 (setq alist (sort (copy-sequence alist)
16745 (lambda (a b) (< (length (car a)) (length (car b))))))
16746 (while (setq entry (pop alist))
16747 (setq template
16748 (replace-regexp-in-string
16749 (concat "%" (regexp-quote (car entry)))
16750 (cdr entry) template t t)))
16751 template))
16753 (defun org-base-buffer (buffer)
16754 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16755 (if (not buffer)
16756 buffer
16757 (or (buffer-base-buffer buffer)
16758 buffer)))
16760 (defun org-trim (s)
16761 "Remove whitespace at beginning and end of string."
16762 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16763 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16766 (defun org-wrap (string &optional width lines)
16767 "Wrap string to either a number of lines, or a width in characters.
16768 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16769 that costs. If there is a word longer than WIDTH, the text is actually
16770 wrapped to the length of that word.
16771 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16772 many lines, whatever width that takes.
16773 The return value is a list of lines, without newlines at the end."
16774 (let* ((words (org-split-string string "[ \t\n]+"))
16775 (maxword (apply 'max (mapcar 'org-string-width words)))
16776 w ll)
16777 (cond (width
16778 (org-do-wrap words (max maxword width)))
16779 (lines
16780 (setq w maxword)
16781 (setq ll (org-do-wrap words maxword))
16782 (if (<= (length ll) lines)
16784 (setq ll words)
16785 (while (> (length ll) lines)
16786 (setq w (1+ w))
16787 (setq ll (org-do-wrap words w)))
16788 ll))
16789 (t (error "Cannot wrap this")))))
16791 (defun org-do-wrap (words width)
16792 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16793 (let (lines line)
16794 (while words
16795 (setq line (pop words))
16796 (while (and words (< (+ (length line) (length (car words))) width))
16797 (setq line (concat line " " (pop words))))
16798 (setq lines (push line lines)))
16799 (nreverse lines)))
16801 (defun org-split-string (string &optional separators)
16802 "Splits STRING into substrings at SEPARATORS.
16803 No empty strings are returned if there are matches at the beginning
16804 and end of string."
16805 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16806 (start 0)
16807 notfirst
16808 (list nil))
16809 (while (and (string-match rexp string
16810 (if (and notfirst
16811 (= start (match-beginning 0))
16812 (< start (length string)))
16813 (1+ start) start))
16814 (< (match-beginning 0) (length string)))
16815 (setq notfirst t)
16816 (or (eq (match-beginning 0) 0)
16817 (and (eq (match-beginning 0) (match-end 0))
16818 (eq (match-beginning 0) start))
16819 (setq list
16820 (cons (substring string start (match-beginning 0))
16821 list)))
16822 (setq start (match-end 0)))
16823 (or (eq start (length string))
16824 (setq list
16825 (cons (substring string start)
16826 list)))
16827 (nreverse list)))
16829 (defun org-quote-vert (s)
16830 "Replace \"|\" with \"\\vert\"."
16831 (while (string-match "|" s)
16832 (setq s (replace-match "\\vert" t t s)))
16835 (defun org-uuidgen-p (s)
16836 "Is S an ID created by UUIDGEN?"
16837 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16839 (defun org-context ()
16840 "Return a list of contexts of the current cursor position.
16841 If several contexts apply, all are returned.
16842 Each context entry is a list with a symbol naming the context, and
16843 two positions indicating start and end of the context. Possible
16844 contexts are:
16846 :headline anywhere in a headline
16847 :headline-stars on the leading stars in a headline
16848 :todo-keyword on a TODO keyword (including DONE) in a headline
16849 :tags on the TAGS in a headline
16850 :priority on the priority cookie in a headline
16851 :item on the first line of a plain list item
16852 :item-bullet on the bullet/number of a plain list item
16853 :checkbox on the checkbox in a plain list item
16854 :table in an org-mode table
16855 :table-special on a special filed in a table
16856 :table-table in a table.el table
16857 :link on a hyperlink
16858 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16859 :target on a <<target>>
16860 :radio-target on a <<<radio-target>>>
16861 :latex-fragment on a LaTeX fragment
16862 :latex-preview on a LaTeX fragment with overlayed preview image
16864 This function expects the position to be visible because it uses font-lock
16865 faces as a help to recognize the following contexts: :table-special, :link,
16866 and :keyword."
16867 (let* ((f (get-text-property (point) 'face))
16868 (faces (if (listp f) f (list f)))
16869 (p (point)) clist o)
16870 ;; First the large context
16871 (cond
16872 ((org-on-heading-p t)
16873 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16874 (when (progn
16875 (beginning-of-line 1)
16876 (looking-at org-todo-line-tags-regexp))
16877 (push (org-point-in-group p 1 :headline-stars) clist)
16878 (push (org-point-in-group p 2 :todo-keyword) clist)
16879 (push (org-point-in-group p 4 :tags) clist))
16880 (goto-char p)
16881 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16882 (if (looking-at "\\[#[A-Z0-9]\\]")
16883 (push (org-point-in-group p 0 :priority) clist)))
16885 ((org-at-item-p)
16886 (push (org-point-in-group p 2 :item-bullet) clist)
16887 (push (list :item (point-at-bol)
16888 (save-excursion (org-end-of-item) (point)))
16889 clist)
16890 (and (org-at-item-checkbox-p)
16891 (push (org-point-in-group p 0 :checkbox) clist)))
16893 ((org-at-table-p)
16894 (push (list :table (org-table-begin) (org-table-end)) clist)
16895 (if (memq 'org-formula faces)
16896 (push (list :table-special
16897 (previous-single-property-change p 'face)
16898 (next-single-property-change p 'face)) clist)))
16899 ((org-at-table-p 'any)
16900 (push (list :table-table) clist)))
16901 (goto-char p)
16903 ;; Now the small context
16904 (cond
16905 ((org-at-timestamp-p)
16906 (push (org-point-in-group p 0 :timestamp) clist))
16907 ((memq 'org-link faces)
16908 (push (list :link
16909 (previous-single-property-change p 'face)
16910 (next-single-property-change p 'face)) clist))
16911 ((memq 'org-special-keyword faces)
16912 (push (list :keyword
16913 (previous-single-property-change p 'face)
16914 (next-single-property-change p 'face)) clist))
16915 ((org-on-target-p)
16916 (push (org-point-in-group p 0 :target) clist)
16917 (goto-char (1- (match-beginning 0)))
16918 (if (looking-at org-radio-target-regexp)
16919 (push (org-point-in-group p 0 :radio-target) clist))
16920 (goto-char p))
16921 ((setq o (car (delq nil
16922 (mapcar
16923 (lambda (x)
16924 (if (memq x org-latex-fragment-image-overlays) x))
16925 (org-overlays-at (point))))))
16926 (push (list :latex-fragment
16927 (org-overlay-start o) (org-overlay-end o)) clist)
16928 (push (list :latex-preview
16929 (org-overlay-start o) (org-overlay-end o)) clist))
16930 ((org-inside-LaTeX-fragment-p)
16931 ;; FIXME: positions wrong.
16932 (push (list :latex-fragment (point) (point)) clist)))
16934 (setq clist (nreverse (delq nil clist)))
16935 clist))
16937 ;; FIXME: Compare with at-regexp-p Do we need both?
16938 (defun org-in-regexp (re &optional nlines visually)
16939 "Check if point is inside a match of regexp.
16940 Normally only the current line is checked, but you can include NLINES extra
16941 lines both before and after point into the search.
16942 If VISUALLY is set, require that the cursor is not after the match but
16943 really on, so that the block visually is on the match."
16944 (catch 'exit
16945 (let ((pos (point))
16946 (eol (point-at-eol (+ 1 (or nlines 0))))
16947 (inc (if visually 1 0)))
16948 (save-excursion
16949 (beginning-of-line (- 1 (or nlines 0)))
16950 (while (re-search-forward re eol t)
16951 (if (and (<= (match-beginning 0) pos)
16952 (>= (+ inc (match-end 0)) pos))
16953 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16955 (defun org-at-regexp-p (regexp)
16956 "Is point inside a match of REGEXP in the current line?"
16957 (catch 'exit
16958 (save-excursion
16959 (let ((pos (point)) (end (point-at-eol)))
16960 (beginning-of-line 1)
16961 (while (re-search-forward regexp end t)
16962 (if (and (<= (match-beginning 0) pos)
16963 (>= (match-end 0) pos))
16964 (throw 'exit t)))
16965 nil))))
16967 (defun org-occur-in-agenda-files (regexp &optional nlines)
16968 "Call `multi-occur' with buffers for all agenda files."
16969 (interactive "sOrg-files matching: \np")
16970 (let* ((files (org-agenda-files))
16971 (tnames (mapcar 'file-truename files))
16972 (extra org-agenda-text-search-extra-files)
16974 (when (eq (car extra) 'agenda-archives)
16975 (setq extra (cdr extra))
16976 (setq files (org-add-archive-files files)))
16977 (while (setq f (pop extra))
16978 (unless (member (file-truename f) tnames)
16979 (add-to-list 'files f 'append)
16980 (add-to-list 'tnames (file-truename f) 'append)))
16981 (multi-occur
16982 (mapcar (lambda (x)
16983 (with-current-buffer
16984 (or (get-file-buffer x) (find-file-noselect x))
16985 (widen)
16986 (current-buffer)))
16987 files)
16988 regexp)))
16990 (if (boundp 'occur-mode-find-occurrence-hook)
16991 ;; Emacs 23
16992 (add-hook 'occur-mode-find-occurrence-hook
16993 (lambda ()
16994 (when (org-mode-p)
16995 (org-reveal))))
16996 ;; Emacs 22
16997 (defadvice occur-mode-goto-occurrence
16998 (after org-occur-reveal activate)
16999 (and (org-mode-p) (org-reveal)))
17000 (defadvice occur-mode-goto-occurrence-other-window
17001 (after org-occur-reveal activate)
17002 (and (org-mode-p) (org-reveal)))
17003 (defadvice occur-mode-display-occurrence
17004 (after org-occur-reveal activate)
17005 (when (org-mode-p)
17006 (let ((pos (occur-mode-find-occurrence)))
17007 (with-current-buffer (marker-buffer pos)
17008 (save-excursion
17009 (goto-char pos)
17010 (org-reveal)))))))
17012 (defun org-occur-link-in-agenda-files ()
17013 "Create a link and search for it in the agendas.
17014 The link is not stored in `org-stored-links', it is just created
17015 for the search purpose."
17016 (interactive)
17017 (let ((link (condition-case nil
17018 (org-store-link nil)
17019 (error "Unable to create a link to here"))))
17020 (org-occur-in-agenda-files (regexp-quote link))))
17022 (defun org-uniquify (list)
17023 "Remove duplicate elements from LIST."
17024 (let (res)
17025 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17026 res))
17028 (defun org-delete-all (elts list)
17029 "Remove all elements in ELTS from LIST."
17030 (while elts
17031 (setq list (delete (pop elts) list)))
17032 list)
17034 (defun org-back-over-empty-lines ()
17035 "Move backwards over whitespace, to the beginning of the first empty line.
17036 Returns the number of empty lines passed."
17037 (let ((pos (point)))
17038 (skip-chars-backward " \t\n\r")
17039 (beginning-of-line 2)
17040 (goto-char (min (point) pos))
17041 (count-lines (point) pos)))
17043 (defun org-skip-whitespace ()
17044 (skip-chars-forward " \t\n\r"))
17046 (defun org-point-in-group (point group &optional context)
17047 "Check if POINT is in match-group GROUP.
17048 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17049 match. If the match group does ot exist or point is not inside it,
17050 return nil."
17051 (and (match-beginning group)
17052 (>= point (match-beginning group))
17053 (<= point (match-end group))
17054 (if context
17055 (list context (match-beginning group) (match-end group))
17056 t)))
17058 (defun org-switch-to-buffer-other-window (&rest args)
17059 "Switch to buffer in a second window on the current frame.
17060 In particular, do not allow pop-up frames."
17061 (let (pop-up-frames special-display-buffer-names special-display-regexps
17062 special-display-function)
17063 (apply 'switch-to-buffer-other-window args)))
17065 (defun org-combine-plists (&rest plists)
17066 "Create a single property list from all plists in PLISTS.
17067 The process starts by copying the first list, and then setting properties
17068 from the other lists. Settings in the last list are the most significant
17069 ones and overrule settings in the other lists."
17070 (let ((rtn (copy-sequence (pop plists)))
17071 p v ls)
17072 (while plists
17073 (setq ls (pop plists))
17074 (while ls
17075 (setq p (pop ls) v (pop ls))
17076 (setq rtn (plist-put rtn p v))))
17077 rtn))
17079 (defun org-move-line-down (arg)
17080 "Move the current line down. With prefix argument, move it past ARG lines."
17081 (interactive "p")
17082 (let ((col (current-column))
17083 beg end pos)
17084 (beginning-of-line 1) (setq beg (point))
17085 (beginning-of-line 2) (setq end (point))
17086 (beginning-of-line (+ 1 arg))
17087 (setq pos (move-marker (make-marker) (point)))
17088 (insert (delete-and-extract-region beg end))
17089 (goto-char pos)
17090 (org-move-to-column col)))
17092 (defun org-move-line-up (arg)
17093 "Move the current line up. With prefix argument, move it past ARG lines."
17094 (interactive "p")
17095 (let ((col (current-column))
17096 beg end pos)
17097 (beginning-of-line 1) (setq beg (point))
17098 (beginning-of-line 2) (setq end (point))
17099 (beginning-of-line (- arg))
17100 (setq pos (move-marker (make-marker) (point)))
17101 (insert (delete-and-extract-region beg end))
17102 (goto-char pos)
17103 (org-move-to-column col)))
17105 (defun org-replace-escapes (string table)
17106 "Replace %-escapes in STRING with values in TABLE.
17107 TABLE is an association list with keys like \"%a\" and string values.
17108 The sequences in STRING may contain normal field width and padding information,
17109 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17110 so values can contain further %-escapes if they are define later in TABLE."
17111 (let ((case-fold-search nil)
17112 e re rpl)
17113 (while (setq e (pop table))
17114 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17115 (while (string-match re string)
17116 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17117 (cdr e)))
17118 (setq string (replace-match rpl t t string))))
17119 string))
17122 (defun org-sublist (list start end)
17123 "Return a section of LIST, from START to END.
17124 Counting starts at 1."
17125 (let (rtn (c start))
17126 (setq list (nthcdr (1- start) list))
17127 (while (and list (<= c end))
17128 (push (pop list) rtn)
17129 (setq c (1+ c)))
17130 (nreverse rtn)))
17132 (defun org-find-base-buffer-visiting (file)
17133 "Like `find-buffer-visiting' but always return the base buffer and
17134 not an indirect buffer."
17135 (let ((buf (or (get-file-buffer file)
17136 (find-buffer-visiting file))))
17137 (if buf
17138 (or (buffer-base-buffer buf) buf)
17139 nil)))
17141 (defun org-image-file-name-regexp (&optional extensions)
17142 "Return regexp matching the file names of images.
17143 If EXTENSIONS is given, only match these."
17144 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17145 (image-file-name-regexp)
17146 (let ((image-file-name-extensions
17147 (or extensions
17148 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17149 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17150 (concat "\\."
17151 (regexp-opt (nconc (mapcar 'upcase
17152 image-file-name-extensions)
17153 image-file-name-extensions)
17155 "\\'"))))
17157 (defun org-file-image-p (file &optional extensions)
17158 "Return non-nil if FILE is an image."
17159 (save-match-data
17160 (string-match (org-image-file-name-regexp extensions) file)))
17162 (defun org-get-cursor-date ()
17163 "Return the date at cursor in as a time.
17164 This works in the calendar and in the agenda, anywhere else it just
17165 returns the current time."
17166 (let (date day defd)
17167 (cond
17168 ((eq major-mode 'calendar-mode)
17169 (setq date (calendar-cursor-to-date)
17170 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17171 ((eq major-mode 'org-agenda-mode)
17172 (setq day (get-text-property (point) 'day))
17173 (if day
17174 (setq date (calendar-gregorian-from-absolute day)
17175 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17176 (nth 2 date))))))
17177 (or defd (current-time))))
17179 (defvar org-agenda-action-marker (make-marker)
17180 "Marker pointing to the entry for the next agenda action.")
17182 (defun org-mark-entry-for-agenda-action ()
17183 "Mark the current entry as target of an agenda action.
17184 Agenda actions are actions executed from the agenda with the key `k',
17185 which make use of the date at the cursor."
17186 (interactive)
17187 (move-marker org-agenda-action-marker
17188 (save-excursion (org-back-to-heading t) (point))
17189 (current-buffer))
17190 (message
17191 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17193 ;;; Paragraph filling stuff.
17194 ;; We want this to be just right, so use the full arsenal.
17196 (defun org-indent-line-function ()
17197 "Indent line like previous, but further if previous was headline or item."
17198 (interactive)
17199 (let* ((pos (point))
17200 (itemp (org-at-item-p))
17201 (case-fold-search t)
17202 (org-drawer-regexp (or org-drawer-regexp "\000"))
17203 column bpos bcol tpos tcol bullet btype bullet-type)
17204 ;; Find the previous relevant line
17205 (beginning-of-line 1)
17206 (cond
17207 ((looking-at "#") (setq column 0))
17208 ((looking-at "\\*+ ") (setq column 0))
17209 ((and (looking-at "[ \t]*:END:")
17210 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17211 (save-excursion
17212 (goto-char (1- (match-beginning 1)))
17213 (setq column (current-column))))
17214 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17215 (save-excursion
17216 (re-search-backward
17217 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17218 (setq column (org-get-indentation (match-string 0))))
17220 (beginning-of-line 0)
17221 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17222 (not (looking-at "[ \t]*:END:"))
17223 (not (looking-at org-drawer-regexp)))
17224 (beginning-of-line 0))
17225 (cond
17226 ((looking-at "\\*+[ \t]+")
17227 (if (not org-adapt-indentation)
17228 (setq column 0)
17229 (goto-char (match-end 0))
17230 (setq column (current-column))))
17231 ((looking-at org-drawer-regexp)
17232 (goto-char (1- (match-beginning 1)))
17233 (setq column (current-column)))
17234 ((looking-at "\\([ \t]*\\):END:")
17235 (goto-char (match-end 1))
17236 (setq column (current-column)))
17237 ((org-in-item-p)
17238 (org-beginning-of-item)
17239 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17240 (setq bpos (match-beginning 1) tpos (match-end 0)
17241 bcol (progn (goto-char bpos) (current-column))
17242 tcol (progn (goto-char tpos) (current-column))
17243 bullet (match-string 1)
17244 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17245 (if (> tcol (+ bcol org-description-max-indent))
17246 (setq tcol (+ bcol 5)))
17247 (if (not itemp)
17248 (setq column tcol)
17249 (goto-char pos)
17250 (beginning-of-line 1)
17251 (if (looking-at "\\S-")
17252 (progn
17253 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17254 (setq bullet (match-string 1)
17255 btype (if (string-match "[0-9]" bullet) "n" bullet))
17256 (setq column (if (equal btype bullet-type) bcol tcol)))
17257 (setq column (org-get-indentation)))))
17258 (t (setq column (org-get-indentation))))))
17259 (goto-char pos)
17260 (if (<= (current-column) (current-indentation))
17261 (org-indent-line-to column)
17262 (save-excursion (org-indent-line-to column)))
17263 (setq column (current-column))
17264 (beginning-of-line 1)
17265 (if (looking-at
17266 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17267 (replace-match (concat (match-string 1)
17268 (format org-property-format
17269 (match-string 2) (match-string 3)))
17270 t t))
17271 (org-move-to-column column)))
17273 (defun org-set-autofill-regexps ()
17274 (interactive)
17275 ;; In the paragraph separator we include headlines, because filling
17276 ;; text in a line directly attached to a headline would otherwise
17277 ;; fill the headline as well.
17278 (org-set-local 'comment-start-skip "^#+[ \t]*")
17279 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17280 ;; The paragraph starter includes hand-formatted lists.
17281 (org-set-local
17282 'paragraph-start
17283 (concat
17284 "\f" "\\|"
17285 "[ ]*$" "\\|"
17286 "\\*+ " "\\|"
17287 "[ \t]*#" "\\|"
17288 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17289 "[ \t]*[:|]" "\\|"
17290 "\\$\\$" "\\|"
17291 "\\\\\\(begin\\|end\\|[][]\\)"))
17292 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17293 ;; But only if the user has not turned off tables or fixed-width regions
17294 (org-set-local
17295 'auto-fill-inhibit-regexp
17296 (concat "\\*+ \\|#\\+"
17297 "\\|[ \t]*" org-keyword-time-regexp
17298 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17299 (concat
17300 "\\|[ \t]*["
17301 (if org-enable-table-editor "|" "")
17302 (if org-enable-fixed-width-editor ":" "")
17303 "]"))))
17304 ;; We use our own fill-paragraph function, to make sure that tables
17305 ;; and fixed-width regions are not wrapped. That function will pass
17306 ;; through to `fill-paragraph' when appropriate.
17307 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17308 ; Adaptive filling: To get full control, first make sure that
17309 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17310 (org-set-local 'adaptive-fill-regexp "\000")
17311 (org-set-local 'adaptive-fill-function
17312 'org-adaptive-fill-function)
17313 (org-set-local
17314 'align-mode-rules-list
17315 '((org-in-buffer-settings
17316 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17317 (modes . '(org-mode))))))
17319 (defun org-fill-paragraph (&optional justify)
17320 "Re-align a table, pass through to fill-paragraph if no table."
17321 (let ((table-p (org-at-table-p))
17322 (table.el-p (org-at-table.el-p)))
17323 (cond ((and (equal (char-after (point-at-bol)) ?*)
17324 (save-excursion (goto-char (point-at-bol))
17325 (looking-at outline-regexp)))
17326 t) ; skip headlines
17327 (table.el-p t) ; skip table.el tables
17328 (table-p (org-table-align) t) ; align org-mode tables
17329 (t nil)))) ; call paragraph-fill
17331 ;; For reference, this is the default value of adaptive-fill-regexp
17332 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17334 (defun org-adaptive-fill-function ()
17335 "Return a fill prefix for org-mode files.
17336 In particular, this makes sure hanging paragraphs for hand-formatted lists
17337 work correctly."
17338 (cond ((looking-at "#[ \t]+")
17339 (match-string 0))
17340 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17341 (save-excursion
17342 (if (> (match-end 1) (+ (match-beginning 1)
17343 org-description-max-indent))
17344 (goto-char (+ (match-beginning 1) 5))
17345 (goto-char (match-end 0)))
17346 (make-string (current-column) ?\ )))
17347 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17348 (save-excursion
17349 (goto-char (match-end 0))
17350 (make-string (current-column) ?\ )))
17351 (t nil)))
17353 ;;; Other stuff.
17355 (defun org-toggle-fixed-width-section (arg)
17356 "Toggle the fixed-width export.
17357 If there is no active region, the QUOTE keyword at the current headline is
17358 inserted or removed. When present, it causes the text between this headline
17359 and the next to be exported as fixed-width text, and unmodified.
17360 If there is an active region, this command adds or removes a colon as the
17361 first character of this line. If the first character of a line is a colon,
17362 this line is also exported in fixed-width font."
17363 (interactive "P")
17364 (let* ((cc 0)
17365 (regionp (org-region-active-p))
17366 (beg (if regionp (region-beginning) (point)))
17367 (end (if regionp (region-end)))
17368 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17369 (case-fold-search nil)
17370 (re "[ \t]*\\(: \\)")
17371 off)
17372 (if regionp
17373 (save-excursion
17374 (goto-char beg)
17375 (setq cc (current-column))
17376 (beginning-of-line 1)
17377 (setq off (looking-at re))
17378 (while (> nlines 0)
17379 (setq nlines (1- nlines))
17380 (beginning-of-line 1)
17381 (cond
17382 (arg
17383 (org-move-to-column cc t)
17384 (insert ": \n")
17385 (forward-line -1))
17386 ((and off (looking-at re))
17387 (replace-match "" t t nil 1))
17388 ((not off) (org-move-to-column cc t) (insert ": ")))
17389 (forward-line 1)))
17390 (save-excursion
17391 (org-back-to-heading)
17392 (if (looking-at (concat outline-regexp
17393 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17394 (replace-match "" t t nil 1)
17395 (if (looking-at outline-regexp)
17396 (progn
17397 (goto-char (match-end 0))
17398 (insert org-quote-string " "))))))))
17400 (defun org-reftex-citation ()
17401 "Use reftex-citation to insert a citation into the buffer.
17402 This looks for a line like
17404 #+BIBLIOGRAPHY: foo plain option:-d
17406 and derives from it that foo.bib is the bibliography file relevant
17407 for this document. It then installs the necessary environment for RefTeX
17408 to work in this buffer and calls `reftex-citation' to insert a citation
17409 into the buffer.
17411 Export of such citations to both LaTeX and HTML is handled by the contributed
17412 package org-exp-bibtex by Taru Karttunen."
17413 (interactive)
17414 (let ((reftex-docstruct-symbol 'rds)
17415 (reftex-cite-format "\\cite{%l}")
17416 rds bib)
17417 (save-excursion
17418 (save-restriction
17419 (widen)
17420 (let ((case-fold-search t)
17421 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17422 (if (not (save-excursion
17423 (or (re-search-forward re nil t)
17424 (re-search-backward re nil t))))
17425 (error "No bibliography defined in file")
17426 (setq bib (concat (match-string 1) ".bib")
17427 rds (list (list 'bib bib)))))))
17428 (call-interactively 'reftex-citation)))
17430 ;;;; Functions extending outline functionality
17432 (defun org-beginning-of-line (&optional arg)
17433 "Go to the beginning of the current line. If that is invisible, continue
17434 to a visible line beginning. This makes the function of C-a more intuitive.
17435 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17436 first attempt, and only move to after the tags when the cursor is already
17437 beyond the end of the headline."
17438 (interactive "P")
17439 (let ((pos (point))
17440 (special (if (consp org-special-ctrl-a/e)
17441 (car org-special-ctrl-a/e)
17442 org-special-ctrl-a/e))
17443 refpos)
17444 (if (org-bound-and-true-p line-move-visual)
17445 (beginning-of-visual-line 1)
17446 (beginning-of-line 1))
17447 (if (and arg (fboundp 'move-beginning-of-line))
17448 (call-interactively 'move-beginning-of-line)
17449 (if (bobp)
17451 (backward-char 1)
17452 (if (org-invisible-p)
17453 (while (and (not (bobp)) (org-invisible-p))
17454 (backward-char 1)
17455 (beginning-of-line 1))
17456 (forward-char 1))))
17457 (when special
17458 (cond
17459 ((and (looking-at org-complex-heading-regexp)
17460 (= (char-after (match-end 1)) ?\ ))
17461 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17462 (point-at-eol)))
17463 (goto-char
17464 (if (eq special t)
17465 (cond ((> pos refpos) refpos)
17466 ((= pos (point)) refpos)
17467 (t (point)))
17468 (cond ((> pos (point)) (point))
17469 ((not (eq last-command this-command)) (point))
17470 (t refpos)))))
17471 ((org-at-item-p)
17472 (goto-char
17473 (if (eq special t)
17474 (cond ((> pos (match-end 4)) (match-end 4))
17475 ((= pos (point)) (match-end 4))
17476 (t (point)))
17477 (cond ((> pos (point)) (point))
17478 ((not (eq last-command this-command)) (point))
17479 (t (match-end 4))))))))
17480 (org-no-warnings
17481 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17483 (defun org-end-of-line (&optional arg)
17484 "Go to the end of the line.
17485 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17486 first attempt, and only move to after the tags when the cursor is already
17487 beyond the end of the headline."
17488 (interactive "P")
17489 (let ((special (if (consp org-special-ctrl-a/e)
17490 (cdr org-special-ctrl-a/e)
17491 org-special-ctrl-a/e)))
17492 (if (or (not special)
17493 (not (org-on-heading-p))
17494 arg)
17495 (call-interactively
17496 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17497 ((fboundp 'move-end-of-line) 'move-end-of-line)
17498 (t 'end-of-line)))
17499 (let ((pos (point)))
17500 (beginning-of-line 1)
17501 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17502 (if (eq special t)
17503 (if (or (< pos (match-beginning 1))
17504 (= pos (match-end 0)))
17505 (goto-char (match-beginning 1))
17506 (goto-char (match-end 0)))
17507 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17508 (goto-char (match-end 0))
17509 (goto-char (match-beginning 1))))
17510 (call-interactively (if (fboundp 'move-end-of-line)
17511 'move-end-of-line
17512 'end-of-line)))))
17513 (org-no-warnings
17514 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17516 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17517 (define-key org-mode-map "\C-e" 'org-end-of-line)
17518 (define-key org-mode-map [home] 'org-beginning-of-line)
17519 (define-key org-mode-map [end] 'org-end-of-line)
17521 (defun org-backward-sentence (&optional arg)
17522 "Go to beginning of sentence, or beginning of table field.
17523 This will call `backward-sentence' or `org-table-beginning-of-field',
17524 depending on context."
17525 (interactive "P")
17526 (cond
17527 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17528 (t (call-interactively 'backward-sentence))))
17530 (defun org-forward-sentence (&optional arg)
17531 "Go to end of sentence, or end of table field.
17532 This will call `forward-sentence' or `org-table-end-of-field',
17533 depending on context."
17534 (interactive "P")
17535 (cond
17536 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17537 (t (call-interactively 'forward-sentence))))
17539 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17540 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17542 (defun org-kill-line (&optional arg)
17543 "Kill line, to tags or end of line."
17544 (interactive "P")
17545 (cond
17546 ((or (not org-special-ctrl-k)
17547 (bolp)
17548 (not (org-on-heading-p)))
17549 (call-interactively 'kill-line))
17550 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17551 (kill-region (point) (match-beginning 1))
17552 (org-set-tags nil t))
17553 (t (kill-region (point) (point-at-eol)))))
17555 (define-key org-mode-map "\C-k" 'org-kill-line)
17557 (defun org-yank (&optional arg)
17558 "Yank. If the kill is a subtree, treat it specially.
17559 This command will look at the current kill and check if is a single
17560 subtree, or a series of subtrees[1]. If it passes the test, and if the
17561 cursor is at the beginning of a line or after the stars of a currently
17562 empty headline, then the yank is handled specially. How exactly depends
17563 on the value of the following variables, both set by default.
17565 org-yank-folded-subtrees
17566 When set, the subtree(s) will be folded after insertion, but only
17567 if doing so would now swallow text after the yanked text.
17569 org-yank-adjusted-subtrees
17570 When set, the subtree will be promoted or demoted in order to
17571 fit into the local outline tree structure, which means that the level
17572 will be adjusted so that it becomes the smaller one of the two
17573 *visible* surrounding headings.
17575 Any prefix to this command will cause `yank' to be called directly with
17576 no special treatment. In particular, a simple `C-u' prefix will just
17577 plainly yank the text as it is.
17579 \[1] The test checks if the first non-white line is a heading
17580 and if there are no other headings with fewer stars."
17581 (interactive "P")
17582 (org-yank-generic 'yank arg))
17584 (defun org-yank-generic (command arg)
17585 "Perform some yank-like command.
17587 This function implements the behavior described in the `org-yank'
17588 documentation. However, it has been generalized to work for any
17589 interactive command with similar behavior."
17591 ;; pretend to be command COMMAND
17592 (setq this-command command)
17594 (if arg
17595 (call-interactively command)
17597 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17598 (and (org-kill-is-subtree-p)
17599 (or (bolp)
17600 (and (looking-at "[ \t]*$")
17601 (string-match
17602 "\\`\\*+\\'"
17603 (buffer-substring (point-at-bol) (point)))))))
17604 swallowp)
17605 (cond
17606 ((and subtreep org-yank-folded-subtrees)
17607 (let ((beg (point))
17608 end)
17609 (if (and subtreep org-yank-adjusted-subtrees)
17610 (org-paste-subtree nil nil 'for-yank)
17611 (call-interactively command))
17613 (setq end (point))
17614 (goto-char beg)
17615 (when (and (bolp) subtreep
17616 (not (setq swallowp
17617 (org-yank-folding-would-swallow-text beg end))))
17618 (or (looking-at outline-regexp)
17619 (re-search-forward (concat "^" outline-regexp) end t))
17620 (while (and (< (point) end) (looking-at outline-regexp))
17621 (hide-subtree)
17622 (org-cycle-show-empty-lines 'folded)
17623 (condition-case nil
17624 (outline-forward-same-level 1)
17625 (error (goto-char end)))))
17626 (when swallowp
17627 (message
17628 "Inserted text not folded because that would swallow text"))
17630 (goto-char end)
17631 (skip-chars-forward " \t\n\r")
17632 (beginning-of-line 1)
17633 (push-mark beg 'nomsg)))
17634 ((and subtreep org-yank-adjusted-subtrees)
17635 (let ((beg (point-at-bol)))
17636 (org-paste-subtree nil nil 'for-yank)
17637 (push-mark beg 'nomsg)))
17639 (call-interactively command))))))
17641 (defun org-yank-folding-would-swallow-text (beg end)
17642 "Would hide-subtree at BEG swallow any text after END?"
17643 (let (level)
17644 (save-excursion
17645 (goto-char beg)
17646 (when (or (looking-at outline-regexp)
17647 (re-search-forward (concat "^" outline-regexp) end t))
17648 (setq level (org-outline-level)))
17649 (goto-char end)
17650 (skip-chars-forward " \t\r\n\v\f")
17651 (if (or (eobp)
17652 (and (bolp) (looking-at org-outline-regexp)
17653 (<= (org-outline-level) level)))
17654 nil ; Nothing would be swallowed
17655 t)))) ; something would swallow
17657 (define-key org-mode-map "\C-y" 'org-yank)
17659 (defun org-invisible-p ()
17660 "Check if point is at a character currently not visible."
17661 ;; Early versions of noutline don't have `outline-invisible-p'.
17662 (if (fboundp 'outline-invisible-p)
17663 (outline-invisible-p)
17664 (get-char-property (point) 'invisible)))
17666 (defun org-invisible-p2 ()
17667 "Check if point is at a character currently not visible."
17668 (save-excursion
17669 (if (and (eolp) (not (bobp))) (backward-char 1))
17670 ;; Early versions of noutline don't have `outline-invisible-p'.
17671 (if (fboundp 'outline-invisible-p)
17672 (outline-invisible-p)
17673 (get-char-property (point) 'invisible))))
17675 (defun org-back-to-heading (&optional invisible-ok)
17676 "Call `outline-back-to-heading', but provide a better error message."
17677 (condition-case nil
17678 (outline-back-to-heading invisible-ok)
17679 (error (error "Before first headline at position %d in buffer %s"
17680 (point) (current-buffer)))))
17682 (defun org-before-first-heading-p ()
17683 "Before first heading?"
17684 (save-excursion
17685 (null (re-search-backward "^\\*+ " nil t))))
17687 (defun org-on-heading-p (&optional ignored)
17688 (outline-on-heading-p t))
17689 (defun org-at-heading-p (&optional ignored)
17690 (outline-on-heading-p t))
17692 (defun org-at-heading-or-item-p ()
17693 (or (org-on-heading-p) (org-at-item-p)))
17695 (defun org-on-target-p ()
17696 (or (org-in-regexp org-radio-target-regexp)
17697 (org-in-regexp org-target-regexp)))
17699 (defun org-up-heading-all (arg)
17700 "Move to the heading line of which the present line is a subheading.
17701 This function considers both visible and invisible heading lines.
17702 With argument, move up ARG levels."
17703 (if (fboundp 'outline-up-heading-all)
17704 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17705 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17707 (defun org-up-heading-safe ()
17708 "Move to the heading line of which the present line is a subheading.
17709 This version will not throw an error. It will return the level of the
17710 headline found, or nil if no higher level is found.
17712 Also, this function will be a lot faster than `outline-up-heading',
17713 because it relies on stars being the outline starters. This can really
17714 make a significant difference in outlines with very many siblings."
17715 (let (start-level re)
17716 (org-back-to-heading t)
17717 (setq start-level (funcall outline-level))
17718 (if (equal start-level 1)
17720 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17721 (if (re-search-backward re nil t)
17722 (funcall outline-level)))))
17724 (defun org-first-sibling-p ()
17725 "Is this heading the first child of its parents?"
17726 (interactive)
17727 (let ((re (concat "^" outline-regexp))
17728 level l)
17729 (unless (org-at-heading-p t)
17730 (error "Not at a heading"))
17731 (setq level (funcall outline-level))
17732 (save-excursion
17733 (if (not (re-search-backward re nil t))
17735 (setq l (funcall outline-level))
17736 (< l level)))))
17738 (defun org-goto-sibling (&optional previous)
17739 "Goto the next sibling, even if it is invisible.
17740 When PREVIOUS is set, go to the previous sibling instead. Returns t
17741 when a sibling was found. When none is found, return nil and don't
17742 move point."
17743 (let ((fun (if previous 're-search-backward 're-search-forward))
17744 (pos (point))
17745 (re (concat "^" outline-regexp))
17746 level l)
17747 (when (condition-case nil (org-back-to-heading t) (error nil))
17748 (setq level (funcall outline-level))
17749 (catch 'exit
17750 (or previous (forward-char 1))
17751 (while (funcall fun re nil t)
17752 (setq l (funcall outline-level))
17753 (when (< l level) (goto-char pos) (throw 'exit nil))
17754 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17755 (goto-char pos)
17756 nil))))
17758 (defun org-show-siblings ()
17759 "Show all siblings of the current headline."
17760 (save-excursion
17761 (while (org-goto-sibling) (org-flag-heading nil)))
17762 (save-excursion
17763 (while (org-goto-sibling 'previous)
17764 (org-flag-heading nil))))
17766 (defun org-show-hidden-entry ()
17767 "Show an entry where even the heading is hidden."
17768 (save-excursion
17769 (org-show-entry)))
17771 (defun org-flag-heading (flag &optional entry)
17772 "Flag the current heading. FLAG non-nil means make invisible.
17773 When ENTRY is non-nil, show the entire entry."
17774 (save-excursion
17775 (org-back-to-heading t)
17776 ;; Check if we should show the entire entry
17777 (if entry
17778 (progn
17779 (org-show-entry)
17780 (save-excursion
17781 (and (outline-next-heading)
17782 (org-flag-heading nil))))
17783 (outline-flag-region (max (point-min) (1- (point)))
17784 (save-excursion (outline-end-of-heading) (point))
17785 flag))))
17787 (defun org-get-next-sibling ()
17788 "Move to next heading of the same level, and return point.
17789 If there is no such heading, return nil.
17790 This is like outline-next-sibling, but invisible headings are ok."
17791 (let ((level (funcall outline-level)))
17792 (outline-next-heading)
17793 (while (and (not (eobp)) (> (funcall outline-level) level))
17794 (outline-next-heading))
17795 (if (or (eobp) (< (funcall outline-level) level))
17797 (point))))
17799 (defun org-get-last-sibling ()
17800 "Move to previous heading of the same level, and return point.
17801 If there is no such heading, return nil."
17802 (let ((opoint (point))
17803 (level (funcall outline-level)))
17804 (outline-previous-heading)
17805 (when (and (/= (point) opoint) (outline-on-heading-p t))
17806 (while (and (> (funcall outline-level) level)
17807 (not (bobp)))
17808 (outline-previous-heading))
17809 (if (< (funcall outline-level) level)
17811 (point)))))
17813 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17814 ;; This contains an exact copy of the original function, but it uses
17815 ;; `org-back-to-heading', to make it work also in invisible
17816 ;; trees. And is uses an invisible-OK argument.
17817 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17818 ;; Furthermore, when used inside Org, finding the end of a large subtree
17819 ;; with many children and grandchildren etc, this can be much faster
17820 ;; than the outline version.
17821 (org-back-to-heading invisible-OK)
17822 (let ((first t)
17823 (level (funcall outline-level)))
17824 (if (and (org-mode-p) (< level 1000))
17825 ;; A true heading (not a plain list item), in Org-mode
17826 ;; This means we can easily find the end by looking
17827 ;; only for the right number of stars. Using a regexp to do
17828 ;; this is so much faster than using a Lisp loop.
17829 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17830 (forward-char 1)
17831 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17832 ;; something else, do it the slow way
17833 (while (and (not (eobp))
17834 (or first (> (funcall outline-level) level)))
17835 (setq first nil)
17836 (outline-next-heading)))
17837 (unless to-heading
17838 (if (memq (preceding-char) '(?\n ?\^M))
17839 (progn
17840 ;; Go to end of line before heading
17841 (forward-char -1)
17842 (if (memq (preceding-char) '(?\n ?\^M))
17843 ;; leave blank line before heading
17844 (forward-char -1))))))
17845 (point))
17847 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17848 "Use Org version in org-mode, for dramatic speed-up."
17849 (if (eq major-mode 'org-mode)
17850 (progn
17851 (org-end-of-subtree nil t)
17852 (unless (eobp) (backward-char 1)))
17853 ad-do-it))
17855 (defun org-forward-same-level (arg &optional invisible-ok)
17856 "Move forward to the arg'th subheading at same level as this one.
17857 Stop at the first and last subheadings of a superior heading."
17858 (interactive "p")
17859 (org-back-to-heading invisible-ok)
17860 (org-on-heading-p)
17861 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17862 (re (format "^\\*\\{1,%d\\} " level))
17864 (forward-char 1)
17865 (while (> arg 0)
17866 (while (and (re-search-forward re nil 'move)
17867 (setq l (- (match-end 0) (match-beginning 0) 1))
17868 (= l level)
17869 (not invisible-ok)
17870 (progn (backward-char 1) (org-invisible-p)))
17871 (if (< l level) (setq arg 1)))
17872 (setq arg (1- arg)))
17873 (beginning-of-line 1)))
17875 (defun org-backward-same-level (arg &optional invisible-ok)
17876 "Move backward to the arg'th subheading at same level as this one.
17877 Stop at the first and last subheadings of a superior heading."
17878 (interactive "p")
17879 (org-back-to-heading)
17880 (org-on-heading-p)
17881 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17882 (re (format "^\\*\\{1,%d\\} " level))
17884 (while (> arg 0)
17885 (while (and (re-search-backward re nil 'move)
17886 (setq l (- (match-end 0) (match-beginning 0) 1))
17887 (= l level)
17888 (not invisible-ok)
17889 (org-invisible-p))
17890 (if (< l level) (setq arg 1)))
17891 (setq arg (1- arg)))))
17893 (defun org-show-subtree ()
17894 "Show everything after this heading at deeper levels."
17895 (outline-flag-region
17896 (point)
17897 (save-excursion
17898 (org-end-of-subtree t t))
17899 nil))
17901 (defun org-show-entry ()
17902 "Show the body directly following this heading.
17903 Show the heading too, if it is currently invisible."
17904 (interactive)
17905 (save-excursion
17906 (condition-case nil
17907 (progn
17908 (org-back-to-heading t)
17909 (outline-flag-region
17910 (max (point-min) (1- (point)))
17911 (save-excursion
17912 (if (re-search-forward
17913 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17914 (match-beginning 1)
17915 (point-max)))
17916 nil)
17917 (org-cycle-hide-drawers 'children))
17918 (error nil))))
17920 (defun org-make-options-regexp (kwds &optional extra)
17921 "Make a regular expression for keyword lines."
17922 (concat
17924 "#?[ \t]*\\+\\("
17925 (mapconcat 'regexp-quote kwds "\\|")
17926 (if extra (concat "\\|" extra))
17927 "\\):[ \t]*"
17928 "\\(.*\\)"))
17930 ;; Make isearch reveal the necessary context
17931 (defun org-isearch-end ()
17932 "Reveal context after isearch exits."
17933 (when isearch-success ; only if search was successful
17934 (if (featurep 'xemacs)
17935 ;; Under XEmacs, the hook is run in the correct place,
17936 ;; we directly show the context.
17937 (org-show-context 'isearch)
17938 ;; In Emacs the hook runs *before* restoring the overlays.
17939 ;; So we have to use a one-time post-command-hook to do this.
17940 ;; (Emacs 22 has a special variable, see function `org-mode')
17941 (unless (and (boundp 'isearch-mode-end-hook-quit)
17942 isearch-mode-end-hook-quit)
17943 ;; Only when the isearch was not quitted.
17944 (org-add-hook 'post-command-hook 'org-isearch-post-command
17945 'append 'local)))))
17947 (defun org-isearch-post-command ()
17948 "Remove self from hook, and show context."
17949 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17950 (org-show-context 'isearch))
17953 ;;;; Integration with and fixes for other packages
17955 ;;; Imenu support
17957 (defvar org-imenu-markers nil
17958 "All markers currently used by Imenu.")
17959 (make-variable-buffer-local 'org-imenu-markers)
17961 (defun org-imenu-new-marker (&optional pos)
17962 "Return a new marker for use by Imenu, and remember the marker."
17963 (let ((m (make-marker)))
17964 (move-marker m (or pos (point)))
17965 (push m org-imenu-markers)
17968 (defun org-imenu-get-tree ()
17969 "Produce the index for Imenu."
17970 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17971 (setq org-imenu-markers nil)
17972 (let* ((n org-imenu-depth)
17973 (re (concat "^" outline-regexp))
17974 (subs (make-vector (1+ n) nil))
17975 (last-level 0)
17976 m level head)
17977 (save-excursion
17978 (save-restriction
17979 (widen)
17980 (goto-char (point-max))
17981 (while (re-search-backward re nil t)
17982 (setq level (org-reduced-level (funcall outline-level)))
17983 (when (<= level n)
17984 (looking-at org-complex-heading-regexp)
17985 (setq head (org-link-display-format
17986 (org-match-string-no-properties 4))
17987 m (org-imenu-new-marker))
17988 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17989 (if (>= level last-level)
17990 (push (cons head m) (aref subs level))
17991 (push (cons head (aref subs (1+ level))) (aref subs level))
17992 (loop for i from (1+ level) to n do (aset subs i nil)))
17993 (setq last-level level)))))
17994 (aref subs 1)))
17996 (eval-after-load "imenu"
17997 '(progn
17998 (add-hook 'imenu-after-jump-hook
17999 (lambda ()
18000 (if (eq major-mode 'org-mode)
18001 (org-show-context 'org-goto))))))
18003 (defun org-link-display-format (link)
18004 "Replace a link with either the description, or the link target
18005 if no description is present"
18006 (save-match-data
18007 (if (string-match org-bracket-link-analytic-regexp link)
18008 (replace-match (if (match-end 5)
18009 (match-string 5 link)
18010 (concat (match-string 1 link)
18011 (match-string 3 link)))
18012 nil t link)
18013 link)))
18015 ;; Speedbar support
18017 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18018 "Overlay marking the agenda restriction line in speedbar.")
18019 (org-overlay-put org-speedbar-restriction-lock-overlay
18020 'face 'org-agenda-restriction-lock)
18021 (org-overlay-put org-speedbar-restriction-lock-overlay
18022 'help-echo "Agendas are currently limited to this item.")
18023 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18025 (defun org-speedbar-set-agenda-restriction ()
18026 "Restrict future agenda commands to the location at point in speedbar.
18027 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18028 (interactive)
18029 (require 'org-agenda)
18030 (let (p m tp np dir txt)
18031 (cond
18032 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18033 'org-imenu t))
18034 (setq m (get-text-property p 'org-imenu-marker))
18035 (with-current-buffer (marker-buffer m)
18036 (goto-char m)
18037 (org-agenda-set-restriction-lock 'subtree)))
18038 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18039 'speedbar-function 'speedbar-find-file))
18040 (setq tp (previous-single-property-change
18041 (1+ p) 'speedbar-function)
18042 np (next-single-property-change
18043 tp 'speedbar-function)
18044 dir (speedbar-line-directory)
18045 txt (buffer-substring-no-properties (or tp (point-min))
18046 (or np (point-max))))
18047 (with-current-buffer (find-file-noselect
18048 (let ((default-directory dir))
18049 (expand-file-name txt)))
18050 (unless (org-mode-p)
18051 (error "Cannot restrict to non-Org-mode file"))
18052 (org-agenda-set-restriction-lock 'file)))
18053 (t (error "Don't know how to restrict Org-mode's agenda")))
18054 (org-move-overlay org-speedbar-restriction-lock-overlay
18055 (point-at-bol) (point-at-eol))
18056 (setq current-prefix-arg nil)
18057 (org-agenda-maybe-redo)))
18059 (eval-after-load "speedbar"
18060 '(progn
18061 (speedbar-add-supported-extension ".org")
18062 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18063 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18064 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18065 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18066 (add-hook 'speedbar-visiting-tag-hook
18067 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18070 ;;; Fixes and Hacks for problems with other packages
18072 ;; Make flyspell not check words in links, to not mess up our keymap
18073 (defun org-mode-flyspell-verify ()
18074 "Don't let flyspell put overlays at active buttons."
18075 (and (not (get-text-property (point) 'keymap))
18076 (not (get-text-property (point) 'org-no-flyspell))))
18078 (defun org-remove-flyspell-overlays-in (beg end)
18079 "Remove flyspell overlays in region."
18080 (and (org-bound-and-true-p flyspell-mode)
18081 (fboundp 'flyspell-delete-region-overlays)
18082 (flyspell-delete-region-overlays beg end))
18083 (add-text-properties beg end '(org-no-flyspell t)))
18085 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18086 (eval-after-load "bookmark"
18087 '(if (boundp 'bookmark-after-jump-hook)
18088 ;; We can use the hook
18089 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18090 ;; Hook not available, use advice
18091 (defadvice bookmark-jump (after org-make-visible activate)
18092 "Make the position visible."
18093 (org-bookmark-jump-unhide))))
18095 ;; Make sure saveplace shows the location if it was hidden
18096 (eval-after-load "saveplace"
18097 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18098 "Make the position visible."
18099 (org-bookmark-jump-unhide)))
18101 ;; Make sure ecb shows the location if it was hidden
18102 (eval-after-load "ecb"
18103 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18104 "Make hierarchy visible when jumping into location from ECB tree buffer."
18105 (if (eq major-mode 'org-mode)
18106 (org-show-context))))
18108 (defun org-bookmark-jump-unhide ()
18109 "Unhide the current position, to show the bookmark location."
18110 (and (org-mode-p)
18111 (or (org-invisible-p)
18112 (save-excursion (goto-char (max (point-min) (1- (point))))
18113 (org-invisible-p)))
18114 (org-show-context 'bookmark-jump)))
18116 ;; Make session.el ignore our circular variable
18117 (eval-after-load "session"
18118 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18120 ;;;; Experimental code
18122 (defun org-closed-in-range ()
18123 "Sparse tree of items closed in a certain time range.
18124 Still experimental, may disappear in the future."
18125 (interactive)
18126 ;; Get the time interval from the user.
18127 (let* ((time1 (org-float-time
18128 (org-read-date nil 'to-time nil "Starting date: ")))
18129 (time2 (org-float-time
18130 (org-read-date nil 'to-time nil "End date:")))
18131 ;; callback function
18132 (callback (lambda ()
18133 (let ((time
18134 (org-float-time
18135 (apply 'encode-time
18136 (org-parse-time-string
18137 (match-string 1))))))
18138 ;; check if time in interval
18139 (and (>= time time1) (<= time time2))))))
18140 ;; make tree, check each match with the callback
18141 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18143 ;;;; Finish up
18145 (provide 'org)
18147 (run-hooks 'org-load-hook)
18149 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18151 ;;; org.el ends here