Save and restore outline visibility when pressing C-c C-c on a meta line
[org-mode.git] / lisp / org.el
blob9d23a0c7507e0bc8e056e82a7e6fd8b509a22cc4
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.33trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.33trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message version)))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " docview: Links to doc-view buffers" org-docview)
193 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
194 (const :tag " id: Global IDs for identifying entries" org-id)
195 (const :tag " info: Links to Info nodes" org-info)
196 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
197 (const :tag " habit: Track your consistency with habits" org-habit)
198 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
199 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
200 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
201 (const :tag " mew Links to Mew folders/messages" org-mew)
202 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
203 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
204 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
205 (const :tag " vm: Links to VM folders/messages" org-vm)
206 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
207 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
208 (const :tag " mouse: Additional mouse support" org-mouse)
210 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
211 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
212 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
213 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
214 (const :tag "C collector: Collect properties into tables" org-collector)
215 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
216 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
217 (const :tag "C eval: Include command output as text" org-eval)
218 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
219 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
220 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
221 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
222 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
224 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
226 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
227 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
228 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
229 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
230 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
231 (const :tag "C mtags: Support for muse-like tags" org-mtags)
232 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
233 (const :tag "C R: Computation using the R language" org-R)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
238 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
239 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
240 (const :tag "C track: Keep up with Org-mode development" org-track)
241 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
243 (defcustom org-support-shift-select nil
244 "Non-nil means, make shift-cursor commands select text when possible.
246 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
247 selecting a region, or enlarge thusly regions started in this way.
248 In Org-mode, in special contexts, these same keys are used for other
249 purposes, important enough to compete with shift selection. Org tries
250 to balance these needs by supporting `shift-select-mode' outside these
251 special contexts, under control of this variable.
253 The default of this variable is nil, to avoid confusing behavior. Shifted
254 cursor keys will then execute Org commands in the following contexts:
255 - on a headline, changing TODO state (left/right) and priority (up/down)
256 - on a time stamp, changing the time
257 - in a plain list item, changing the bullet type
258 - in a property definition line, switching between allowed values
259 - in the BEGIN line of a clock table (changing the time block).
260 Outside these contexts, the commands will throw an error.
262 When this variable is t and the cursor is not in a special context,
263 Org-mode will support shift-selection for making and enlarging regions.
264 To make this more effective, the bullet cycling will no longer happen
265 anywhere in an item line, but only if the cursor is exactly on the bullet.
267 If you set this variable to the symbol `always', then the keys
268 will not be special in headlines, property lines, and item lines, to make
269 shift selection work there as well. If this is what you want, you can
270 use the following alternative commands: `C-c C-t' and `C-c ,' to
271 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
272 TODO sets, `C-c -' to cycle item bullet types, and properties can be
273 edited by hand or in column view.
275 However, when the cursor is on a timestamp, shift-cursor commands
276 will still edit the time stamp - this is just too good to give up.
278 XEmacs user should have this variable set to nil, because shift-select-mode
279 is Emacs 23 only."
280 :group 'org
281 :type '(choice
282 (const :tag "Never" nil)
283 (const :tag "When outside special context" t)
284 (const :tag "Everywhere except timestamps" always)))
286 (defgroup org-startup nil
287 "Options concerning startup of Org-mode."
288 :tag "Org Startup"
289 :group 'org)
291 (defcustom org-startup-folded t
292 "Non-nil means, entering Org-mode will switch to OVERVIEW.
293 This can also be configured on a per-file basis by adding one of
294 the following lines anywhere in the buffer:
296 #+STARTUP: fold (or `overview', this is equivalent)
297 #+STARTUP: nofold (or `showall', this is equivalent)
298 #+STARTUP: content
299 #+STARTUP: showeverything"
300 :group 'org-startup
301 :type '(choice
302 (const :tag "nofold: show all" nil)
303 (const :tag "fold: overview" t)
304 (const :tag "content: all headlines" content)
305 (const :tag "show everything, even drawers" showeverything)))
307 (defcustom org-startup-truncated t
308 "Non-nil means, entering Org-mode will set `truncate-lines'.
309 This is useful since some lines containing links can be very long and
310 uninteresting. Also tables look terrible when wrapped."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-startup-indented nil
315 "Non-nil means, turn on `org-indent-mode' on startup.
316 This can also be configured on a per-file basis by adding one of
317 the following lines anywhere in the buffer:
319 #+STARTUP: indent
320 #+STARTUP: noindent"
321 :group 'org-structure
322 :type '(choice
323 (const :tag "Not" nil)
324 (const :tag "Globally (slow on startup in large files)" t)))
326 (defcustom org-startup-with-beamer-mode nil
327 "Non-nil means, turn on `org-beamer-mode' on startup.
328 This can also be configured on a per-file basis by adding one of
329 the following lines anywhere in the buffer:
331 #+STARTUP: beamer"
332 :group 'org-startup
333 :type 'boolean)
335 (defcustom org-startup-align-all-tables nil
336 "Non-nil means, align all tables when visiting a file.
337 This is useful when the column width in tables is forced with <N> cookies
338 in table fields. Such tables will look correct only after the first re-align.
339 This can also be configured on a per-file basis by adding one of
340 the following lines anywhere in the buffer:
341 #+STARTUP: align
342 #+STARTUP: noalign"
343 :group 'org-startup
344 :type 'boolean)
346 (defcustom org-insert-mode-line-in-empty-file nil
347 "Non-nil means insert the first line setting Org-mode in empty files.
348 When the function `org-mode' is called interactively in an empty file, this
349 normally means that the file name does not automatically trigger Org-mode.
350 To ensure that the file will always be in Org-mode in the future, a
351 line enforcing Org-mode will be inserted into the buffer, if this option
352 has been set."
353 :group 'org-startup
354 :type 'boolean)
356 (defcustom org-replace-disputed-keys nil
357 "Non-nil means use alternative key bindings for some keys.
358 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
359 These keys are also used by other packages like shift-selection-mode'
360 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
361 If you want to use Org-mode together with one of these other modes,
362 or more generally if you would like to move some Org-mode commands to
363 other keys, set this variable and configure the keys with the variable
364 `org-disputed-keys'.
366 This option is only relevant at load-time of Org-mode, and must be set
367 *before* org.el is loaded. Changing it requires a restart of Emacs to
368 become effective."
369 :group 'org-startup
370 :type 'boolean)
372 (defcustom org-use-extra-keys nil
373 "Non-nil means use extra key sequence definitions for certain
374 commands. This happens automatically if you run XEmacs or if
375 window-system is nil. This variable lets you do the same
376 manually. You must set it before loading org.
378 Example: on Carbon Emacs 22 running graphically, with an external
379 keyboard on a Powerbook, the default way of setting M-left might
380 not work for either Alt or ESC. Setting this variable will make
381 it work for ESC."
382 :group 'org-startup
383 :type 'boolean)
385 (if (fboundp 'defvaralias)
386 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
388 (defcustom org-disputed-keys
389 '(([(shift up)] . [(meta p)])
390 ([(shift down)] . [(meta n)])
391 ([(shift left)] . [(meta -)])
392 ([(shift right)] . [(meta +)])
393 ([(control shift right)] . [(meta shift +)])
394 ([(control shift left)] . [(meta shift -)]))
395 "Keys for which Org-mode and other modes compete.
396 This is an alist, cars are the default keys, second element specifies
397 the alternative to use when `org-replace-disputed-keys' is t.
399 Keys can be specified in any syntax supported by `define-key'.
400 The value of this option takes effect only at Org-mode's startup,
401 therefore you'll have to restart Emacs to apply it after changing."
402 :group 'org-startup
403 :type 'alist)
405 (defun org-key (key)
406 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
407 Or return the original if not disputed."
408 (if org-replace-disputed-keys
409 (let* ((nkey (key-description key))
410 (x (org-find-if (lambda (x)
411 (equal (key-description (car x)) nkey))
412 org-disputed-keys)))
413 (if x (cdr x) key))
414 key))
416 (defun org-find-if (predicate seq)
417 (catch 'exit
418 (while seq
419 (if (funcall predicate (car seq))
420 (throw 'exit (car seq))
421 (pop seq)))))
423 (defun org-defkey (keymap key def)
424 "Define a key, possibly translated, as returned by `org-key'."
425 (define-key keymap (org-key key) def))
427 (defcustom org-ellipsis nil
428 "The ellipsis to use in the Org-mode outline.
429 When nil, just use the standard three dots. When a string, use that instead,
430 When a face, use the standard 3 dots, but with the specified face.
431 The change affects only Org-mode (which will then use its own display table).
432 Changing this requires executing `M-x org-mode' in a buffer to become
433 effective."
434 :group 'org-startup
435 :type '(choice (const :tag "Default" nil)
436 (face :tag "Face" :value org-warning)
437 (string :tag "String" :value "...#")))
439 (defvar org-display-table nil
440 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
442 (defgroup org-keywords nil
443 "Keywords in Org-mode."
444 :tag "Org Keywords"
445 :group 'org)
447 (defcustom org-deadline-string "DEADLINE:"
448 "String to mark deadline entries.
449 A deadline is this string, followed by a time stamp. Should be a word,
450 terminated by a colon. You can insert a schedule keyword and
451 a timestamp with \\[org-deadline].
452 Changes become only effective after restarting Emacs."
453 :group 'org-keywords
454 :type 'string)
456 (defcustom org-scheduled-string "SCHEDULED:"
457 "String to mark scheduled TODO entries.
458 A schedule is this string, followed by a time stamp. Should be a word,
459 terminated by a colon. You can insert a schedule keyword and
460 a timestamp with \\[org-schedule].
461 Changes become only effective after restarting Emacs."
462 :group 'org-keywords
463 :type 'string)
465 (defcustom org-closed-string "CLOSED:"
466 "String used as the prefix for timestamps logging closing a TODO entry."
467 :group 'org-keywords
468 :type 'string)
470 (defcustom org-clock-string "CLOCK:"
471 "String used as prefix for timestamps clocking work hours on an item."
472 :group 'org-keywords
473 :type 'string)
475 (defcustom org-comment-string "COMMENT"
476 "Entries starting with this keyword will never be exported.
477 An entry can be toggled between COMMENT and normal with
478 \\[org-toggle-comment].
479 Changes become only effective after restarting Emacs."
480 :group 'org-keywords
481 :type 'string)
483 (defcustom org-quote-string "QUOTE"
484 "Entries starting with this keyword will be exported in fixed-width font.
485 Quoting applies only to the text in the entry following the headline, and does
486 not extend beyond the next headline, even if that is lower level.
487 An entry can be toggled between QUOTE and normal with
488 \\[org-toggle-fixed-width-section]."
489 :group 'org-keywords
490 :type 'string)
492 (defconst org-repeat-re
493 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
494 "Regular expression for specifying repeated events.
495 After a match, group 1 contains the repeat expression.")
497 (defgroup org-structure nil
498 "Options concerning the general structure of Org-mode files."
499 :tag "Org Structure"
500 :group 'org)
502 (defgroup org-reveal-location nil
503 "Options about how to make context of a location visible."
504 :tag "Org Reveal Location"
505 :group 'org-structure)
507 (defconst org-context-choice
508 '(choice
509 (const :tag "Always" t)
510 (const :tag "Never" nil)
511 (repeat :greedy t :tag "Individual contexts"
512 (cons
513 (choice :tag "Context"
514 (const agenda)
515 (const org-goto)
516 (const occur-tree)
517 (const tags-tree)
518 (const link-search)
519 (const mark-goto)
520 (const bookmark-jump)
521 (const isearch)
522 (const default))
523 (boolean))))
524 "Contexts for the reveal options.")
526 (defcustom org-show-hierarchy-above '((default . t))
527 "Non-nil means, show full hierarchy when revealing a location.
528 Org-mode often shows locations in an org-mode file which might have
529 been invisible before. When this is set, the hierarchy of headings
530 above the exposed location is shown.
531 Turning this off for example for sparse trees makes them very compact.
532 Instead of t, this can also be an alist specifying this option for different
533 contexts. Valid contexts are
534 agenda when exposing an entry from the agenda
535 org-goto when using the command `org-goto' on key C-c C-j
536 occur-tree when using the command `org-occur' on key C-c /
537 tags-tree when constructing a sparse tree based on tags matches
538 link-search when exposing search matches associated with a link
539 mark-goto when exposing the jump goal of a mark
540 bookmark-jump when exposing a bookmark location
541 isearch when exiting from an incremental search
542 default default for all contexts not set explicitly"
543 :group 'org-reveal-location
544 :type org-context-choice)
546 (defcustom org-show-following-heading '((default . nil))
547 "Non-nil means, show following heading when revealing a location.
548 Org-mode often shows locations in an org-mode file which might have
549 been invisible before. When this is set, the heading following the
550 match is shown.
551 Turning this off for example for sparse trees makes them very compact,
552 but makes it harder to edit the location of the match. In such a case,
553 use the command \\[org-reveal] to show more context.
554 Instead of t, this can also be an alist specifying this option for different
555 contexts. See `org-show-hierarchy-above' for valid contexts."
556 :group 'org-reveal-location
557 :type org-context-choice)
559 (defcustom org-show-siblings '((default . nil) (isearch t))
560 "Non-nil means, show all sibling heading when revealing a location.
561 Org-mode often shows locations in an org-mode file which might have
562 been invisible before. When this is set, the sibling of the current entry
563 heading are all made visible. If `org-show-hierarchy-above' is t,
564 the same happens on each level of the hierarchy above the current entry.
566 By default this is on for the isearch context, off for all other contexts.
567 Turning this off for example for sparse trees makes them very compact,
568 but makes it harder to edit the location of the match. In such a case,
569 use the command \\[org-reveal] to show more context.
570 Instead of t, this can also be an alist specifying this option for different
571 contexts. See `org-show-hierarchy-above' for valid contexts."
572 :group 'org-reveal-location
573 :type org-context-choice)
575 (defcustom org-show-entry-below '((default . nil))
576 "Non-nil means, show the entry below a headline when revealing a location.
577 Org-mode often shows locations in an org-mode file which might have
578 been invisible before. When this is set, the text below the headline that is
579 exposed is also shown.
581 By default this is off for all contexts.
582 Instead of t, this can also be an alist specifying this option for different
583 contexts. See `org-show-hierarchy-above' for valid contexts."
584 :group 'org-reveal-location
585 :type org-context-choice)
587 (defcustom org-indirect-buffer-display 'other-window
588 "How should indirect tree buffers be displayed?
589 This applies to indirect buffers created with the commands
590 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
591 Valid values are:
592 current-window Display in the current window
593 other-window Just display in another window.
594 dedicated-frame Create one new frame, and re-use it each time.
595 new-frame Make a new frame each time. Note that in this case
596 previously-made indirect buffers are kept, and you need to
597 kill these buffers yourself."
598 :group 'org-structure
599 :group 'org-agenda-windows
600 :type '(choice
601 (const :tag "In current window" current-window)
602 (const :tag "In current frame, other window" other-window)
603 (const :tag "Each time a new frame" new-frame)
604 (const :tag "One dedicated frame" dedicated-frame)))
606 (defcustom org-use-speed-commands nil
607 "Non-nil means, activate single letter commands at beginning of a headline.
608 This may also be a function to test for appropriate locations where speed
609 commands should be active."
610 :group 'org-structure
611 :type '(choice
612 (const :tag "Never" nil)
613 (const :tag "At beginning of headline stars" t)
614 (function)))
616 (defcustom org-speed-commands-user nil
617 "Alist of additional speed commands.
618 This list will be checked before `org-speed-commands-default'
619 when the variable `org-use-speed-commands' is non-nil
620 and when the cursor is at the beginning of a headline.
621 The car if each entry is a string with a single letter, which must
622 be assigned to `self-insert-command' in the global map.
623 The cdr is either a command to be called interactively, a function
624 to be called, or a form to be evaluated.
625 An entry that is just a list with a single string will be interpreted
626 as a descriptive headline that will be added when listing the speed
627 copmmands in the Help buffer using the `?' speed command."
628 :group 'org-structure
629 :type '(repeat :value ("k" . ignore)
630 (choice :value ("k" . ignore)
631 (list :tag "Descriptive Headline" (string :tag "Headline"))
632 (cons :tag "Letter and Command"
633 (string :tag "Command letter")
634 (choice
635 (function)
636 (sexp))))))
638 (defgroup org-cycle nil
639 "Options concerning visibility cycling in Org-mode."
640 :tag "Org Cycle"
641 :group 'org-structure)
643 (defcustom org-cycle-skip-children-state-if-no-children t
644 "Non-nil means, skip CHILDREN state in entries that don't have any."
645 :group 'org-cycle
646 :type 'boolean)
648 (defcustom org-cycle-max-level nil
649 "Maximum level which should still be subject to visibility cycling.
650 Levels higher than this will, for cycling, be treated as text, not a headline.
651 When `org-odd-levels-only' is set, a value of N in this variable actually
652 means 2N-1 stars as the limiting headline.
653 When nil, cycle all levels.
654 Note that the limiting level of cycling is also influenced by
655 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
656 `org-inlinetask-min-level' is, cycling will be limited to levels one less
657 than its value."
658 :group 'org-cycle
659 :type '(choice
660 (const :tag "No limit" nil)
661 (integer :tag "Maximum level")))
663 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
664 "Names of drawers. Drawers are not opened by cycling on the headline above.
665 Drawers only open with a TAB on the drawer line itself. A drawer looks like
666 this:
667 :DRAWERNAME:
668 .....
669 :END:
670 The drawer \"PROPERTIES\" is special for capturing properties through
671 the property API.
673 Drawers can be defined on the per-file basis with a line like:
675 #+DRAWERS: HIDDEN STATE PROPERTIES"
676 :group 'org-structure
677 :group 'org-cycle
678 :type '(repeat (string :tag "Drawer Name")))
680 (defcustom org-hide-block-startup nil
681 "Non-nil means, , entering Org-mode will fold all blocks.
682 This can also be set in on a per-file basis with
684 #+STARTUP: hideblocks
685 #+STARTUP: showblocks"
686 :group 'org-startup
687 :group 'org-cycle
688 :type 'boolean)
690 (defcustom org-cycle-global-at-bob nil
691 "Cycle globally if cursor is at beginning of buffer and not at a headline.
692 This makes it possible to do global cycling without having to use S-TAB or
693 C-u TAB. For this special case to work, the first line of the buffer
694 must not be a headline - it may be empty or some other text. When used in
695 this way, `org-cycle-hook' is disables temporarily, to make sure the
696 cursor stays at the beginning of the buffer.
697 When this option is nil, don't do anything special at the beginning
698 of the buffer."
699 :group 'org-cycle
700 :type 'boolean)
702 (defcustom org-cycle-level-after-item/entry-creation t
703 "Non-nil means, cycle entry level or item indentation in new empty entries.
705 When the cursor is at the end of an empty headline, i.e with only stars
706 and maybe a TODO keyword, TAB will then switch the entry to become a child,
707 and then all possible anchestor states, before returning to the original state.
708 This makes data entry extremely fast: M-RET to create a new headline,
709 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
711 When the cursor is at the end of an empty plain list item, one TAB will
712 make it a subitem, two or more tabs will back up to make this an item
713 higher up in the item hierarchy."
714 :group 'org-cycle
715 :type 'boolean)
717 (defcustom org-cycle-emulate-tab t
718 "Where should `org-cycle' emulate TAB.
719 nil Never
720 white Only in completely white lines
721 whitestart Only at the beginning of lines, before the first non-white char
722 t Everywhere except in headlines
723 exc-hl-bol Everywhere except at the start of a headline
724 If TAB is used in a place where it does not emulate TAB, the current subtree
725 visibility is cycled."
726 :group 'org-cycle
727 :type '(choice (const :tag "Never" nil)
728 (const :tag "Only in completely white lines" white)
729 (const :tag "Before first char in a line" whitestart)
730 (const :tag "Everywhere except in headlines" t)
731 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
734 (defcustom org-cycle-separator-lines 2
735 "Number of empty lines needed to keep an empty line between collapsed trees.
736 If you leave an empty line between the end of a subtree and the following
737 headline, this empty line is hidden when the subtree is folded.
738 Org-mode will leave (exactly) one empty line visible if the number of
739 empty lines is equal or larger to the number given in this variable.
740 So the default 2 means, at least 2 empty lines after the end of a subtree
741 are needed to produce free space between a collapsed subtree and the
742 following headline.
744 If the number is negative, and the number of empty lines is at least -N,
745 all empty lines are shown.
747 Special case: when 0, never leave empty lines in collapsed view."
748 :group 'org-cycle
749 :type 'integer)
750 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
752 (defcustom org-pre-cycle-hook nil
753 "Hook that is run before visibility cycling is happening.
754 The function(s) in this hook must accept a single argument which indicates
755 the new state that will be set right after running this hook. The
756 argument is a symbol. Before a global state change, it can have the values
757 `overview', `content', or `all'. Before a local state change, it can have
758 the values `folded', `children', or `subtree'."
759 :group 'org-cycle
760 :type 'hook)
762 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
763 org-cycle-hide-drawers
764 org-cycle-show-empty-lines
765 org-optimize-window-after-visibility-change)
766 "Hook that is run after `org-cycle' has changed the buffer visibility.
767 The function(s) in this hook must accept a single argument which indicates
768 the new state that was set by the most recent `org-cycle' command. The
769 argument is a symbol. After a global state change, it can have the values
770 `overview', `content', or `all'. After a local state change, it can have
771 the values `folded', `children', or `subtree'."
772 :group 'org-cycle
773 :type 'hook)
775 (defgroup org-edit-structure nil
776 "Options concerning structure editing in Org-mode."
777 :tag "Org Edit Structure"
778 :group 'org-structure)
780 (defcustom org-odd-levels-only nil
781 "Non-nil means, skip even levels and only use odd levels for the outline.
782 This has the effect that two stars are being added/taken away in
783 promotion/demotion commands. It also influences how levels are
784 handled by the exporters.
785 Changing it requires restart of `font-lock-mode' to become effective
786 for fontification also in regions already fontified.
787 You may also set this on a per-file basis by adding one of the following
788 lines to the buffer:
790 #+STARTUP: odd
791 #+STARTUP: oddeven"
792 :group 'org-edit-structure
793 :group 'org-font-lock
794 :type 'boolean)
796 (defcustom org-adapt-indentation t
797 "Non-nil means, adapt indentation to outline node level.
799 When this variable is set, Org assumes that you write outlines by
800 indenting text in each node to align with the headline (after the stars).
801 The following issues are influenced by this variable:
803 - When this is set and the *entire* text in an entry is indented, the
804 indentation is increased by one space in a demotion command, and
805 decreased by one in a promotion command. If any line in the entry
806 body starts with text at column 0, indentation is not changed at all.
808 - Property drawers and planning information is inserted indented when
809 this variable s set. When nil, they will not be indented.
811 - TAB indents a line relative to context. The lines below a headline
812 will be indented when this variable is set.
814 Note that this is all about true indentation, by adding and removing
815 space characters. See also `org-indent.el' which does level-dependent
816 indentation in a virtual way, i.e. at display time in Emacs."
817 :group 'org-edit-structure
818 :type 'boolean)
820 (defcustom org-special-ctrl-a/e nil
821 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
823 When t, `C-a' will bring back the cursor to the beginning of the
824 headline text, i.e. after the stars and after a possible TODO keyword.
825 In an item, this will be the position after the bullet.
826 When the cursor is already at that position, another `C-a' will bring
827 it to the beginning of the line.
829 `C-e' will jump to the end of the headline, ignoring the presence of tags
830 in the headline. A second `C-e' will then jump to the true end of the
831 line, after any tags. This also means that, when this variable is
832 non-nil, `C-e' also will never jump beyond the end of the heading of a
833 folded section, i.e. not after the ellipses.
835 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
836 going to the true line boundary first. Only a directly following, identical
837 keypress will bring the cursor to the special positions.
839 This may also be a cons cell where the behavior for `C-a' and `C-e' is
840 set separately."
841 :group 'org-edit-structure
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on: after stars/bullet and before tags first" t)
845 (const :tag "reversed: true line boundary first" reversed)
846 (cons :tag "Set C-a and C-e separately"
847 (choice :tag "Special C-a"
848 (const :tag "off" nil)
849 (const :tag "on: after stars/bullet first" t)
850 (const :tag "reversed: before stars/bullet first" reversed))
851 (choice :tag "Special C-e"
852 (const :tag "off" nil)
853 (const :tag "on: before tags first" t)
854 (const :tag "reversed: after tags first" reversed)))))
855 (if (fboundp 'defvaralias)
856 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
858 (defcustom org-special-ctrl-k nil
859 "Non-nil means `C-k' will behave specially in headlines.
860 When nil, `C-k' will call the default `kill-line' command.
861 When t, the following will happen while the cursor is in the headline:
863 - When the cursor is at the beginning of a headline, kill the entire
864 line and possible the folded subtree below the line.
865 - When in the middle of the headline text, kill the headline up to the tags.
866 - When after the headline text, kill the tags."
867 :group 'org-edit-structure
868 :type 'boolean)
870 (defcustom org-yank-folded-subtrees t
871 "Non-nil means, when yanking subtrees, fold them.
872 If the kill is a single subtree, or a sequence of subtrees, i.e. if
873 it starts with a heading and all other headings in it are either children
874 or siblings, then fold all the subtrees. However, do this only if no
875 text after the yank would be swallowed into a folded tree by this action."
876 :group 'org-edit-structure
877 :type 'boolean)
879 (defcustom org-yank-adjusted-subtrees nil
880 "Non-nil means, when yanking subtrees, adjust the level.
881 With this setting, `org-paste-subtree' is used to insert the subtree, see
882 this function for details."
883 :group 'org-edit-structure
884 :type 'boolean)
886 (defcustom org-M-RET-may-split-line '((default . t))
887 "Non-nil means, M-RET will split the line at the cursor position.
888 When nil, it will go to the end of the line before making a
889 new line.
890 You may also set this option in a different way for different
891 contexts. Valid contexts are:
893 headline when creating a new headline
894 item when creating a new item
895 table in a table field
896 default the value to be used for all contexts not explicitly
897 customized"
898 :group 'org-structure
899 :group 'org-table
900 :type '(choice
901 (const :tag "Always" t)
902 (const :tag "Never" nil)
903 (repeat :greedy t :tag "Individual contexts"
904 (cons
905 (choice :tag "Context"
906 (const headline)
907 (const item)
908 (const table)
909 (const default))
910 (boolean)))))
913 (defcustom org-insert-heading-respect-content nil
914 "Non-nil means, insert new headings after the current subtree.
915 When nil, the new heading is created directly after the current line.
916 The commands \\[org-insert-heading-respect-content] and
917 \\[org-insert-todo-heading-respect-content] turn this variable on
918 for the duration of the command."
919 :group 'org-structure
920 :type 'boolean)
922 (defcustom org-blank-before-new-entry '((heading . auto)
923 (plain-list-item . auto))
924 "Should `org-insert-heading' leave a blank line before new heading/item?
925 The value is an alist, with `heading' and `plain-list-item' as car,
926 and a boolean flag as cdr. For plain lists, if the variable
927 `org-empty-line-terminates-plain-lists' is set, the setting here
928 is ignored and no empty line is inserted, to keep the list in tact."
929 :group 'org-edit-structure
930 :type '(list
931 (cons (const heading)
932 (choice (const :tag "Never" nil)
933 (const :tag "Always" t)
934 (const :tag "Auto" auto)))
935 (cons (const plain-list-item)
936 (choice (const :tag "Never" nil)
937 (const :tag "Always" t)
938 (const :tag "Auto" auto)))))
940 (defcustom org-insert-heading-hook nil
941 "Hook being run after inserting a new heading."
942 :group 'org-edit-structure
943 :type 'hook)
945 (defcustom org-enable-fixed-width-editor t
946 "Non-nil means, lines starting with \":\" are treated as fixed-width.
947 This currently only means, they are never auto-wrapped.
948 When nil, such lines will be treated like ordinary lines.
949 See also the QUOTE keyword."
950 :group 'org-edit-structure
951 :type 'boolean)
954 (defcustom org-goto-auto-isearch t
955 "Non-nil means, typing characters in org-goto starts incremental search."
956 :group 'org-edit-structure
957 :type 'boolean)
959 (defgroup org-sparse-trees nil
960 "Options concerning sparse trees in Org-mode."
961 :tag "Org Sparse Trees"
962 :group 'org-structure)
964 (defcustom org-highlight-sparse-tree-matches t
965 "Non-nil means, highlight all matches that define a sparse tree.
966 The highlights will automatically disappear the next time the buffer is
967 changed by an edit command."
968 :group 'org-sparse-trees
969 :type 'boolean)
971 (defcustom org-remove-highlights-with-change t
972 "Non-nil means, any change to the buffer will remove temporary highlights.
973 Such highlights are created by `org-occur' and `org-clock-display'.
974 When nil, `C-c C-c needs to be used to get rid of the highlights.
975 The highlights created by `org-preview-latex-fragment' always need
976 `C-c C-c' to be removed."
977 :group 'org-sparse-trees
978 :group 'org-time
979 :type 'boolean)
982 (defcustom org-occur-hook '(org-first-headline-recenter)
983 "Hook that is run after `org-occur' has constructed a sparse tree.
984 This can be used to recenter the window to show as much of the structure
985 as possible."
986 :group 'org-sparse-trees
987 :type 'hook)
989 (defgroup org-imenu-and-speedbar nil
990 "Options concerning imenu and speedbar in Org-mode."
991 :tag "Org Imenu and Speedbar"
992 :group 'org-structure)
994 (defcustom org-imenu-depth 2
995 "The maximum level for Imenu access to Org-mode headlines.
996 This also applied for speedbar access."
997 :group 'org-imenu-and-speedbar
998 :type 'integer)
1000 (defgroup org-table nil
1001 "Options concerning tables in Org-mode."
1002 :tag "Org Table"
1003 :group 'org)
1005 (defcustom org-enable-table-editor 'optimized
1006 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1007 When nil, such lines will be treated like ordinary lines.
1009 When equal to the symbol `optimized', the table editor will be optimized to
1010 do the following:
1011 - Automatic overwrite mode in front of whitespace in table fields.
1012 This makes the structure of the table stay in tact as long as the edited
1013 field does not exceed the column width.
1014 - Minimize the number of realigns. Normally, the table is aligned each time
1015 TAB or RET are pressed to move to another field. With optimization this
1016 happens only if changes to a field might have changed the column width.
1017 Optimization requires replacing the functions `self-insert-command',
1018 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1019 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1020 very good at guessing when a re-align will be necessary, but you can always
1021 force one with \\[org-ctrl-c-ctrl-c].
1023 If you would like to use the optimized version in Org-mode, but the
1024 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1026 This variable can be used to turn on and off the table editor during a session,
1027 but in order to toggle optimization, a restart is required.
1029 See also the variable `org-table-auto-blank-field'."
1030 :group 'org-table
1031 :type '(choice
1032 (const :tag "off" nil)
1033 (const :tag "on" t)
1034 (const :tag "on, optimized" optimized)))
1036 (defcustom org-self-insert-cluster-for-undo t
1037 "Non-nil means cluster self-insert commands for undo when possible.
1038 If this is set, then, like in the Emacs command loop, 20 consecutive
1039 characters will be undone together.
1040 This is configurable, because there is some impact on typing performance."
1041 :group 'org-table
1042 :type 'boolean)
1044 (defcustom org-table-tab-recognizes-table.el t
1045 "Non-nil means, TAB will automatically notice a table.el table.
1046 When it sees such a table, it moves point into it and - if necessary -
1047 calls `table-recognize-table'."
1048 :group 'org-table-editing
1049 :type 'boolean)
1051 (defgroup org-link nil
1052 "Options concerning links in Org-mode."
1053 :tag "Org Link"
1054 :group 'org)
1056 (defvar org-link-abbrev-alist-local nil
1057 "Buffer-local version of `org-link-abbrev-alist', which see.
1058 The value of this is taken from the #+LINK lines.")
1059 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1061 (defcustom org-link-abbrev-alist nil
1062 "Alist of link abbreviations.
1063 The car of each element is a string, to be replaced at the start of a link.
1064 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1065 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1067 [[linkkey:tag][description]]
1069 The 'linkkey' must be a word word, starting with a letter, followed
1070 by letters, numbers, '-' or '_'.
1072 If REPLACE is a string, the tag will simply be appended to create the link.
1073 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1074 the placeholder \"%h\" will cause a url-encoded version of the tag to
1075 be inserted at that point (see the function `url-hexify-string').
1077 REPLACE may also be a function that will be called with the tag as the
1078 only argument to create the link, which should be returned as a string.
1080 See the manual for examples."
1081 :group 'org-link
1082 :type '(repeat
1083 (cons
1084 (string :tag "Protocol")
1085 (choice
1086 (string :tag "Format")
1087 (function)))))
1089 (defcustom org-descriptive-links t
1090 "Non-nil means, hide link part and only show description of bracket links.
1091 Bracket links are like [[link][description]]. This variable sets the initial
1092 state in new org-mode buffers. The setting can then be toggled on a
1093 per-buffer basis from the Org->Hyperlinks menu."
1094 :group 'org-link
1095 :type 'boolean)
1097 (defcustom org-link-file-path-type 'adaptive
1098 "How the path name in file links should be stored.
1099 Valid values are:
1101 relative Relative to the current directory, i.e. the directory of the file
1102 into which the link is being inserted.
1103 absolute Absolute path, if possible with ~ for home directory.
1104 noabbrev Absolute path, no abbreviation of home directory.
1105 adaptive Use relative path for files in the current directory and sub-
1106 directories of it. For other files, use an absolute path."
1107 :group 'org-link
1108 :type '(choice
1109 (const relative)
1110 (const absolute)
1111 (const noabbrev)
1112 (const adaptive)))
1114 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1115 "Types of links that should be activated in Org-mode files.
1116 This is a list of symbols, each leading to the activation of a certain link
1117 type. In principle, it does not hurt to turn on most link types - there may
1118 be a small gain when turning off unused link types. The types are:
1120 bracket The recommended [[link][description]] or [[link]] links with hiding.
1121 angular Links in angular brackets that may contain whitespace like
1122 <bbdb:Carsten Dominik>.
1123 plain Plain links in normal text, no whitespace, like http://google.com.
1124 radio Text that is matched by a radio target, see manual for details.
1125 tag Tag settings in a headline (link to tag search).
1126 date Time stamps (link to calendar).
1127 footnote Footnote labels.
1129 Changing this variable requires a restart of Emacs to become effective."
1130 :group 'org-link
1131 :type '(set :greedy t
1132 (const :tag "Double bracket links (new style)" bracket)
1133 (const :tag "Angular bracket links (old style)" angular)
1134 (const :tag "Plain text links" plain)
1135 (const :tag "Radio target matches" radio)
1136 (const :tag "Tags" tag)
1137 (const :tag "Timestamps" date)
1138 (const :tag "Footnotes" footnote)))
1140 (defcustom org-make-link-description-function nil
1141 "Function to use to generate link descriptions from links. If
1142 nil the link location will be used. This function must take two
1143 parameters; the first is the link and the second the description
1144 org-insert-link has generated, and should return the description
1145 to use."
1146 :group 'org-link
1147 :type 'function)
1149 (defgroup org-link-store nil
1150 "Options concerning storing links in Org-mode."
1151 :tag "Org Store Link"
1152 :group 'org-link)
1154 (defcustom org-email-link-description-format "Email %c: %.30s"
1155 "Format of the description part of a link to an email or usenet message.
1156 The following %-escapes will be replaced by corresponding information:
1158 %F full \"From\" field
1159 %f name, taken from \"From\" field, address if no name
1160 %T full \"To\" field
1161 %t first name in \"To\" field, address if no name
1162 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1163 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1164 %s subject
1165 %m message-id.
1167 You may use normal field width specification between the % and the letter.
1168 This is for example useful to limit the length of the subject.
1170 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1171 :group 'org-link-store
1172 :type 'string)
1174 (defcustom org-from-is-user-regexp
1175 (let (r1 r2)
1176 (when (and user-mail-address (not (string= user-mail-address "")))
1177 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1178 (when (and user-full-name (not (string= user-full-name "")))
1179 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1180 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1181 "Regexp matched against the \"From:\" header of an email or usenet message.
1182 It should match if the message is from the user him/herself."
1183 :group 'org-link-store
1184 :type 'regexp)
1186 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1187 "Non-nil means, storing a link to an Org file will use entry IDs.
1189 Note that before this variable is even considered, org-id must be loaded,
1190 so please customize `org-modules' and turn it on.
1192 The variable can have the following values:
1194 t Create an ID if needed to make a link to the current entry.
1196 create-if-interactive
1197 If `org-store-link' is called directly (interactively, as a user
1198 command), do create an ID to support the link. But when doing the
1199 job for remember, only use the ID if it already exists. The
1200 purpose of this setting is to avoid proliferation of unwanted
1201 IDs, just because you happen to be in an Org file when you
1202 call `org-remember' that automatically and preemptively
1203 creates a link. If you do want to get an ID link in a remember
1204 template to an entry not having an ID, create it first by
1205 explicitly creating a link to it, using `C-c C-l' first.
1207 create-if-interactive-and-no-custom-id
1208 Like create-if-interactive, but do not create an ID if there is
1209 a CUSTOM_ID property defined in the entry. This is the default.
1211 use-existing
1212 Use existing ID, do not create one.
1214 nil Never use an ID to make a link, instead link using a text search for
1215 the headline text."
1216 :group 'org-link-store
1217 :type '(choice
1218 (const :tag "Create ID to make link" t)
1219 (const :tag "Create if storing link interactively"
1220 create-if-interactive)
1221 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1222 create-if-interactive-and-no-custom-id)
1223 (const :tag "Only use existing" use-existing)
1224 (const :tag "Do not use ID to create link" nil)))
1226 (defcustom org-context-in-file-links t
1227 "Non-nil means, file links from `org-store-link' contain context.
1228 A search string will be added to the file name with :: as separator and
1229 used to find the context when the link is activated by the command
1230 `org-open-at-point'.
1231 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1232 negates this setting for the duration of the command."
1233 :group 'org-link-store
1234 :type 'boolean)
1236 (defcustom org-keep-stored-link-after-insertion nil
1237 "Non-nil means, keep link in list for entire session.
1239 The command `org-store-link' adds a link pointing to the current
1240 location to an internal list. These links accumulate during a session.
1241 The command `org-insert-link' can be used to insert links into any
1242 Org-mode file (offering completion for all stored links). When this
1243 option is nil, every link which has been inserted once using \\[org-insert-link]
1244 will be removed from the list, to make completing the unused links
1245 more efficient."
1246 :group 'org-link-store
1247 :type 'boolean)
1249 (defgroup org-link-follow nil
1250 "Options concerning following links in Org-mode."
1251 :tag "Org Follow Link"
1252 :group 'org-link)
1254 (defcustom org-link-translation-function nil
1255 "Function to translate links with different syntax to Org syntax.
1256 This can be used to translate links created for example by the Planner
1257 or emacs-wiki packages to Org syntax.
1258 The function must accept two parameters, a TYPE containing the link
1259 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1260 which is everything after the link protocol. It should return a cons
1261 with possibly modified values of type and path.
1262 Org contains a function for this, so if you set this variable to
1263 `org-translate-link-from-planner', you should be able follow many
1264 links created by planner."
1265 :group 'org-link-follow
1266 :type 'function)
1268 (defcustom org-follow-link-hook nil
1269 "Hook that is run after a link has been followed."
1270 :group 'org-link-follow
1271 :type 'hook)
1273 (defcustom org-tab-follows-link nil
1274 "Non-nil means, on links TAB will follow the link.
1275 Needs to be set before org.el is loaded.
1276 This really should not be used, it does not make sense, and the
1277 implementation is bad."
1278 :group 'org-link-follow
1279 :type 'boolean)
1281 (defcustom org-return-follows-link nil
1282 "Non-nil means, on links RET will follow the link.
1283 Needs to be set before org.el is loaded."
1284 :group 'org-link-follow
1285 :type 'boolean)
1287 (defcustom org-mouse-1-follows-link
1288 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1289 "Non-nil means, mouse-1 on a link will follow the link.
1290 A longer mouse click will still set point. Does not work on XEmacs.
1291 Needs to be set before org.el is loaded."
1292 :group 'org-link-follow
1293 :type 'boolean)
1295 (defcustom org-mark-ring-length 4
1296 "Number of different positions to be recorded in the ring
1297 Changing this requires a restart of Emacs to work correctly."
1298 :group 'org-link-follow
1299 :type 'integer)
1301 (defcustom org-link-frame-setup
1302 '((vm . vm-visit-folder-other-frame)
1303 (gnus . gnus-other-frame)
1304 (file . find-file-other-window))
1305 "Setup the frame configuration for following links.
1306 When following a link with Emacs, it may often be useful to display
1307 this link in another window or frame. This variable can be used to
1308 set this up for the different types of links.
1309 For VM, use any of
1310 `vm-visit-folder'
1311 `vm-visit-folder-other-frame'
1312 For Gnus, use any of
1313 `gnus'
1314 `gnus-other-frame'
1315 `org-gnus-no-new-news'
1316 For FILE, use any of
1317 `find-file'
1318 `find-file-other-window'
1319 `find-file-other-frame'
1320 For the calendar, use the variable `calendar-setup'.
1321 For BBDB, it is currently only possible to display the matches in
1322 another window."
1323 :group 'org-link-follow
1324 :type '(list
1325 (cons (const vm)
1326 (choice
1327 (const vm-visit-folder)
1328 (const vm-visit-folder-other-window)
1329 (const vm-visit-folder-other-frame)))
1330 (cons (const gnus)
1331 (choice
1332 (const gnus)
1333 (const gnus-other-frame)
1334 (const org-gnus-no-new-news)))
1335 (cons (const file)
1336 (choice
1337 (const find-file)
1338 (const find-file-other-window)
1339 (const find-file-other-frame)))))
1341 (defcustom org-display-internal-link-with-indirect-buffer nil
1342 "Non-nil means, use indirect buffer to display infile links.
1343 Activating internal links (from one location in a file to another location
1344 in the same file) normally just jumps to the location. When the link is
1345 activated with a C-u prefix (or with mouse-3), the link is displayed in
1346 another window. When this option is set, the other window actually displays
1347 an indirect buffer clone of the current buffer, to avoid any visibility
1348 changes to the current buffer."
1349 :group 'org-link-follow
1350 :type 'boolean)
1352 (defcustom org-open-non-existing-files nil
1353 "Non-nil means, `org-open-file' will open non-existing files.
1354 When nil, an error will be generated.
1355 This variable applies only to external applications because they
1356 might choke on non-existing files. If the link is to a file that
1357 will be opened in Emacs, the variable is ignored."
1358 :group 'org-link-follow
1359 :type 'boolean)
1361 (defcustom org-open-directory-means-index-dot-org nil
1362 "Non-nil means, a link to a directory really means to index.org.
1363 When nil, following a directory link will run dired or open a finder/explorer
1364 window on that directory."
1365 :group 'org-link-follow
1366 :type 'boolean)
1368 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1369 "Function and arguments to call for following mailto links.
1370 This is a list with the first element being a lisp function, and the
1371 remaining elements being arguments to the function. In string arguments,
1372 %a will be replaced by the address, and %s will be replaced by the subject
1373 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1374 :group 'org-link-follow
1375 :type '(choice
1376 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1377 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1378 (const :tag "message-mail" (message-mail "%a" "%s"))
1379 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1381 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1382 "Non-nil means, ask for confirmation before executing shell links.
1383 Shell links can be dangerous: just think about a link
1385 [[shell:rm -rf ~/*][Google Search]]
1387 This link would show up in your Org-mode document as \"Google Search\",
1388 but really it would remove your entire home directory.
1389 Therefore we advise against setting this variable to nil.
1390 Just change it to `y-or-n-p' if you want to confirm with a
1391 single keystroke rather than having to type \"yes\"."
1392 :group 'org-link-follow
1393 :type '(choice
1394 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1395 (const :tag "with y-or-n (faster)" y-or-n-p)
1396 (const :tag "no confirmation (dangerous)" nil)))
1398 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1399 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1400 Elisp links can be dangerous: just think about a link
1402 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1404 This link would show up in your Org-mode document as \"Google Search\",
1405 but really it would remove your entire home directory.
1406 Therefore we advise against setting this variable to nil.
1407 Just change it to `y-or-n-p' if you want to confirm with a
1408 single keystroke rather than having to type \"yes\"."
1409 :group 'org-link-follow
1410 :type '(choice
1411 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1412 (const :tag "with y-or-n (faster)" y-or-n-p)
1413 (const :tag "no confirmation (dangerous)" nil)))
1415 (defconst org-file-apps-defaults-gnu
1416 '((remote . emacs)
1417 (system . mailcap)
1418 (t . mailcap))
1419 "Default file applications on a UNIX or GNU/Linux system.
1420 See `org-file-apps'.")
1422 (defconst org-file-apps-defaults-macosx
1423 '((remote . emacs)
1424 (t . "open %s")
1425 (system . "open %s")
1426 ("ps.gz" . "gv %s")
1427 ("eps.gz" . "gv %s")
1428 ("dvi" . "xdvi %s")
1429 ("fig" . "xfig %s"))
1430 "Default file applications on a MacOS X system.
1431 The system \"open\" is known as a default, but we use X11 applications
1432 for some files for which the OS does not have a good default.
1433 See `org-file-apps'.")
1435 (defconst org-file-apps-defaults-windowsnt
1436 (list
1437 '(remote . emacs)
1438 (cons t
1439 (list (if (featurep 'xemacs)
1440 'mswindows-shell-execute
1441 'w32-shell-execute)
1442 "open" 'file))
1443 (cons 'system
1444 (list (if (featurep 'xemacs)
1445 'mswindows-shell-execute
1446 'w32-shell-execute)
1447 "open" 'file)))
1448 "Default file applications on a Windows NT system.
1449 The system \"open\" is used for most files.
1450 See `org-file-apps'.")
1452 (defcustom org-file-apps
1454 (auto-mode . emacs)
1455 ("\\.mm\\'" . default)
1456 ("\\.x?html?\\'" . default)
1457 ("\\.pdf\\'" . default)
1459 "External applications for opening `file:path' items in a document.
1460 Org-mode uses system defaults for different file types, but
1461 you can use this variable to set the application for a given file
1462 extension. The entries in this list are cons cells where the car identifies
1463 files and the cdr the corresponding command. Possible values for the
1464 file identifier are
1465 \"regex\" Regular expression matched against the file name. For backward
1466 compatibility, this can also be a string with only alphanumeric
1467 characters, which is then interpreted as an extension.
1468 `directory' Matches a directory
1469 `remote' Matches a remote file, accessible through tramp or efs.
1470 Remote files most likely should be visited through Emacs
1471 because external applications cannot handle such paths.
1472 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1473 so all files Emacs knows how to handle. Using this with
1474 command `emacs' will open most files in Emacs. Beware that this
1475 will also open html files inside Emacs, unless you add
1476 (\"html\" . default) to the list as well.
1477 t Default for files not matched by any of the other options.
1478 `system' The system command to open files, like `open' on Windows
1479 and Mac OS X, and mailcap under GNU/Linux. This is the command
1480 that will be selected if you call `C-c C-o' with a double
1481 `C-u C-u' prefix.
1483 Possible values for the command are:
1484 `emacs' The file will be visited by the current Emacs process.
1485 `default' Use the default application for this file type, which is the
1486 association for t in the list, most likely in the system-specific
1487 part.
1488 This can be used to overrule an unwanted setting in the
1489 system-specific variable.
1490 `system' Use the system command for opening files, like \"open\".
1491 This command is specified by the entry whose car is `system'.
1492 Most likely, the system-specific version of this variable
1493 does define this command, but you can overrule/replace it
1494 here.
1495 string A command to be executed by a shell; %s will be replaced
1496 by the path to the file.
1497 sexp A Lisp form which will be evaluated. The file path will
1498 be available in the Lisp variable `file'.
1499 For more examples, see the system specific constants
1500 `org-file-apps-defaults-macosx'
1501 `org-file-apps-defaults-windowsnt'
1502 `org-file-apps-defaults-gnu'."
1503 :group 'org-link-follow
1504 :type '(repeat
1505 (cons (choice :value ""
1506 (string :tag "Extension")
1507 (const :tag "System command to open files" system)
1508 (const :tag "Default for unrecognized files" t)
1509 (const :tag "Remote file" remote)
1510 (const :tag "Links to a directory" directory)
1511 (const :tag "Any files that have Emacs modes"
1512 auto-mode))
1513 (choice :value ""
1514 (const :tag "Visit with Emacs" emacs)
1515 (const :tag "Use default" default)
1516 (const :tag "Use the system command" system)
1517 (string :tag "Command")
1518 (sexp :tag "Lisp form")))))
1520 (defgroup org-refile nil
1521 "Options concerning refiling entries in Org-mode."
1522 :tag "Org Refile"
1523 :group 'org)
1525 (defcustom org-directory "~/org"
1526 "Directory with org files.
1527 This is just a default location to look for Org files. There is no need
1528 at all to put your files into this directory. It is only used in the
1529 following situations:
1531 1. When a remember template specifies a target file that is not an
1532 absolute path. The path will then be interpreted relative to
1533 `org-directory'
1534 2. When a remember note is filed away in an interactive way (when exiting the
1535 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1536 with `org-directory' as the default path."
1537 :group 'org-refile
1538 :group 'org-remember
1539 :type 'directory)
1541 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1542 "Default target for storing notes.
1543 Used by the hooks for remember.el. This can be a string, or nil to mean
1544 the value of `remember-data-file'.
1545 You can set this on a per-template basis with the variable
1546 `org-remember-templates'."
1547 :group 'org-refile
1548 :group 'org-remember
1549 :type '(choice
1550 (const :tag "Default from remember-data-file" nil)
1551 file))
1553 (defcustom org-goto-interface 'outline
1554 "The default interface to be used for `org-goto'.
1555 Allowed values are:
1556 outline The interface shows an outline of the relevant file
1557 and the correct heading is found by moving through
1558 the outline or by searching with incremental search.
1559 outline-path-completion Headlines in the current buffer are offered via
1560 completion. This is the interface also used by
1561 the refile command."
1562 :group 'org-refile
1563 :type '(choice
1564 (const :tag "Outline" outline)
1565 (const :tag "Outline-path-completion" outline-path-completion)))
1567 (defcustom org-goto-max-level 5
1568 "Maximum level to be considered when running org-goto with refile interface."
1569 :group 'org-refile
1570 :type 'integer)
1572 (defcustom org-reverse-note-order nil
1573 "Non-nil means, store new notes at the beginning of a file or entry.
1574 When nil, new notes will be filed to the end of a file or entry.
1575 This can also be a list with cons cells of regular expressions that
1576 are matched against file names, and values."
1577 :group 'org-remember
1578 :group 'org-refile
1579 :type '(choice
1580 (const :tag "Reverse always" t)
1581 (const :tag "Reverse never" nil)
1582 (repeat :tag "By file name regexp"
1583 (cons regexp boolean))))
1585 (defcustom org-refile-targets nil
1586 "Targets for refiling entries with \\[org-refile].
1587 This is list of cons cells. Each cell contains:
1588 - a specification of the files to be considered, either a list of files,
1589 or a symbol whose function or variable value will be used to retrieve
1590 a file name or a list of file names. If you use `org-agenda-files' for
1591 that, all agenda files will be scanned for targets. Nil means, consider
1592 headings in the current buffer.
1593 - A specification of how to find candidate refile targets. This may be
1594 any of:
1595 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1596 This tag has to be present in all target headlines, inheritance will
1597 not be considered.
1598 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1599 todo keyword.
1600 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1601 headlines that are refiling targets.
1602 - a cons cell (:level . N). Any headline of level N is considered a target.
1603 Note that, when `org-odd-levels-only' is set, level corresponds to
1604 order in hierarchy, not to the number of stars.
1605 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1606 Note that, when `org-odd-levels-only' is set, level corresponds to
1607 order in hierarchy, not to the number of stars.
1609 You can set the variable `org-refile-target-verify-function' to a function
1610 to verify each headline found by the simple critery above.
1612 When this variable is nil, all top-level headlines in the current buffer
1613 are used, equivalent to the value `((nil . (:level . 1))'."
1614 :group 'org-refile
1615 :type '(repeat
1616 (cons
1617 (choice :value org-agenda-files
1618 (const :tag "All agenda files" org-agenda-files)
1619 (const :tag "Current buffer" nil)
1620 (function) (variable) (file))
1621 (choice :tag "Identify target headline by"
1622 (cons :tag "Specific tag" (const :value :tag) (string))
1623 (cons :tag "TODO keyword" (const :value :todo) (string))
1624 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1625 (cons :tag "Level number" (const :value :level) (integer))
1626 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1628 (defcustom org-refile-target-verify-function nil
1629 "Function to verify if the headline at point should be a refile target.
1630 The function will be called without arguments, with point at the
1631 beginning of the headline. It should return t and leave point
1632 where it is if the headline is a valid target for refiling.
1634 If the target should not be selected, the function must return nil.
1635 In addition to this, it may move point to a place from where the search
1636 should be continued. For example, the function may decide that the entire
1637 subtree of the current entry should be excluded and move point to the end
1638 of the subtree."
1639 :group 'org-refile
1640 :type 'function)
1642 (defcustom org-refile-use-outline-path nil
1643 "Non-nil means, provide refile targets as paths.
1644 So a level 3 headline will be available as level1/level2/level3.
1646 When the value is `file', also include the file name (without directory)
1647 into the path. In this case, you can also stop the completion after
1648 the file name, to get entries inserted as top level in the file.
1650 When `full-file-path', include the full file path."
1651 :group 'org-refile
1652 :type '(choice
1653 (const :tag "Not" nil)
1654 (const :tag "Yes" t)
1655 (const :tag "Start with file name" file)
1656 (const :tag "Start with full file path" full-file-path)))
1658 (defcustom org-outline-path-complete-in-steps t
1659 "Non-nil means, complete the outline path in hierarchical steps.
1660 When Org-mode uses the refile interface to select an outline path
1661 \(see variable `org-refile-use-outline-path'), the completion of
1662 the path can be done is a single go, or if can be done in steps down
1663 the headline hierarchy. Going in steps is probably the best if you
1664 do not use a special completion package like `ido' or `icicles'.
1665 However, when using these packages, going in one step can be very
1666 fast, while still showing the whole path to the entry."
1667 :group 'org-refile
1668 :type 'boolean)
1670 (defcustom org-refile-allow-creating-parent-nodes nil
1671 "Non-nil means, allow to create new nodes as refile targets.
1672 New nodes are then created by adding \"/new node name\" to the completion
1673 of an existing node. When the value of this variable is `confirm',
1674 new node creation must be confirmed by the user (recommended)
1675 When nil, the completion must match an existing entry.
1677 Note that, if the new heading is not seen by the criteria
1678 listed in `org-refile-targets', multiple instances of the same
1679 heading would be created by trying again to file under the new
1680 heading."
1681 :group 'org-refile
1682 :type '(choice
1683 (const :tag "Never" nil)
1684 (const :tag "Always" t)
1685 (const :tag "Prompt for confirmation" confirm)))
1687 (defgroup org-todo nil
1688 "Options concerning TODO items in Org-mode."
1689 :tag "Org TODO"
1690 :group 'org)
1692 (defgroup org-progress nil
1693 "Options concerning Progress logging in Org-mode."
1694 :tag "Org Progress"
1695 :group 'org-time)
1697 (defvar org-todo-interpretation-widgets
1699 (:tag "Sequence (cycling hits every state)" sequence)
1700 (:tag "Type (cycling directly to DONE)" type))
1701 "The available interpretation symbols for customizing
1702 `org-todo-keywords'.
1703 Interested libraries should add to this list.")
1705 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1706 "List of TODO entry keyword sequences and their interpretation.
1707 \\<org-mode-map>This is a list of sequences.
1709 Each sequence starts with a symbol, either `sequence' or `type',
1710 indicating if the keywords should be interpreted as a sequence of
1711 action steps, or as different types of TODO items. The first
1712 keywords are states requiring action - these states will select a headline
1713 for inclusion into the global TODO list Org-mode produces. If one of
1714 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1715 signify that no further action is necessary. If \"|\" is not found,
1716 the last keyword is treated as the only DONE state of the sequence.
1718 The command \\[org-todo] cycles an entry through these states, and one
1719 additional state where no keyword is present. For details about this
1720 cycling, see the manual.
1722 TODO keywords and interpretation can also be set on a per-file basis with
1723 the special #+SEQ_TODO and #+TYP_TODO lines.
1725 Each keyword can optionally specify a character for fast state selection
1726 \(in combination with the variable `org-use-fast-todo-selection')
1727 and specifiers for state change logging, using the same syntax
1728 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1729 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1730 indicates to record a time stamp each time this state is selected.
1732 Each keyword may also specify if a timestamp or a note should be
1733 recorded when entering or leaving the state, by adding additional
1734 characters in the parenthesis after the keyword. This looks like this:
1735 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1736 record only the time of the state change. With X and Y being either
1737 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1738 Y when leaving the state if and only if the *target* state does not
1739 define X. You may omit any of the fast-selection key or X or /Y,
1740 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1742 For backward compatibility, this variable may also be just a list
1743 of keywords - in this case the interpretation (sequence or type) will be
1744 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1745 :group 'org-todo
1746 :group 'org-keywords
1747 :type '(choice
1748 (repeat :tag "Old syntax, just keywords"
1749 (string :tag "Keyword"))
1750 (repeat :tag "New syntax"
1751 (cons
1752 (choice
1753 :tag "Interpretation"
1754 ;;Quick and dirty way to see
1755 ;;`org-todo-interpretations'. This takes the
1756 ;;place of item arguments
1757 :convert-widget
1758 (lambda (widget)
1759 (widget-put widget
1760 :args (mapcar
1761 #'(lambda (x)
1762 (widget-convert
1763 (cons 'const x)))
1764 org-todo-interpretation-widgets))
1765 widget))
1766 (repeat
1767 (string :tag "Keyword"))))))
1769 (defvar org-todo-keywords-1 nil
1770 "All TODO and DONE keywords active in a buffer.")
1771 (make-variable-buffer-local 'org-todo-keywords-1)
1772 (defvar org-todo-keywords-for-agenda nil)
1773 (defvar org-done-keywords-for-agenda nil)
1774 (defvar org-drawers-for-agenda nil)
1775 (defvar org-todo-keyword-alist-for-agenda nil)
1776 (defvar org-tag-alist-for-agenda nil)
1777 (defvar org-agenda-contributing-files nil)
1778 (defvar org-not-done-keywords nil)
1779 (make-variable-buffer-local 'org-not-done-keywords)
1780 (defvar org-done-keywords nil)
1781 (make-variable-buffer-local 'org-done-keywords)
1782 (defvar org-todo-heads nil)
1783 (make-variable-buffer-local 'org-todo-heads)
1784 (defvar org-todo-sets nil)
1785 (make-variable-buffer-local 'org-todo-sets)
1786 (defvar org-todo-log-states nil)
1787 (make-variable-buffer-local 'org-todo-log-states)
1788 (defvar org-todo-kwd-alist nil)
1789 (make-variable-buffer-local 'org-todo-kwd-alist)
1790 (defvar org-todo-key-alist nil)
1791 (make-variable-buffer-local 'org-todo-key-alist)
1792 (defvar org-todo-key-trigger nil)
1793 (make-variable-buffer-local 'org-todo-key-trigger)
1795 (defcustom org-todo-interpretation 'sequence
1796 "Controls how TODO keywords are interpreted.
1797 This variable is in principle obsolete and is only used for
1798 backward compatibility, if the interpretation of todo keywords is
1799 not given already in `org-todo-keywords'. See that variable for
1800 more information."
1801 :group 'org-todo
1802 :group 'org-keywords
1803 :type '(choice (const sequence)
1804 (const type)))
1806 (defcustom org-use-fast-todo-selection t
1807 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1808 This variable describes if and under what circumstances the cycling
1809 mechanism for TODO keywords will be replaced by a single-key, direct
1810 selection scheme.
1812 When nil, fast selection is never used.
1814 When the symbol `prefix', it will be used when `org-todo' is called with
1815 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1816 in an agenda buffer.
1818 When t, fast selection is used by default. In this case, the prefix
1819 argument forces cycling instead.
1821 In all cases, the special interface is only used if access keys have actually
1822 been assigned by the user, i.e. if keywords in the configuration are followed
1823 by a letter in parenthesis, like TODO(t)."
1824 :group 'org-todo
1825 :type '(choice
1826 (const :tag "Never" nil)
1827 (const :tag "By default" t)
1828 (const :tag "Only with C-u C-c C-t" prefix)))
1830 (defcustom org-provide-todo-statistics t
1831 "Non-nil means, update todo statistics after insert and toggle.
1832 ALL-HEADLINES means update todo statistics by including headlines
1833 with no TODO keyword as well, counting them as not done.
1834 A list of TODO keywords means the same, but skip keywords that are
1835 not in this list.
1837 When this is set, todo statistics is updated in the parent of the
1838 current entry each time a todo state is changed."
1839 :group 'org-todo
1840 :type '(choice
1841 (const :tag "Yes, only for TODO entries" t)
1842 (const :tag "Yes, including all entries" 'all-headlines)
1843 (repeat :tag "Yes, for TODOs in this list"
1844 (string :tag "TODO keyword"))
1845 (other :tag "No TODO statistics" nil)))
1847 (defcustom org-hierarchical-todo-statistics t
1848 "Non-nil means, TODO statistics covers just direct children.
1849 When nil, all entries in the subtree are considered.
1850 This has only an effect if `org-provide-todo-statistics' is set.
1851 To set this to nil for only a single subtree, use a COOKIE_DATA
1852 property and include the word \"recursive\" into the value."
1853 :group 'org-todo
1854 :type 'boolean)
1856 (defcustom org-after-todo-state-change-hook nil
1857 "Hook which is run after the state of a TODO item was changed.
1858 The new state (a string with a TODO keyword, or nil) is available in the
1859 Lisp variable `state'."
1860 :group 'org-todo
1861 :type 'hook)
1863 (defvar org-blocker-hook nil
1864 "Hook for functions that are allowed to block a state change.
1866 Each function gets as its single argument a property list, see
1867 `org-trigger-hook' for more information about this list.
1869 If any of the functions in this hook returns nil, the state change
1870 is blocked.")
1872 (defvar org-trigger-hook nil
1873 "Hook for functions that are triggered by a state change.
1875 Each function gets as its single argument a property list with at least
1876 the following elements:
1878 (:type type-of-change :position pos-at-entry-start
1879 :from old-state :to new-state)
1881 Depending on the type, more properties may be present.
1883 This mechanism is currently implemented for:
1885 TODO state changes
1886 ------------------
1887 :type todo-state-change
1888 :from previous state (keyword as a string), or nil, or a symbol
1889 'todo' or 'done', to indicate the general type of state.
1890 :to new state, like in :from")
1892 (defcustom org-enforce-todo-dependencies nil
1893 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1894 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1895 be blocked if any prior sibling is not yet done.
1896 Finally, if the parent is blocked because of ordered siblings of its own,
1897 the child will also be blocked.
1898 This variable needs to be set before org.el is loaded, and you need to
1899 restart Emacs after a change to make the change effective. The only way
1900 to change is while Emacs is running is through the customize interface."
1901 :set (lambda (var val)
1902 (set var val)
1903 (if val
1904 (add-hook 'org-blocker-hook
1905 'org-block-todo-from-children-or-siblings-or-parent)
1906 (remove-hook 'org-blocker-hook
1907 'org-block-todo-from-children-or-siblings-or-parent)))
1908 :group 'org-todo
1909 :type 'boolean)
1911 (defcustom org-enforce-todo-checkbox-dependencies nil
1912 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1913 When this is nil, checkboxes have no influence on switching TODO states.
1914 When non-nil, you first need to check off all check boxes before the TODO
1915 entry can be switched to DONE.
1916 This variable needs to be set before org.el is loaded, and you need to
1917 restart Emacs after a change to make the change effective. The only way
1918 to change is while Emacs is running is through the customize interface."
1919 :set (lambda (var val)
1920 (set var val)
1921 (if val
1922 (add-hook 'org-blocker-hook
1923 'org-block-todo-from-checkboxes)
1924 (remove-hook 'org-blocker-hook
1925 'org-block-todo-from-checkboxes)))
1926 :group 'org-todo
1927 :type 'boolean)
1929 (defcustom org-treat-insert-todo-heading-as-state-change nil
1930 "Non-nil means, inserting a TODO heading is treated as state change.
1931 So when the command \\[org-insert-todo-heading] is used, state change
1932 logging will apply if appropriate. When nil, the new TODO item will
1933 be inserted directly, and no logging will take place."
1934 :group 'org-todo
1935 :type 'boolean)
1937 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1938 "Non-nil means, switching TODO states with S-cursor counts as state change.
1939 This is the default behavior. However, setting this to nil allows a
1940 convenient way to select a TODO state and bypass any logging associated
1941 with that."
1942 :group 'org-todo
1943 :type 'boolean)
1945 (defcustom org-todo-state-tags-triggers nil
1946 "Tag changes that should be triggered by TODO state changes.
1947 This is a list. Each entry is
1949 (state-change (tag . flag) .......)
1951 State-change can be a string with a state, and empty string to indicate the
1952 state that has no TODO keyword, or it can be one of the symbols `todo'
1953 or `done', meaning any not-done or done state, respectively."
1954 :group 'org-todo
1955 :group 'org-tags
1956 :type '(repeat
1957 (cons (choice :tag "When changing to"
1958 (const :tag "Not-done state" todo)
1959 (const :tag "Done state" done)
1960 (string :tag "State"))
1961 (repeat
1962 (cons :tag "Tag action"
1963 (string :tag "Tag")
1964 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1966 (defcustom org-log-done nil
1967 "Information to record when a task moves to the DONE state.
1969 Possible values are:
1971 nil Don't add anything, just change the keyword
1972 time Add a time stamp to the task
1973 note Prompt for a note and add it with template `org-log-note-headings'
1975 This option can also be set with on a per-file-basis with
1977 #+STARTUP: nologdone
1978 #+STARTUP: logdone
1979 #+STARTUP: lognotedone
1981 You can have local logging settings for a subtree by setting the LOGGING
1982 property to one or more of these keywords."
1983 :group 'org-todo
1984 :group 'org-progress
1985 :type '(choice
1986 (const :tag "No logging" nil)
1987 (const :tag "Record CLOSED timestamp" time)
1988 (const :tag "Record CLOSED timestamp with note." note)))
1990 ;; Normalize old uses of org-log-done.
1991 (cond
1992 ((eq org-log-done t) (setq org-log-done 'time))
1993 ((and (listp org-log-done) (memq 'done org-log-done))
1994 (setq org-log-done 'note)))
1996 (defcustom org-log-reschedule nil
1997 "Information to record when the scheduling date of a tasks is modified.
1999 Possible values are:
2001 nil Don't add anything, just change the date
2002 time Add a time stamp to the task
2003 note Prompt for a note and add it with template `org-log-note-headings'
2005 This option can also be set with on a per-file-basis with
2007 #+STARTUP: nologreschedule
2008 #+STARTUP: logreschedule
2009 #+STARTUP: lognotereschedule"
2010 :group 'org-todo
2011 :group 'org-progress
2012 :type '(choice
2013 (const :tag "No logging" nil)
2014 (const :tag "Record timestamp" time)
2015 (const :tag "Record timestamp with note." note)))
2017 (defcustom org-log-redeadline nil
2018 "Information to record when the deadline date of a tasks is modified.
2020 Possible values are:
2022 nil Don't add anything, just change the date
2023 time Add a time stamp to the task
2024 note Prompt for a note and add it with template `org-log-note-headings'
2026 This option can also be set with on a per-file-basis with
2028 #+STARTUP: nologredeadline
2029 #+STARTUP: logredeadline
2030 #+STARTUP: lognoteredeadline
2032 You can have local logging settings for a subtree by setting the LOGGING
2033 property to one or more of these keywords."
2034 :group 'org-todo
2035 :group 'org-progress
2036 :type '(choice
2037 (const :tag "No logging" nil)
2038 (const :tag "Record timestamp" time)
2039 (const :tag "Record timestamp with note." note)))
2041 (defcustom org-log-note-clock-out nil
2042 "Non-nil means, record a note when clocking out of an item.
2043 This can also be configured on a per-file basis by adding one of
2044 the following lines anywhere in the buffer:
2046 #+STARTUP: lognoteclock-out
2047 #+STARTUP: nolognoteclock-out"
2048 :group 'org-todo
2049 :group 'org-progress
2050 :type 'boolean)
2052 (defcustom org-log-done-with-time t
2053 "Non-nil means, the CLOSED time stamp will contain date and time.
2054 When nil, only the date will be recorded."
2055 :group 'org-progress
2056 :type 'boolean)
2058 (defcustom org-log-note-headings
2059 '((done . "CLOSING NOTE %t")
2060 (state . "State %-12s from %-12S %t")
2061 (note . "Note taken on %t")
2062 (reschedule . "Rescheduled from %S on %t")
2063 (redeadline . "New deadline from %S on %t")
2064 (clock-out . ""))
2065 "Headings for notes added to entries.
2066 The value is an alist, with the car being a symbol indicating the note
2067 context, and the cdr is the heading to be used. The heading may also be the
2068 empty string.
2069 %t in the heading will be replaced by a time stamp.
2070 %s will be replaced by the new TODO state, in double quotes.
2071 %S will be replaced by the old TODO state, in double quotes.
2072 %u will be replaced by the user name.
2073 %U will be replaced by the full user name."
2074 :group 'org-todo
2075 :group 'org-progress
2076 :type '(list :greedy t
2077 (cons (const :tag "Heading when closing an item" done) string)
2078 (cons (const :tag
2079 "Heading when changing todo state (todo sequence only)"
2080 state) string)
2081 (cons (const :tag "Heading when just taking a note" note) string)
2082 (cons (const :tag "Heading when clocking out" clock-out) string)
2083 (cons (const :tag "Heading when rescheduling" reschedule) string)
2084 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2086 (unless (assq 'note org-log-note-headings)
2087 (push '(note . "%t") org-log-note-headings))
2089 (defcustom org-log-into-drawer nil
2090 "Non-nil means, insert state change notes and time stamps into a drawer.
2091 When nil, state changes notes will be inserted after the headline and
2092 any scheduling and clock lines, but not inside a drawer.
2094 The value of this variable should be the name of the drawer to use.
2095 LOGBOOK is proposed at the default drawer for this purpose, you can
2096 also set this to a string to define the drawer of your choice.
2098 A value of t is also allowed, representing \"LOGBOOK\".
2100 If this variable is set, `org-log-state-notes-insert-after-drawers'
2101 will be ignored.
2103 You can set the property LOG_INTO_DRAWER to overrule this setting for
2104 a subtree."
2105 :group 'org-todo
2106 :group 'org-progress
2107 :type '(choice
2108 (const :tag "Not into a drawer" nil)
2109 (const :tag "LOGBOOK" t)
2110 (string :tag "Other")))
2112 (if (fboundp 'defvaralias)
2113 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2115 (defun org-log-into-drawer ()
2116 "Return the value of `org-log-into-drawer', but let properties overrule.
2117 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2118 used instead of the default value."
2119 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2120 (cond
2121 ((or (not p) (equal p "nil")) org-log-into-drawer)
2122 ((equal p "t") "LOGBOOK")
2123 (t p))))
2125 (defcustom org-log-state-notes-insert-after-drawers nil
2126 "Non-nil means, insert state change notes after any drawers in entry.
2127 Only the drawers that *immediately* follow the headline and the
2128 deadline/scheduled line are skipped.
2129 When nil, insert notes right after the heading and perhaps the line
2130 with deadline/scheduling if present.
2132 This variable will have no effect if `org-log-into-drawer' is
2133 set."
2134 :group 'org-todo
2135 :group 'org-progress
2136 :type 'boolean)
2138 (defcustom org-log-states-order-reversed t
2139 "Non-nil means, the latest state change note will be directly after heading.
2140 When nil, the notes will be orderer according to time."
2141 :group 'org-todo
2142 :group 'org-progress
2143 :type 'boolean)
2145 (defcustom org-log-repeat 'time
2146 "Non-nil means, record moving through the DONE state when triggering repeat.
2147 An auto-repeating task is immediately switched back to TODO when
2148 marked DONE. If you are not logging state changes (by adding \"@\"
2149 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2150 record a closing note, there will be no record of the task moving
2151 through DONE. This variable forces taking a note anyway.
2153 nil Don't force a record
2154 time Record a time stamp
2155 note Record a note
2157 This option can also be set with on a per-file-basis with
2159 #+STARTUP: logrepeat
2160 #+STARTUP: lognoterepeat
2161 #+STARTUP: nologrepeat
2163 You can have local logging settings for a subtree by setting the LOGGING
2164 property to one or more of these keywords."
2165 :group 'org-todo
2166 :group 'org-progress
2167 :type '(choice
2168 (const :tag "Don't force a record" nil)
2169 (const :tag "Force recording the DONE state" time)
2170 (const :tag "Force recording a note with the DONE state" note)))
2173 (defgroup org-priorities nil
2174 "Priorities in Org-mode."
2175 :tag "Org Priorities"
2176 :group 'org-todo)
2178 (defcustom org-enable-priority-commands t
2179 "Non-nil means, priority commands are active.
2180 When nil, these commands will be disabled, so that you never accidentally
2181 set a priority."
2182 :group 'org-priorities
2183 :type 'boolean)
2185 (defcustom org-highest-priority ?A
2186 "The highest priority of TODO items. A character like ?A, ?B etc.
2187 Must have a smaller ASCII number than `org-lowest-priority'."
2188 :group 'org-priorities
2189 :type 'character)
2191 (defcustom org-lowest-priority ?C
2192 "The lowest priority of TODO items. A character like ?A, ?B etc.
2193 Must have a larger ASCII number than `org-highest-priority'."
2194 :group 'org-priorities
2195 :type 'character)
2197 (defcustom org-default-priority ?B
2198 "The default priority of TODO items.
2199 This is the priority an item get if no explicit priority is given."
2200 :group 'org-priorities
2201 :type 'character)
2203 (defcustom org-priority-start-cycle-with-default t
2204 "Non-nil means, start with default priority when starting to cycle.
2205 When this is nil, the first step in the cycle will be (depending on the
2206 command used) one higher or lower that the default priority."
2207 :group 'org-priorities
2208 :type 'boolean)
2210 (defgroup org-time nil
2211 "Options concerning time stamps and deadlines in Org-mode."
2212 :tag "Org Time"
2213 :group 'org)
2215 (defcustom org-insert-labeled-timestamps-at-point nil
2216 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2217 When nil, these labeled time stamps are forces into the second line of an
2218 entry, just after the headline. When scheduling from the global TODO list,
2219 the time stamp will always be forced into the second line."
2220 :group 'org-time
2221 :type 'boolean)
2223 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2224 "Formats for `format-time-string' which are used for time stamps.
2225 It is not recommended to change this constant.")
2227 (defcustom org-time-stamp-rounding-minutes '(0 5)
2228 "Number of minutes to round time stamps to.
2229 These are two values, the first applies when first creating a time stamp.
2230 The second applies when changing it with the commands `S-up' and `S-down'.
2231 When changing the time stamp, this means that it will change in steps
2232 of N minutes, as given by the second value.
2234 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2235 numbers should be factors of 60, so for example 5, 10, 15.
2237 When this is larger than 1, you can still force an exact time-stamp by using
2238 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2239 and by using a prefix arg to `S-up/down' to specify the exact number
2240 of minutes to shift."
2241 :group 'org-time
2242 :get '(lambda (var) ; Make sure all entries have 5 elements
2243 (if (integerp (default-value var))
2244 (list (default-value var) 5)
2245 (default-value var)))
2246 :type '(list
2247 (integer :tag "when inserting times")
2248 (integer :tag "when modifying times")))
2250 ;; Normalize old customizations of this variable.
2251 (when (integerp org-time-stamp-rounding-minutes)
2252 (setq org-time-stamp-rounding-minutes
2253 (list org-time-stamp-rounding-minutes
2254 org-time-stamp-rounding-minutes)))
2256 (defcustom org-display-custom-times nil
2257 "Non-nil means, overlay custom formats over all time stamps.
2258 The formats are defined through the variable `org-time-stamp-custom-formats'.
2259 To turn this on on a per-file basis, insert anywhere in the file:
2260 #+STARTUP: customtime"
2261 :group 'org-time
2262 :set 'set-default
2263 :type 'sexp)
2264 (make-variable-buffer-local 'org-display-custom-times)
2266 (defcustom org-time-stamp-custom-formats
2267 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2268 "Custom formats for time stamps. See `format-time-string' for the syntax.
2269 These are overlayed over the default ISO format if the variable
2270 `org-display-custom-times' is set. Time like %H:%M should be at the
2271 end of the second format. The custom formats are also honored by export
2272 commands, if custom time display is turned on at the time of export."
2273 :group 'org-time
2274 :type 'sexp)
2276 (defun org-time-stamp-format (&optional long inactive)
2277 "Get the right format for a time string."
2278 (let ((f (if long (cdr org-time-stamp-formats)
2279 (car org-time-stamp-formats))))
2280 (if inactive
2281 (concat "[" (substring f 1 -1) "]")
2282 f)))
2284 (defcustom org-time-clocksum-format "%d:%02d"
2285 "The format string used when creating CLOCKSUM lines, or when
2286 org-mode generates a time duration."
2287 :group 'org-time
2288 :type 'string)
2290 (defcustom org-time-clocksum-use-fractional nil
2291 "If non-nil, \\[org-clock-display] uses fractional times.
2292 org-mode generates a time duration."
2293 :group 'org-time
2294 :type 'boolean)
2296 (defcustom org-time-clocksum-fractional-format "%.2f"
2297 "The format string used when creating CLOCKSUM lines, or when
2298 org-mode generates a time duration."
2299 :group 'org-time
2300 :type 'string)
2302 (defcustom org-deadline-warning-days 14
2303 "No. of days before expiration during which a deadline becomes active.
2304 This variable governs the display in sparse trees and in the agenda.
2305 When 0 or negative, it means use this number (the absolute value of it)
2306 even if a deadline has a different individual lead time specified.
2308 Custom commands can set this variable in the options section."
2309 :group 'org-time
2310 :group 'org-agenda-daily/weekly
2311 :type 'integer)
2313 (defcustom org-read-date-prefer-future t
2314 "Non-nil means, assume future for incomplete date input from user.
2315 This affects the following situations:
2316 1. The user gives a month but not a year.
2317 For example, if it is april and you enter \"feb 2\", this will be read
2318 as feb 2, *next* year. \"May 5\", however, will be this year.
2319 2. The user gives a day, but no month.
2320 For example, if today is the 15th, and you enter \"3\", Org-mode will
2321 read this as the third of *next* month. However, if you enter \"17\",
2322 it will be considered as *this* month.
2324 If you set this variable to the symbol `time', then also the following
2325 will work:
2327 3. If the user gives a time, but no day. If the time is before now,
2328 to will be interpreted as tomorrow.
2330 Currently none of this works for ISO week specifications.
2332 When this option is nil, the current day, month and year will always be
2333 used as defaults."
2334 :group 'org-time
2335 :type '(choice
2336 (const :tag "Never" nil)
2337 (const :tag "Check month and day" t)
2338 (const :tag "Check month, day, and time" time)))
2340 (defcustom org-read-date-display-live t
2341 "Non-nil means, display current interpretation of date prompt live.
2342 This display will be in an overlay, in the minibuffer."
2343 :group 'org-time
2344 :type 'boolean)
2346 (defcustom org-read-date-popup-calendar t
2347 "Non-nil means, pop up a calendar when prompting for a date.
2348 In the calendar, the date can be selected with mouse-1. However, the
2349 minibuffer will also be active, and you can simply enter the date as well.
2350 When nil, only the minibuffer will be available."
2351 :group 'org-time
2352 :type 'boolean)
2353 (if (fboundp 'defvaralias)
2354 (defvaralias 'org-popup-calendar-for-date-prompt
2355 'org-read-date-popup-calendar))
2357 (defcustom org-read-date-minibuffer-setup-hook nil
2358 "Hook to be used to set up keys for the date/time interface.
2359 Add key definitions to `minibuffer-local-map', which will be a temporary
2360 copy."
2361 :group 'org-time
2362 :type 'hook)
2364 (defcustom org-extend-today-until 0
2365 "The hour when your day really ends. Must be an integer.
2366 This has influence for the following applications:
2367 - When switching the agenda to \"today\". It it is still earlier than
2368 the time given here, the day recognized as TODAY is actually yesterday.
2369 - When a date is read from the user and it is still before the time given
2370 here, the current date and time will be assumed to be yesterday, 23:59.
2371 Also, timestamps inserted in remember templates follow this rule.
2373 IMPORTANT: This is a feature whose implementation is and likely will
2374 remain incomplete. Really, it is only here because past midnight seems to
2375 be the favorite working time of John Wiegley :-)"
2376 :group 'org-time
2377 :type 'integer)
2379 (defcustom org-edit-timestamp-down-means-later nil
2380 "Non-nil means, S-down will increase the time in a time stamp.
2381 When nil, S-up will increase."
2382 :group 'org-time
2383 :type 'boolean)
2385 (defcustom org-calendar-follow-timestamp-change t
2386 "Non-nil means, make the calendar window follow timestamp changes.
2387 When a timestamp is modified and the calendar window is visible, it will be
2388 moved to the new date."
2389 :group 'org-time
2390 :type 'boolean)
2392 (defgroup org-tags nil
2393 "Options concerning tags in Org-mode."
2394 :tag "Org Tags"
2395 :group 'org)
2397 (defcustom org-tag-alist nil
2398 "List of tags allowed in Org-mode files.
2399 When this list is nil, Org-mode will base TAG input on what is already in the
2400 buffer.
2401 The value of this variable is an alist, the car of each entry must be a
2402 keyword as a string, the cdr may be a character that is used to select
2403 that tag through the fast-tag-selection interface.
2404 See the manual for details."
2405 :group 'org-tags
2406 :type '(repeat
2407 (choice
2408 (cons (string :tag "Tag name")
2409 (character :tag "Access char"))
2410 (list :tag "Start radio group"
2411 (const :startgroup)
2412 (option (string :tag "Group description")))
2413 (list :tag "End radio group"
2414 (const :endgroup)
2415 (option (string :tag "Group description")))
2416 (const :tag "New line" (:newline)))))
2418 (defcustom org-tag-persistent-alist nil
2419 "List of tags that will always appear in all Org-mode files.
2420 This is in addition to any in buffer settings or customizations
2421 of `org-tag-alist'.
2422 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2423 The value of this variable is an alist, the car of each entry must be a
2424 keyword as a string, the cdr may be a character that is used to select
2425 that tag through the fast-tag-selection interface.
2426 See the manual for details.
2427 To disable these tags on a per-file basis, insert anywhere in the file:
2428 #+STARTUP: noptag"
2429 :group 'org-tags
2430 :type '(repeat
2431 (choice
2432 (cons (string :tag "Tag name")
2433 (character :tag "Access char"))
2434 (const :tag "Start radio group" (:startgroup))
2435 (const :tag "End radio group" (:endgroup))
2436 (const :tag "New line" (:newline)))))
2438 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2439 "If non-nil, always offer completion for all tags of all agenda files.
2440 Instead of customizing this variable directly, you might want to
2441 set it locally for remember buffers, because there no list of
2442 tags in that file can be created dynamically (there are none).
2444 (add-hook 'org-remember-mode-hook
2445 (lambda ()
2446 (set (make-local-variable
2447 'org-complete-tags-always-offer-all-agenda-tags)
2448 t)))"
2449 :group 'org-tags
2450 :type 'boolean)
2452 (defvar org-file-tags nil
2453 "List of tags that can be inherited by all entries in the file.
2454 The tags will be inherited if the variable `org-use-tag-inheritance'
2455 says they should be.
2456 This variable is populated from #+FILETAGS lines.")
2458 (defcustom org-use-fast-tag-selection 'auto
2459 "Non-nil means, use fast tag selection scheme.
2460 This is a special interface to select and deselect tags with single keys.
2461 When nil, fast selection is never used.
2462 When the symbol `auto', fast selection is used if and only if selection
2463 characters for tags have been configured, either through the variable
2464 `org-tag-alist' or through a #+TAGS line in the buffer.
2465 When t, fast selection is always used and selection keys are assigned
2466 automatically if necessary."
2467 :group 'org-tags
2468 :type '(choice
2469 (const :tag "Always" t)
2470 (const :tag "Never" nil)
2471 (const :tag "When selection characters are configured" 'auto)))
2473 (defcustom org-fast-tag-selection-single-key nil
2474 "Non-nil means, fast tag selection exits after first change.
2475 When nil, you have to press RET to exit it.
2476 During fast tag selection, you can toggle this flag with `C-c'.
2477 This variable can also have the value `expert'. In this case, the window
2478 displaying the tags menu is not even shown, until you press C-c again."
2479 :group 'org-tags
2480 :type '(choice
2481 (const :tag "No" nil)
2482 (const :tag "Yes" t)
2483 (const :tag "Expert" expert)))
2485 (defvar org-fast-tag-selection-include-todo nil
2486 "Non-nil means, fast tags selection interface will also offer TODO states.
2487 This is an undocumented feature, you should not rely on it.")
2489 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2490 "The column to which tags should be indented in a headline.
2491 If this number is positive, it specifies the column. If it is negative,
2492 it means that the tags should be flushright to that column. For example,
2493 -80 works well for a normal 80 character screen."
2494 :group 'org-tags
2495 :type 'integer)
2497 (defcustom org-auto-align-tags t
2498 "Non-nil means, realign tags after pro/demotion of TODO state change.
2499 These operations change the length of a headline and therefore shift
2500 the tags around. With this options turned on, after each such operation
2501 the tags are again aligned to `org-tags-column'."
2502 :group 'org-tags
2503 :type 'boolean)
2505 (defcustom org-use-tag-inheritance t
2506 "Non-nil means, tags in levels apply also for sublevels.
2507 When nil, only the tags directly given in a specific line apply there.
2508 This may also be a list of tags that should be inherited, or a regexp that
2509 matches tags that should be inherited. Additional control is possible
2510 with the variable `org-tags-exclude-from-inheritance' which gives an
2511 explicit list of tags to be excluded from inheritance., even if the value of
2512 `org-use-tag-inheritance' would select it for inheritance.
2514 If this option is t, a match early-on in a tree can lead to a large
2515 number of matches in the subtree when constructing the agenda or creating
2516 a sparse tree. If you only want to see the first match in a tree during
2517 a search, check out the variable `org-tags-match-list-sublevels'."
2518 :group 'org-tags
2519 :type '(choice
2520 (const :tag "Not" nil)
2521 (const :tag "Always" t)
2522 (repeat :tag "Specific tags" (string :tag "Tag"))
2523 (regexp :tag "Tags matched by regexp")))
2525 (defcustom org-tags-exclude-from-inheritance nil
2526 "List of tags that should never be inherited.
2527 This is a way to exclude a few tags from inheritance. For way to do
2528 the opposite, to actively allow inheritance for selected tags,
2529 see the variable `org-use-tag-inheritance'."
2530 :group 'org-tags
2531 :type '(repeat (string :tag "Tag")))
2533 (defun org-tag-inherit-p (tag)
2534 "Check if TAG is one that should be inherited."
2535 (cond
2536 ((member tag org-tags-exclude-from-inheritance) nil)
2537 ((eq org-use-tag-inheritance t) t)
2538 ((not org-use-tag-inheritance) nil)
2539 ((stringp org-use-tag-inheritance)
2540 (string-match org-use-tag-inheritance tag))
2541 ((listp org-use-tag-inheritance)
2542 (member tag org-use-tag-inheritance))
2543 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2545 (defcustom org-tags-match-list-sublevels t
2546 "Non-nil means list also sublevels of headlines matching a search.
2547 This variable applies to tags/property searches, and also to stuck
2548 projects because this search is based on a tags match as well.
2550 When set to the symbol `indented', sublevels are indented with
2551 leading dots.
2553 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2554 the sublevels of a headline matching a tag search often also match
2555 the same search. Listing all of them can create very long lists.
2556 Setting this variable to nil causes subtrees of a match to be skipped.
2558 This variable is semi-obsolete and probably should always be true. It
2559 is better to limit inheritance to certain tags using the variables
2560 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2561 :group 'org-tags
2562 :type '(choice
2563 (const :tag "No, don't list them" nil)
2564 (const :tag "Yes, do list them" t)
2565 (const :tag "List them, indented with leading dots" indented)))
2567 (defcustom org-tags-sort-function nil
2568 "When set, tags are sorted using this function as a comparator"
2569 :group 'org-tags
2570 :type '(choice
2571 (const :tag "No sorting" nil)
2572 (const :tag "Alphabetical" string<)
2573 (const :tag "Reverse alphabetical" string>)
2574 (function :tag "Custom function" nil)))
2576 (defvar org-tags-history nil
2577 "History of minibuffer reads for tags.")
2578 (defvar org-last-tags-completion-table nil
2579 "The last used completion table for tags.")
2580 (defvar org-after-tags-change-hook nil
2581 "Hook that is run after the tags in a line have changed.")
2583 (defgroup org-properties nil
2584 "Options concerning properties in Org-mode."
2585 :tag "Org Properties"
2586 :group 'org)
2588 (defcustom org-property-format "%-10s %s"
2589 "How property key/value pairs should be formatted by `indent-line'.
2590 When `indent-line' hits a property definition, it will format the line
2591 according to this format, mainly to make sure that the values are
2592 lined-up with respect to each other."
2593 :group 'org-properties
2594 :type 'string)
2596 (defcustom org-use-property-inheritance nil
2597 "Non-nil means, properties apply also for sublevels.
2599 This setting is chiefly used during property searches. Turning it on can
2600 cause significant overhead when doing a search, which is why it is not
2601 on by default.
2603 When nil, only the properties directly given in the current entry count.
2604 When t, every property is inherited. The value may also be a list of
2605 properties that should have inheritance, or a regular expression matching
2606 properties that should be inherited.
2608 However, note that some special properties use inheritance under special
2609 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2610 and the properties ending in \"_ALL\" when they are used as descriptor
2611 for valid values of a property.
2613 Note for programmers:
2614 When querying an entry with `org-entry-get', you can control if inheritance
2615 should be used. By default, `org-entry-get' looks only at the local
2616 properties. You can request inheritance by setting the inherit argument
2617 to t (to force inheritance) or to `selective' (to respect the setting
2618 in this variable)."
2619 :group 'org-properties
2620 :type '(choice
2621 (const :tag "Not" nil)
2622 (const :tag "Always" t)
2623 (repeat :tag "Specific properties" (string :tag "Property"))
2624 (regexp :tag "Properties matched by regexp")))
2626 (defun org-property-inherit-p (property)
2627 "Check if PROPERTY is one that should be inherited."
2628 (cond
2629 ((eq org-use-property-inheritance t) t)
2630 ((not org-use-property-inheritance) nil)
2631 ((stringp org-use-property-inheritance)
2632 (string-match org-use-property-inheritance property))
2633 ((listp org-use-property-inheritance)
2634 (member property org-use-property-inheritance))
2635 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2637 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2638 "The default column format, if no other format has been defined.
2639 This variable can be set on the per-file basis by inserting a line
2641 #+COLUMNS: %25ITEM ....."
2642 :group 'org-properties
2643 :type 'string)
2645 (defcustom org-columns-ellipses ".."
2646 "The ellipses to be used when a field in column view is truncated.
2647 When this is the empty string, as many characters as possible are shown,
2648 but then there will be no visual indication that the field has been truncated.
2649 When this is a string of length N, the last N characters of a truncated
2650 field are replaced by this string. If the column is narrower than the
2651 ellipses string, only part of the ellipses string will be shown."
2652 :group 'org-properties
2653 :type 'string)
2655 (defcustom org-columns-modify-value-for-display-function nil
2656 "Function that modifies values for display in column view.
2657 For example, it can be used to cut out a certain part from a time stamp.
2658 The function must take 2 arguments:
2660 column-title The title of the column (*not* the property name)
2661 value The value that should be modified.
2663 The function should return the value that should be displayed,
2664 or nil if the normal value should be used."
2665 :group 'org-properties
2666 :type 'function)
2668 (defcustom org-effort-property "Effort"
2669 "The property that is being used to keep track of effort estimates.
2670 Effort estimates given in this property need to have the format H:MM."
2671 :group 'org-properties
2672 :group 'org-progress
2673 :type '(string :tag "Property"))
2675 (defconst org-global-properties-fixed
2676 '(("VISIBILITY_ALL" . "folded children content all")
2677 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2678 "List of property/value pairs that can be inherited by any entry.
2680 These are fixed values, for the preset properties. The user variable
2681 that can be used to add to this list is `org-global-properties'.
2683 The entries in this list are cons cells where the car is a property
2684 name and cdr is a string with the value. If the value represents
2685 multiple items like an \"_ALL\" property, separate the items by
2686 spaces.")
2688 (defcustom org-global-properties nil
2689 "List of property/value pairs that can be inherited by any entry.
2691 This list will be combined with the constant `org-global-properties-fixed'.
2693 The entries in this list are cons cells where the car is a property
2694 name and cdr is a string with the value.
2696 You can set buffer-local values for the same purpose in the variable
2697 `org-file-properties' this by adding lines like
2699 #+PROPERTY: NAME VALUE"
2700 :group 'org-properties
2701 :type '(repeat
2702 (cons (string :tag "Property")
2703 (string :tag "Value"))))
2705 (defvar org-file-properties nil
2706 "List of property/value pairs that can be inherited by any entry.
2707 Valid for the current buffer.
2708 This variable is populated from #+PROPERTY lines.")
2709 (make-variable-buffer-local 'org-file-properties)
2711 (defgroup org-agenda nil
2712 "Options concerning agenda views in Org-mode."
2713 :tag "Org Agenda"
2714 :group 'org)
2716 (defvar org-category nil
2717 "Variable used by org files to set a category for agenda display.
2718 Such files should use a file variable to set it, for example
2720 # -*- mode: org; org-category: \"ELisp\"
2722 or contain a special line
2724 #+CATEGORY: ELisp
2726 If the file does not specify a category, then file's base name
2727 is used instead.")
2728 (make-variable-buffer-local 'org-category)
2729 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2731 (defcustom org-agenda-files nil
2732 "The files to be used for agenda display.
2733 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2734 \\[org-remove-file]. You can also use customize to edit the list.
2736 If an entry is a directory, all files in that directory that are matched by
2737 `org-agenda-file-regexp' will be part of the file list.
2739 If the value of the variable is not a list but a single file name, then
2740 the list of agenda files is actually stored and maintained in that file, one
2741 agenda file per line."
2742 :group 'org-agenda
2743 :type '(choice
2744 (repeat :tag "List of files and directories" file)
2745 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2747 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2748 "Regular expression to match files for `org-agenda-files'.
2749 If any element in the list in that variable contains a directory instead
2750 of a normal file, all files in that directory that are matched by this
2751 regular expression will be included."
2752 :group 'org-agenda
2753 :type 'regexp)
2755 (defcustom org-agenda-text-search-extra-files nil
2756 "List of extra files to be searched by text search commands.
2757 These files will be search in addition to the agenda files by the
2758 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2759 Note that these files will only be searched for text search commands,
2760 not for the other agenda views like todo lists, tag searches or the weekly
2761 agenda. This variable is intended to list notes and possibly archive files
2762 that should also be searched by these two commands.
2763 In fact, if the first element in the list is the symbol `agenda-archives',
2764 than all archive files of all agenda files will be added to the search
2765 scope."
2766 :group 'org-agenda
2767 :type '(set :greedy t
2768 (const :tag "Agenda Archives" agenda-archives)
2769 (repeat :inline t (file))))
2771 (if (fboundp 'defvaralias)
2772 (defvaralias 'org-agenda-multi-occur-extra-files
2773 'org-agenda-text-search-extra-files))
2775 (defcustom org-agenda-skip-unavailable-files nil
2776 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2777 A nil value means to remove them, after a query, from the list."
2778 :group 'org-agenda
2779 :type 'boolean)
2781 (defcustom org-calendar-to-agenda-key [?c]
2782 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2783 The command `org-calendar-goto-agenda' will be bound to this key. The
2784 default is the character `c' because then `c' can be used to switch back and
2785 forth between agenda and calendar."
2786 :group 'org-agenda
2787 :type 'sexp)
2789 (defcustom org-calendar-agenda-action-key [?k]
2790 "The key to be installed in `calendar-mode-map' for agenda-action.
2791 The command `org-agenda-action' will be bound to this key. The
2792 default is the character `k' because we use the same key in the agenda."
2793 :group 'org-agenda
2794 :type 'sexp)
2796 (defcustom org-calendar-insert-diary-entry-key [?i]
2797 "The key to be installed in `calendar-mode-map' for adding diary entries.
2798 This option is irrelevant until `org-agenda-diary-file' has been configured
2799 to point to an Org-mode file. When that is the case, the command
2800 `org-agenda-diary-entry' will be bound to the key given here, by default
2801 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2802 if you want to continue doing this, you need to change this to a different
2803 key."
2804 :group 'org-agenda
2805 :type 'sexp)
2807 (defcustom org-agenda-diary-file 'diary-file
2808 "File to which to add new entries with the `i' key in agenda and calendar.
2809 When this is the symbol `diary-file', the functionality in the Emacs
2810 calendar will be used to add entries to the `diary-file'. But when this
2811 points to a file, `org-agenda-diary-entry' will be used instead."
2812 :group 'org-agenda
2813 :type '(choice
2814 (const :tag "The standard Emacs diary file" diary-file)
2815 (file :tag "Special Org file diary entries")))
2817 (eval-after-load "calendar"
2818 '(progn
2819 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2820 'org-calendar-goto-agenda)
2821 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2822 'org-agenda-action)
2823 (add-hook 'calendar-mode-hook
2824 (lambda ()
2825 (unless (eq org-agenda-diary-file 'diary-file)
2826 (define-key calendar-mode-map
2827 org-calendar-insert-diary-entry-key
2828 'org-agenda-diary-entry))))))
2830 (defgroup org-latex nil
2831 "Options for embedding LaTeX code into Org-mode."
2832 :tag "Org LaTeX"
2833 :group 'org)
2835 (defcustom org-format-latex-options
2836 '(:foreground default :background default :scale 1.0
2837 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2838 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2839 "Options for creating images from LaTeX fragments.
2840 This is a property list with the following properties:
2841 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2842 `default' means use the foreground of the default face.
2843 :background the background color, or \"Transparent\".
2844 `default' means use the background of the default face.
2845 :scale a scaling factor for the size of the images.
2846 :html-foreground, :html-background, :html-scale
2847 the same numbers for HTML export.
2848 :matchers a list indicating which matchers should be used to
2849 find LaTeX fragments. Valid members of this list are:
2850 \"begin\" find environments
2851 \"$1\" find single characters surrounded by $.$
2852 \"$\" find math expressions surrounded by $...$
2853 \"$$\" find math expressions surrounded by $$....$$
2854 \"\\(\" find math expressions surrounded by \\(...\\)
2855 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2856 :group 'org-latex
2857 :type 'plist)
2859 (defcustom org-format-latex-header "\\documentclass{article}
2860 \\usepackage{amssymb}
2861 \\usepackage[usenames]{color}
2862 \\usepackage{amsmath}
2863 \\usepackage{latexsym}
2864 \\usepackage[mathscr]{eucal}
2865 \\pagestyle{empty} % do not remove
2866 % The settings below are copied from fullpage.sty
2867 \\setlength{\\textwidth}{\\paperwidth}
2868 \\addtolength{\\textwidth}{-3cm}
2869 \\setlength{\\oddsidemargin}{1.5cm}
2870 \\addtolength{\\oddsidemargin}{-2.54cm}
2871 \\setlength{\\evensidemargin}{\\oddsidemargin}
2872 \\setlength{\\textheight}{\\paperheight}
2873 \\addtolength{\\textheight}{-\\headheight}
2874 \\addtolength{\\textheight}{-\\headsep}
2875 \\addtolength{\\textheight}{-\\footskip}
2876 \\addtolength{\\textheight}{-3cm}
2877 \\setlength{\\topmargin}{1.5cm}
2878 \\addtolength{\\topmargin}{-2.54cm}"
2879 "The document header used for processing LaTeX fragments.
2880 It is imperative that this header make sure that no page number
2881 appears on the page."
2882 :group 'org-latex
2883 :type 'string)
2885 ;; The following variable is defined here because is it also used
2886 ;; when formatting latex fragments. Originally it was part of the
2887 ;; LaTeX exporter, which is why the name includes "export".
2888 (defcustom org-export-latex-packages-alist nil
2889 "Alist of packages to be inserted in the header.
2890 Each cell is of the format \( \"option\" . \"package\" \)."
2891 :group 'org-export-latex
2892 :type '(repeat
2893 (list
2894 (string :tag "option")
2895 (string :tag "package"))))
2897 (defgroup org-font-lock nil
2898 "Font-lock settings for highlighting in Org-mode."
2899 :tag "Org Font Lock"
2900 :group 'org)
2902 (defcustom org-level-color-stars-only nil
2903 "Non-nil means fontify only the stars in each headline.
2904 When nil, the entire headline is fontified.
2905 Changing it requires restart of `font-lock-mode' to become effective
2906 also in regions already fontified."
2907 :group 'org-font-lock
2908 :type 'boolean)
2910 (defcustom org-hide-leading-stars nil
2911 "Non-nil means, hide the first N-1 stars in a headline.
2912 This works by using the face `org-hide' for these stars. This
2913 face is white for a light background, and black for a dark
2914 background. You may have to customize the face `org-hide' to
2915 make this work.
2916 Changing it requires restart of `font-lock-mode' to become effective
2917 also in regions already fontified.
2918 You may also set this on a per-file basis by adding one of the following
2919 lines to the buffer:
2921 #+STARTUP: hidestars
2922 #+STARTUP: showstars"
2923 :group 'org-font-lock
2924 :type 'boolean)
2926 (defcustom org-fontify-done-headline nil
2927 "Non-nil means, change the face of a headline if it is marked DONE.
2928 Normally, only the TODO/DONE keyword indicates the state of a headline.
2929 When this is non-nil, the headline after the keyword is set to the
2930 `org-headline-done' as an additional indication."
2931 :group 'org-font-lock
2932 :type 'boolean)
2934 (defcustom org-fontify-emphasized-text t
2935 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2936 Changing this variable requires a restart of Emacs to take effect."
2937 :group 'org-font-lock
2938 :type 'boolean)
2940 (defcustom org-fontify-whole-heading-line nil
2941 "Non-nil means fontify the whole line for headings.
2942 This is useful when setting a background color for the
2943 org-level-* faces."
2944 :group 'org-font-lock
2945 :type 'boolean)
2947 (defcustom org-highlight-latex-fragments-and-specials nil
2948 "Non-nil means, fontify what is treated specially by the exporters."
2949 :group 'org-font-lock
2950 :type 'boolean)
2952 (defcustom org-hide-emphasis-markers nil
2953 "Non-nil mean font-lock should hide the emphasis marker characters."
2954 :group 'org-font-lock
2955 :type 'boolean)
2957 (defvar org-emph-re nil
2958 "Regular expression for matching emphasis.")
2959 (defvar org-verbatim-re nil
2960 "Regular expression for matching verbatim text.")
2961 (defvar org-emphasis-regexp-components) ; defined just below
2962 (defvar org-emphasis-alist) ; defined just below
2963 (defun org-set-emph-re (var val)
2964 "Set variable and compute the emphasis regular expression."
2965 (set var val)
2966 (when (and (boundp 'org-emphasis-alist)
2967 (boundp 'org-emphasis-regexp-components)
2968 org-emphasis-alist org-emphasis-regexp-components)
2969 (let* ((e org-emphasis-regexp-components)
2970 (pre (car e))
2971 (post (nth 1 e))
2972 (border (nth 2 e))
2973 (body (nth 3 e))
2974 (nl (nth 4 e))
2975 (body1 (concat body "*?"))
2976 (markers (mapconcat 'car org-emphasis-alist ""))
2977 (vmarkers (mapconcat
2978 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2979 org-emphasis-alist "")))
2980 ;; make sure special characters appear at the right position in the class
2981 (if (string-match "\\^" markers)
2982 (setq markers (concat (replace-match "" t t markers) "^")))
2983 (if (string-match "-" markers)
2984 (setq markers (concat (replace-match "" t t markers) "-")))
2985 (if (string-match "\\^" vmarkers)
2986 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2987 (if (string-match "-" vmarkers)
2988 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2989 (if (> nl 0)
2990 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2991 (int-to-string nl) "\\}")))
2992 ;; Make the regexp
2993 (setq org-emph-re
2994 (concat "\\([" pre "]\\|^\\)"
2995 "\\("
2996 "\\([" markers "]\\)"
2997 "\\("
2998 "[^" border "]\\|"
2999 "[^" border "]"
3000 body1
3001 "[^" border "]"
3002 "\\)"
3003 "\\3\\)"
3004 "\\([" post "]\\|$\\)"))
3005 (setq org-verbatim-re
3006 (concat "\\([" pre "]\\|^\\)"
3007 "\\("
3008 "\\([" vmarkers "]\\)"
3009 "\\("
3010 "[^" border "]\\|"
3011 "[^" border "]"
3012 body1
3013 "[^" border "]"
3014 "\\)"
3015 "\\3\\)"
3016 "\\([" post "]\\|$\\)")))))
3018 (defcustom org-emphasis-regexp-components
3019 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3020 "Components used to build the regular expression for emphasis.
3021 This is a list with 6 entries. Terminology: In an emphasis string
3022 like \" *strong word* \", we call the initial space PREMATCH, the final
3023 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3024 and \"trong wor\" is the body. The different components in this variable
3025 specify what is allowed/forbidden in each part:
3027 pre Chars allowed as prematch. Beginning of line will be allowed too.
3028 post Chars allowed as postmatch. End of line will be allowed too.
3029 border The chars *forbidden* as border characters.
3030 body-regexp A regexp like \".\" to match a body character. Don't use
3031 non-shy groups here, and don't allow newline here.
3032 newline The maximum number of newlines allowed in an emphasis exp.
3034 Use customize to modify this, or restart Emacs after changing it."
3035 :group 'org-font-lock
3036 :set 'org-set-emph-re
3037 :type '(list
3038 (sexp :tag "Allowed chars in pre ")
3039 (sexp :tag "Allowed chars in post ")
3040 (sexp :tag "Forbidden chars in border ")
3041 (sexp :tag "Regexp for body ")
3042 (integer :tag "number of newlines allowed")
3043 (option (boolean :tag "Please ignore this button"))))
3045 (defcustom org-emphasis-alist
3046 `(("*" bold "<b>" "</b>")
3047 ("/" italic "<i>" "</i>")
3048 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3049 ("=" org-code "<code>" "</code>" verbatim)
3050 ("~" org-verbatim "<code>" "</code>" verbatim)
3051 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3052 "<del>" "</del>")
3054 "Special syntax for emphasized text.
3055 Text starting and ending with a special character will be emphasized, for
3056 example *bold*, _underlined_ and /italic/. This variable sets the marker
3057 characters, the face to be used by font-lock for highlighting in Org-mode
3058 Emacs buffers, and the HTML tags to be used for this.
3059 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3060 Use customize to modify this, or restart Emacs after changing it."
3061 :group 'org-font-lock
3062 :set 'org-set-emph-re
3063 :type '(repeat
3064 (list
3065 (string :tag "Marker character")
3066 (choice
3067 (face :tag "Font-lock-face")
3068 (plist :tag "Face property list"))
3069 (string :tag "HTML start tag")
3070 (string :tag "HTML end tag")
3071 (option (const verbatim)))))
3073 (defvar org-protecting-blocks
3074 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3075 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3076 This is needed for font-lock setup.")
3078 ;;; Miscellaneous options
3080 (defgroup org-completion nil
3081 "Completion in Org-mode."
3082 :tag "Org Completion"
3083 :group 'org)
3085 (defcustom org-completion-use-ido nil
3086 "Non-nil means, use ido completion wherever possible.
3087 Note that `ido-mode' must be active for this variable to be relevant.
3088 If you decide to turn this variable on, you might well want to turn off
3089 `org-outline-path-complete-in-steps'.
3090 See also `org-completion-use-iswitchb'."
3091 :group 'org-completion
3092 :type 'boolean)
3094 (defcustom org-completion-use-iswitchb nil
3095 "Non-nil means, use iswitchb completion wherever possible.
3096 Note that `iswitchb-mode' must be active for this variable to be relevant.
3097 If you decide to turn this variable on, you might well want to turn off
3098 `org-outline-path-complete-in-steps'.
3099 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3100 :group 'org-completion
3101 :type 'boolean)
3103 (defcustom org-completion-fallback-command 'hippie-expand
3104 "The expansion command called by \\[org-complete] in normal context.
3105 Normal means, no org-mode-specific context."
3106 :group 'org-completion
3107 :type 'function)
3109 ;;; Functions and variables from their packages
3110 ;; Declared here to avoid compiler warnings
3112 ;; XEmacs only
3113 (defvar outline-mode-menu-heading)
3114 (defvar outline-mode-menu-show)
3115 (defvar outline-mode-menu-hide)
3116 (defvar zmacs-regions) ; XEmacs regions
3118 ;; Emacs only
3119 (defvar mark-active)
3121 ;; Various packages
3122 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3123 (declare-function calendar-forward-day "cal-move" (arg))
3124 (declare-function calendar-goto-date "cal-move" (date))
3125 (declare-function calendar-goto-today "cal-move" ())
3126 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3127 (defvar calc-embedded-close-formula)
3128 (defvar calc-embedded-open-formula)
3129 (declare-function cdlatex-tab "ext:cdlatex" ())
3130 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3131 (defvar font-lock-unfontify-region-function)
3132 (declare-function iswitchb-read-buffer "iswitchb"
3133 (prompt &optional default require-match start matches-set))
3134 (defvar iswitchb-temp-buflist)
3135 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3136 (defvar org-agenda-tags-todo-honor-ignore-options)
3137 (declare-function org-agenda-skip "org-agenda" ())
3138 (declare-function
3139 org-format-agenda-item "org-agenda"
3140 (extra txt &optional category tags dotime noprefix remove-re habitp))
3141 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3142 (declare-function org-agenda-change-all-lines "org-agenda"
3143 (newhead hdmarker &optional fixface just-this))
3144 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3145 (declare-function org-agenda-maybe-redo "org-agenda" ())
3146 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3147 (beg end))
3148 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3149 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3150 "org-agenda" (&optional end))
3151 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3152 (declare-function org-indent-mode "org-indent" (&optional arg))
3153 (declare-function parse-time-string "parse-time" (string))
3154 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3155 (defvar remember-data-file)
3156 (defvar texmathp-why)
3157 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3158 (declare-function table--at-cell-p "table" (position &optional object at-column))
3160 (defvar w3m-current-url)
3161 (defvar w3m-current-title)
3163 (defvar org-latex-regexps)
3165 ;;; Autoload and prepare some org modules
3167 ;; Some table stuff that needs to be defined here, because it is used
3168 ;; by the functions setting up org-mode or checking for table context.
3170 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3171 "Detects an org-type or table-type table.")
3172 (defconst org-table-line-regexp "^[ \t]*|"
3173 "Detects an org-type table line.")
3174 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3175 "Detects an org-type table line.")
3176 (defconst org-table-hline-regexp "^[ \t]*|-"
3177 "Detects an org-type table hline.")
3178 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3179 "Detects a table-type table hline.")
3180 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3181 "Searching from within a table (any type) this finds the first line
3182 outside the table.")
3184 ;; Autoload the functions in org-table.el that are needed by functions here.
3186 (eval-and-compile
3187 (org-autoload "org-table"
3188 '(org-table-align org-table-begin org-table-blank-field
3189 org-table-convert org-table-convert-region org-table-copy-down
3190 org-table-copy-region org-table-create
3191 org-table-create-or-convert-from-region
3192 org-table-create-with-table.el org-table-current-dline
3193 org-table-cut-region org-table-delete-column org-table-edit-field
3194 org-table-edit-formulas org-table-end org-table-eval-formula
3195 org-table-export org-table-field-info
3196 org-table-get-stored-formulas org-table-goto-column
3197 org-table-hline-and-move org-table-import org-table-insert-column
3198 org-table-insert-hline org-table-insert-row org-table-iterate
3199 org-table-justify-field-maybe org-table-kill-row
3200 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3201 org-table-move-column org-table-move-column-left
3202 org-table-move-column-right org-table-move-row
3203 org-table-move-row-down org-table-move-row-up
3204 org-table-next-field org-table-next-row org-table-paste-rectangle
3205 org-table-previous-field org-table-recalculate
3206 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3207 org-table-toggle-coordinate-overlays
3208 org-table-toggle-formula-debugger org-table-wrap-region
3209 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3211 (defun org-at-table-p (&optional table-type)
3212 "Return t if the cursor is inside an org-type table.
3213 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3214 (if org-enable-table-editor
3215 (save-excursion
3216 (beginning-of-line 1)
3217 (looking-at (if table-type org-table-any-line-regexp
3218 org-table-line-regexp)))
3219 nil))
3220 (defsubst org-table-p () (org-at-table-p))
3222 (defun org-at-table.el-p ()
3223 "Return t if and only if we are at a table.el table."
3224 (and (org-at-table-p 'any)
3225 (save-excursion
3226 (goto-char (org-table-begin 'any))
3227 (looking-at org-table1-hline-regexp))))
3228 (defun org-table-recognize-table.el ()
3229 "If there is a table.el table nearby, recognize it and move into it."
3230 (if org-table-tab-recognizes-table.el
3231 (if (org-at-table.el-p)
3232 (progn
3233 (beginning-of-line 1)
3234 (if (looking-at org-table-dataline-regexp)
3236 (if (looking-at org-table1-hline-regexp)
3237 (progn
3238 (beginning-of-line 2)
3239 (if (looking-at org-table-any-border-regexp)
3240 (beginning-of-line -1)))))
3241 (if (re-search-forward "|" (org-table-end t) t)
3242 (progn
3243 (require 'table)
3244 (if (table--at-cell-p (point))
3246 (message "recognizing table.el table...")
3247 (table-recognize-table)
3248 (message "recognizing table.el table...done")))
3249 (error "This should not happen..."))
3251 nil)
3252 nil))
3254 (defun org-at-table-hline-p ()
3255 "Return t if the cursor is inside a hline in a table."
3256 (if org-enable-table-editor
3257 (save-excursion
3258 (beginning-of-line 1)
3259 (looking-at org-table-hline-regexp))
3260 nil))
3262 (defvar org-table-clean-did-remove-column nil)
3264 (defun org-table-map-tables (function)
3265 "Apply FUNCTION to the start of all tables in the buffer."
3266 (save-excursion
3267 (save-restriction
3268 (widen)
3269 (goto-char (point-min))
3270 (while (re-search-forward org-table-any-line-regexp nil t)
3271 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3272 (beginning-of-line 1)
3273 (when (looking-at org-table-line-regexp)
3274 (save-excursion (funcall function))
3275 (or (looking-at org-table-line-regexp)
3276 (forward-char 1)))
3277 (re-search-forward org-table-any-border-regexp nil 1))))
3278 (message "Mapping tables: done"))
3280 ;; Declare and autoload functions from org-exp.el & Co
3282 (declare-function org-default-export-plist "org-exp")
3283 (declare-function org-infile-export-plist "org-exp")
3284 (declare-function org-get-current-options "org-exp")
3285 (eval-and-compile
3286 (org-autoload "org-exp"
3287 '(org-export org-export-visible
3288 org-insert-export-options-template
3289 org-table-clean-before-export))
3290 (org-autoload "org-ascii"
3291 '(org-export-as-ascii org-export-ascii-preprocess
3292 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3293 org-export-region-as-ascii))
3294 (org-autoload "org-latex"
3295 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3296 org-replace-region-by-latex org-export-region-as-latex
3297 org-export-as-latex org-export-as-pdf
3298 org-export-as-pdf-and-open))
3299 (org-autoload "org-html"
3300 '(org-export-as-html-and-open
3301 org-export-as-html-batch org-export-as-html-to-buffer
3302 org-replace-region-by-html org-export-region-as-html
3303 org-export-as-html))
3304 (org-autoload "org-docbook"
3305 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3306 org-replace-region-by-docbook org-export-region-as-docbook
3307 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3308 org-export-as-docbook))
3309 (org-autoload "org-icalendar"
3310 '(org-export-icalendar-this-file
3311 org-export-icalendar-all-agenda-files
3312 org-export-icalendar-combine-agenda-files))
3313 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3314 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3316 ;; Declare and autoload functions from org-agenda.el
3318 (eval-and-compile
3319 (org-autoload "org-agenda"
3320 '(org-agenda org-agenda-list org-search-view
3321 org-todo-list org-tags-view org-agenda-list-stuck-projects
3322 org-diary org-agenda-to-appt
3323 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3325 ;; Autoload org-remember
3327 (eval-and-compile
3328 (org-autoload "org-remember"
3329 '(org-remember-insinuate org-remember-annotation
3330 org-remember-apply-template org-remember org-remember-handler)))
3332 ;; Autoload org-clock.el
3335 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3336 (beg end))
3337 (declare-function org-clock-update-mode-line "org-clock" ())
3338 (declare-function org-resolve-clocks "org-clock"
3339 (&optional also-non-dangling-p prompt last-valid))
3340 (defvar org-clock-start-time)
3341 (defvar org-clock-marker (make-marker)
3342 "Marker recording the last clock-in.")
3343 (defvar org-clock-hd-marker (make-marker)
3344 "Marker recording the last clock-in, but the headline position.")
3345 (defvar org-clock-heading ""
3346 "The heading of the current clock entry.")
3347 (defun org-clock-is-active ()
3348 "Return non-nil if clock is currently running.
3349 The return value is actually the clock marker."
3350 (marker-buffer org-clock-marker))
3352 (eval-and-compile
3353 (org-autoload
3354 "org-clock"
3355 '(org-clock-in org-clock-out org-clock-cancel
3356 org-clock-goto org-clock-sum org-clock-display
3357 org-clock-remove-overlays org-clock-report
3358 org-clocktable-shift org-dblock-write:clocktable
3359 org-get-clocktable org-resolve-clocks)))
3361 (defun org-clock-update-time-maybe ()
3362 "If this is a CLOCK line, update it and return t.
3363 Otherwise, return nil."
3364 (interactive)
3365 (save-excursion
3366 (beginning-of-line 1)
3367 (skip-chars-forward " \t")
3368 (when (looking-at org-clock-string)
3369 (let ((re (concat "[ \t]*" org-clock-string
3370 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3371 "\\([ \t]*=>.*\\)?\\)?"))
3372 ts te h m s neg)
3373 (cond
3374 ((not (looking-at re))
3375 nil)
3376 ((not (match-end 2))
3377 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3378 (> org-clock-marker (point))
3379 (<= org-clock-marker (point-at-eol)))
3380 ;; The clock is running here
3381 (setq org-clock-start-time
3382 (apply 'encode-time
3383 (org-parse-time-string (match-string 1))))
3384 (org-clock-update-mode-line)))
3386 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3387 (end-of-line 1)
3388 (setq ts (match-string 1)
3389 te (match-string 3))
3390 (setq s (- (org-float-time
3391 (apply 'encode-time (org-parse-time-string te)))
3392 (org-float-time
3393 (apply 'encode-time (org-parse-time-string ts))))
3394 neg (< s 0)
3395 s (abs s)
3396 h (floor (/ s 3600))
3397 s (- s (* 3600 h))
3398 m (floor (/ s 60))
3399 s (- s (* 60 s)))
3400 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3401 t))))))
3403 (defun org-check-running-clock ()
3404 "Check if the current buffer contains the running clock.
3405 If yes, offer to stop it and to save the buffer with the changes."
3406 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3407 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3408 (buffer-name))))
3409 (org-clock-out)
3410 (when (y-or-n-p "Save changed buffer?")
3411 (save-buffer))))
3413 (defun org-clocktable-try-shift (dir n)
3414 "Check if this line starts a clock table, if yes, shift the time block."
3415 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3416 (org-clocktable-shift dir n)))
3418 ;; Autoload org-timer.el
3420 (eval-and-compile
3421 (org-autoload
3422 "org-timer"
3423 '(org-timer-start org-timer org-timer-item
3424 org-timer-change-times-in-region
3425 org-timer-set-timer
3426 org-timer-reset-timers
3427 org-timer-show-remaining-time)))
3429 ;; Autoload org-feed.el
3431 (eval-and-compile
3432 (org-autoload
3433 "org-feed"
3434 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3437 ;; Autoload org-indent.el
3439 ;; Define the variable already here, to make sure we have it.
3440 (defvar org-indent-mode nil
3441 "Non-nil if Org-Indent mode is enabled.
3442 Use the command `org-indent-mode' to change this variable.")
3444 (eval-and-compile
3445 (org-autoload
3446 "org-indent"
3447 '(org-indent-mode)))
3449 ;; Autoload org-mobile.el
3451 (eval-and-compile
3452 (org-autoload
3453 "org-mobile"
3454 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3456 ;; Autoload archiving code
3457 ;; The stuff that is needed for cycling and tags has to be defined here.
3459 (defgroup org-archive nil
3460 "Options concerning archiving in Org-mode."
3461 :tag "Org Archive"
3462 :group 'org-structure)
3464 (defcustom org-archive-location "%s_archive::"
3465 "The location where subtrees should be archived.
3467 The value of this variable is a string, consisting of two parts,
3468 separated by a double-colon. The first part is a filename and
3469 the second part is a headline.
3471 When the filename is omitted, archiving happens in the same file.
3472 %s in the filename will be replaced by the current file
3473 name (without the directory part). Archiving to a different file
3474 is useful to keep archived entries from contributing to the
3475 Org-mode Agenda.
3477 The archived entries will be filed as subtrees of the specified
3478 headline. When the headline is omitted, the subtrees are simply
3479 filed away at the end of the file, as top-level entries. Also in
3480 the heading you can use %s to represent the file name, this can be
3481 useful when using the same archive for a number of different files.
3483 Here are a few examples:
3484 \"%s_archive::\"
3485 If the current file is Projects.org, archive in file
3486 Projects.org_archive, as top-level trees. This is the default.
3488 \"::* Archived Tasks\"
3489 Archive in the current file, under the top-level headline
3490 \"* Archived Tasks\".
3492 \"~/org/archive.org::\"
3493 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3495 \"~/org/archive.org::From %s\"
3496 Archive in file ~/org/archive.org (absolute path), under headlines
3497 \"From FILENAME\" where file name is the current file name.
3499 \"basement::** Finished Tasks\"
3500 Archive in file ./basement (relative path), as level 3 trees
3501 below the level 2 heading \"** Finished Tasks\".
3503 You may set this option on a per-file basis by adding to the buffer a
3504 line like
3506 #+ARCHIVE: basement::** Finished Tasks
3508 You may also define it locally for a subtree by setting an ARCHIVE property
3509 in the entry. If such a property is found in an entry, or anywhere up
3510 the hierarchy, it will be used."
3511 :group 'org-archive
3512 :type 'string)
3514 (defcustom org-archive-tag "ARCHIVE"
3515 "The tag that marks a subtree as archived.
3516 An archived subtree does not open during visibility cycling, and does
3517 not contribute to the agenda listings.
3518 After changing this, font-lock must be restarted in the relevant buffers to
3519 get the proper fontification."
3520 :group 'org-archive
3521 :group 'org-keywords
3522 :type 'string)
3524 (defcustom org-agenda-skip-archived-trees t
3525 "Non-nil means, the agenda will skip any items located in archived trees.
3526 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3527 variable is no longer recommended, you should leave it at the value t.
3528 Instead, use the key `v' to cycle the archives-mode in the agenda."
3529 :group 'org-archive
3530 :group 'org-agenda-skip
3531 :type 'boolean)
3533 (defcustom org-columns-skip-archived-trees t
3534 "Non-nil means, ignore archived trees when creating column view."
3535 :group 'org-archive
3536 :group 'org-properties
3537 :type 'boolean)
3539 (defcustom org-cycle-open-archived-trees nil
3540 "Non-nil means, `org-cycle' will open archived trees.
3541 An archived tree is a tree marked with the tag ARCHIVE.
3542 When nil, archived trees will stay folded. You can still open them with
3543 normal outline commands like `show-all', but not with the cycling commands."
3544 :group 'org-archive
3545 :group 'org-cycle
3546 :type 'boolean)
3548 (defcustom org-sparse-tree-open-archived-trees nil
3549 "Non-nil means sparse tree construction shows matches in archived trees.
3550 When nil, matches in these trees are highlighted, but the trees are kept in
3551 collapsed state."
3552 :group 'org-archive
3553 :group 'org-sparse-trees
3554 :type 'boolean)
3556 (defun org-cycle-hide-archived-subtrees (state)
3557 "Re-hide all archived subtrees after a visibility state change."
3558 (when (and (not org-cycle-open-archived-trees)
3559 (not (memq state '(overview folded))))
3560 (save-excursion
3561 (let* ((globalp (memq state '(contents all)))
3562 (beg (if globalp (point-min) (point)))
3563 (end (if globalp (point-max) (org-end-of-subtree t))))
3564 (org-hide-archived-subtrees beg end)
3565 (goto-char beg)
3566 (if (looking-at (concat ".*:" org-archive-tag ":"))
3567 (message "%s" (substitute-command-keys
3568 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3570 (defun org-force-cycle-archived ()
3571 "Cycle subtree even if it is archived."
3572 (interactive)
3573 (setq this-command 'org-cycle)
3574 (let ((org-cycle-open-archived-trees t))
3575 (call-interactively 'org-cycle)))
3577 (defun org-hide-archived-subtrees (beg end)
3578 "Re-hide all archived subtrees after a visibility state change."
3579 (save-excursion
3580 (let* ((re (concat ":" org-archive-tag ":")))
3581 (goto-char beg)
3582 (while (re-search-forward re end t)
3583 (and (org-on-heading-p) (org-flag-subtree t))
3584 (org-end-of-subtree t)))))
3586 (defun org-flag-subtree (flag)
3587 (save-excursion
3588 (org-back-to-heading t)
3589 (outline-end-of-heading)
3590 (outline-flag-region (point)
3591 (progn (org-end-of-subtree t) (point))
3592 flag)))
3594 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3596 (eval-and-compile
3597 (org-autoload "org-archive"
3598 '(org-add-archive-files org-archive-subtree
3599 org-archive-to-archive-sibling org-toggle-archive-tag
3600 org-archive-subtree-default
3601 org-archive-subtree-default-with-confirmation)))
3603 ;; Autoload Column View Code
3605 (declare-function org-columns-number-to-string "org-colview")
3606 (declare-function org-columns-get-format-and-top-level "org-colview")
3607 (declare-function org-columns-compute "org-colview")
3609 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3610 '(org-columns-number-to-string org-columns-get-format-and-top-level
3611 org-columns-compute org-agenda-columns org-columns-remove-overlays
3612 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3614 ;; Autoload ID code
3616 (declare-function org-id-store-link "org-id")
3617 (declare-function org-id-locations-load "org-id")
3618 (declare-function org-id-locations-save "org-id")
3619 (defvar org-id-track-globally)
3620 (org-autoload "org-id"
3621 '(org-id-get-create org-id-new org-id-copy org-id-get
3622 org-id-get-with-outline-path-completion
3623 org-id-get-with-outline-drilling
3624 org-id-goto org-id-find org-id-store-link))
3626 ;; Autoload Plotting Code
3628 (org-autoload "org-plot"
3629 '(org-plot/gnuplot))
3631 ;;; Variables for pre-computed regular expressions, all buffer local
3633 (defvar org-drawer-regexp nil
3634 "Matches first line of a hidden block.")
3635 (make-variable-buffer-local 'org-drawer-regexp)
3636 (defvar org-todo-regexp nil
3637 "Matches any of the TODO state keywords.")
3638 (make-variable-buffer-local 'org-todo-regexp)
3639 (defvar org-not-done-regexp nil
3640 "Matches any of the TODO state keywords except the last one.")
3641 (make-variable-buffer-local 'org-not-done-regexp)
3642 (defvar org-not-done-heading-regexp nil
3643 "Matches a TODO headline that is not done.")
3644 (make-variable-buffer-local 'org-not-done-regexp)
3645 (defvar org-todo-line-regexp nil
3646 "Matches a headline and puts TODO state into group 2 if present.")
3647 (make-variable-buffer-local 'org-todo-line-regexp)
3648 (defvar org-complex-heading-regexp nil
3649 "Matches a headline and puts everything into groups:
3650 group 1: the stars
3651 group 2: The todo keyword, maybe
3652 group 3: Priority cookie
3653 group 4: True headline
3654 group 5: Tags")
3655 (make-variable-buffer-local 'org-complex-heading-regexp)
3656 (defvar org-complex-heading-regexp-format nil)
3657 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3658 (defvar org-todo-line-tags-regexp nil
3659 "Matches a headline and puts TODO state into group 2 if present.
3660 Also put tags into group 4 if tags are present.")
3661 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3662 (defvar org-nl-done-regexp nil
3663 "Matches newline followed by a headline with the DONE keyword.")
3664 (make-variable-buffer-local 'org-nl-done-regexp)
3665 (defvar org-looking-at-done-regexp nil
3666 "Matches the DONE keyword a point.")
3667 (make-variable-buffer-local 'org-looking-at-done-regexp)
3668 (defvar org-ds-keyword-length 12
3669 "Maximum length of the Deadline and SCHEDULED keywords.")
3670 (make-variable-buffer-local 'org-ds-keyword-length)
3671 (defvar org-deadline-regexp nil
3672 "Matches the DEADLINE keyword.")
3673 (make-variable-buffer-local 'org-deadline-regexp)
3674 (defvar org-deadline-time-regexp nil
3675 "Matches the DEADLINE keyword together with a time stamp.")
3676 (make-variable-buffer-local 'org-deadline-time-regexp)
3677 (defvar org-deadline-line-regexp nil
3678 "Matches the DEADLINE keyword and the rest of the line.")
3679 (make-variable-buffer-local 'org-deadline-line-regexp)
3680 (defvar org-scheduled-regexp nil
3681 "Matches the SCHEDULED keyword.")
3682 (make-variable-buffer-local 'org-scheduled-regexp)
3683 (defvar org-scheduled-time-regexp nil
3684 "Matches the SCHEDULED keyword together with a time stamp.")
3685 (make-variable-buffer-local 'org-scheduled-time-regexp)
3686 (defvar org-closed-time-regexp nil
3687 "Matches the CLOSED keyword together with a time stamp.")
3688 (make-variable-buffer-local 'org-closed-time-regexp)
3690 (defvar org-keyword-time-regexp nil
3691 "Matches any of the 4 keywords, together with the time stamp.")
3692 (make-variable-buffer-local 'org-keyword-time-regexp)
3693 (defvar org-keyword-time-not-clock-regexp nil
3694 "Matches any of the 3 keywords, together with the time stamp.")
3695 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3696 (defvar org-maybe-keyword-time-regexp nil
3697 "Matches a timestamp, possibly preceeded by a keyword.")
3698 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3699 (defvar org-planning-or-clock-line-re nil
3700 "Matches a line with planning or clock info.")
3701 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3703 (defconst org-plain-time-of-day-regexp
3704 (concat
3705 "\\(\\<[012]?[0-9]"
3706 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3707 "\\(--?"
3708 "\\(\\<[012]?[0-9]"
3709 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3710 "\\)?")
3711 "Regular expression to match a plain time or time range.
3712 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3713 groups carry important information:
3714 0 the full match
3715 1 the first time, range or not
3716 8 the second time, if it is a range.")
3718 (defconst org-plain-time-extension-regexp
3719 (concat
3720 "\\(\\<[012]?[0-9]"
3721 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3722 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3723 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3724 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3725 groups carry important information:
3726 0 the full match
3727 7 hours of duration
3728 9 minutes of duration")
3730 (defconst org-stamp-time-of-day-regexp
3731 (concat
3732 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3733 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3734 "\\(--?"
3735 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3736 "Regular expression to match a timestamp time or time range.
3737 After a match, the following groups carry important information:
3738 0 the full match
3739 1 date plus weekday, for back referencing to make sure both times are on the same day
3740 2 the first time, range or not
3741 4 the second time, if it is a range.")
3743 (defconst org-startup-options
3744 '(("fold" org-startup-folded t)
3745 ("overview" org-startup-folded t)
3746 ("nofold" org-startup-folded nil)
3747 ("showall" org-startup-folded nil)
3748 ("showeverything" org-startup-folded showeverything)
3749 ("content" org-startup-folded content)
3750 ("indent" org-startup-indented t)
3751 ("noindent" org-startup-indented nil)
3752 ("hidestars" org-hide-leading-stars t)
3753 ("showstars" org-hide-leading-stars nil)
3754 ("odd" org-odd-levels-only t)
3755 ("oddeven" org-odd-levels-only nil)
3756 ("align" org-startup-align-all-tables t)
3757 ("noalign" org-startup-align-all-tables nil)
3758 ("customtime" org-display-custom-times t)
3759 ("logdone" org-log-done time)
3760 ("lognotedone" org-log-done note)
3761 ("nologdone" org-log-done nil)
3762 ("lognoteclock-out" org-log-note-clock-out t)
3763 ("nolognoteclock-out" org-log-note-clock-out nil)
3764 ("logrepeat" org-log-repeat state)
3765 ("lognoterepeat" org-log-repeat note)
3766 ("nologrepeat" org-log-repeat nil)
3767 ("logreschedule" org-log-reschedule time)
3768 ("lognotereschedule" org-log-reschedule note)
3769 ("nologreschedule" org-log-reschedule nil)
3770 ("logredeadline" org-log-redeadline time)
3771 ("lognoteredeadline" org-log-redeadline note)
3772 ("nologredeadline" org-log-redeadline nil)
3773 ("fninline" org-footnote-define-inline t)
3774 ("nofninline" org-footnote-define-inline nil)
3775 ("fnlocal" org-footnote-section nil)
3776 ("fnauto" org-footnote-auto-label t)
3777 ("fnprompt" org-footnote-auto-label nil)
3778 ("fnconfirm" org-footnote-auto-label confirm)
3779 ("fnplain" org-footnote-auto-label plain)
3780 ("fnadjust" org-footnote-auto-adjust t)
3781 ("nofnadjust" org-footnote-auto-adjust nil)
3782 ("constcgs" constants-unit-system cgs)
3783 ("constSI" constants-unit-system SI)
3784 ("noptag" org-tag-persistent-alist nil)
3785 ("hideblocks" org-hide-block-startup t)
3786 ("nohideblocks" org-hide-block-startup nil)
3787 ("beamer" org-startup-with-beamer-mode t))
3788 "Variable associated with STARTUP options for org-mode.
3789 Each element is a list of three items: The startup options as written
3790 in the #+STARTUP line, the corresponding variable, and the value to
3791 set this variable to if the option is found. An optional forth element PUSH
3792 means to push this value onto the list in the variable.")
3794 (defun org-set-regexps-and-options ()
3795 "Precompute regular expressions for current buffer."
3796 (when (org-mode-p)
3797 (org-set-local 'org-todo-kwd-alist nil)
3798 (org-set-local 'org-todo-key-alist nil)
3799 (org-set-local 'org-todo-key-trigger nil)
3800 (org-set-local 'org-todo-keywords-1 nil)
3801 (org-set-local 'org-done-keywords nil)
3802 (org-set-local 'org-todo-heads nil)
3803 (org-set-local 'org-todo-sets nil)
3804 (org-set-local 'org-todo-log-states nil)
3805 (org-set-local 'org-file-properties nil)
3806 (org-set-local 'org-file-tags nil)
3807 (let ((re (org-make-options-regexp
3808 '("CATEGORY" "TODO" "COLUMNS"
3809 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3810 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3811 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3812 (splitre "[ \t]+")
3813 kwds kws0 kwsa key log value cat arch tags const links hw dws
3814 tail sep kws1 prio props ftags drawers beamer-p
3815 ext-setup-or-nil setup-contents (start 0))
3816 (save-excursion
3817 (save-restriction
3818 (widen)
3819 (goto-char (point-min))
3820 (while (or (and ext-setup-or-nil
3821 (string-match re ext-setup-or-nil start)
3822 (setq start (match-end 0)))
3823 (and (setq ext-setup-or-nil nil start 0)
3824 (re-search-forward re nil t)))
3825 (setq key (upcase (match-string 1 ext-setup-or-nil))
3826 value (org-match-string-no-properties 2 ext-setup-or-nil))
3827 (cond
3828 ((equal key "CATEGORY")
3829 (if (string-match "[ \t]+$" value)
3830 (setq value (replace-match "" t t value)))
3831 (setq cat value))
3832 ((member key '("SEQ_TODO" "TODO"))
3833 (push (cons 'sequence (org-split-string value splitre)) kwds))
3834 ((equal key "TYP_TODO")
3835 (push (cons 'type (org-split-string value splitre)) kwds))
3836 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3837 ;; general TODO-like setup
3838 (push (cons (intern (downcase (match-string 1 key)))
3839 (org-split-string value splitre)) kwds))
3840 ((equal key "TAGS")
3841 (setq tags (append tags (if tags '("\\n") nil)
3842 (org-split-string value splitre))))
3843 ((equal key "COLUMNS")
3844 (org-set-local 'org-columns-default-format value))
3845 ((equal key "LINK")
3846 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3847 (push (cons (match-string 1 value)
3848 (org-trim (match-string 2 value)))
3849 links)))
3850 ((equal key "PRIORITIES")
3851 (setq prio (org-split-string value " +")))
3852 ((equal key "PROPERTY")
3853 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3854 (push (cons (match-string 1 value) (match-string 2 value))
3855 props)))
3856 ((equal key "FILETAGS")
3857 (when (string-match "\\S-" value)
3858 (setq ftags
3859 (append
3860 ftags
3861 (apply 'append
3862 (mapcar (lambda (x) (org-split-string x ":"))
3863 (org-split-string value)))))))
3864 ((equal key "DRAWERS")
3865 (setq drawers (org-split-string value splitre)))
3866 ((equal key "CONSTANTS")
3867 (setq const (append const (org-split-string value splitre))))
3868 ((equal key "STARTUP")
3869 (let ((opts (org-split-string value splitre))
3870 l var val)
3871 (while (setq l (pop opts))
3872 (when (setq l (assoc l org-startup-options))
3873 (setq var (nth 1 l) val (nth 2 l))
3874 (if (not (nth 3 l))
3875 (set (make-local-variable var) val)
3876 (if (not (listp (symbol-value var)))
3877 (set (make-local-variable var) nil))
3878 (set (make-local-variable var) (symbol-value var))
3879 (add-to-list var val))))))
3880 ((equal key "ARCHIVE")
3881 (string-match " *$" value)
3882 (setq arch (replace-match "" t t value))
3883 (remove-text-properties 0 (length arch)
3884 '(face t fontified t) arch))
3885 ((equal key "LATEX_CLASS")
3886 (setq beamer-p (equal value "beamer")))
3887 ((equal key "SETUPFILE")
3888 (setq setup-contents (org-file-contents
3889 (expand-file-name
3890 (org-remove-double-quotes value))
3891 'noerror))
3892 (if (not ext-setup-or-nil)
3893 (setq ext-setup-or-nil setup-contents start 0)
3894 (setq ext-setup-or-nil
3895 (concat (substring ext-setup-or-nil 0 start)
3896 "\n" setup-contents "\n"
3897 (substring ext-setup-or-nil start)))))
3898 ))))
3899 (when cat
3900 (org-set-local 'org-category (intern cat))
3901 (push (cons "CATEGORY" cat) props))
3902 (when prio
3903 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3904 (setq prio (mapcar 'string-to-char prio))
3905 (org-set-local 'org-highest-priority (nth 0 prio))
3906 (org-set-local 'org-lowest-priority (nth 1 prio))
3907 (org-set-local 'org-default-priority (nth 2 prio)))
3908 (and props (org-set-local 'org-file-properties (nreverse props)))
3909 (and ftags (org-set-local 'org-file-tags
3910 (mapcar 'org-add-prop-inherited ftags)))
3911 (and drawers (org-set-local 'org-drawers drawers))
3912 (and arch (org-set-local 'org-archive-location arch))
3913 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3914 ;; Process the TODO keywords
3915 (unless kwds
3916 ;; Use the global values as if they had been given locally.
3917 (setq kwds (default-value 'org-todo-keywords))
3918 (if (stringp (car kwds))
3919 (setq kwds (list (cons org-todo-interpretation
3920 (default-value 'org-todo-keywords)))))
3921 (setq kwds (reverse kwds)))
3922 (setq kwds (nreverse kwds))
3923 (let (inter kws kw)
3924 (while (setq kws (pop kwds))
3925 (let ((kws (or
3926 (run-hook-with-args-until-success
3927 'org-todo-setup-filter-hook kws)
3928 kws)))
3929 (setq inter (pop kws) sep (member "|" kws)
3930 kws0 (delete "|" (copy-sequence kws))
3931 kwsa nil
3932 kws1 (mapcar
3933 (lambda (x)
3934 ;; 1 2
3935 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3936 (progn
3937 (setq kw (match-string 1 x)
3938 key (and (match-end 2) (match-string 2 x))
3939 log (org-extract-log-state-settings x))
3940 (push (cons kw (and key (string-to-char key))) kwsa)
3941 (and log (push log org-todo-log-states))
3943 (error "Invalid TODO keyword %s" x)))
3944 kws0)
3945 kwsa (if kwsa (append '((:startgroup))
3946 (nreverse kwsa)
3947 '((:endgroup))))
3948 hw (car kws1)
3949 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3950 tail (list inter hw (car dws) (org-last dws))))
3951 (add-to-list 'org-todo-heads hw 'append)
3952 (push kws1 org-todo-sets)
3953 (setq org-done-keywords (append org-done-keywords dws nil))
3954 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3955 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3956 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3957 (setq org-todo-sets (nreverse org-todo-sets)
3958 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3959 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3960 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3961 ;; Process the constants
3962 (when const
3963 (let (e cst)
3964 (while (setq e (pop const))
3965 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3966 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3967 (setq org-table-formula-constants-local cst)))
3969 ;; Process the tags.
3970 (when tags
3971 (let (e tgs)
3972 (while (setq e (pop tags))
3973 (cond
3974 ((equal e "{") (push '(:startgroup) tgs))
3975 ((equal e "}") (push '(:endgroup) tgs))
3976 ((equal e "\\n") (push '(:newline) tgs))
3977 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3978 (push (cons (match-string 1 e)
3979 (string-to-char (match-string 2 e)))
3980 tgs))
3981 (t (push (list e) tgs))))
3982 (org-set-local 'org-tag-alist nil)
3983 (while (setq e (pop tgs))
3984 (or (and (stringp (car e))
3985 (assoc (car e) org-tag-alist))
3986 (push e org-tag-alist)))))
3988 ;; Compute the regular expressions and other local variables
3989 (if (not org-done-keywords)
3990 (setq org-done-keywords (and org-todo-keywords-1
3991 (list (org-last org-todo-keywords-1)))))
3992 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3993 (length org-scheduled-string)
3994 (length org-clock-string)
3995 (length org-closed-string)))
3996 org-drawer-regexp
3997 (concat "^[ \t]*:\\("
3998 (mapconcat 'regexp-quote org-drawers "\\|")
3999 "\\):[ \t]*$")
4000 org-not-done-keywords
4001 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4002 org-todo-regexp
4003 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4004 "\\|") "\\)\\>")
4005 org-not-done-regexp
4006 (concat "\\<\\("
4007 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4008 "\\)\\>")
4009 org-not-done-heading-regexp
4010 (concat "^\\(\\*+\\)[ \t]+\\("
4011 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4012 "\\)\\>")
4013 org-todo-line-regexp
4014 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4015 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4016 "\\)\\>\\)?[ \t]*\\(.*\\)")
4017 org-complex-heading-regexp
4018 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4019 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4020 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4021 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4022 org-complex-heading-regexp-format
4023 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4024 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4025 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4026 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4027 org-nl-done-regexp
4028 (concat "\n\\*+[ \t]+"
4029 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4030 "\\)" "\\>")
4031 org-todo-line-tags-regexp
4032 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4033 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4034 (org-re
4035 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4036 org-looking-at-done-regexp
4037 (concat "^" "\\(?:"
4038 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4039 "\\>")
4040 org-deadline-regexp (concat "\\<" org-deadline-string)
4041 org-deadline-time-regexp
4042 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4043 org-deadline-line-regexp
4044 (concat "\\<\\(" org-deadline-string "\\).*")
4045 org-scheduled-regexp
4046 (concat "\\<" org-scheduled-string)
4047 org-scheduled-time-regexp
4048 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4049 org-closed-time-regexp
4050 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4051 org-keyword-time-regexp
4052 (concat "\\<\\(" org-scheduled-string
4053 "\\|" org-deadline-string
4054 "\\|" org-closed-string
4055 "\\|" org-clock-string "\\)"
4056 " *[[<]\\([^]>]+\\)[]>]")
4057 org-keyword-time-not-clock-regexp
4058 (concat "\\<\\(" org-scheduled-string
4059 "\\|" org-deadline-string
4060 "\\|" org-closed-string
4061 "\\)"
4062 " *[[<]\\([^]>]+\\)[]>]")
4063 org-maybe-keyword-time-regexp
4064 (concat "\\(\\<\\(" org-scheduled-string
4065 "\\|" org-deadline-string
4066 "\\|" org-closed-string
4067 "\\|" org-clock-string "\\)\\)?"
4068 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4069 org-planning-or-clock-line-re
4070 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4071 "\\|" org-deadline-string
4072 "\\|" org-closed-string "\\|" org-clock-string
4073 "\\)\\>\\)")
4075 (org-compute-latex-and-specials-regexp)
4076 (org-set-font-lock-defaults))))
4078 (defun org-file-contents (file &optional noerror)
4079 "Return the contents of FILE, as a string."
4080 (if (or (not file)
4081 (not (file-readable-p file)))
4082 (if noerror
4083 (progn
4084 (message "Cannot read file %s" file)
4085 (ding) (sit-for 2)
4087 (error "Cannot read file %s" file))
4088 (with-temp-buffer
4089 (insert-file-contents file)
4090 (buffer-string))))
4092 (defun org-extract-log-state-settings (x)
4093 "Extract the log state setting from a TODO keyword string.
4094 This will extract info from a string like \"WAIT(w@/!)\"."
4095 (let (kw key log1 log2)
4096 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4097 (setq kw (match-string 1 x)
4098 key (and (match-end 2) (match-string 2 x))
4099 log1 (and (match-end 3) (match-string 3 x))
4100 log2 (and (match-end 4) (match-string 4 x)))
4101 (and (or log1 log2)
4102 (list kw
4103 (and log1 (if (equal log1 "!") 'time 'note))
4104 (and log2 (if (equal log2 "!") 'time 'note)))))))
4106 (defun org-remove-keyword-keys (list)
4107 "Remove a pair of parenthesis at the end of each string in LIST."
4108 (mapcar (lambda (x)
4109 (if (string-match "(.*)$" x)
4110 (substring x 0 (match-beginning 0))
4112 list))
4114 ;; FIXME: this could be done much better, using second characters etc.
4115 (defun org-assign-fast-keys (alist)
4116 "Assign fast keys to a keyword-key alist.
4117 Respect keys that are already there."
4118 (let (new e k c c1 c2 (char ?a))
4119 (while (setq e (pop alist))
4120 (cond
4121 ((equal e '(:startgroup)) (push e new))
4122 ((equal e '(:endgroup)) (push e new))
4123 ((equal e '(:newline)) (push e new))
4125 (setq k (car e) c2 nil)
4126 (if (cdr e)
4127 (setq c (cdr e))
4128 ;; automatically assign a character.
4129 (setq c1 (string-to-char
4130 (downcase (substring
4131 k (if (= (string-to-char k) ?@) 1 0)))))
4132 (if (or (rassoc c1 new) (rassoc c1 alist))
4133 (while (or (rassoc char new) (rassoc char alist))
4134 (setq char (1+ char)))
4135 (setq c2 c1))
4136 (setq c (or c2 char)))
4137 (push (cons k c) new))))
4138 (nreverse new)))
4140 ;;; Some variables used in various places
4142 (defvar org-window-configuration nil
4143 "Used in various places to store a window configuration.")
4144 (defvar org-selected-window nil
4145 "Used in various places to store a window configuration.")
4146 (defvar org-finish-function nil
4147 "Function to be called when `C-c C-c' is used.
4148 This is for getting out of special buffers like remember.")
4151 ;; FIXME: Occasionally check by commenting these, to make sure
4152 ;; no other functions uses these, forgetting to let-bind them.
4153 (defvar entry)
4154 (defvar last-state)
4155 (defvar date)
4157 ;; Defined somewhere in this file, but used before definition.
4158 (defvar org-html-entities)
4159 (defvar org-struct-menu)
4160 (defvar org-org-menu)
4161 (defvar org-tbl-menu)
4163 ;;;; Define the Org-mode
4165 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4166 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
4169 ;; We use a before-change function to check if a table might need
4170 ;; an update.
4171 (defvar org-table-may-need-update t
4172 "Indicates that a table might need an update.
4173 This variable is set by `org-before-change-function'.
4174 `org-table-align' sets it back to nil.")
4175 (defun org-before-change-function (beg end)
4176 "Every change indicates that a table might need an update."
4177 (setq org-table-may-need-update t))
4178 (defvar org-mode-map)
4179 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4180 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4181 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4182 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4183 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4184 (defvar org-table-buffer-is-an nil)
4185 (defconst org-outline-regexp "\\*+ ")
4187 ;;;###autoload
4188 (define-derived-mode org-mode outline-mode "Org"
4189 "Outline-based notes management and organizer, alias
4190 \"Carsten's outline-mode for keeping track of everything.\"
4192 Org-mode develops organizational tasks around a NOTES file which
4193 contains information about projects as plain text. Org-mode is
4194 implemented on top of outline-mode, which is ideal to keep the content
4195 of large files well structured. It supports ToDo items, deadlines and
4196 time stamps, which magically appear in the diary listing of the Emacs
4197 calendar. Tables are easily created with a built-in table editor.
4198 Plain text URL-like links connect to websites, emails (VM), Usenet
4199 messages (Gnus), BBDB entries, and any files related to the project.
4200 For printing and sharing of notes, an Org-mode file (or a part of it)
4201 can be exported as a structured ASCII or HTML file.
4203 The following commands are available:
4205 \\{org-mode-map}"
4207 ;; Get rid of Outline menus, they are not needed
4208 ;; Need to do this here because define-derived-mode sets up
4209 ;; the keymap so late. Still, it is a waste to call this each time
4210 ;; we switch another buffer into org-mode.
4211 (if (featurep 'xemacs)
4212 (when (boundp 'outline-mode-menu-heading)
4213 ;; Assume this is Greg's port, it used easymenu
4214 (easy-menu-remove outline-mode-menu-heading)
4215 (easy-menu-remove outline-mode-menu-show)
4216 (easy-menu-remove outline-mode-menu-hide))
4217 (define-key org-mode-map [menu-bar headings] 'undefined)
4218 (define-key org-mode-map [menu-bar hide] 'undefined)
4219 (define-key org-mode-map [menu-bar show] 'undefined))
4221 (org-load-modules-maybe)
4222 (easy-menu-add org-org-menu)
4223 (easy-menu-add org-tbl-menu)
4224 (org-install-agenda-files-menu)
4225 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4226 (org-add-to-invisibility-spec '(org-cwidth))
4227 (org-add-to-invisibility-spec '(org-hide-block . t))
4228 (when (featurep 'xemacs)
4229 (org-set-local 'line-move-ignore-invisible t))
4230 (org-set-local 'outline-regexp org-outline-regexp)
4231 (org-set-local 'outline-level 'org-outline-level)
4232 (when (and org-ellipsis
4233 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4234 (fboundp 'make-glyph-code))
4235 (unless org-display-table
4236 (setq org-display-table (make-display-table)))
4237 (set-display-table-slot
4238 org-display-table 4
4239 (vconcat (mapcar
4240 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4241 org-ellipsis)))
4242 (if (stringp org-ellipsis) org-ellipsis "..."))))
4243 (setq buffer-display-table org-display-table))
4244 (org-set-regexps-and-options)
4245 (when (and org-tag-faces (not org-tags-special-faces-re))
4246 ;; tag faces set outside customize.... force initialization.
4247 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4248 ;; Calc embedded
4249 (org-set-local 'calc-embedded-open-mode "# ")
4250 (modify-syntax-entry ?# "<")
4251 (modify-syntax-entry ?@ "w")
4252 (if org-startup-truncated (setq truncate-lines t))
4253 (org-set-local 'font-lock-unfontify-region-function
4254 'org-unfontify-region)
4255 ;; Activate before-change-function
4256 (org-set-local 'org-table-may-need-update t)
4257 (org-add-hook 'before-change-functions 'org-before-change-function nil
4258 'local)
4259 ;; Check for running clock before killing a buffer
4260 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4261 ;; Paragraphs and auto-filling
4262 (org-set-autofill-regexps)
4263 (setq indent-line-function 'org-indent-line-function)
4264 (org-update-radio-target-regexp)
4265 ;; Make sure dependence stuff works reliably, even for users who set it
4266 ;; too late :-(
4267 (if org-enforce-todo-dependencies
4268 (add-hook 'org-blocker-hook
4269 'org-block-todo-from-children-or-siblings-or-parent)
4270 (remove-hook 'org-blocker-hook
4271 'org-block-todo-from-children-or-siblings-or-parent))
4272 (if org-enforce-todo-checkbox-dependencies
4273 (add-hook 'org-blocker-hook
4274 'org-block-todo-from-checkboxes)
4275 (remove-hook 'org-blocker-hook
4276 'org-block-todo-from-checkboxes))
4278 ;; Comment characters
4279 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4280 (org-set-local 'comment-padding " ")
4282 ;; Align options lines
4283 (org-set-local
4284 'align-mode-rules-list
4285 '((org-in-buffer-settings
4286 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4287 (modes . '(org-mode)))))
4289 ;; Imenu
4290 (org-set-local 'imenu-create-index-function
4291 'org-imenu-get-tree)
4293 ;; Make isearch reveal context
4294 (if (or (featurep 'xemacs)
4295 (not (boundp 'outline-isearch-open-invisible-function)))
4296 ;; Emacs 21 and XEmacs make use of the hook
4297 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4298 ;; Emacs 22 deals with this through a special variable
4299 (org-set-local 'outline-isearch-open-invisible-function
4300 (lambda (&rest ignore) (org-show-context 'isearch))))
4302 ;; Turn on org-beamer-mode?
4303 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4305 ;; If empty file that did not turn on org-mode automatically, make it to.
4306 (if (and org-insert-mode-line-in-empty-file
4307 (interactive-p)
4308 (= (point-min) (point-max)))
4309 (insert "# -*- mode: org -*-\n\n"))
4310 (unless org-inhibit-startup
4311 (when org-startup-align-all-tables
4312 (let ((bmp (buffer-modified-p)))
4313 (org-table-map-tables 'org-table-align)
4314 (set-buffer-modified-p bmp)))
4315 (when org-startup-indented
4316 (require 'org-indent)
4317 (org-indent-mode 1))
4318 (unless org-inhibit-startup-visibility-stuff
4319 (org-set-startup-visibility))))
4321 (when (fboundp 'abbrev-table-put)
4322 (abbrev-table-put org-mode-abbrev-table
4323 :parents (list text-mode-abbrev-table)))
4325 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4327 (defun org-current-time ()
4328 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4329 (if (> (car org-time-stamp-rounding-minutes) 1)
4330 (let ((r (car org-time-stamp-rounding-minutes))
4331 (time (decode-time)))
4332 (apply 'encode-time
4333 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4334 (nthcdr 2 time))))
4335 (current-time)))
4337 ;;;; Font-Lock stuff, including the activators
4339 (defvar org-mouse-map (make-sparse-keymap))
4340 (org-defkey org-mouse-map
4341 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4342 (org-defkey org-mouse-map
4343 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4344 (when org-mouse-1-follows-link
4345 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4346 (when org-tab-follows-link
4347 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4348 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4350 (require 'font-lock)
4352 (defconst org-non-link-chars "]\t\n\r<>")
4353 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4354 "shell" "elisp"))
4355 (defvar org-link-types-re nil
4356 "Matches a link that has a url-like prefix like \"http:\"")
4357 (defvar org-link-re-with-space nil
4358 "Matches a link with spaces, optional angular brackets around it.")
4359 (defvar org-link-re-with-space2 nil
4360 "Matches a link with spaces, optional angular brackets around it.")
4361 (defvar org-link-re-with-space3 nil
4362 "Matches a link with spaces, only for internal part in bracket links.")
4363 (defvar org-angle-link-re nil
4364 "Matches link with angular brackets, spaces are allowed.")
4365 (defvar org-plain-link-re nil
4366 "Matches plain link, without spaces.")
4367 (defvar org-bracket-link-regexp nil
4368 "Matches a link in double brackets.")
4369 (defvar org-bracket-link-analytic-regexp nil
4370 "Regular expression used to analyze links.
4371 Here is what the match groups contain after a match:
4372 1: http:
4373 2: http
4374 3: path
4375 4: [desc]
4376 5: desc")
4377 (defvar org-bracket-link-analytic-regexp++ nil
4378 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4379 (defvar org-any-link-re nil
4380 "Regular expression matching any link.")
4382 (defun org-make-link-regexps ()
4383 "Update the link regular expressions.
4384 This should be called after the variable `org-link-types' has changed."
4385 (setq org-link-types-re
4386 (concat
4387 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4388 org-link-re-with-space
4389 (concat
4390 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4391 "\\([^" org-non-link-chars " ]"
4392 "[^" org-non-link-chars "]*"
4393 "[^" org-non-link-chars " ]\\)>?")
4394 org-link-re-with-space2
4395 (concat
4396 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4397 "\\([^" org-non-link-chars " ]"
4398 "[^\t\n\r]*"
4399 "[^" org-non-link-chars " ]\\)>?")
4400 org-link-re-with-space3
4401 (concat
4402 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4403 "\\([^" org-non-link-chars " ]"
4404 "[^\t\n\r]*\\)")
4405 org-angle-link-re
4406 (concat
4407 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4408 "\\([^" org-non-link-chars " ]"
4409 "[^" org-non-link-chars "]*"
4410 "\\)>")
4411 org-plain-link-re
4412 (concat
4413 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4414 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4415 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4416 org-bracket-link-regexp
4417 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4418 org-bracket-link-analytic-regexp
4419 (concat
4420 "\\[\\["
4421 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4422 "\\([^]]+\\)"
4423 "\\]"
4424 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4425 "\\]")
4426 org-bracket-link-analytic-regexp++
4427 (concat
4428 "\\[\\["
4429 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4430 "\\([^]]+\\)"
4431 "\\]"
4432 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4433 "\\]")
4434 org-any-link-re
4435 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4436 org-angle-link-re "\\)\\|\\("
4437 org-plain-link-re "\\)")))
4439 (org-make-link-regexps)
4441 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4442 "Regular expression for fast time stamp matching.")
4443 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4444 "Regular expression for fast time stamp matching.")
4445 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4446 "Regular expression matching time strings for analysis.
4447 This one does not require the space after the date, so it can be used
4448 on a string that terminates immediately after the date.")
4449 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4450 "Regular expression matching time strings for analysis.")
4451 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4452 "Regular expression matching time stamps, with groups.")
4453 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4454 "Regular expression matching time stamps (also [..]), with groups.")
4455 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4456 "Regular expression matching a time stamp range.")
4457 (defconst org-tr-regexp-both
4458 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4459 "Regular expression matching a time stamp range.")
4460 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4461 org-ts-regexp "\\)?")
4462 "Regular expression matching a time stamp or time stamp range.")
4463 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4464 org-ts-regexp-both "\\)?")
4465 "Regular expression matching a time stamp or time stamp range.
4466 The time stamps may be either active or inactive.")
4468 (defvar org-emph-face nil)
4470 (defun org-do-emphasis-faces (limit)
4471 "Run through the buffer and add overlays to links."
4472 (let (rtn a)
4473 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4474 (if (not (= (char-after (match-beginning 3))
4475 (char-after (match-beginning 4))))
4476 (progn
4477 (setq rtn t)
4478 (setq a (assoc (match-string 3) org-emphasis-alist))
4479 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4480 'face
4481 (nth 1 a))
4482 (and (nth 4 a)
4483 (org-remove-flyspell-overlays-in
4484 (match-beginning 0) (match-end 0)))
4485 (add-text-properties (match-beginning 2) (match-end 2)
4486 '(font-lock-multiline t))
4487 (when org-hide-emphasis-markers
4488 (add-text-properties (match-end 4) (match-beginning 5)
4489 '(invisible org-link))
4490 (add-text-properties (match-beginning 3) (match-end 3)
4491 '(invisible org-link)))))
4492 (backward-char 1))
4493 rtn))
4495 (defun org-emphasize (&optional char)
4496 "Insert or change an emphasis, i.e. a font like bold or italic.
4497 If there is an active region, change that region to a new emphasis.
4498 If there is no region, just insert the marker characters and position
4499 the cursor between them.
4500 CHAR should be either the marker character, or the first character of the
4501 HTML tag associated with that emphasis. If CHAR is a space, the means
4502 to remove the emphasis of the selected region.
4503 If char is not given (for example in an interactive call) it
4504 will be prompted for."
4505 (interactive)
4506 (let ((eal org-emphasis-alist) e det
4507 (erc org-emphasis-regexp-components)
4508 (prompt "")
4509 (string "") beg end move tag c s)
4510 (if (org-region-active-p)
4511 (setq beg (region-beginning) end (region-end)
4512 string (buffer-substring beg end))
4513 (setq move t))
4515 (while (setq e (pop eal))
4516 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4517 c (aref tag 0))
4518 (push (cons c (string-to-char (car e))) det)
4519 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4520 (substring tag 1)))))
4521 (setq det (nreverse det))
4522 (unless char
4523 (message "%s" (concat "Emphasis marker or tag:" prompt))
4524 (setq char (read-char-exclusive)))
4525 (setq char (or (cdr (assoc char det)) char))
4526 (if (equal char ?\ )
4527 (setq s "" move nil)
4528 (unless (assoc (char-to-string char) org-emphasis-alist)
4529 (error "No such emphasis marker: \"%c\"" char))
4530 (setq s (char-to-string char)))
4531 (while (and (> (length string) 1)
4532 (equal (substring string 0 1) (substring string -1))
4533 (assoc (substring string 0 1) org-emphasis-alist))
4534 (setq string (substring string 1 -1)))
4535 (setq string (concat s string s))
4536 (if beg (delete-region beg end))
4537 (unless (or (bolp)
4538 (string-match (concat "[" (nth 0 erc) "\n]")
4539 (char-to-string (char-before (point)))))
4540 (insert " "))
4541 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4542 (char-to-string (char-after (point))))
4543 (insert " ") (backward-char 1))
4544 (insert string)
4545 (and move (backward-char 1))))
4547 (defconst org-nonsticky-props
4548 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4550 (defsubst org-rear-nonsticky-at (pos)
4551 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4553 (defun org-activate-plain-links (limit)
4554 "Run through the buffer and add overlays to links."
4555 (catch 'exit
4556 (let (f)
4557 (if (re-search-forward org-plain-link-re limit t)
4558 (progn
4559 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4560 (setq f (get-text-property (match-beginning 0) 'face))
4561 (if (or (eq f 'org-tag)
4562 (and (listp f) (memq 'org-tag f)))
4564 (add-text-properties (match-beginning 0) (match-end 0)
4565 (list 'mouse-face 'highlight
4566 'face 'org-link
4567 'keymap org-mouse-map))
4568 (org-rear-nonsticky-at (match-end 0)))
4569 t)))))
4571 (defun org-activate-code (limit)
4572 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4573 (progn
4574 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4575 (remove-text-properties (match-beginning 0) (match-end 0)
4576 '(display t invisible t intangible t))
4577 t)))
4579 (defun org-fontify-meta-lines-and-blocks (limit)
4580 "Fontify #+ lines and blocks, in the correct ways."
4581 (let ((case-fold-search t))
4582 (if (re-search-forward
4583 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4584 limit t)
4585 (let ((beg (match-beginning 0))
4586 (beg1 (line-beginning-position 2))
4587 (dc1 (downcase (match-string 2)))
4588 (dc3 (downcase (match-string 3)))
4589 end end1 quoting block-type)
4590 (cond
4591 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4592 ;; a single line of backend-specific content
4593 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4594 (remove-text-properties (match-beginning 0) (match-end 0)
4595 '(display t invisible t intangible t))
4596 (add-text-properties (match-beginning 1) (match-end 3)
4597 '(font-lock-fontified t face org-meta-line))
4598 (add-text-properties (match-beginning 6) (match-end 6)
4599 '(font-lock-fontified t face org-block))
4601 ((and (match-end 4) (equal dc3 "begin"))
4602 ;; Truely a block
4603 (setq block-type (downcase (match-string 5))
4604 quoting (member block-type org-protecting-blocks))
4605 (when (re-search-forward
4606 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4607 nil t) ;; on purpose, we look further than LIMIT
4608 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4609 (when quoting
4610 (remove-text-properties beg end
4611 '(display t invisible t intangible t)))
4612 (add-text-properties
4613 beg end
4614 '(font-lock-fontified t font-lock-multiline t))
4615 (add-text-properties beg beg1 '(face org-meta-line))
4616 (add-text-properties end1 end '(face org-meta-line))
4617 (cond
4618 (quoting
4619 (add-text-properties beg1 end1 '(face org-block)))
4620 ((string= block-type "quote")
4621 (add-text-properties beg1 end1 '(face org-quote)))
4622 ((string= block-type "verse")
4623 (add-text-properties beg1 end1 '(face org-verse))))
4625 ((not (member (char-after beg) '(?\ ?\t)))
4626 ;; just any other in-buffer setting, but not indented
4627 (add-text-properties
4628 beg (match-end 0)
4629 '(font-lock-fontified t face org-meta-line))
4631 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4632 "orgtbl:" "tblfm:" "tblname:"))
4633 (and (match-end 4) (equal dc3 "attr")))
4634 (add-text-properties
4635 beg (match-end 0)
4636 '(font-lock-fontified t face org-meta-line))
4638 ((member dc3 '(" " ""))
4639 (add-text-properties
4640 beg (match-end 0)
4641 '(font-lock-fontified t face font-lock-comment-face)))
4642 (t nil))))))
4644 (defun org-activate-angle-links (limit)
4645 "Run through the buffer and add overlays to links."
4646 (if (re-search-forward org-angle-link-re limit t)
4647 (progn
4648 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4649 (add-text-properties (match-beginning 0) (match-end 0)
4650 (list 'mouse-face 'highlight
4651 'keymap org-mouse-map))
4652 (org-rear-nonsticky-at (match-end 0))
4653 t)))
4655 (defun org-activate-footnote-links (limit)
4656 "Run through the buffer and add overlays to links."
4657 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4658 limit t)
4659 (progn
4660 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4661 (add-text-properties (match-beginning 2) (match-end 2)
4662 (list 'mouse-face 'highlight
4663 'keymap org-mouse-map
4664 'help-echo
4665 (if (= (point-at-bol) (match-beginning 2))
4666 "Footnote definition"
4667 "Footnote reference")
4669 (org-rear-nonsticky-at (match-end 2))
4670 t)))
4672 (defun org-activate-bracket-links (limit)
4673 "Run through the buffer and add overlays to bracketed links."
4674 (if (re-search-forward org-bracket-link-regexp limit t)
4675 (let* ((help (concat "LINK: "
4676 (org-match-string-no-properties 1)))
4677 ;; FIXME: above we should remove the escapes.
4678 ;; but that requires another match, protecting match data,
4679 ;; a lot of overhead for font-lock.
4680 (ip (org-maybe-intangible
4681 (list 'invisible 'org-link
4682 'keymap org-mouse-map 'mouse-face 'highlight
4683 'font-lock-multiline t 'help-echo help)))
4684 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4685 'font-lock-multiline t 'help-echo help)))
4686 ;; We need to remove the invisible property here. Table narrowing
4687 ;; may have made some of this invisible.
4688 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4689 (remove-text-properties (match-beginning 0) (match-end 0)
4690 '(invisible nil))
4691 (if (match-end 3)
4692 (progn
4693 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4694 (org-rear-nonsticky-at (match-beginning 3))
4695 (add-text-properties (match-beginning 3) (match-end 3) vp)
4696 (org-rear-nonsticky-at (match-end 3))
4697 (add-text-properties (match-end 3) (match-end 0) ip)
4698 (org-rear-nonsticky-at (match-end 0)))
4699 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4700 (org-rear-nonsticky-at (match-beginning 1))
4701 (add-text-properties (match-beginning 1) (match-end 1) vp)
4702 (org-rear-nonsticky-at (match-end 1))
4703 (add-text-properties (match-end 1) (match-end 0) ip)
4704 (org-rear-nonsticky-at (match-end 0)))
4705 t)))
4707 (defun org-activate-dates (limit)
4708 "Run through the buffer and add overlays to dates."
4709 (if (re-search-forward org-tsr-regexp-both limit t)
4710 (progn
4711 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4712 (add-text-properties (match-beginning 0) (match-end 0)
4713 (list 'mouse-face 'highlight
4714 'keymap org-mouse-map))
4715 (org-rear-nonsticky-at (match-end 0))
4716 (when org-display-custom-times
4717 (if (match-end 3)
4718 (org-display-custom-time (match-beginning 3) (match-end 3)))
4719 (org-display-custom-time (match-beginning 1) (match-end 1)))
4720 t)))
4722 (defvar org-target-link-regexp nil
4723 "Regular expression matching radio targets in plain text.")
4724 (make-variable-buffer-local 'org-target-link-regexp)
4725 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4726 "Regular expression matching a link target.")
4727 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4728 "Regular expression matching a radio target.")
4729 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4730 "Regular expression matching any target.")
4732 (defun org-activate-target-links (limit)
4733 "Run through the buffer and add overlays to target matches."
4734 (when org-target-link-regexp
4735 (let ((case-fold-search t))
4736 (if (re-search-forward org-target-link-regexp limit t)
4737 (progn
4738 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4739 (add-text-properties (match-beginning 0) (match-end 0)
4740 (list 'mouse-face 'highlight
4741 'keymap org-mouse-map
4742 'help-echo "Radio target link"
4743 'org-linked-text t))
4744 (org-rear-nonsticky-at (match-end 0))
4745 t)))))
4747 (defun org-update-radio-target-regexp ()
4748 "Find all radio targets in this file and update the regular expression."
4749 (interactive)
4750 (when (memq 'radio org-activate-links)
4751 (setq org-target-link-regexp
4752 (org-make-target-link-regexp (org-all-targets 'radio)))
4753 (org-restart-font-lock)))
4755 (defun org-hide-wide-columns (limit)
4756 (let (s e)
4757 (setq s (text-property-any (point) (or limit (point-max))
4758 'org-cwidth t))
4759 (when s
4760 (setq e (next-single-property-change s 'org-cwidth))
4761 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4762 (goto-char e)
4763 t)))
4765 (defvar org-latex-and-specials-regexp nil
4766 "Regular expression for highlighting export special stuff.")
4767 (defvar org-match-substring-regexp)
4768 (defvar org-match-substring-with-braces-regexp)
4770 ;; This should be with the exporter code, but we also use if for font-locking
4771 (defconst org-export-html-special-string-regexps
4772 '(("\\\\-" . "&shy;")
4773 ("---\\([^-]\\)" . "&mdash;\\1")
4774 ("--\\([^-]\\)" . "&ndash;\\1")
4775 ("\\.\\.\\." . "&hellip;"))
4776 "Regular expressions for special string conversion.")
4779 (defun org-compute-latex-and-specials-regexp ()
4780 "Compute regular expression for stuff treated specially by exporters."
4781 (if (not org-highlight-latex-fragments-and-specials)
4782 (org-set-local 'org-latex-and-specials-regexp nil)
4783 (require 'org-exp)
4784 (let*
4785 ((matchers (plist-get org-format-latex-options :matchers))
4786 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4787 org-latex-regexps)))
4788 (options (org-combine-plists (org-default-export-plist)
4789 (org-infile-export-plist)))
4790 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4791 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4792 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4793 (org-export-html-expand (plist-get options :expand-quoted-html))
4794 (org-export-with-special-strings (plist-get options :special-strings))
4795 (re-sub
4796 (cond
4797 ((equal org-export-with-sub-superscripts '{})
4798 (list org-match-substring-with-braces-regexp))
4799 (org-export-with-sub-superscripts
4800 (list org-match-substring-regexp))
4801 (t nil)))
4802 (re-latex
4803 (if org-export-with-LaTeX-fragments
4804 (mapcar (lambda (x) (nth 1 x)) latexs)))
4805 (re-macros
4806 (if org-export-with-TeX-macros
4807 (list (concat "\\\\"
4808 (regexp-opt
4809 (append (mapcar 'car org-html-entities)
4810 (if (boundp 'org-latex-entities)
4811 (mapcar (lambda (x)
4812 (or (car-safe x) x))
4813 org-latex-entities)
4814 nil))
4815 'words))) ; FIXME
4817 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4818 (re-special (if org-export-with-special-strings
4819 (mapcar (lambda (x) (car x))
4820 org-export-html-special-string-regexps)))
4821 (re-rest
4822 (delq nil
4823 (list
4824 (if org-export-html-expand "@<[^>\n]+>")
4825 ))))
4826 (org-set-local
4827 'org-latex-and-specials-regexp
4828 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4829 re-rest) "\\|")))))
4831 (defun org-do-latex-and-special-faces (limit)
4832 "Run through the buffer and add overlays to links."
4833 (when org-latex-and-specials-regexp
4834 (let (rtn d)
4835 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4836 limit t))
4837 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4838 'face))
4839 '(org-code org-verbatim underline)))
4840 (progn
4841 (setq rtn t
4842 d (cond ((member (char-after (1+ (match-beginning 0)))
4843 '(?_ ?^)) 1)
4844 (t 0)))
4845 (font-lock-prepend-text-property
4846 (+ d (match-beginning 0)) (match-end 0)
4847 'face 'org-latex-and-export-specials)
4848 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4849 '(font-lock-multiline t)))))
4850 rtn)))
4852 (defun org-restart-font-lock ()
4853 "Restart font-lock-mode, to force refontification."
4854 (when (and (boundp 'font-lock-mode) font-lock-mode)
4855 (font-lock-mode -1)
4856 (font-lock-mode 1)))
4858 (defun org-all-targets (&optional radio)
4859 "Return a list of all targets in this file.
4860 With optional argument RADIO, only find radio targets."
4861 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4862 rtn)
4863 (save-excursion
4864 (goto-char (point-min))
4865 (while (re-search-forward re nil t)
4866 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4867 rtn)))
4869 (defun org-make-target-link-regexp (targets)
4870 "Make regular expression matching all strings in TARGETS.
4871 The regular expression finds the targets also if there is a line break
4872 between words."
4873 (and targets
4874 (concat
4875 "\\<\\("
4876 (mapconcat
4877 (lambda (x)
4878 (while (string-match " +" x)
4879 (setq x (replace-match "\\s-+" t t x)))
4881 targets
4882 "\\|")
4883 "\\)\\>")))
4885 (defun org-activate-tags (limit)
4886 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4887 (progn
4888 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4889 (add-text-properties (match-beginning 1) (match-end 1)
4890 (list 'mouse-face 'highlight
4891 'keymap org-mouse-map))
4892 (org-rear-nonsticky-at (match-end 1))
4893 t)))
4895 (defun org-outline-level ()
4896 "Compute the outline level of the heading at point.
4897 This function assumes that the cursor is at the beginning of a line matched
4898 by outline-regexp. Otherwise it returns garbage.
4899 If this is called at a normal headline, the level is the number of stars.
4900 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4901 For plain list items, if they are matched by `outline-regexp', this returns
4902 1000 plus the line indentation."
4903 (save-excursion
4904 (looking-at outline-regexp)
4905 (if (match-beginning 1)
4906 (+ (org-get-string-indentation (match-string 1)) 1000)
4907 (1- (- (match-end 0) (match-beginning 0))))))
4909 (defvar org-font-lock-keywords nil)
4911 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4912 "Regular expression matching a property line.")
4914 (defvar org-font-lock-hook nil
4915 "Functions to be called for special font lock stuff.")
4917 (defun org-font-lock-hook (limit)
4918 (run-hook-with-args 'org-font-lock-hook limit))
4920 (defun org-set-font-lock-defaults ()
4921 (let* ((em org-fontify-emphasized-text)
4922 (lk org-activate-links)
4923 (org-font-lock-extra-keywords
4924 (list
4925 ;; Call the hook
4926 '(org-font-lock-hook)
4927 ;; Headlines
4928 `(,(if org-fontify-whole-heading-line
4929 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4930 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4931 (1 (org-get-level-face 1))
4932 (2 (org-get-level-face 2))
4933 (3 (org-get-level-face 3)))
4934 ;; Table lines
4935 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4936 (1 'org-table t))
4937 ;; Table internals
4938 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4939 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4940 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4941 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4942 ;; Drawers
4943 (list org-drawer-regexp '(0 'org-special-keyword t))
4944 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4945 ;; Properties
4946 (list org-property-re
4947 '(1 'org-special-keyword t)
4948 '(3 'org-property-value t))
4949 ;; Links
4950 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4951 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4952 (if (memq 'plain lk) '(org-activate-plain-links))
4953 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4954 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4955 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4956 (if (memq 'footnote lk) '(org-activate-footnote-links
4957 (2 'org-footnote t)))
4958 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4959 '(org-hide-wide-columns (0 nil append))
4960 ;; TODO lines
4961 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4962 '(1 (org-get-todo-face 1) t))
4963 ;; DONE
4964 (if org-fontify-done-headline
4965 (list (concat "^[*]+ +\\<\\("
4966 (mapconcat 'regexp-quote org-done-keywords "\\|")
4967 "\\)\\(.*\\)")
4968 '(2 'org-headline-done t))
4969 nil)
4970 ;; Priorities
4971 '(org-font-lock-add-priority-faces)
4972 ;; Tags
4973 '(org-font-lock-add-tag-faces)
4974 ;; Special keywords
4975 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4976 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4977 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4978 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4979 ;; Emphasis
4980 (if em
4981 (if (featurep 'xemacs)
4982 '(org-do-emphasis-faces (0 nil append))
4983 '(org-do-emphasis-faces)))
4984 ;; Checkboxes
4985 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4986 2 'org-checkbox prepend)
4987 (if org-provide-checkbox-statistics
4988 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4989 (0 (org-get-checkbox-statistics-face) t)))
4990 ;; Description list items
4991 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4992 2 'bold prepend)
4993 ;; ARCHIVEd headings
4994 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4995 '(1 'org-archived prepend))
4996 ;; Specials
4997 '(org-do-latex-and-special-faces)
4998 ;; Code
4999 '(org-activate-code (1 'org-code t))
5000 ;; COMMENT
5001 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5002 "\\|" org-quote-string "\\)\\>")
5003 '(1 'org-special-keyword t))
5004 '("^#.*" (0 'font-lock-comment-face t))
5005 ;; Blocks and meta lines
5006 '(org-fontify-meta-lines-and-blocks)
5008 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5009 ;; Now set the full font-lock-keywords
5010 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5011 (org-set-local 'font-lock-defaults
5012 '(org-font-lock-keywords t nil nil backward-paragraph))
5013 (kill-local-variable 'font-lock-keywords) nil))
5015 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5016 "Fontify string S like in Org-mode"
5017 (with-temp-buffer
5018 (insert s)
5019 (let ((org-odd-levels-only odd-levels))
5020 (org-mode)
5021 (font-lock-fontify-buffer)
5022 (buffer-string))))
5024 (defvar org-m nil)
5025 (defvar org-l nil)
5026 (defvar org-f nil)
5027 (defun org-get-level-face (n)
5028 "Get the right face for match N in font-lock matching of headlines."
5029 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5030 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5031 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5032 (cond
5033 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5034 ((eq n 2) org-f)
5035 (t (if org-level-color-stars-only nil org-f))))
5037 (defun org-get-todo-face (kwd)
5038 "Get the right face for a TODO keyword KWD.
5039 If KWD is a number, get the corresponding match group."
5040 (if (numberp kwd) (setq kwd (match-string kwd)))
5041 (or (cdr (assoc kwd org-todo-keyword-faces))
5042 (and (member kwd org-done-keywords) 'org-done)
5043 'org-todo))
5045 (defun org-font-lock-add-tag-faces (limit)
5046 "Add the special tag faces."
5047 (when (and org-tag-faces org-tags-special-faces-re)
5048 (while (re-search-forward org-tags-special-faces-re limit t)
5049 (add-text-properties (match-beginning 1) (match-end 1)
5050 (list 'face (org-get-tag-face 1)
5051 'font-lock-fontified t))
5052 (backward-char 1))))
5054 (defun org-font-lock-add-priority-faces (limit)
5055 "Add the special priority faces."
5056 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5057 (add-text-properties
5058 (match-beginning 0) (match-end 0)
5059 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5060 org-priority-faces))
5061 'org-special-keyword)
5062 'font-lock-fontified t))))
5064 (defun org-get-tag-face (kwd)
5065 "Get the right face for a TODO keyword KWD.
5066 If KWD is a number, get the corresponding match group."
5067 (if (numberp kwd) (setq kwd (match-string kwd)))
5068 (or (cdr (assoc kwd org-tag-faces))
5069 'org-tag))
5071 (defun org-unfontify-region (beg end &optional maybe_loudly)
5072 "Remove fontification and activation overlays from links."
5073 (font-lock-default-unfontify-region beg end)
5074 (let* ((buffer-undo-list t)
5075 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5076 (inhibit-modification-hooks t)
5077 deactivate-mark buffer-file-name buffer-file-truename)
5078 (remove-text-properties
5079 beg end
5080 (if org-indent-mode
5081 ;; also remove line-prefix and wrap-prefix properties
5082 '(mouse-face t keymap t org-linked-text t
5083 invisible t intangible t
5084 line-prefix t wrap-prefix t
5085 org-no-flyspell t)
5086 '(mouse-face t keymap t org-linked-text t
5087 invisible t intangible t
5088 org-no-flyspell t)))))
5090 ;;;; Visibility cycling, including org-goto and indirect buffer
5092 ;;; Cycling
5094 (defvar org-cycle-global-status nil)
5095 (make-variable-buffer-local 'org-cycle-global-status)
5096 (defvar org-cycle-subtree-status nil)
5097 (make-variable-buffer-local 'org-cycle-subtree-status)
5099 ;;;###autoload
5101 (defvar org-inlinetask-min-level)
5103 (defun org-cycle (&optional arg)
5104 "TAB-action and visibility cycling for Org-mode.
5106 This is the command invoked in Org-mode by the TAB key. Its main purpose
5107 is outline visibility cycling, but it also invokes other actions
5108 in special contexts.
5110 - When this function is called with a prefix argument, rotate the entire
5111 buffer through 3 states (global cycling)
5112 1. OVERVIEW: Show only top-level headlines.
5113 2. CONTENTS: Show all headlines of all levels, but no body text.
5114 3. SHOW ALL: Show everything.
5115 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5116 determined by the variable `org-startup-folded', and by any VISIBILITY
5117 properties in the buffer.
5118 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5119 including any drawers.
5121 - When inside a table, re-align the table and move to the next field.
5123 - When point is at the beginning of a headline, rotate the subtree started
5124 by this line through 3 different states (local cycling)
5125 1. FOLDED: Only the main headline is shown.
5126 2. CHILDREN: The main headline and the direct children are shown.
5127 From this state, you can move to one of the children
5128 and zoom in further.
5129 3. SUBTREE: Show the entire subtree, including body text.
5130 If there is no subtree, switch directly from CHILDREN to FOLDED.
5132 - When there is a numeric prefix, go up to a heading with level ARG, do
5133 a `show-subtree' and return to the previous cursor position. If ARG
5134 is negative, go up that many levels.
5136 - When point is not at the beginning of a headline, execute the global
5137 binding for TAB, which is re-indenting the line. See the option
5138 `org-cycle-emulate-tab' for details.
5140 - Special case: if point is at the beginning of the buffer and there is
5141 no headline in line 1, this function will act as if called with prefix arg.
5142 But only if also the variable `org-cycle-global-at-bob' is t."
5143 (interactive "P")
5144 (org-load-modules-maybe)
5145 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5146 (and org-cycle-level-after-item/entry-creation
5147 (or (org-cycle-level)
5148 (org-cycle-item-indentation))))
5149 (let* ((limit-level
5150 (or org-cycle-max-level
5151 (and (boundp 'org-inlinetask-min-level)
5152 org-inlinetask-min-level
5153 (1- org-inlinetask-min-level))))
5154 (nstars (and limit-level
5155 (if org-odd-levels-only
5156 (and limit-level (1- (* limit-level 2)))
5157 limit-level)))
5158 (outline-regexp
5159 (cond
5160 ((not (org-mode-p)) outline-regexp)
5161 ((or (eq org-cycle-include-plain-lists 'integrate)
5162 (and org-cycle-include-plain-lists (org-at-item-p)))
5163 (concat "\\(?:\\*"
5164 (if nstars (format "\\{1,%d\\}" nstars) "+")
5165 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5166 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5167 (bob-special (and org-cycle-global-at-bob (bobp)
5168 (not (looking-at outline-regexp))))
5169 (org-cycle-hook
5170 (if bob-special
5171 (delq 'org-optimize-window-after-visibility-change
5172 (copy-sequence org-cycle-hook))
5173 org-cycle-hook))
5174 (pos (point)))
5176 (if (or bob-special (equal arg '(4)))
5177 ;; special case: use global cycling
5178 (setq arg t))
5180 (cond
5182 ((equal arg '(16))
5183 (org-set-startup-visibility)
5184 (message "Startup visibility, plus VISIBILITY properties"))
5186 ((equal arg '(64))
5187 (show-all)
5188 (message "Entire buffer visible, including drawers"))
5190 ((org-at-table-p 'any)
5191 ;; Enter the table or move to the next field in the table
5192 (or (org-table-recognize-table.el)
5193 (progn
5194 (if arg (org-table-edit-field t)
5195 (org-table-justify-field-maybe)
5196 (call-interactively 'org-table-next-field)))))
5198 ((run-hook-with-args-until-success
5199 'org-tab-after-check-for-table-hook))
5201 ((eq arg t) ;; Global cycling
5202 (org-cycle-internal-global))
5204 ((and org-drawers org-drawer-regexp
5205 (save-excursion
5206 (beginning-of-line 1)
5207 (looking-at org-drawer-regexp)))
5208 ;; Toggle block visibility
5209 (org-flag-drawer
5210 (not (get-char-property (match-end 0) 'invisible))))
5212 ((integerp arg)
5213 ;; Show-subtree, ARG levels up from here.
5214 (save-excursion
5215 (org-back-to-heading)
5216 (outline-up-heading (if (< arg 0) (- arg)
5217 (- (funcall outline-level) arg)))
5218 (org-show-subtree)))
5220 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5221 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5223 (org-cycle-internal-local))
5225 ;; TAB emulation and template completion
5226 (buffer-read-only (org-back-to-heading))
5228 ((run-hook-with-args-until-success
5229 'org-tab-after-check-for-cycling-hook))
5231 ((org-try-structure-completion))
5233 ((org-try-cdlatex-tab))
5235 ((run-hook-with-args-until-success
5236 'org-tab-before-tab-emulation-hook))
5238 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5239 (or (not (bolp))
5240 (not (looking-at outline-regexp))))
5241 (call-interactively (global-key-binding "\t")))
5243 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5244 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5245 (or (and (eq org-cycle-emulate-tab 'white)
5246 (= (match-end 0) (point-at-eol)))
5247 (and (eq org-cycle-emulate-tab 'whitestart)
5248 (>= (match-end 0) pos))))
5250 (eq org-cycle-emulate-tab t))
5251 (call-interactively (global-key-binding "\t")))
5253 (t (save-excursion
5254 (org-back-to-heading)
5255 (org-cycle)))))))
5257 (defun org-cycle-internal-global ()
5258 "Do the global cycling action."
5259 (cond
5260 ((and (eq last-command this-command)
5261 (eq org-cycle-global-status 'overview))
5262 ;; We just created the overview - now do table of contents
5263 ;; This can be slow in very large buffers, so indicate action
5264 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5265 (message "CONTENTS...")
5266 (org-content)
5267 (message "CONTENTS...done")
5268 (setq org-cycle-global-status 'contents)
5269 (run-hook-with-args 'org-cycle-hook 'contents))
5271 ((and (eq last-command this-command)
5272 (eq org-cycle-global-status 'contents))
5273 ;; We just showed the table of contents - now show everything
5274 (run-hook-with-args 'org-pre-cycle-hook 'all)
5275 (show-all)
5276 (message "SHOW ALL")
5277 (setq org-cycle-global-status 'all)
5278 (run-hook-with-args 'org-cycle-hook 'all))
5281 ;; Default action: go to overview
5282 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5283 (org-overview)
5284 (message "OVERVIEW")
5285 (setq org-cycle-global-status 'overview)
5286 (run-hook-with-args 'org-cycle-hook 'overview))))
5288 (defun org-cycle-internal-local ()
5289 "Do the local cycling action."
5290 (org-back-to-heading)
5291 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5292 ;; First, some boundaries
5293 (save-excursion
5294 (org-back-to-heading)
5295 (setq level (funcall outline-level))
5296 (save-excursion
5297 (beginning-of-line 2)
5298 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5299 ; XEmacs does not have `next-single-char-property-change'
5300 ; I'm not sure about Emacs 21.
5301 (while (and (not (eobp)) ;; this is like `next-line'
5302 (get-char-property (1- (point)) 'invisible))
5303 (beginning-of-line 2))
5304 (while (and (not (eobp)) ;; this is like `next-line'
5305 (get-char-property (1- (point)) 'invisible))
5306 (goto-char (next-single-char-property-change (point) 'invisible))
5307 ;;;??? (or (bolp) (beginning-of-line 2))))
5308 (and (eolp) (beginning-of-line 2))))
5309 (setq eol (point)))
5310 (outline-end-of-heading) (setq eoh (point))
5311 (save-excursion
5312 (outline-next-heading)
5313 (setq has-children (and (org-at-heading-p t)
5314 (> (funcall outline-level) level))))
5315 (org-end-of-subtree t)
5316 (unless (eobp)
5317 (skip-chars-forward " \t\n")
5318 (beginning-of-line 1) ; in case this is an item
5320 (setq eos (if (eobp) (point) (1- (point)))))
5321 ;; Find out what to do next and set `this-command'
5322 (cond
5323 ((= eos eoh)
5324 ;; Nothing is hidden behind this heading
5325 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5326 (message "EMPTY ENTRY")
5327 (setq org-cycle-subtree-status nil)
5328 (save-excursion
5329 (goto-char eos)
5330 (outline-next-heading)
5331 (if (org-invisible-p) (org-flag-heading nil))))
5332 ((and (or (>= eol eos)
5333 (not (string-match "\\S-" (buffer-substring eol eos))))
5334 (or has-children
5335 (not (setq children-skipped
5336 org-cycle-skip-children-state-if-no-children))))
5337 ;; Entire subtree is hidden in one line: children view
5338 (run-hook-with-args 'org-pre-cycle-hook 'children)
5339 (org-show-entry)
5340 (show-children)
5341 (message "CHILDREN")
5342 (save-excursion
5343 (goto-char eos)
5344 (outline-next-heading)
5345 (if (org-invisible-p) (org-flag-heading nil)))
5346 (setq org-cycle-subtree-status 'children)
5347 (run-hook-with-args 'org-cycle-hook 'children))
5348 ((or children-skipped
5349 (and (eq last-command this-command)
5350 (eq org-cycle-subtree-status 'children)))
5351 ;; We just showed the children, or no children are there,
5352 ;; now show everything.
5353 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5354 (org-show-subtree)
5355 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5356 (setq org-cycle-subtree-status 'subtree)
5357 (run-hook-with-args 'org-cycle-hook 'subtree))
5359 ;; Default action: hide the subtree.
5360 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5361 (hide-subtree)
5362 (message "FOLDED")
5363 (setq org-cycle-subtree-status 'folded)
5364 (run-hook-with-args 'org-cycle-hook 'folded)))))
5366 ;;;###autoload
5367 (defun org-global-cycle (&optional arg)
5368 "Cycle the global visibility. For details see `org-cycle'.
5369 With C-u prefix arg, switch to startup visibility.
5370 With a numeric prefix, show all headlines up to that level."
5371 (interactive "P")
5372 (let ((org-cycle-include-plain-lists
5373 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5374 (cond
5375 ((integerp arg)
5376 (show-all)
5377 (hide-sublevels arg)
5378 (setq org-cycle-global-status 'contents))
5379 ((equal arg '(4))
5380 (org-set-startup-visibility)
5381 (message "Startup visibility, plus VISIBILITY properties."))
5383 (org-cycle '(4))))))
5385 (defun org-set-startup-visibility ()
5386 "Set the visibility required by startup options and properties."
5387 (cond
5388 ((eq org-startup-folded t)
5389 (org-cycle '(4)))
5390 ((eq org-startup-folded 'content)
5391 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5392 (org-cycle '(4)) (org-cycle '(4)))))
5393 (unless (eq org-startup-folded 'showeverything)
5394 (if org-hide-block-startup (org-hide-block-all))
5395 (org-set-visibility-according-to-property 'no-cleanup)
5396 (org-cycle-hide-archived-subtrees 'all)
5397 (org-cycle-hide-drawers 'all)
5398 (org-cycle-show-empty-lines 'all)))
5400 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5401 "Switch subtree visibilities according to :VISIBILITY: property."
5402 (interactive)
5403 (let (org-show-entry-below state)
5404 (save-excursion
5405 (goto-char (point-min))
5406 (while (re-search-forward
5407 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5408 nil t)
5409 (setq state (match-string 1))
5410 (save-excursion
5411 (org-back-to-heading t)
5412 (hide-subtree)
5413 (org-reveal)
5414 (cond
5415 ((equal state '("fold" "folded"))
5416 (hide-subtree))
5417 ((equal state "children")
5418 (org-show-hidden-entry)
5419 (show-children))
5420 ((equal state "content")
5421 (save-excursion
5422 (save-restriction
5423 (org-narrow-to-subtree)
5424 (org-content))))
5425 ((member state '("all" "showall"))
5426 (show-subtree)))))
5427 (unless no-cleanup
5428 (org-cycle-hide-archived-subtrees 'all)
5429 (org-cycle-hide-drawers 'all)
5430 (org-cycle-show-empty-lines 'all)))))
5432 (defun org-overview ()
5433 "Switch to overview mode, showing only top-level headlines.
5434 Really, this shows all headlines with level equal or greater than the level
5435 of the first headline in the buffer. This is important, because if the
5436 first headline is not level one, then (hide-sublevels 1) gives confusing
5437 results."
5438 (interactive)
5439 (let ((level (save-excursion
5440 (goto-char (point-min))
5441 (if (re-search-forward (concat "^" outline-regexp) nil t)
5442 (progn
5443 (goto-char (match-beginning 0))
5444 (funcall outline-level))))))
5445 (and level (hide-sublevels level))))
5447 (defun org-content (&optional arg)
5448 "Show all headlines in the buffer, like a table of contents.
5449 With numerical argument N, show content up to level N."
5450 (interactive "P")
5451 (save-excursion
5452 ;; Visit all headings and show their offspring
5453 (and (integerp arg) (org-overview))
5454 (goto-char (point-max))
5455 (catch 'exit
5456 (while (and (progn (condition-case nil
5457 (outline-previous-visible-heading 1)
5458 (error (goto-char (point-min))))
5460 (looking-at outline-regexp))
5461 (if (integerp arg)
5462 (show-children (1- arg))
5463 (show-branches))
5464 (if (bobp) (throw 'exit nil))))))
5467 (defun org-optimize-window-after-visibility-change (state)
5468 "Adjust the window after a change in outline visibility.
5469 This function is the default value of the hook `org-cycle-hook'."
5470 (when (get-buffer-window (current-buffer))
5471 (cond
5472 ((eq state 'content) nil)
5473 ((eq state 'all) nil)
5474 ((eq state 'folded) nil)
5475 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5476 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5478 (defun org-remove-empty-overlays-at (pos)
5479 "Remove outline overlays that do not contain non-white stuff."
5480 (mapc
5481 (lambda (o)
5482 (and (eq 'outline (org-overlay-get o 'invisible))
5483 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5484 (org-overlay-end o))))
5485 (org-delete-overlay o)))
5486 (org-overlays-at pos)))
5488 (defun org-clean-visibility-after-subtree-move ()
5489 "Fix visibility issues after moving a subtree."
5490 ;; First, find a reasonable region to look at:
5491 ;; Start two siblings above, end three below
5492 (let* ((beg (save-excursion
5493 (and (org-get-last-sibling)
5494 (org-get-last-sibling))
5495 (point)))
5496 (end (save-excursion
5497 (and (org-get-next-sibling)
5498 (org-get-next-sibling)
5499 (org-get-next-sibling))
5500 (if (org-at-heading-p)
5501 (point-at-eol)
5502 (point))))
5503 (level (looking-at "\\*+"))
5504 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5505 (save-excursion
5506 (save-restriction
5507 (narrow-to-region beg end)
5508 (when re
5509 ;; Properly fold already folded siblings
5510 (goto-char (point-min))
5511 (while (re-search-forward re nil t)
5512 (if (and (not (org-invisible-p))
5513 (save-excursion
5514 (goto-char (point-at-eol)) (org-invisible-p)))
5515 (hide-entry))))
5516 (org-cycle-show-empty-lines 'overview)
5517 (org-cycle-hide-drawers 'overview)))))
5519 (defun org-cycle-show-empty-lines (state)
5520 "Show empty lines above all visible headlines.
5521 The region to be covered depends on STATE when called through
5522 `org-cycle-hook'. Lisp program can use t for STATE to get the
5523 entire buffer covered. Note that an empty line is only shown if there
5524 are at least `org-cycle-separator-lines' empty lines before the headline."
5525 (when (not (= org-cycle-separator-lines 0))
5526 (save-excursion
5527 (let* ((n (abs org-cycle-separator-lines))
5528 (re (cond
5529 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5530 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5531 (t (let ((ns (number-to-string (- n 2))))
5532 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5533 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5534 beg end b e)
5535 (cond
5536 ((memq state '(overview contents t))
5537 (setq beg (point-min) end (point-max)))
5538 ((memq state '(children folded))
5539 (setq beg (point) end (progn (org-end-of-subtree t t)
5540 (beginning-of-line 2)
5541 (point)))))
5542 (when beg
5543 (goto-char beg)
5544 (while (re-search-forward re end t)
5545 (unless (get-char-property (match-end 1) 'invisible)
5546 (setq e (match-end 1))
5547 (if (< org-cycle-separator-lines 0)
5548 (setq b (save-excursion
5549 (goto-char (match-beginning 0))
5550 (org-back-over-empty-lines)
5551 (if (save-excursion
5552 (goto-char (max (point-min) (1- (point))))
5553 (org-on-heading-p))
5554 (1- (point))
5555 (point))))
5556 (setq b (match-beginning 1)))
5557 (outline-flag-region b e nil)))))))
5558 ;; Never hide empty lines at the end of the file.
5559 (save-excursion
5560 (goto-char (point-max))
5561 (outline-previous-heading)
5562 (outline-end-of-heading)
5563 (if (and (looking-at "[ \t\n]+")
5564 (= (match-end 0) (point-max)))
5565 (outline-flag-region (point) (match-end 0) nil))))
5567 (defun org-show-empty-lines-in-parent ()
5568 "Move to the parent and re-show empty lines before visible headlines."
5569 (save-excursion
5570 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5571 (org-cycle-show-empty-lines context))))
5573 (defun org-files-list ()
5574 "Return `org-agenda-files' list, plus all open org-mode files.
5575 This is useful for operations that need to scan all of a user's
5576 open and agenda-wise Org files."
5577 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5578 (dolist (buf (buffer-list))
5579 (with-current-buffer buf
5580 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5581 (let ((file (expand-file-name (buffer-file-name))))
5582 (unless (member file files)
5583 (push file files))))))
5584 files))
5586 (defsubst org-entry-beginning-position ()
5587 "Return the beginning position of the current entry."
5588 (save-excursion (outline-back-to-heading t) (point)))
5590 (defsubst org-entry-end-position ()
5591 "Return the end position of the current entry."
5592 (save-excursion (outline-next-heading) (point)))
5594 (defun org-cycle-hide-drawers (state)
5595 "Re-hide all drawers after a visibility state change."
5596 (when (and (org-mode-p)
5597 (not (memq state '(overview folded contents))))
5598 (save-excursion
5599 (let* ((globalp (memq state '(contents all)))
5600 (beg (if globalp (point-min) (point)))
5601 (end (if globalp (point-max)
5602 (if (eq state 'children)
5603 (save-excursion (outline-next-heading) (point))
5604 (org-end-of-subtree t)))))
5605 (goto-char beg)
5606 (while (re-search-forward org-drawer-regexp end t)
5607 (org-flag-drawer t))))))
5609 (defun org-flag-drawer (flag)
5610 (save-excursion
5611 (beginning-of-line 1)
5612 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5613 (let ((b (match-end 0))
5614 (outline-regexp org-outline-regexp))
5615 (if (re-search-forward
5616 "^[ \t]*:END:"
5617 (save-excursion (outline-next-heading) (point)) t)
5618 (outline-flag-region b (point-at-eol) flag)
5619 (error ":END: line missing at position %s" b))))))
5621 (defun org-subtree-end-visible-p ()
5622 "Is the end of the current subtree visible?"
5623 (pos-visible-in-window-p
5624 (save-excursion (org-end-of-subtree t) (point))))
5626 (defun org-first-headline-recenter (&optional N)
5627 "Move cursor to the first headline and recenter the headline.
5628 Optional argument N means, put the headline into the Nth line of the window."
5629 (goto-char (point-min))
5630 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5631 (beginning-of-line)
5632 (recenter (prefix-numeric-value N))))
5634 ;;; Saving and restoring visibility
5636 (defun org-outline-overlay-data (&optional use-markers)
5637 "Return a list of the locations of all outline overlays.
5638 The are overlays with the `invisible' property value `outline'.
5639 The return valus is a list of cons cells, with start and stop
5640 positions for each overlay.
5641 If USE-MARKERS is set, return the positions as markers."
5642 (let (beg end)
5643 (save-excursion
5644 (save-restriction
5645 (widen)
5646 (delq nil
5647 (mapcar (lambda (o)
5648 (when (eq (org-overlay-get o 'invisible) 'outline)
5649 (setq beg (org-overlay-start o)
5650 end (org-overlay-end o))
5651 (and beg end (> end beg)
5652 (if use-markers
5653 (cons (move-marker (make-marker) beg)
5654 (move-marker (make-marker) end))
5655 (cons beg end)))))
5656 (org-overlays-in (point-min) (point-max))))))))
5658 (defun org-set-outline-overlay-data (data)
5659 "Create visibility overlays for all positions in DATA.
5660 DATA should have been made by `org-outline-overlay-data'."
5661 (let (o)
5662 (save-excursion
5663 (save-restriction
5664 (widen)
5665 (show-all)
5666 (mapc (lambda (c)
5667 (setq o (org-make-overlay (car c) (cdr c)))
5668 (org-overlay-put o 'invisible 'outline))
5669 data)))))
5671 (defmacro org-save-outline-visibility (use-markers &rest body)
5672 "Save and restore outline visibility around BODY.
5673 If USE-MARKERS is non-nil, use markers for the positions.
5674 This means that the buffer may change while running BODY,
5675 but it also means that the buffer should stay alive
5676 during the operation, because otherwise all these markers will
5677 point nowhere."
5678 `(let ((data (org-outline-overlay-data ,use-markers)))
5679 (unwind-protect
5680 (progn
5681 ,@body
5682 (org-set-outline-overlay-data data))
5683 (when ,use-markers
5684 (mapc (lambda (c)
5685 (and (markerp (car c)) (move-marker (car c) nil))
5686 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5687 data)))))
5690 ;;; Folding of blocks
5692 (defconst org-block-regexp
5694 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5695 "Regular expression for hiding blocks.")
5697 (defvar org-hide-block-overlays nil
5698 "Overlays hiding blocks.")
5699 (make-variable-buffer-local 'org-hide-block-overlays)
5701 (defun org-block-map (function &optional start end)
5702 "Call func at the head of all source blocks in the current
5703 buffer. Optional arguments START and END can be used to limit
5704 the range."
5705 (let ((start (or start (point-min)))
5706 (end (or end (point-max))))
5707 (save-excursion
5708 (goto-char start)
5709 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5710 (save-excursion
5711 (save-match-data
5712 (goto-char (match-beginning 0))
5713 (funcall function)))))))
5715 (defun org-hide-block-toggle-all ()
5716 "Toggle the visibility of all blocks in the current buffer."
5717 (org-block-map #'org-hide-block-toggle))
5719 (defun org-hide-block-all ()
5720 "Fold all blocks in the current buffer."
5721 (interactive)
5722 (org-show-block-all)
5723 (org-block-map #'org-hide-block-toggle-maybe))
5725 (defun org-show-block-all ()
5726 "Unfold all blocks in the current buffer."
5727 (mapc 'org-delete-overlay org-hide-block-overlays)
5728 (setq org-hide-block-overlays nil))
5730 (defun org-hide-block-toggle-maybe ()
5731 "Toggle visibility of block at point."
5732 (interactive)
5733 (let ((case-fold-search t))
5734 (if (save-excursion
5735 (beginning-of-line 1)
5736 (looking-at org-block-regexp))
5737 (progn (org-hide-block-toggle)
5738 t) ;; to signal that we took action
5739 nil))) ;; to signal that we did not
5741 (defun org-hide-block-toggle (&optional force)
5742 "Toggle the visibility of the current block."
5743 (interactive)
5744 (save-excursion
5745 (beginning-of-line)
5746 (if (re-search-forward org-block-regexp nil t)
5747 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5748 (end (match-end 0)) ;; end of entire body
5750 (if (memq t (mapcar (lambda (overlay)
5751 (eq (org-overlay-get overlay 'invisible)
5752 'org-hide-block))
5753 (org-overlays-at start)))
5754 (if (or (not force) (eq force 'off))
5755 (mapc (lambda (ov)
5756 (when (member ov org-hide-block-overlays)
5757 (setq org-hide-block-overlays
5758 (delq ov org-hide-block-overlays)))
5759 (when (eq (org-overlay-get ov 'invisible)
5760 'org-hide-block)
5761 (org-delete-overlay ov)))
5762 (org-overlays-at start)))
5763 (setq ov (org-make-overlay start end))
5764 (org-overlay-put ov 'invisible 'org-hide-block)
5765 ;; make the block accessible to isearch
5766 (org-overlay-put
5767 ov 'isearch-open-invisible
5768 (lambda (ov)
5769 (when (member ov org-hide-block-overlays)
5770 (setq org-hide-block-overlays
5771 (delq ov org-hide-block-overlays)))
5772 (when (eq (org-overlay-get ov 'invisible)
5773 'org-hide-block)
5774 (org-delete-overlay ov))))
5775 (push ov org-hide-block-overlays)))
5776 (error "Not looking at a source block"))))
5778 ;; org-tab-after-check-for-cycling-hook
5779 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5780 ;; Remove overlays when changing major mode
5781 (add-hook 'org-mode-hook
5782 (lambda () (org-add-hook 'change-major-mode-hook
5783 'org-show-block-all 'append 'local)))
5785 ;;; Org-goto
5787 (defvar org-goto-window-configuration nil)
5788 (defvar org-goto-marker nil)
5789 (defvar org-goto-map
5790 (let ((map (make-sparse-keymap)))
5791 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5792 (while (setq cmd (pop cmds))
5793 (substitute-key-definition cmd cmd map global-map)))
5794 (suppress-keymap map)
5795 (org-defkey map "\C-m" 'org-goto-ret)
5796 (org-defkey map [(return)] 'org-goto-ret)
5797 (org-defkey map [(left)] 'org-goto-left)
5798 (org-defkey map [(right)] 'org-goto-right)
5799 (org-defkey map [(control ?g)] 'org-goto-quit)
5800 (org-defkey map "\C-i" 'org-cycle)
5801 (org-defkey map [(tab)] 'org-cycle)
5802 (org-defkey map [(down)] 'outline-next-visible-heading)
5803 (org-defkey map [(up)] 'outline-previous-visible-heading)
5804 (if org-goto-auto-isearch
5805 (if (fboundp 'define-key-after)
5806 (define-key-after map [t] 'org-goto-local-auto-isearch)
5807 nil)
5808 (org-defkey map "q" 'org-goto-quit)
5809 (org-defkey map "n" 'outline-next-visible-heading)
5810 (org-defkey map "p" 'outline-previous-visible-heading)
5811 (org-defkey map "f" 'outline-forward-same-level)
5812 (org-defkey map "b" 'outline-backward-same-level)
5813 (org-defkey map "u" 'outline-up-heading))
5814 (org-defkey map "/" 'org-occur)
5815 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5816 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5817 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5818 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5819 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5820 map))
5822 (defconst org-goto-help
5823 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5824 RET=jump to location [Q]uit and return to previous location
5825 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5827 (defvar org-goto-start-pos) ; dynamically scoped parameter
5829 ;; FIXME: Docstring does not mention both interfaces
5830 (defun org-goto (&optional alternative-interface)
5831 "Look up a different location in the current file, keeping current visibility.
5833 When you want look-up or go to a different location in a document, the
5834 fastest way is often to fold the entire buffer and then dive into the tree.
5835 This method has the disadvantage, that the previous location will be folded,
5836 which may not be what you want.
5838 This command works around this by showing a copy of the current buffer
5839 in an indirect buffer, in overview mode. You can dive into the tree in
5840 that copy, use org-occur and incremental search to find a location.
5841 When pressing RET or `Q', the command returns to the original buffer in
5842 which the visibility is still unchanged. After RET is will also jump to
5843 the location selected in the indirect buffer and expose the
5844 the headline hierarchy above."
5845 (interactive "P")
5846 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5847 (org-refile-use-outline-path t)
5848 (org-refile-target-verify-function nil)
5849 (interface
5850 (if (not alternative-interface)
5851 org-goto-interface
5852 (if (eq org-goto-interface 'outline)
5853 'outline-path-completion
5854 'outline)))
5855 (org-goto-start-pos (point))
5856 (selected-point
5857 (if (eq interface 'outline)
5858 (car (org-get-location (current-buffer) org-goto-help))
5859 (nth 3 (org-refile-get-location "Goto: ")))))
5860 (if selected-point
5861 (progn
5862 (org-mark-ring-push org-goto-start-pos)
5863 (goto-char selected-point)
5864 (if (or (org-invisible-p) (org-invisible-p2))
5865 (org-show-context 'org-goto)))
5866 (message "Quit"))))
5868 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5869 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5870 (defvar org-goto-local-auto-isearch-map) ; defined below
5872 (defun org-get-location (buf help)
5873 "Let the user select a location in the Org-mode buffer BUF.
5874 This function uses a recursive edit. It returns the selected position
5875 or nil."
5876 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5877 (isearch-hide-immediately nil)
5878 (isearch-search-fun-function
5879 (lambda () 'org-goto-local-search-headings))
5880 (org-goto-selected-point org-goto-exit-command))
5881 (save-excursion
5882 (save-window-excursion
5883 (delete-other-windows)
5884 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5885 (switch-to-buffer
5886 (condition-case nil
5887 (make-indirect-buffer (current-buffer) "*org-goto*")
5888 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5889 (with-output-to-temp-buffer "*Help*"
5890 (princ help))
5891 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5892 (setq buffer-read-only nil)
5893 (let ((org-startup-truncated t)
5894 (org-startup-folded nil)
5895 (org-startup-align-all-tables nil))
5896 (org-mode)
5897 (org-overview))
5898 (setq buffer-read-only t)
5899 (if (and (boundp 'org-goto-start-pos)
5900 (integer-or-marker-p org-goto-start-pos))
5901 (let ((org-show-hierarchy-above t)
5902 (org-show-siblings t)
5903 (org-show-following-heading t))
5904 (goto-char org-goto-start-pos)
5905 (and (org-invisible-p) (org-show-context)))
5906 (goto-char (point-min)))
5907 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5908 (message "Select location and press RET")
5909 (use-local-map org-goto-map)
5910 (recursive-edit)
5912 (kill-buffer "*org-goto*")
5913 (cons org-goto-selected-point org-goto-exit-command)))
5915 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5916 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5917 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5918 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5920 (defun org-goto-local-search-headings (string bound noerror)
5921 "Search and make sure that any matches are in headlines."
5922 (catch 'return
5923 (while (if isearch-forward
5924 (search-forward string bound noerror)
5925 (search-backward string bound noerror))
5926 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5927 (and (member :headline context)
5928 (not (member :tags context))))
5929 (throw 'return (point))))))
5931 (defun org-goto-local-auto-isearch ()
5932 "Start isearch."
5933 (interactive)
5934 (goto-char (point-min))
5935 (let ((keys (this-command-keys)))
5936 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5937 (isearch-mode t)
5938 (isearch-process-search-char (string-to-char keys)))))
5940 (defun org-goto-ret (&optional arg)
5941 "Finish `org-goto' by going to the new location."
5942 (interactive "P")
5943 (setq org-goto-selected-point (point)
5944 org-goto-exit-command 'return)
5945 (throw 'exit nil))
5947 (defun org-goto-left ()
5948 "Finish `org-goto' by going to the new location."
5949 (interactive)
5950 (if (org-on-heading-p)
5951 (progn
5952 (beginning-of-line 1)
5953 (setq org-goto-selected-point (point)
5954 org-goto-exit-command 'left)
5955 (throw 'exit nil))
5956 (error "Not on a heading")))
5958 (defun org-goto-right ()
5959 "Finish `org-goto' by going to the new location."
5960 (interactive)
5961 (if (org-on-heading-p)
5962 (progn
5963 (setq org-goto-selected-point (point)
5964 org-goto-exit-command 'right)
5965 (throw 'exit nil))
5966 (error "Not on a heading")))
5968 (defun org-goto-quit ()
5969 "Finish `org-goto' without cursor motion."
5970 (interactive)
5971 (setq org-goto-selected-point nil)
5972 (setq org-goto-exit-command 'quit)
5973 (throw 'exit nil))
5975 ;;; Indirect buffer display of subtrees
5977 (defvar org-indirect-dedicated-frame nil
5978 "This is the frame being used for indirect tree display.")
5979 (defvar org-last-indirect-buffer nil)
5981 (defun org-tree-to-indirect-buffer (&optional arg)
5982 "Create indirect buffer and narrow it to current subtree.
5983 With numerical prefix ARG, go up to this level and then take that tree.
5984 If ARG is negative, go up that many levels.
5985 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5986 indirect buffer previously made with this command, to avoid proliferation of
5987 indirect buffers. However, when you call the command with a `C-u' prefix, or
5988 when `org-indirect-buffer-display' is `new-frame', the last buffer
5989 is kept so that you can work with several indirect buffers at the same time.
5990 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5991 requests that a new frame be made for the new buffer, so that the dedicated
5992 frame is not changed."
5993 (interactive "P")
5994 (let ((cbuf (current-buffer))
5995 (cwin (selected-window))
5996 (pos (point))
5997 beg end level heading ibuf)
5998 (save-excursion
5999 (org-back-to-heading t)
6000 (when (numberp arg)
6001 (setq level (org-outline-level))
6002 (if (< arg 0) (setq arg (+ level arg)))
6003 (while (> (setq level (org-outline-level)) arg)
6004 (outline-up-heading 1 t)))
6005 (setq beg (point)
6006 heading (org-get-heading))
6007 (org-end-of-subtree t t) (setq end (point)))
6008 (if (and (buffer-live-p org-last-indirect-buffer)
6009 (not (eq org-indirect-buffer-display 'new-frame))
6010 (not arg))
6011 (kill-buffer org-last-indirect-buffer))
6012 (setq ibuf (org-get-indirect-buffer cbuf)
6013 org-last-indirect-buffer ibuf)
6014 (cond
6015 ((or (eq org-indirect-buffer-display 'new-frame)
6016 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6017 (select-frame (make-frame))
6018 (delete-other-windows)
6019 (switch-to-buffer ibuf)
6020 (org-set-frame-title heading))
6021 ((eq org-indirect-buffer-display 'dedicated-frame)
6022 (raise-frame
6023 (select-frame (or (and org-indirect-dedicated-frame
6024 (frame-live-p org-indirect-dedicated-frame)
6025 org-indirect-dedicated-frame)
6026 (setq org-indirect-dedicated-frame (make-frame)))))
6027 (delete-other-windows)
6028 (switch-to-buffer ibuf)
6029 (org-set-frame-title (concat "Indirect: " heading)))
6030 ((eq org-indirect-buffer-display 'current-window)
6031 (switch-to-buffer ibuf))
6032 ((eq org-indirect-buffer-display 'other-window)
6033 (pop-to-buffer ibuf))
6034 (t (error "Invalid value")))
6035 (if (featurep 'xemacs)
6036 (save-excursion (org-mode) (turn-on-font-lock)))
6037 (narrow-to-region beg end)
6038 (show-all)
6039 (goto-char pos)
6040 (and (window-live-p cwin) (select-window cwin))))
6042 (defun org-get-indirect-buffer (&optional buffer)
6043 (setq buffer (or buffer (current-buffer)))
6044 (let ((n 1) (base (buffer-name buffer)) bname)
6045 (while (buffer-live-p
6046 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6047 (setq n (1+ n)))
6048 (condition-case nil
6049 (make-indirect-buffer buffer bname 'clone)
6050 (error (make-indirect-buffer buffer bname)))))
6052 (defun org-set-frame-title (title)
6053 "Set the title of the current frame to the string TITLE."
6054 ;; FIXME: how to name a single frame in XEmacs???
6055 (unless (featurep 'xemacs)
6056 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6058 ;;;; Structure editing
6060 ;;; Inserting headlines
6062 (defun org-previous-line-empty-p ()
6063 (save-excursion
6064 (and (not (bobp))
6065 (or (beginning-of-line 0) t)
6066 (save-match-data
6067 (looking-at "[ \t]*$")))))
6069 (defun org-insert-heading (&optional force-heading)
6070 "Insert a new heading or item with same depth at point.
6071 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6072 If point is at the beginning of a headline, insert a sibling before the
6073 current headline. If point is not at the beginning, do not split the line,
6074 but create the new headline after the current line."
6075 (interactive "P")
6076 (if (or (= (buffer-size) 0)
6077 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
6078 (org-on-heading-p))))
6079 (not (org-in-item-p))))
6080 (insert "\n* ")
6081 (when (or force-heading (not (org-insert-item)))
6082 (let* ((empty-line-p nil)
6083 (head (save-excursion
6084 (condition-case nil
6085 (progn
6086 (org-back-to-heading)
6087 (setq empty-line-p (org-previous-line-empty-p))
6088 (match-string 0))
6089 (error "*"))))
6090 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6091 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6092 pos hide-previous previous-pos)
6093 (cond
6094 ((and (org-on-heading-p) (bolp)
6095 (or (bobp)
6096 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6097 ;; insert before the current line
6098 (open-line (if blank 2 1)))
6099 ((and (bolp)
6100 (not org-insert-heading-respect-content)
6101 (or (bobp)
6102 (save-excursion
6103 (backward-char 1) (not (org-invisible-p)))))
6104 ;; insert right here
6105 nil)
6107 ;; somewhere in the line
6108 (save-excursion
6109 (setq previous-pos (point-at-bol))
6110 (end-of-line)
6111 (setq hide-previous (org-invisible-p)))
6112 (and org-insert-heading-respect-content (org-show-subtree))
6113 (let ((split
6114 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6115 (save-excursion
6116 (let ((p (point)))
6117 (goto-char (point-at-bol))
6118 (and (looking-at org-complex-heading-regexp)
6119 (> p (match-beginning 4)))))))
6120 tags pos)
6121 (cond
6122 (org-insert-heading-respect-content
6123 (org-end-of-subtree nil t)
6124 (or (bolp) (newline))
6125 (or (org-previous-line-empty-p)
6126 (and blank (newline)))
6127 (open-line 1))
6128 ((org-on-heading-p)
6129 (when hide-previous
6130 (show-children)
6131 (org-show-entry))
6132 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6133 (setq tags (and (match-end 2) (match-string 2)))
6134 (and (match-end 1)
6135 (delete-region (match-beginning 1) (match-end 1)))
6136 (setq pos (point-at-bol))
6137 (or split (end-of-line 1))
6138 (delete-horizontal-space)
6139 (newline (if blank 2 1))
6140 (when tags
6141 (save-excursion
6142 (goto-char pos)
6143 (end-of-line 1)
6144 (insert " " tags)
6145 (org-set-tags nil 'align))))
6147 (or split (end-of-line 1))
6148 (newline (if blank 2 1)))))))
6149 (insert head) (just-one-space)
6150 (setq pos (point))
6151 (end-of-line 1)
6152 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6153 (when (and org-insert-heading-respect-content hide-previous)
6154 (save-excursion
6155 (goto-char previous-pos)
6156 (hide-subtree)))
6157 (run-hooks 'org-insert-heading-hook)))))
6159 (defun org-get-heading (&optional no-tags)
6160 "Return the heading of the current entry, without the stars."
6161 (save-excursion
6162 (org-back-to-heading t)
6163 (if (looking-at
6164 (if no-tags
6165 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6166 "\\*+[ \t]+\\([^\r\n]*\\)"))
6167 (match-string 1) "")))
6169 (defun org-heading-components ()
6170 "Return the components of the current heading.
6171 This is a list with the following elements:
6172 - the level as an integer
6173 - the reduced level, different if `org-odd-levels-only' is set.
6174 - the TODO keyword, or nil
6175 - the priority character, like ?A, or nil if no priority is given
6176 - the headline text itself, or the tags string if no headline text
6177 - the tags string, or nil."
6178 (save-excursion
6179 (org-back-to-heading t)
6180 (if (looking-at org-complex-heading-regexp)
6181 (list (length (match-string 1))
6182 (org-reduced-level (length (match-string 1)))
6183 (org-match-string-no-properties 2)
6184 (and (match-end 3) (aref (match-string 3) 2))
6185 (org-match-string-no-properties 4)
6186 (org-match-string-no-properties 5)))))
6188 (defun org-get-entry ()
6189 "Get the entry text, after heading, entire subtree."
6190 (save-excursion
6191 (org-back-to-heading t)
6192 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6194 (defun org-insert-heading-after-current ()
6195 "Insert a new heading with same level as current, after current subtree."
6196 (interactive)
6197 (org-back-to-heading)
6198 (org-insert-heading)
6199 (org-move-subtree-down)
6200 (end-of-line 1))
6202 (defun org-insert-heading-respect-content ()
6203 (interactive)
6204 (let ((org-insert-heading-respect-content t))
6205 (org-insert-heading t)))
6207 (defun org-insert-todo-heading-respect-content (&optional force-state)
6208 (interactive "P")
6209 (let ((org-insert-heading-respect-content t))
6210 (org-insert-todo-heading force-state t)))
6212 (defun org-insert-todo-heading (arg &optional force-heading)
6213 "Insert a new heading with the same level and TODO state as current heading.
6214 If the heading has no TODO state, or if the state is DONE, use the first
6215 state (TODO by default). Also with prefix arg, force first state."
6216 (interactive "P")
6217 (when (or force-heading (not (org-insert-item 'checkbox)))
6218 (org-insert-heading force-heading)
6219 (save-excursion
6220 (org-back-to-heading)
6221 (outline-previous-heading)
6222 (looking-at org-todo-line-regexp))
6223 (let*
6224 ((new-mark-x
6225 (if (or arg
6226 (not (match-beginning 2))
6227 (member (match-string 2) org-done-keywords))
6228 (car org-todo-keywords-1)
6229 (match-string 2)))
6230 (new-mark
6232 (run-hook-with-args-until-success
6233 'org-todo-get-default-hook new-mark-x nil)
6234 new-mark-x)))
6235 (beginning-of-line 1)
6236 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6237 (if org-treat-insert-todo-heading-as-state-change
6238 (org-todo new-mark)
6239 (insert new-mark " "))))
6240 (when org-provide-todo-statistics
6241 (org-update-parent-todo-statistics))))
6243 (defun org-insert-subheading (arg)
6244 "Insert a new subheading and demote it.
6245 Works for outline headings and for plain lists alike."
6246 (interactive "P")
6247 (org-insert-heading arg)
6248 (cond
6249 ((org-on-heading-p) (org-do-demote))
6250 ((org-at-item-p) (org-indent-item 1))))
6252 (defun org-insert-todo-subheading (arg)
6253 "Insert a new subheading with TODO keyword or checkbox and demote it.
6254 Works for outline headings and for plain lists alike."
6255 (interactive "P")
6256 (org-insert-todo-heading arg)
6257 (cond
6258 ((org-on-heading-p) (org-do-demote))
6259 ((org-at-item-p) (org-indent-item 1))))
6261 ;;; Promotion and Demotion
6263 (defvar org-after-demote-entry-hook nil
6264 "Hook run after an entry has been demoted.
6265 The cursor will be at the beginning of the entry.
6266 When a subtree is being demoted, the hook will be called for each node.")
6268 (defvar org-after-promote-entry-hook nil
6269 "Hook run after an entry has been promoted.
6270 The cursor will be at the beginning of the entry.
6271 When a subtree is being promoted, the hook will be called for each node.")
6273 (defun org-promote-subtree ()
6274 "Promote the entire subtree.
6275 See also `org-promote'."
6276 (interactive)
6277 (save-excursion
6278 (org-map-tree 'org-promote))
6279 (org-fix-position-after-promote))
6281 (defun org-demote-subtree ()
6282 "Demote the entire subtree. See `org-demote'.
6283 See also `org-promote'."
6284 (interactive)
6285 (save-excursion
6286 (org-map-tree 'org-demote))
6287 (org-fix-position-after-promote))
6290 (defun org-do-promote ()
6291 "Promote the current heading higher up the tree.
6292 If the region is active in `transient-mark-mode', promote all headings
6293 in the region."
6294 (interactive)
6295 (save-excursion
6296 (if (org-region-active-p)
6297 (org-map-region 'org-promote (region-beginning) (region-end))
6298 (org-promote)))
6299 (org-fix-position-after-promote))
6301 (defun org-do-demote ()
6302 "Demote the current heading lower down the tree.
6303 If the region is active in `transient-mark-mode', demote all headings
6304 in the region."
6305 (interactive)
6306 (save-excursion
6307 (if (org-region-active-p)
6308 (org-map-region 'org-demote (region-beginning) (region-end))
6309 (org-demote)))
6310 (org-fix-position-after-promote))
6312 (defun org-fix-position-after-promote ()
6313 "Make sure that after pro/demotion cursor position is right."
6314 (let ((pos (point)))
6315 (when (save-excursion
6316 (beginning-of-line 1)
6317 (looking-at org-todo-line-regexp)
6318 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6319 (cond ((eobp) (insert " "))
6320 ((eolp) (insert " "))
6321 ((equal (char-after) ?\ ) (forward-char 1))))))
6323 (defun org-current-level ()
6324 "Return the level of the current entry, or nil if before the first headline.
6325 The level is the number of stars at the beginning of the headline."
6326 (save-excursion
6327 (condition-case nil
6328 (progn
6329 (org-back-to-heading t)
6330 (funcall outline-level))
6331 (error nil))))
6333 (defun org-reduced-level (l)
6334 "Compute the effective level of a heading.
6335 This takes into account the setting of `org-odd-levels-only'."
6336 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6338 (defun org-get-valid-level (level &optional change)
6339 "Rectify a level change under the influence of `org-odd-levels-only'
6340 LEVEL is a current level, CHANGE is by how much the level should be
6341 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6342 even level numbers will become the next higher odd number."
6343 (if org-odd-levels-only
6344 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6345 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6346 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6347 (max 1 (+ level (or change 0)))))
6349 (if (boundp 'define-obsolete-function-alias)
6350 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6351 (define-obsolete-function-alias 'org-get-legal-level
6352 'org-get-valid-level)
6353 (define-obsolete-function-alias 'org-get-legal-level
6354 'org-get-valid-level "23.1")))
6356 (defun org-promote ()
6357 "Promote the current heading higher up the tree.
6358 If the region is active in `transient-mark-mode', promote all headings
6359 in the region."
6360 (org-back-to-heading t)
6361 (let* ((level (save-match-data (funcall outline-level)))
6362 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6363 (diff (abs (- level (length up-head) -1))))
6364 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6365 (replace-match up-head nil t)
6366 ;; Fixup tag positioning
6367 (and org-auto-align-tags (org-set-tags nil t))
6368 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6369 (run-hooks 'org-after-promote-entry-hook)))
6371 (defun org-demote ()
6372 "Demote the current heading lower down the tree.
6373 If the region is active in `transient-mark-mode', demote all headings
6374 in the region."
6375 (org-back-to-heading t)
6376 (let* ((level (save-match-data (funcall outline-level)))
6377 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6378 (diff (abs (- level (length down-head) -1))))
6379 (replace-match down-head nil t)
6380 ;; Fixup tag positioning
6381 (and org-auto-align-tags (org-set-tags nil t))
6382 (if org-adapt-indentation (org-fixup-indentation diff))
6383 (run-hooks 'org-after-demote-entry-hook)))
6385 (defvar org-tab-ind-state nil)
6387 (defun org-cycle-level ()
6388 (let ((org-adapt-indentation nil))
6389 (when (and (looking-at "[ \t]*$")
6390 (org-looking-back
6391 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6392 (setq this-command 'org-cycle-level)
6393 (if (eq last-command 'org-cycle-level)
6394 (condition-case nil
6395 (progn (org-do-promote)
6396 (if (equal org-tab-ind-state (org-current-level))
6397 (org-do-promote)))
6398 (error
6399 (progn
6400 (save-excursion
6401 (beginning-of-line 1)
6402 (and (looking-at "\\*+")
6403 (replace-match
6404 (make-string org-tab-ind-state ?*))))
6405 (setq this-command 'org-cycle))))
6406 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6407 (org-do-demote))
6408 t)))
6410 (defun org-map-tree (fun)
6411 "Call FUN for every heading underneath the current one."
6412 (org-back-to-heading)
6413 (let ((level (funcall outline-level)))
6414 (save-excursion
6415 (funcall fun)
6416 (while (and (progn
6417 (outline-next-heading)
6418 (> (funcall outline-level) level))
6419 (not (eobp)))
6420 (funcall fun)))))
6422 (defun org-map-region (fun beg end)
6423 "Call FUN for every heading between BEG and END."
6424 (let ((org-ignore-region t))
6425 (save-excursion
6426 (setq end (copy-marker end))
6427 (goto-char beg)
6428 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6429 (< (point) end))
6430 (funcall fun))
6431 (while (and (progn
6432 (outline-next-heading)
6433 (< (point) end))
6434 (not (eobp)))
6435 (funcall fun)))))
6437 (defun org-fixup-indentation (diff)
6438 "Change the indentation in the current entry by DIFF
6439 However, if any line in the current entry has no indentation, or if it
6440 would end up with no indentation after the change, nothing at all is done."
6441 (save-excursion
6442 (let ((end (save-excursion (outline-next-heading)
6443 (point-marker)))
6444 (prohibit (if (> diff 0)
6445 "^\\S-"
6446 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6447 col)
6448 (unless (save-excursion (end-of-line 1)
6449 (re-search-forward prohibit end t))
6450 (while (and (< (point) end)
6451 (re-search-forward "^[ \t]+" end t))
6452 (goto-char (match-end 0))
6453 (setq col (current-column))
6454 (if (< diff 0) (replace-match ""))
6455 (org-indent-to-column (+ diff col))))
6456 (move-marker end nil))))
6458 (defun org-convert-to-odd-levels ()
6459 "Convert an org-mode file with all levels allowed to one with odd levels.
6460 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6461 level 5 etc."
6462 (interactive)
6463 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6464 (let ((outline-regexp org-outline-regexp)
6465 (outline-level 'org-outline-level)
6466 (org-odd-levels-only nil) n)
6467 (save-excursion
6468 (goto-char (point-min))
6469 (while (re-search-forward "^\\*\\*+ " nil t)
6470 (setq n (- (length (match-string 0)) 2))
6471 (while (>= (setq n (1- n)) 0)
6472 (org-demote))
6473 (end-of-line 1))))))
6475 (defun org-convert-to-oddeven-levels ()
6476 "Convert an org-mode file with only odd levels to one with odd and even levels.
6477 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6478 section with an even level, conversion would destroy the structure of the file. An error
6479 is signaled in this case."
6480 (interactive)
6481 (goto-char (point-min))
6482 ;; First check if there are no even levels
6483 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6484 (org-show-context t)
6485 (error "Not all levels are odd in this file. Conversion not possible"))
6486 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6487 (let ((outline-regexp org-outline-regexp)
6488 (outline-level 'org-outline-level)
6489 (org-odd-levels-only nil) n)
6490 (save-excursion
6491 (goto-char (point-min))
6492 (while (re-search-forward "^\\*\\*+ " nil t)
6493 (setq n (/ (1- (length (match-string 0))) 2))
6494 (while (>= (setq n (1- n)) 0)
6495 (org-promote))
6496 (end-of-line 1))))))
6498 (defun org-tr-level (n)
6499 "Make N odd if required."
6500 (if org-odd-levels-only (1+ (/ n 2)) n))
6502 ;;; Vertical tree motion, cutting and pasting of subtrees
6504 (defun org-move-subtree-up (&optional arg)
6505 "Move the current subtree up past ARG headlines of the same level."
6506 (interactive "p")
6507 (org-move-subtree-down (- (prefix-numeric-value arg))))
6509 (defun org-move-subtree-down (&optional arg)
6510 "Move the current subtree down past ARG headlines of the same level."
6511 (interactive "p")
6512 (setq arg (prefix-numeric-value arg))
6513 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6514 'org-get-last-sibling))
6515 (ins-point (make-marker))
6516 (cnt (abs arg))
6517 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6518 ;; Select the tree
6519 (org-back-to-heading)
6520 (setq beg0 (point))
6521 (save-excursion
6522 (setq ne-beg (org-back-over-empty-lines))
6523 (setq beg (point)))
6524 (save-match-data
6525 (save-excursion (outline-end-of-heading)
6526 (setq folded (org-invisible-p)))
6527 (outline-end-of-subtree))
6528 (outline-next-heading)
6529 (setq ne-end (org-back-over-empty-lines))
6530 (setq end (point))
6531 (goto-char beg0)
6532 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6533 ;; include less whitespace
6534 (save-excursion
6535 (goto-char beg)
6536 (forward-line (- ne-beg ne-end))
6537 (setq beg (point))))
6538 ;; Find insertion point, with error handling
6539 (while (> cnt 0)
6540 (or (and (funcall movfunc) (looking-at outline-regexp))
6541 (progn (goto-char beg0)
6542 (error "Cannot move past superior level or buffer limit")))
6543 (setq cnt (1- cnt)))
6544 (if (> arg 0)
6545 ;; Moving forward - still need to move over subtree
6546 (progn (org-end-of-subtree t t)
6547 (save-excursion
6548 (org-back-over-empty-lines)
6549 (or (bolp) (newline)))))
6550 (setq ne-ins (org-back-over-empty-lines))
6551 (move-marker ins-point (point))
6552 (setq txt (buffer-substring beg end))
6553 (org-save-markers-in-region beg end)
6554 (delete-region beg end)
6555 (org-remove-empty-overlays-at beg)
6556 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6557 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6558 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6559 (let ((bbb (point)))
6560 (insert-before-markers txt)
6561 (org-reinstall-markers-in-region bbb)
6562 (move-marker ins-point bbb))
6563 (or (bolp) (insert "\n"))
6564 (setq ins-end (point))
6565 (goto-char ins-point)
6566 (org-skip-whitespace)
6567 (when (and (< arg 0)
6568 (org-first-sibling-p)
6569 (> ne-ins ne-beg))
6570 ;; Move whitespace back to beginning
6571 (save-excursion
6572 (goto-char ins-end)
6573 (let ((kill-whole-line t))
6574 (kill-line (- ne-ins ne-beg)) (point)))
6575 (insert (make-string (- ne-ins ne-beg) ?\n)))
6576 (move-marker ins-point nil)
6577 (if folded
6578 (hide-subtree)
6579 (org-show-entry)
6580 (show-children)
6581 (org-cycle-hide-drawers 'children))
6582 (org-clean-visibility-after-subtree-move)))
6584 (defvar org-subtree-clip ""
6585 "Clipboard for cut and paste of subtrees.
6586 This is actually only a copy of the kill, because we use the normal kill
6587 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6589 (defvar org-subtree-clip-folded nil
6590 "Was the last copied subtree folded?
6591 This is used to fold the tree back after pasting.")
6593 (defun org-cut-subtree (&optional n)
6594 "Cut the current subtree into the clipboard.
6595 With prefix arg N, cut this many sequential subtrees.
6596 This is a short-hand for marking the subtree and then cutting it."
6597 (interactive "p")
6598 (org-copy-subtree n 'cut))
6600 (defun org-copy-subtree (&optional n cut force-store-markers)
6601 "Cut the current subtree into the clipboard.
6602 With prefix arg N, cut this many sequential subtrees.
6603 This is a short-hand for marking the subtree and then copying it.
6604 If CUT is non-nil, actually cut the subtree.
6605 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6606 of some markers in the region, even if CUT is non-nil. This is
6607 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6608 (interactive "p")
6609 (let (beg end folded (beg0 (point)))
6610 (if (interactive-p)
6611 (org-back-to-heading nil) ; take what looks like a subtree
6612 (org-back-to-heading t)) ; take what is really there
6613 (org-back-over-empty-lines)
6614 (setq beg (point))
6615 (skip-chars-forward " \t\r\n")
6616 (save-match-data
6617 (save-excursion (outline-end-of-heading)
6618 (setq folded (org-invisible-p)))
6619 (condition-case nil
6620 (org-forward-same-level (1- n) t)
6621 (error nil))
6622 (org-end-of-subtree t t))
6623 (org-back-over-empty-lines)
6624 (setq end (point))
6625 (goto-char beg0)
6626 (when (> end beg)
6627 (setq org-subtree-clip-folded folded)
6628 (when (or cut force-store-markers)
6629 (org-save-markers-in-region beg end))
6630 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6631 (setq org-subtree-clip (current-kill 0))
6632 (message "%s: Subtree(s) with %d characters"
6633 (if cut "Cut" "Copied")
6634 (length org-subtree-clip)))))
6636 (defun org-paste-subtree (&optional level tree for-yank)
6637 "Paste the clipboard as a subtree, with modification of headline level.
6638 The entire subtree is promoted or demoted in order to match a new headline
6639 level.
6641 If the cursor is at the beginning of a headline, the same level as
6642 that headline is used to paste the tree
6644 If not, the new level is derived from the *visible* headings
6645 before and after the insertion point, and taken to be the inferior headline
6646 level of the two. So if the previous visible heading is level 3 and the
6647 next is level 4 (or vice versa), level 4 will be used for insertion.
6648 This makes sure that the subtree remains an independent subtree and does
6649 not swallow low level entries.
6651 You can also force a different level, either by using a numeric prefix
6652 argument, or by inserting the heading marker by hand. For example, if the
6653 cursor is after \"*****\", then the tree will be shifted to level 5.
6655 If optional TREE is given, use this text instead of the kill ring.
6657 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6658 move back over whitespace before inserting, and move point to the end of
6659 the inserted text when done."
6660 (interactive "P")
6661 (setq tree (or tree (and kill-ring (current-kill 0))))
6662 (unless (org-kill-is-subtree-p tree)
6663 (error "%s"
6664 (substitute-command-keys
6665 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6666 (let* ((visp (not (org-invisible-p)))
6667 (txt tree)
6668 (^re (concat "^\\(" outline-regexp "\\)"))
6669 (re (concat "\\(" outline-regexp "\\)"))
6670 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6672 (old-level (if (string-match ^re txt)
6673 (- (match-end 0) (match-beginning 0) 1)
6674 -1))
6675 (force-level (cond (level (prefix-numeric-value level))
6676 ((and (looking-at "[ \t]*$")
6677 (string-match
6678 ^re_ (buffer-substring
6679 (point-at-bol) (point))))
6680 (- (match-end 1) (match-beginning 1)))
6681 ((and (bolp)
6682 (looking-at org-outline-regexp))
6683 (- (match-end 0) (point) 1))
6684 (t nil)))
6685 (previous-level (save-excursion
6686 (condition-case nil
6687 (progn
6688 (outline-previous-visible-heading 1)
6689 (if (looking-at re)
6690 (- (match-end 0) (match-beginning 0) 1)
6692 (error 1))))
6693 (next-level (save-excursion
6694 (condition-case nil
6695 (progn
6696 (or (looking-at outline-regexp)
6697 (outline-next-visible-heading 1))
6698 (if (looking-at re)
6699 (- (match-end 0) (match-beginning 0) 1)
6701 (error 1))))
6702 (new-level (or force-level (max previous-level next-level)))
6703 (shift (if (or (= old-level -1)
6704 (= new-level -1)
6705 (= old-level new-level))
6707 (- new-level old-level)))
6708 (delta (if (> shift 0) -1 1))
6709 (func (if (> shift 0) 'org-demote 'org-promote))
6710 (org-odd-levels-only nil)
6711 beg end newend)
6712 ;; Remove the forced level indicator
6713 (if force-level
6714 (delete-region (point-at-bol) (point)))
6715 ;; Paste
6716 (beginning-of-line 1)
6717 (unless for-yank (org-back-over-empty-lines))
6718 (setq beg (point))
6719 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6720 (insert-before-markers txt)
6721 (unless (string-match "\n\\'" txt) (insert "\n"))
6722 (setq newend (point))
6723 (org-reinstall-markers-in-region beg)
6724 (setq end (point))
6725 (goto-char beg)
6726 (skip-chars-forward " \t\n\r")
6727 (setq beg (point))
6728 (if (and (org-invisible-p) visp)
6729 (save-excursion (outline-show-heading)))
6730 ;; Shift if necessary
6731 (unless (= shift 0)
6732 (save-restriction
6733 (narrow-to-region beg end)
6734 (while (not (= shift 0))
6735 (org-map-region func (point-min) (point-max))
6736 (setq shift (+ delta shift)))
6737 (goto-char (point-min))
6738 (setq newend (point-max))))
6739 (when (or (interactive-p) for-yank)
6740 (message "Clipboard pasted as level %d subtree" new-level))
6741 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6742 kill-ring
6743 (eq org-subtree-clip (current-kill 0))
6744 org-subtree-clip-folded)
6745 ;; The tree was folded before it was killed/copied
6746 (hide-subtree))
6747 (and for-yank (goto-char newend))))
6749 (defun org-kill-is-subtree-p (&optional txt)
6750 "Check if the current kill is an outline subtree, or a set of trees.
6751 Returns nil if kill does not start with a headline, or if the first
6752 headline level is not the largest headline level in the tree.
6753 So this will actually accept several entries of equal levels as well,
6754 which is OK for `org-paste-subtree'.
6755 If optional TXT is given, check this string instead of the current kill."
6756 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6757 (start-level (and kill
6758 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6759 org-outline-regexp "\\)")
6760 kill)
6761 (- (match-end 2) (match-beginning 2) 1)))
6762 (re (concat "^" org-outline-regexp))
6763 (start (1+ (or (match-beginning 2) -1))))
6764 (if (not start-level)
6765 (progn
6766 nil) ;; does not even start with a heading
6767 (catch 'exit
6768 (while (setq start (string-match re kill (1+ start)))
6769 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6770 (throw 'exit nil)))
6771 t))))
6773 (defvar org-markers-to-move nil
6774 "Markers that should be moved with a cut-and-paste operation.
6775 Those markers are stored together with their positions relative to
6776 the start of the region.")
6778 (defun org-save-markers-in-region (beg end)
6779 "Check markers in region.
6780 If these markers are between BEG and END, record their position relative
6781 to BEG, so that after moving the block of text, we can put the markers back
6782 into place.
6783 This function gets called just before an entry or tree gets cut from the
6784 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6785 called immediately, to move the markers with the entries."
6786 (setq org-markers-to-move nil)
6787 (when (featurep 'org-clock)
6788 (org-clock-save-markers-for-cut-and-paste beg end))
6789 (when (featurep 'org-agenda)
6790 (org-agenda-save-markers-for-cut-and-paste beg end)))
6792 (defun org-check-and-save-marker (marker beg end)
6793 "Check if MARKER is between BEG and END.
6794 If yes, remember the marker and the distance to BEG."
6795 (when (and (marker-buffer marker)
6796 (equal (marker-buffer marker) (current-buffer)))
6797 (if (and (>= marker beg) (< marker end))
6798 (push (cons marker (- marker beg)) org-markers-to-move))))
6800 (defun org-reinstall-markers-in-region (beg)
6801 "Move all remembered markers to their position relative to BEG."
6802 (mapc (lambda (x)
6803 (move-marker (car x) (+ beg (cdr x))))
6804 org-markers-to-move)
6805 (setq org-markers-to-move nil))
6807 (defun org-narrow-to-subtree ()
6808 "Narrow buffer to the current subtree."
6809 (interactive)
6810 (save-excursion
6811 (save-match-data
6812 (narrow-to-region
6813 (progn (org-back-to-heading t) (point))
6814 (progn (org-end-of-subtree t t) (point))))))
6816 (defun org-clone-subtree-with-time-shift (n &optional shift)
6817 "Clone the task (subtree) at point N times.
6818 The clones will be inserted as siblings.
6820 In interactive use, the user will be prompted for the number of clones
6821 to be produced, and for a time SHIFT, which may be a repeater as used
6822 in time stamps, for example `+3d'.
6824 When a valid repeater is given and the entry contains any time stamps,
6825 the clones will become a sequence in time, with time stamps in the
6826 subtree shifted for each clone produced. If SHIFT is nil or the
6827 empty string, time stamps will be left alone.
6829 If the original subtree did contain time stamps with a repeater,
6830 the following will happen:
6831 - the repeater will be removed in each clone
6832 - an additional clone will be produced, with the current, unshifted
6833 date(s) in the entry.
6834 - the original entry will be placed *after* all the clones, with
6835 repeater intact.
6836 - the start days in the repeater in the original entry will be shifted
6837 to past the last clone.
6838 I this way you can spell out a number of instances of a repeating task,
6839 and still retain the repeater to cover future instances of the task."
6840 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6841 (let (beg end template task
6842 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6843 (if (not (and (integerp n) (> n 0)))
6844 (error "Invalid number of replications %s" n))
6845 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6846 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6847 shift)))
6848 (error "Invalid shift specification %s" shift))
6849 (when doshift
6850 (setq shift-n (string-to-number (match-string 1 shift))
6851 shift-what (cdr (assoc (match-string 2 shift)
6852 '(("d" . day) ("w" . week)
6853 ("m" . month) ("y" . year))))))
6854 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6855 (setq nmin 1 nmax n)
6856 (org-back-to-heading t)
6857 (setq beg (point))
6858 (org-end-of-subtree t t)
6859 (or (bolp) (insert "\n"))
6860 (setq end (point))
6861 (setq template (buffer-substring beg end))
6862 (when (and doshift
6863 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6864 (delete-region beg end)
6865 (setq end beg)
6866 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6867 (goto-char end)
6868 (loop for n from nmin to nmax do
6869 (if (not doshift)
6870 (setq task template)
6871 (with-temp-buffer
6872 (insert template)
6873 (org-mode)
6874 (goto-char (point-min))
6875 (while (re-search-forward org-ts-regexp-both nil t)
6876 (org-timestamp-change (* n shift-n) shift-what))
6877 (unless (= n n-no-remove)
6878 (goto-char (point-min))
6879 (while (re-search-forward org-ts-regexp nil t)
6880 (save-excursion
6881 (goto-char (match-beginning 0))
6882 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6883 (delete-region (match-beginning 1) (match-end 1))))))
6884 (setq task (buffer-string))))
6885 (insert task))
6886 (goto-char beg)))
6888 ;;; Outline Sorting
6890 (defun org-sort (with-case)
6891 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6892 Optional argument WITH-CASE means sort case-sensitively.
6893 With a double prefix argument, also remove duplicate entries."
6894 (interactive "P")
6895 (if (org-at-table-p)
6896 (org-call-with-arg 'org-table-sort-lines with-case)
6897 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6899 (defun org-sort-remove-invisible (s)
6900 (remove-text-properties 0 (length s) org-rm-props s)
6901 (while (string-match org-bracket-link-regexp s)
6902 (setq s (replace-match (if (match-end 2)
6903 (match-string 3 s)
6904 (match-string 1 s)) t t s)))
6907 (defvar org-priority-regexp) ; defined later in the file
6909 (defvar org-after-sorting-entries-or-items-hook nil
6910 "Hook that is run after a bunch of entries or items have been sorted.
6911 When children are sorted, the cursor is in the parent line when this
6912 hook gets called. When a region or a plain list is sorted, the cursor
6913 will be in the first entry of the sorted region/list.")
6915 (defun org-sort-entries-or-items
6916 (&optional with-case sorting-type getkey-func compare-func property)
6917 "Sort entries on a certain level of an outline tree, or plain list items.
6918 If there is an active region, the entries in the region are sorted.
6919 Else, if the cursor is before the first entry, sort the top-level items.
6920 Else, the children of the entry at point are sorted.
6921 If the cursor is at the first item in a plain list, the list items will be
6922 sorted.
6924 Sorting can be alphabetically, numerically, by date/time as given by
6925 a time stamp, by a property or by priority.
6927 The command prompts for the sorting type unless it has been given to the
6928 function through the SORTING-TYPE argument, which needs to a character,
6929 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6930 precise meaning of each character:
6932 n Numerically, by converting the beginning of the entry/item to a number.
6933 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6934 t By date/time, either the first active time stamp in the entry, or, if
6935 none exist, by the first inactive one.
6936 In items, only the first line will be checked.
6937 s By the scheduled date/time.
6938 d By deadline date/time.
6939 c By creation time, which is assumed to be the first inactive time stamp
6940 at the beginning of a line.
6941 p By priority according to the cookie.
6942 r By the value of a property.
6944 Capital letters will reverse the sort order.
6946 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6947 called with point at the beginning of the record. It must return either
6948 a string or a number that should serve as the sorting key for that record.
6950 Comparing entries ignores case by default. However, with an optional argument
6951 WITH-CASE, the sorting considers case as well."
6952 (interactive "P")
6953 (let ((case-func (if with-case 'identity 'downcase))
6954 start beg end stars re re2
6955 txt what tmp plain-list-p)
6956 ;; Find beginning and end of region to sort
6957 (cond
6958 ((org-region-active-p)
6959 ;; we will sort the region
6960 (setq end (region-end)
6961 what "region")
6962 (goto-char (region-beginning))
6963 (if (not (org-on-heading-p)) (outline-next-heading))
6964 (setq start (point)))
6965 ((org-at-item-p)
6966 ;; we will sort this plain list
6967 (org-beginning-of-item-list) (setq start (point))
6968 (org-end-of-item-list)
6969 (or (bolp) (insert "\n"))
6970 (setq end (point))
6971 (goto-char start)
6972 (setq plain-list-p t
6973 what "plain list"))
6974 ((or (org-on-heading-p)
6975 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6976 ;; we will sort the children of the current headline
6977 (org-back-to-heading)
6978 (setq start (point)
6979 end (progn (org-end-of-subtree t t)
6980 (or (bolp) (insert "\n"))
6981 (org-back-over-empty-lines)
6982 (point))
6983 what "children")
6984 (goto-char start)
6985 (show-subtree)
6986 (outline-next-heading))
6988 ;; we will sort the top-level entries in this file
6989 (goto-char (point-min))
6990 (or (org-on-heading-p) (outline-next-heading))
6991 (setq start (point))
6992 (goto-char (point-max))
6993 (beginning-of-line 1)
6994 (when (looking-at ".*?\\S-")
6995 ;; File ends in a non-white line
6996 (end-of-line 1)
6997 (insert "\n"))
6998 (setq end (point-max))
6999 (setq what "top-level")
7000 (goto-char start)
7001 (show-all)))
7003 (setq beg (point))
7004 (if (>= beg end) (error "Nothing to sort"))
7006 (unless plain-list-p
7007 (looking-at "\\(\\*+\\)")
7008 (setq stars (match-string 1)
7009 re (concat "^" (regexp-quote stars) " +")
7010 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7011 txt (buffer-substring beg end))
7012 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7013 (if (and (not (equal stars "*")) (string-match re2 txt))
7014 (error "Region to sort contains a level above the first entry")))
7016 (unless sorting-type
7017 (message
7018 (if plain-list-p
7019 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7020 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7021 [t]ime [s]cheduled [d]eadline [c]reated
7022 A/N/T/S/D/C/P/O/F means reversed:")
7023 what)
7024 (setq sorting-type (read-char-exclusive))
7026 (and (= (downcase sorting-type) ?f)
7027 (setq getkey-func
7028 (org-icompleting-read "Sort using function: "
7029 obarray 'fboundp t nil nil))
7030 (setq getkey-func (intern getkey-func)))
7032 (and (= (downcase sorting-type) ?r)
7033 (setq property
7034 (org-icompleting-read "Property: "
7035 (mapcar 'list (org-buffer-property-keys t))
7036 nil t))))
7038 (message "Sorting entries...")
7040 (save-restriction
7041 (narrow-to-region start end)
7043 (let ((dcst (downcase sorting-type))
7044 (case-fold-search nil)
7045 (now (current-time)))
7046 (sort-subr
7047 (/= dcst sorting-type)
7048 ;; This function moves to the beginning character of the "record" to
7049 ;; be sorted.
7050 (if plain-list-p
7051 (lambda nil
7052 (if (org-at-item-p) t (goto-char (point-max))))
7053 (lambda nil
7054 (if (re-search-forward re nil t)
7055 (goto-char (match-beginning 0))
7056 (goto-char (point-max)))))
7057 ;; This function moves to the last character of the "record" being
7058 ;; sorted.
7059 (if plain-list-p
7060 'org-end-of-item
7061 (lambda nil
7062 (save-match-data
7063 (condition-case nil
7064 (outline-forward-same-level 1)
7065 (error
7066 (goto-char (point-max)))))))
7068 ;; This function returns the value that gets sorted against.
7069 (if plain-list-p
7070 (lambda nil
7071 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7072 (cond
7073 ((= dcst ?n)
7074 (string-to-number (buffer-substring (match-end 0)
7075 (point-at-eol))))
7076 ((= dcst ?a)
7077 (buffer-substring (match-end 0) (point-at-eol)))
7078 ((= dcst ?t)
7079 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7080 (re-search-forward org-ts-regexp-both
7081 (point-at-eol) t))
7082 (org-time-string-to-seconds (match-string 0))
7083 (org-float-time now)))
7084 ((= dcst ?f)
7085 (if getkey-func
7086 (progn
7087 (setq tmp (funcall getkey-func))
7088 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7089 tmp)
7090 (error "Invalid key function `%s'" getkey-func)))
7091 (t (error "Invalid sorting type `%c'" sorting-type)))))
7092 (lambda nil
7093 (cond
7094 ((= dcst ?n)
7095 (if (looking-at org-complex-heading-regexp)
7096 (string-to-number (match-string 4))
7097 nil))
7098 ((= dcst ?a)
7099 (if (looking-at org-complex-heading-regexp)
7100 (funcall case-func (match-string 4))
7101 nil))
7102 ((= dcst ?t)
7103 (let ((end (save-excursion (outline-next-heading) (point))))
7104 (if (or (re-search-forward org-ts-regexp end t)
7105 (re-search-forward org-ts-regexp-both end t))
7106 (org-time-string-to-seconds (match-string 0))
7107 (org-float-time now))))
7108 ((= dcst ?c)
7109 (let ((end (save-excursion (outline-next-heading) (point))))
7110 (if (re-search-forward
7111 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7112 end t)
7113 (org-time-string-to-seconds (match-string 0))
7114 (org-float-time now))))
7115 ((= dcst ?s)
7116 (let ((end (save-excursion (outline-next-heading) (point))))
7117 (if (re-search-forward org-scheduled-time-regexp end t)
7118 (org-time-string-to-seconds (match-string 1))
7119 (org-float-time now))))
7120 ((= dcst ?d)
7121 (let ((end (save-excursion (outline-next-heading) (point))))
7122 (if (re-search-forward org-deadline-time-regexp end t)
7123 (org-time-string-to-seconds (match-string 1))
7124 (org-float-time now))))
7125 ((= dcst ?p)
7126 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7127 (string-to-char (match-string 2))
7128 org-default-priority))
7129 ((= dcst ?r)
7130 (or (org-entry-get nil property) ""))
7131 ((= dcst ?o)
7132 (if (looking-at org-complex-heading-regexp)
7133 (- 9999 (length (member (match-string 2)
7134 org-todo-keywords-1)))))
7135 ((= dcst ?f)
7136 (if getkey-func
7137 (progn
7138 (setq tmp (funcall getkey-func))
7139 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7140 tmp)
7141 (error "Invalid key function `%s'" getkey-func)))
7142 (t (error "Invalid sorting type `%c'" sorting-type)))))
7144 (cond
7145 ((= dcst ?a) 'string<)
7146 ((= dcst ?f) compare-func)
7147 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7148 (t nil)))))
7149 (run-hooks 'org-after-sorting-entries-or-items-hook)
7150 (message "Sorting entries...done")))
7152 (defun org-do-sort (table what &optional with-case sorting-type)
7153 "Sort TABLE of WHAT according to SORTING-TYPE.
7154 The user will be prompted for the SORTING-TYPE if the call to this
7155 function does not specify it. WHAT is only for the prompt, to indicate
7156 what is being sorted. The sorting key will be extracted from
7157 the car of the elements of the table.
7158 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7159 (unless sorting-type
7160 (message
7161 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7162 what)
7163 (setq sorting-type (read-char-exclusive)))
7164 (let ((dcst (downcase sorting-type))
7165 extractfun comparefun)
7166 ;; Define the appropriate functions
7167 (cond
7168 ((= dcst ?n)
7169 (setq extractfun 'string-to-number
7170 comparefun (if (= dcst sorting-type) '< '>)))
7171 ((= dcst ?a)
7172 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7173 (lambda(x) (downcase (org-sort-remove-invisible x))))
7174 comparefun (if (= dcst sorting-type)
7175 'string<
7176 (lambda (a b) (and (not (string< a b))
7177 (not (string= a b)))))))
7178 ((= dcst ?t)
7179 (setq extractfun
7180 (lambda (x)
7181 (if (or (string-match org-ts-regexp x)
7182 (string-match org-ts-regexp-both x))
7183 (org-float-time
7184 (org-time-string-to-time (match-string 0 x)))
7186 comparefun (if (= dcst sorting-type) '< '>)))
7187 (t (error "Invalid sorting type `%c'" sorting-type)))
7189 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7190 table)
7191 (lambda (a b) (funcall comparefun (car a) (car b))))))
7194 ;;; The orgstruct minor mode
7196 ;; Define a minor mode which can be used in other modes in order to
7197 ;; integrate the org-mode structure editing commands.
7199 ;; This is really a hack, because the org-mode structure commands use
7200 ;; keys which normally belong to the major mode. Here is how it
7201 ;; works: The minor mode defines all the keys necessary to operate the
7202 ;; structure commands, but wraps the commands into a function which
7203 ;; tests if the cursor is currently at a headline or a plain list
7204 ;; item. If that is the case, the structure command is used,
7205 ;; temporarily setting many Org-mode variables like regular
7206 ;; expressions for filling etc. However, when any of those keys is
7207 ;; used at a different location, function uses `key-binding' to look
7208 ;; up if the key has an associated command in another currently active
7209 ;; keymap (minor modes, major mode, global), and executes that
7210 ;; command. There might be problems if any of the keys is otherwise
7211 ;; used as a prefix key.
7213 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7214 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7215 ;; addresses this by checking explicitly for both bindings.
7217 (defvar orgstruct-mode-map (make-sparse-keymap)
7218 "Keymap for the minor `orgstruct-mode'.")
7220 (defvar org-local-vars nil
7221 "List of local variables, for use by `orgstruct-mode'")
7223 ;;;###autoload
7224 (define-minor-mode orgstruct-mode
7225 "Toggle the minor more `orgstruct-mode'.
7226 This mode is for using Org-mode structure commands in other modes.
7227 The following key behave as if Org-mode was active, if the cursor
7228 is on a headline, or on a plain list item (both in the definition
7229 of Org-mode).
7231 M-up Move entry/item up
7232 M-down Move entry/item down
7233 M-left Promote
7234 M-right Demote
7235 M-S-up Move entry/item up
7236 M-S-down Move entry/item down
7237 M-S-left Promote subtree
7238 M-S-right Demote subtree
7239 M-q Fill paragraph and items like in Org-mode
7240 C-c ^ Sort entries
7241 C-c - Cycle list bullet
7242 TAB Cycle item visibility
7243 M-RET Insert new heading/item
7244 S-M-RET Insert new TODO heading / Checkbox item
7245 C-c C-c Set tags / toggle checkbox"
7246 nil " OrgStruct" nil
7247 (org-load-modules-maybe)
7248 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7250 ;;;###autoload
7251 (defun turn-on-orgstruct ()
7252 "Unconditionally turn on `orgstruct-mode'."
7253 (orgstruct-mode 1))
7255 (defun orgstruct++-mode (&optional arg)
7256 "Toggle `orgstruct-mode', the enhanced version of it.
7257 In addition to setting orgstruct-mode, this also exports all indentation
7258 and autofilling variables from org-mode into the buffer. It will also
7259 recognize item context in multiline items.
7260 Note that turning off orgstruct-mode will *not* remove the
7261 indentation/paragraph settings. This can only be done by refreshing the
7262 major mode, for example with \\[normal-mode]."
7263 (interactive "P")
7264 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7265 (if (< arg 1)
7266 (orgstruct-mode -1)
7267 (orgstruct-mode 1)
7268 (let (var val)
7269 (mapc
7270 (lambda (x)
7271 (when (string-match
7272 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7273 (symbol-name (car x)))
7274 (setq var (car x) val (nth 1 x))
7275 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7276 org-local-vars)
7277 (org-set-local 'orgstruct-is-++ t))))
7279 (defvar orgstruct-is-++ nil
7280 "Is orgstruct-mode in ++ version in the current-buffer?")
7281 (make-variable-buffer-local 'orgstruct-is-++)
7283 ;;;###autoload
7284 (defun turn-on-orgstruct++ ()
7285 "Unconditionally turn on `orgstruct++-mode'."
7286 (orgstruct++-mode 1))
7288 (defun orgstruct-error ()
7289 "Error when there is no default binding for a structure key."
7290 (interactive)
7291 (error "This key has no function outside structure elements"))
7293 (defun orgstruct-setup ()
7294 "Setup orgstruct keymaps."
7295 (let ((nfunc 0)
7296 (bindings
7297 (list
7298 '([(meta up)] org-metaup)
7299 '([(meta down)] org-metadown)
7300 '([(meta left)] org-metaleft)
7301 '([(meta right)] org-metaright)
7302 '([(meta shift up)] org-shiftmetaup)
7303 '([(meta shift down)] org-shiftmetadown)
7304 '([(meta shift left)] org-shiftmetaleft)
7305 '([(meta shift right)] org-shiftmetaright)
7306 '([?\e (up)] org-metaup)
7307 '([?\e (down)] org-metadown)
7308 '([?\e (left)] org-metaleft)
7309 '([?\e (right)] org-metaright)
7310 '([?\e (shift up)] org-shiftmetaup)
7311 '([?\e (shift down)] org-shiftmetadown)
7312 '([?\e (shift left)] org-shiftmetaleft)
7313 '([?\e (shift right)] org-shiftmetaright)
7314 '([(shift up)] org-shiftup)
7315 '([(shift down)] org-shiftdown)
7316 '([(shift left)] org-shiftleft)
7317 '([(shift right)] org-shiftright)
7318 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7319 '("\M-q" fill-paragraph)
7320 '("\C-c^" org-sort)
7321 '("\C-c-" org-cycle-list-bullet)))
7322 elt key fun cmd)
7323 (while (setq elt (pop bindings))
7324 (setq nfunc (1+ nfunc))
7325 (setq key (org-key (car elt))
7326 fun (nth 1 elt)
7327 cmd (orgstruct-make-binding fun nfunc key))
7328 (org-defkey orgstruct-mode-map key cmd))
7330 ;; Special treatment needed for TAB and RET
7331 (org-defkey orgstruct-mode-map [(tab)]
7332 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7333 (org-defkey orgstruct-mode-map "\C-i"
7334 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7336 (org-defkey orgstruct-mode-map "\M-\C-m"
7337 (orgstruct-make-binding 'org-insert-heading 105
7338 "\M-\C-m" [(meta return)]))
7339 (org-defkey orgstruct-mode-map [(meta return)]
7340 (orgstruct-make-binding 'org-insert-heading 106
7341 [(meta return)] "\M-\C-m"))
7343 (org-defkey orgstruct-mode-map [(shift meta return)]
7344 (orgstruct-make-binding 'org-insert-todo-heading 107
7345 [(meta return)] "\M-\C-m"))
7347 (org-defkey orgstruct-mode-map "\e\C-m"
7348 (orgstruct-make-binding 'org-insert-heading 108
7349 "\e\C-m" [?\e (return)]))
7350 (org-defkey orgstruct-mode-map [?\e (return)]
7351 (orgstruct-make-binding 'org-insert-heading 109
7352 [?\e (return)] "\e\C-m"))
7353 (org-defkey orgstruct-mode-map [?\e (shift return)]
7354 (orgstruct-make-binding 'org-insert-todo-heading 110
7355 [?\e (return)] "\e\C-m"))
7357 (unless org-local-vars
7358 (setq org-local-vars (org-get-local-variables)))
7362 (defun orgstruct-make-binding (fun n &rest keys)
7363 "Create a function for binding in the structure minor mode.
7364 FUN is the command to call inside a table. N is used to create a unique
7365 command name. KEYS are keys that should be checked in for a command
7366 to execute outside of tables."
7367 (eval
7368 (list 'defun
7369 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7370 '(arg)
7371 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7372 "Outside of structure, run the binding of `"
7373 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7374 "'.")
7375 '(interactive "p")
7376 (list 'if
7377 `(org-context-p 'headline 'item
7378 (and orgstruct-is-++
7379 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7380 'item-body))
7381 (list 'org-run-like-in-org-mode (list 'quote fun))
7382 (list 'let '(orgstruct-mode)
7383 (list 'call-interactively
7384 (append '(or)
7385 (mapcar (lambda (k)
7386 (list 'key-binding k))
7387 keys)
7388 '('orgstruct-error))))))))
7390 (defun org-context-p (&rest contexts)
7391 "Check if local context is any of CONTEXTS.
7392 Possible values in the list of contexts are `table', `headline', and `item'."
7393 (let ((pos (point)))
7394 (goto-char (point-at-bol))
7395 (prog1 (or (and (memq 'table contexts)
7396 (looking-at "[ \t]*|"))
7397 (and (memq 'headline contexts)
7398 ;;????????? (looking-at "\\*+"))
7399 (looking-at outline-regexp))
7400 (and (memq 'item contexts)
7401 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7402 (and (memq 'item-body contexts)
7403 (org-in-item-p)))
7404 (goto-char pos))))
7406 (defun org-get-local-variables ()
7407 "Return a list of all local variables in an org-mode buffer."
7408 (let (varlist)
7409 (with-current-buffer (get-buffer-create "*Org tmp*")
7410 (erase-buffer)
7411 (org-mode)
7412 (setq varlist (buffer-local-variables)))
7413 (kill-buffer "*Org tmp*")
7414 (delq nil
7415 (mapcar
7416 (lambda (x)
7417 (setq x
7418 (if (symbolp x)
7419 (list x)
7420 (list (car x) (list 'quote (cdr x)))))
7421 (if (string-match
7422 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7423 (symbol-name (car x)))
7424 x nil))
7425 varlist))))
7427 ;;;###autoload
7428 (defun org-run-like-in-org-mode (cmd)
7429 "Run a command, pretending that the current buffer is in Org-mode.
7430 This will temporarily bind local variables that are typically bound in
7431 Org-mode to the values they have in Org-mode, and then interactively
7432 call CMD."
7433 (org-load-modules-maybe)
7434 (unless org-local-vars
7435 (setq org-local-vars (org-get-local-variables)))
7436 (eval (list 'let org-local-vars
7437 (list 'call-interactively (list 'quote cmd)))))
7439 ;;;; Archiving
7441 (defun org-get-category (&optional pos)
7442 "Get the category applying to position POS."
7443 (get-text-property (or pos (point)) 'org-category))
7445 (defun org-refresh-category-properties ()
7446 "Refresh category text properties in the buffer."
7447 (let ((def-cat (cond
7448 ((null org-category)
7449 (if buffer-file-name
7450 (file-name-sans-extension
7451 (file-name-nondirectory buffer-file-name))
7452 "???"))
7453 ((symbolp org-category) (symbol-name org-category))
7454 (t org-category)))
7455 beg end cat pos optionp)
7456 (org-unmodified
7457 (save-excursion
7458 (save-restriction
7459 (widen)
7460 (goto-char (point-min))
7461 (put-text-property (point) (point-max) 'org-category def-cat)
7462 (while (re-search-forward
7463 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7464 (setq pos (match-end 0)
7465 optionp (equal (char-after (match-beginning 0)) ?#)
7466 cat (org-trim (match-string 2)))
7467 (if optionp
7468 (setq beg (point-at-bol) end (point-max))
7469 (org-back-to-heading t)
7470 (setq beg (point) end (org-end-of-subtree t t)))
7471 (put-text-property beg end 'org-category cat)
7472 (goto-char pos)))))))
7475 ;;;; Link Stuff
7477 ;;; Link abbreviations
7479 (defun org-link-expand-abbrev (link)
7480 "Apply replacements as defined in `org-link-abbrev-alist."
7481 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7482 (let* ((key (match-string 1 link))
7483 (as (or (assoc key org-link-abbrev-alist-local)
7484 (assoc key org-link-abbrev-alist)))
7485 (tag (and (match-end 2) (match-string 3 link)))
7486 rpl)
7487 (if (not as)
7488 link
7489 (setq rpl (cdr as))
7490 (cond
7491 ((symbolp rpl) (funcall rpl tag))
7492 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7493 ((string-match "%h" rpl)
7494 (replace-match (url-hexify-string (or tag "")) t t rpl))
7495 (t (concat rpl tag)))))
7496 link))
7498 ;;; Storing and inserting links
7500 (defvar org-insert-link-history nil
7501 "Minibuffer history for links inserted with `org-insert-link'.")
7503 (defvar org-stored-links nil
7504 "Contains the links stored with `org-store-link'.")
7506 (defvar org-store-link-plist nil
7507 "Plist with info about the most recently link created with `org-store-link'.")
7509 (defvar org-link-protocols nil
7510 "Link protocols added to Org-mode using `org-add-link-type'.")
7512 (defvar org-store-link-functions nil
7513 "List of functions that are called to create and store a link.
7514 Each function will be called in turn until one returns a non-nil
7515 value. Each function should check if it is responsible for creating
7516 this link (for example by looking at the major mode).
7517 If not, it must exit and return nil.
7518 If yes, it should return a non-nil value after a calling
7519 `org-store-link-props' with a list of properties and values.
7520 Special properties are:
7522 :type The link prefix. like \"http\". This must be given.
7523 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7524 This is obligatory as well.
7525 :description Optional default description for the second pair
7526 of brackets in an Org-mode link. The user can still change
7527 this when inserting this link into an Org-mode buffer.
7529 In addition to these, any additional properties can be specified
7530 and then used in remember templates.")
7532 (defun org-add-link-type (type &optional follow export)
7533 "Add TYPE to the list of `org-link-types'.
7534 Re-compute all regular expressions depending on `org-link-types'
7536 FOLLOW and EXPORT are two functions.
7538 FOLLOW should take the link path as the single argument and do whatever
7539 is necessary to follow the link, for example find a file or display
7540 a mail message.
7542 EXPORT should format the link path for export to one of the export formats.
7543 It should be a function accepting three arguments:
7545 path the path of the link, the text after the prefix (like \"http:\")
7546 desc the description of the link, if any, nil if there was no description
7547 format the export format, a symbol like `html' or `latex'.
7549 The function may use the FORMAT information to return different values
7550 depending on the format. The return value will be put literally into
7551 the exported file.
7552 Org-mode has a built-in default for exporting links. If you are happy with
7553 this default, there is no need to define an export function for the link
7554 type. For a simple example of an export function, see `org-bbdb.el'."
7555 (add-to-list 'org-link-types type t)
7556 (org-make-link-regexps)
7557 (if (assoc type org-link-protocols)
7558 (setcdr (assoc type org-link-protocols) (list follow export))
7559 (push (list type follow export) org-link-protocols)))
7561 (defvar org-agenda-buffer-name)
7563 ;;;###autoload
7564 (defun org-store-link (arg)
7565 "\\<org-mode-map>Store an org-link to the current location.
7566 This link is added to `org-stored-links' and can later be inserted
7567 into an org-buffer with \\[org-insert-link].
7569 For some link types, a prefix arg is interpreted:
7570 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7571 For file links, arg negates `org-context-in-file-links'."
7572 (interactive "P")
7573 (org-load-modules-maybe)
7574 (setq org-store-link-plist nil) ; reset
7575 (let ((outline-regexp (org-get-limited-outline-regexp))
7576 link cpltxt desc description search txt custom-id)
7577 (cond
7579 ((run-hook-with-args-until-success 'org-store-link-functions)
7580 (setq link (plist-get org-store-link-plist :link)
7581 desc (or (plist-get org-store-link-plist :description) link)))
7583 ((equal (buffer-name) "*Org Edit Src Example*")
7584 (let (label gc)
7585 (while (or (not label)
7586 (save-excursion
7587 (save-restriction
7588 (widen)
7589 (goto-char (point-min))
7590 (re-search-forward
7591 (regexp-quote (format org-coderef-label-format label))
7592 nil t))))
7593 (when label (message "Label exists already") (sit-for 2))
7594 (setq label (read-string "Code line label: " label)))
7595 (end-of-line 1)
7596 (setq link (format org-coderef-label-format label))
7597 (setq gc (- 79 (length link)))
7598 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7599 (insert link)
7600 (setq link (concat "(" label ")") desc nil)))
7602 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7603 ;; We are in the agenda, link to referenced location
7604 (let ((m (or (get-text-property (point) 'org-hd-marker)
7605 (get-text-property (point) 'org-marker))))
7606 (when m
7607 (org-with-point-at m
7608 (call-interactively 'org-store-link)))))
7610 ((eq major-mode 'calendar-mode)
7611 (let ((cd (calendar-cursor-to-date)))
7612 (setq link
7613 (format-time-string
7614 (car org-time-stamp-formats)
7615 (apply 'encode-time
7616 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7617 nil nil nil))))
7618 (org-store-link-props :type "calendar" :date cd)))
7620 ((eq major-mode 'w3-mode)
7621 (setq cpltxt (if (and (buffer-name)
7622 (not (string-match "Untitled" (buffer-name))))
7623 (buffer-name)
7624 (url-view-url t))
7625 link (org-make-link (url-view-url t)))
7626 (org-store-link-props :type "w3" :url (url-view-url t)))
7628 ((eq major-mode 'w3m-mode)
7629 (setq cpltxt (or w3m-current-title w3m-current-url)
7630 link (org-make-link w3m-current-url))
7631 (org-store-link-props :type "w3m" :url (url-view-url t)))
7633 ((setq search (run-hook-with-args-until-success
7634 'org-create-file-search-functions))
7635 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7636 "::" search))
7637 (setq cpltxt (or description link)))
7639 ((eq major-mode 'image-mode)
7640 (setq cpltxt (concat "file:"
7641 (abbreviate-file-name buffer-file-name))
7642 link (org-make-link cpltxt))
7643 (org-store-link-props :type "image" :file buffer-file-name))
7645 ((eq major-mode 'dired-mode)
7646 ;; link to the file in the current line
7647 (setq cpltxt (concat "file:"
7648 (abbreviate-file-name
7649 (expand-file-name
7650 (dired-get-filename nil t))))
7651 link (org-make-link cpltxt)))
7653 ((and buffer-file-name (org-mode-p))
7654 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7655 (cond
7656 ((org-in-regexp "<<\\(.*?\\)>>")
7657 (setq cpltxt
7658 (concat "file:"
7659 (abbreviate-file-name buffer-file-name)
7660 "::" (match-string 1))
7661 link (org-make-link cpltxt)))
7662 ((and (featurep 'org-id)
7663 (or (eq org-link-to-org-use-id t)
7664 (and (eq org-link-to-org-use-id 'create-if-interactive)
7665 (interactive-p))
7666 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7667 (interactive-p)
7668 (not custom-id))
7669 (and org-link-to-org-use-id
7670 (condition-case nil
7671 (org-entry-get nil "ID")
7672 (error nil)))))
7673 ;; We can make a link using the ID.
7674 (setq link (condition-case nil
7675 (prog1 (org-id-store-link)
7676 (setq desc (plist-get org-store-link-plist
7677 :description)))
7678 (error
7679 ;; probably before first headline, link to file only
7680 (concat "file:"
7681 (abbreviate-file-name buffer-file-name))))))
7683 ;; Just link to current headline
7684 (setq cpltxt (concat "file:"
7685 (abbreviate-file-name buffer-file-name)))
7686 ;; Add a context search string
7687 (when (org-xor org-context-in-file-links arg)
7688 (setq txt (cond
7689 ((org-on-heading-p) nil)
7690 ((org-region-active-p)
7691 (buffer-substring (region-beginning) (region-end)))
7692 (t nil)))
7693 (when (or (null txt) (string-match "\\S-" txt))
7694 (setq cpltxt
7695 (concat cpltxt "::"
7696 (condition-case nil
7697 (org-make-org-heading-search-string txt)
7698 (error "")))
7699 desc (or (nth 4 (ignore-errors
7700 (org-heading-components))) "NONE"))))
7701 (if (string-match "::\\'" cpltxt)
7702 (setq cpltxt (substring cpltxt 0 -2)))
7703 (setq link (org-make-link cpltxt)))))
7705 ((buffer-file-name (buffer-base-buffer))
7706 ;; Just link to this file here.
7707 (setq cpltxt (concat "file:"
7708 (abbreviate-file-name
7709 (buffer-file-name (buffer-base-buffer)))))
7710 ;; Add a context string
7711 (when (org-xor org-context-in-file-links arg)
7712 (setq txt (if (org-region-active-p)
7713 (buffer-substring (region-beginning) (region-end))
7714 (buffer-substring (point-at-bol) (point-at-eol))))
7715 ;; Only use search option if there is some text.
7716 (when (string-match "\\S-" txt)
7717 (setq cpltxt
7718 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7719 desc "NONE")))
7720 (setq link (org-make-link cpltxt)))
7722 ((interactive-p)
7723 (error "Cannot link to a buffer which is not visiting a file"))
7725 (t (setq link nil)))
7727 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7728 (setq link (or link cpltxt)
7729 desc (or desc cpltxt))
7730 (if (equal desc "NONE") (setq desc nil))
7732 (if (and (or (interactive-p) executing-kbd-macro) link)
7733 (progn
7734 (setq org-stored-links
7735 (cons (list link desc) org-stored-links))
7736 (message "Stored: %s" (or desc link))
7737 (when custom-id
7738 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7739 "::#" custom-id))
7740 (setq org-stored-links
7741 (cons (list link desc) org-stored-links))))
7742 (and link (org-make-link-string link desc)))))
7744 (defun org-store-link-props (&rest plist)
7745 "Store link properties, extract names and addresses."
7746 (let (x adr)
7747 (when (setq x (plist-get plist :from))
7748 (setq adr (mail-extract-address-components x))
7749 (setq plist (plist-put plist :fromname (car adr)))
7750 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7751 (when (setq x (plist-get plist :to))
7752 (setq adr (mail-extract-address-components x))
7753 (setq plist (plist-put plist :toname (car adr)))
7754 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7755 (let ((from (plist-get plist :from))
7756 (to (plist-get plist :to)))
7757 (when (and from to org-from-is-user-regexp)
7758 (setq plist
7759 (plist-put plist :fromto
7760 (if (string-match org-from-is-user-regexp from)
7761 (concat "to %t")
7762 (concat "from %f"))))))
7763 (setq org-store-link-plist plist))
7765 (defun org-add-link-props (&rest plist)
7766 "Add these properties to the link property list."
7767 (let (key value)
7768 (while plist
7769 (setq key (pop plist) value (pop plist))
7770 (setq org-store-link-plist
7771 (plist-put org-store-link-plist key value)))))
7773 (defun org-email-link-description (&optional fmt)
7774 "Return the description part of an email link.
7775 This takes information from `org-store-link-plist' and formats it
7776 according to FMT (default from `org-email-link-description-format')."
7777 (setq fmt (or fmt org-email-link-description-format))
7778 (let* ((p org-store-link-plist)
7779 (to (plist-get p :toaddress))
7780 (from (plist-get p :fromaddress))
7781 (table
7782 (list
7783 (cons "%c" (plist-get p :fromto))
7784 (cons "%F" (plist-get p :from))
7785 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7786 (cons "%T" (plist-get p :to))
7787 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7788 (cons "%s" (plist-get p :subject))
7789 (cons "%m" (plist-get p :message-id)))))
7790 (when (string-match "%c" fmt)
7791 ;; Check if the user wrote this message
7792 (if (and org-from-is-user-regexp from to
7793 (save-match-data (string-match org-from-is-user-regexp from)))
7794 (setq fmt (replace-match "to %t" t t fmt))
7795 (setq fmt (replace-match "from %f" t t fmt))))
7796 (org-replace-escapes fmt table)))
7798 (defun org-make-org-heading-search-string (&optional string heading)
7799 "Make search string for STRING or current headline."
7800 (interactive)
7801 (let ((s (or string (org-get-heading))))
7802 (unless (and string (not heading))
7803 ;; We are using a headline, clean up garbage in there.
7804 (if (string-match org-todo-regexp s)
7805 (setq s (replace-match "" t t s)))
7806 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7807 (setq s (replace-match "" t t s)))
7808 (setq s (org-trim s))
7809 (if (string-match (concat "^\\(" org-quote-string "\\|"
7810 org-comment-string "\\)") s)
7811 (setq s (replace-match "" t t s)))
7812 (while (string-match org-ts-regexp s)
7813 (setq s (replace-match "" t t s))))
7814 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7815 (setq s (replace-match " " t t s)))
7816 (or string (setq s (concat "*" s))) ; Add * for headlines
7817 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7819 (defun org-make-link (&rest strings)
7820 "Concatenate STRINGS."
7821 (apply 'concat strings))
7823 (defun org-make-link-string (link &optional description)
7824 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7825 (unless (string-match "\\S-" link)
7826 (error "Empty link"))
7827 (when (and description
7828 (stringp description)
7829 (not (string-match "\\S-" description)))
7830 (setq description nil))
7831 (when (stringp description)
7832 ;; Remove brackets from the description, they are fatal.
7833 (while (string-match "\\[" description)
7834 (setq description (replace-match "{" t t description)))
7835 (while (string-match "\\]" description)
7836 (setq description (replace-match "}" t t description))))
7837 (when (equal (org-link-escape link) description)
7838 ;; No description needed, it is identical
7839 (setq description nil))
7840 (when (and (not description)
7841 (not (equal link (org-link-escape link))))
7842 (setq description (org-extract-attributes link)))
7843 (concat "[[" (org-link-escape link) "]"
7844 (if description (concat "[" description "]") "")
7845 "]"))
7847 (defconst org-link-escape-chars
7848 '((?\ . "%20")
7849 (?\[ . "%5B")
7850 (?\] . "%5D")
7851 (?\340 . "%E0") ; `a
7852 (?\342 . "%E2") ; ^a
7853 (?\347 . "%E7") ; ,c
7854 (?\350 . "%E8") ; `e
7855 (?\351 . "%E9") ; 'e
7856 (?\352 . "%EA") ; ^e
7857 (?\356 . "%EE") ; ^i
7858 (?\364 . "%F4") ; ^o
7859 (?\371 . "%F9") ; `u
7860 (?\373 . "%FB") ; ^u
7861 (?\; . "%3B")
7862 (?? . "%3F")
7863 (?= . "%3D")
7864 (?+ . "%2B")
7866 "Association list of escapes for some characters problematic in links.
7867 This is the list that is used for internal purposes.")
7869 (defvar org-url-encoding-use-url-hexify nil)
7871 (defconst org-link-escape-chars-browser
7872 '((?\ . "%20")) ; 32 for the SPC char
7873 "Association list of escapes for some characters problematic in links.
7874 This is the list that is used before handing over to the browser.")
7876 (defun org-link-escape (text &optional table)
7877 "Escape characters in TEXT that are problematic for links."
7878 (if org-url-encoding-use-url-hexify
7879 (url-hexify-string text)
7880 (setq table (or table org-link-escape-chars))
7881 (when text
7882 (let ((re (mapconcat (lambda (x) (regexp-quote
7883 (char-to-string (car x))))
7884 table "\\|")))
7885 (while (string-match re text)
7886 (setq text
7887 (replace-match
7888 (cdr (assoc (string-to-char (match-string 0 text))
7889 table))
7890 t t text)))
7891 text))))
7893 (defun org-link-unescape (text &optional table)
7894 "Reverse the action of `org-link-escape'."
7895 (if org-url-encoding-use-url-hexify
7896 (url-unhex-string text)
7897 (setq table (or table org-link-escape-chars))
7898 (when text
7899 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7900 table "\\|")))
7901 (while (string-match re text)
7902 (setq text
7903 (replace-match
7904 (char-to-string (car (rassoc (match-string 0 text) table)))
7905 t t text)))
7906 text))))
7908 (defun org-xor (a b)
7909 "Exclusive or."
7910 (if a (not b) b))
7912 (defun org-fixup-message-id-for-http (s)
7913 "Replace special characters in a message id, so it can be used in an http query."
7914 (while (string-match "<" s)
7915 (setq s (replace-match "%3C" t t s)))
7916 (while (string-match ">" s)
7917 (setq s (replace-match "%3E" t t s)))
7918 (while (string-match "@" s)
7919 (setq s (replace-match "%40" t t s)))
7922 ;;;###autoload
7923 (defun org-insert-link-global ()
7924 "Insert a link like Org-mode does.
7925 This command can be called in any mode to insert a link in Org-mode syntax."
7926 (interactive)
7927 (org-load-modules-maybe)
7928 (org-run-like-in-org-mode 'org-insert-link))
7930 (defun org-insert-link (&optional complete-file link-location)
7931 "Insert a link. At the prompt, enter the link.
7933 Completion can be used to insert any of the link protocol prefixes like
7934 http or ftp in use.
7936 The history can be used to select a link previously stored with
7937 `org-store-link'. When the empty string is entered (i.e. if you just
7938 press RET at the prompt), the link defaults to the most recently
7939 stored link. As SPC triggers completion in the minibuffer, you need to
7940 use M-SPC or C-q SPC to force the insertion of a space character.
7942 You will also be prompted for a description, and if one is given, it will
7943 be displayed in the buffer instead of the link.
7945 If there is already a link at point, this command will allow you to edit link
7946 and description parts.
7948 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7949 be selected using completion. The path to the file will be relative to the
7950 current directory if the file is in the current directory or a subdirectory.
7951 Otherwise, the link will be the absolute path as completed in the minibuffer
7952 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7953 option `org-link-file-path-type'.
7955 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7956 the current directory or below.
7958 With three \\[universal-argument] prefixes, negate the meaning of
7959 `org-keep-stored-link-after-insertion'.
7961 If `org-make-link-description-function' is non-nil, this function will be
7962 called with the link target, and the result will be the default
7963 link description.
7965 If the LINK-LOCATION parameter is non-nil, this value will be
7966 used as the link location instead of reading one interactively."
7967 (interactive "P")
7968 (let* ((wcf (current-window-configuration))
7969 (region (if (org-region-active-p)
7970 (buffer-substring (region-beginning) (region-end))))
7971 (remove (and region (list (region-beginning) (region-end))))
7972 (desc region)
7973 tmphist ; byte-compile incorrectly complains about this
7974 (link link-location)
7975 entry file all-prefixes)
7976 (cond
7977 (link-location) ; specified by arg, just use it.
7978 ((org-in-regexp org-bracket-link-regexp 1)
7979 ;; We do have a link at point, and we are going to edit it.
7980 (setq remove (list (match-beginning 0) (match-end 0)))
7981 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7982 (setq link (read-string "Link: "
7983 (org-link-unescape
7984 (org-match-string-no-properties 1)))))
7985 ((or (org-in-regexp org-angle-link-re)
7986 (org-in-regexp org-plain-link-re))
7987 ;; Convert to bracket link
7988 (setq remove (list (match-beginning 0) (match-end 0))
7989 link (read-string "Link: "
7990 (org-remove-angle-brackets (match-string 0)))))
7991 ((member complete-file '((4) (16)))
7992 ;; Completing read for file names.
7993 (setq link (org-file-complete-link complete-file)))
7995 ;; Read link, with completion for stored links.
7996 (with-output-to-temp-buffer "*Org Links*"
7997 (princ "Insert a link.
7998 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7999 (when org-stored-links
8000 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8001 (princ (mapconcat
8002 (lambda (x)
8003 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8004 (reverse org-stored-links) "\n"))))
8005 (let ((cw (selected-window)))
8006 (select-window (get-buffer-window "*Org Links*"))
8007 (setq truncate-lines t)
8008 (unless (pos-visible-in-window-p (point-max))
8009 (org-fit-window-to-buffer))
8010 (and (window-live-p cw) (select-window cw)))
8011 ;; Fake a link history, containing the stored links.
8012 (setq tmphist (append (mapcar 'car org-stored-links)
8013 org-insert-link-history))
8014 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8015 (mapcar 'car org-link-abbrev-alist)
8016 org-link-types))
8017 (unwind-protect
8018 (progn
8019 (setq link
8020 (let ((org-completion-use-ido nil)
8021 (org-completion-use-iswitchb nil))
8022 (org-completing-read
8023 "Link: "
8024 (append
8025 (mapcar (lambda (x) (list (concat x ":")))
8026 all-prefixes)
8027 (mapcar 'car org-stored-links))
8028 nil nil nil
8029 'tmphist
8030 (car (car org-stored-links)))))
8031 (if (not (string-match "\\S-" link))
8032 (error "No link selected"))
8033 (if (or (member link all-prefixes)
8034 (and (equal ":" (substring link -1))
8035 (member (substring link 0 -1) all-prefixes)
8036 (setq link (substring link 0 -1))))
8037 (setq link (org-link-try-special-completion link))))
8038 (set-window-configuration wcf)
8039 (kill-buffer "*Org Links*"))
8040 (setq entry (assoc link org-stored-links))
8041 (or entry (push link org-insert-link-history))
8042 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8043 (not org-keep-stored-link-after-insertion))
8044 (setq org-stored-links (delq (assoc link org-stored-links)
8045 org-stored-links)))
8046 (setq desc (or desc (nth 1 entry)))))
8048 (if (string-match org-plain-link-re link)
8049 ;; URL-like link, normalize the use of angular brackets.
8050 (setq link (org-make-link (org-remove-angle-brackets link))))
8052 ;; Check if we are linking to the current file with a search option
8053 ;; If yes, simplify the link by using only the search option.
8054 (when (and buffer-file-name
8055 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8056 (let* ((path (match-string 1 link))
8057 (case-fold-search nil)
8058 (search (match-string 2 link)))
8059 (save-match-data
8060 (if (equal (file-truename buffer-file-name) (file-truename path))
8061 ;; We are linking to this same file, with a search option
8062 (setq link search)))))
8064 ;; Check if we can/should use a relative path. If yes, simplify the link
8065 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8066 (let* ((type (match-string 1 link))
8067 (path (match-string 2 link))
8068 (origpath path)
8069 (case-fold-search nil))
8070 (cond
8071 ((or (eq org-link-file-path-type 'absolute)
8072 (equal complete-file '(16)))
8073 (setq path (abbreviate-file-name (expand-file-name path))))
8074 ((eq org-link-file-path-type 'noabbrev)
8075 (setq path (expand-file-name path)))
8076 ((eq org-link-file-path-type 'relative)
8077 (setq path (file-relative-name path)))
8079 (save-match-data
8080 (if (string-match (concat "^" (regexp-quote
8081 (file-name-as-directory
8082 (expand-file-name "."))))
8083 (expand-file-name path))
8084 ;; We are linking a file with relative path name.
8085 (setq path (substring (expand-file-name path)
8086 (match-end 0)))
8087 (setq path (abbreviate-file-name (expand-file-name path)))))))
8088 (setq link (concat type path))
8089 (if (equal desc origpath)
8090 (setq desc path))))
8092 (if org-make-link-description-function
8093 (setq desc (funcall org-make-link-description-function link desc)))
8095 (setq desc (read-string "Description: " desc))
8096 (unless (string-match "\\S-" desc) (setq desc nil))
8097 (if remove (apply 'delete-region remove))
8098 (insert (org-make-link-string link desc))))
8100 (defun org-link-try-special-completion (type)
8101 "If there is completion support for link type TYPE, offer it."
8102 (let ((fun (intern (concat "org-" type "-complete-link"))))
8103 (if (functionp fun)
8104 (funcall fun)
8105 (read-string "Link (no completion support): " (concat type ":")))))
8107 (defun org-file-complete-link (&optional arg)
8108 "Create a file link using completion."
8109 (let (file link)
8110 (setq file (read-file-name "File: "))
8111 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8112 (pwd1 (file-name-as-directory (abbreviate-file-name
8113 (expand-file-name ".")))))
8114 (cond
8115 ((equal arg '(16))
8116 (setq link (org-make-link
8117 "file:"
8118 (abbreviate-file-name (expand-file-name file)))))
8119 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8120 (setq link (org-make-link "file:" (match-string 1 file))))
8121 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8122 (expand-file-name file))
8123 (setq link (org-make-link
8124 "file:" (match-string 1 (expand-file-name file)))))
8125 (t (setq link (org-make-link "file:" file)))))
8126 link))
8128 (defun org-completing-read (&rest args)
8129 "Completing-read with SPACE being a normal character."
8130 (let ((minibuffer-local-completion-map
8131 (copy-keymap minibuffer-local-completion-map)))
8132 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8133 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8134 (apply 'org-icompleting-read args)))
8136 (defun org-completing-read-no-i (&rest args)
8137 (let (org-completion-use-ido org-completion-use-iswitchb)
8138 (apply 'org-completing-read args)))
8140 (defun org-iswitchb-completing-read (prompt choices &rest args)
8141 "Use iswitch as a completing-read replacement to choose from choices.
8142 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8143 from."
8144 (let* ((iswitchb-use-virtual-buffers nil)
8145 (iswitchb-make-buflist-hook
8146 (lambda ()
8147 (setq iswitchb-temp-buflist choices))))
8148 (iswitchb-read-buffer prompt)))
8150 (defun org-icompleting-read (&rest args)
8151 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8152 (org-without-partial-completion
8153 (if (and org-completion-use-ido
8154 (fboundp 'ido-completing-read)
8155 (boundp 'ido-mode) ido-mode
8156 (listp (second args)))
8157 (let ((ido-enter-matching-directory nil))
8158 (apply 'ido-completing-read (concat (car args))
8159 (if (consp (car (nth 1 args)))
8160 (mapcar (lambda (x) (car x)) (nth 1 args))
8161 (nth 1 args))
8162 (cddr args)))
8163 (if (and org-completion-use-iswitchb
8164 (boundp 'iswitchb-mode) iswitchb-mode
8165 (listp (second args)))
8166 (apply 'org-iswitchb-completing-read (concat (car args))
8167 (if (consp (car (nth 1 args)))
8168 (mapcar (lambda (x) (car x)) (nth 1 args))
8169 (nth 1 args))
8170 (cddr args))
8171 (apply 'completing-read args)))))
8173 (defun org-extract-attributes (s)
8174 "Extract the attributes cookie from a string and set as text property."
8175 (let (a attr (start 0) key value)
8176 (save-match-data
8177 (when (string-match "{{\\([^}]+\\)}}$" s)
8178 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8179 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8180 (setq key (match-string 1 a) value (match-string 2 a)
8181 start (match-end 0)
8182 attr (plist-put attr (intern key) value))))
8183 (org-add-props s nil 'org-attr attr))
8186 (defun org-extract-attributes-from-string (tag)
8187 (let (key value attr)
8188 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8189 (setq key (match-string 1 tag) value (match-string 2 tag)
8190 tag (replace-match "" t t tag)
8191 attr (plist-put attr (intern key) value)))
8192 (cons tag attr)))
8194 (defun org-attributes-to-string (plist)
8195 "Format a property list into an HTML attribute list."
8196 (let ((s "") key value)
8197 (while plist
8198 (setq key (pop plist) value (pop plist))
8199 (and value
8200 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8203 ;;; Opening/following a link
8205 (defvar org-link-search-failed nil)
8207 (defun org-next-link ()
8208 "Move forward to the next link.
8209 If the link is in hidden text, expose it."
8210 (interactive)
8211 (when (and org-link-search-failed (eq this-command last-command))
8212 (goto-char (point-min))
8213 (message "Link search wrapped back to beginning of buffer"))
8214 (setq org-link-search-failed nil)
8215 (let* ((pos (point))
8216 (ct (org-context))
8217 (a (assoc :link ct)))
8218 (if a (goto-char (nth 2 a)))
8219 (if (re-search-forward org-any-link-re nil t)
8220 (progn
8221 (goto-char (match-beginning 0))
8222 (if (org-invisible-p) (org-show-context)))
8223 (goto-char pos)
8224 (setq org-link-search-failed t)
8225 (error "No further link found"))))
8227 (defun org-previous-link ()
8228 "Move backward to the previous link.
8229 If the link is in hidden text, expose it."
8230 (interactive)
8231 (when (and org-link-search-failed (eq this-command last-command))
8232 (goto-char (point-max))
8233 (message "Link search wrapped back to end of buffer"))
8234 (setq org-link-search-failed nil)
8235 (let* ((pos (point))
8236 (ct (org-context))
8237 (a (assoc :link ct)))
8238 (if a (goto-char (nth 1 a)))
8239 (if (re-search-backward org-any-link-re nil t)
8240 (progn
8241 (goto-char (match-beginning 0))
8242 (if (org-invisible-p) (org-show-context)))
8243 (goto-char pos)
8244 (setq org-link-search-failed t)
8245 (error "No further link found"))))
8247 (defun org-translate-link (s)
8248 "Translate a link string if a translation function has been defined."
8249 (if (and org-link-translation-function
8250 (fboundp org-link-translation-function)
8251 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8252 (progn
8253 (setq s (funcall org-link-translation-function
8254 (match-string 1) (match-string 2)))
8255 (concat (car s) ":" (cdr s)))
8258 (defun org-translate-link-from-planner (type path)
8259 "Translate a link from Emacs Planner syntax so that Org can follow it.
8260 This is still an experimental function, your mileage may vary."
8261 (cond
8262 ((member type '("http" "https" "news" "ftp"))
8263 ;; standard Internet links are the same.
8264 nil)
8265 ((and (equal type "irc") (string-match "^//" path))
8266 ;; Planner has two / at the beginning of an irc link, we have 1.
8267 ;; We should have zero, actually....
8268 (setq path (substring path 1)))
8269 ((and (equal type "lisp") (string-match "^/" path))
8270 ;; Planner has a slash, we do not.
8271 (setq type "elisp" path (substring path 1)))
8272 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8273 ;; A typical message link. Planner has the id after the final slash,
8274 ;; we separate it with a hash mark
8275 (setq path (concat (match-string 1 path) "#"
8276 (org-remove-angle-brackets (match-string 2 path)))))
8278 (cons type path))
8280 (defun org-find-file-at-mouse (ev)
8281 "Open file link or URL at mouse."
8282 (interactive "e")
8283 (mouse-set-point ev)
8284 (org-open-at-point 'in-emacs))
8286 (defun org-open-at-mouse (ev)
8287 "Open file link or URL at mouse."
8288 (interactive "e")
8289 (mouse-set-point ev)
8290 (if (eq major-mode 'org-agenda-mode)
8291 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8292 (org-open-at-point))
8294 (defvar org-window-config-before-follow-link nil
8295 "The window configuration before following a link.
8296 This is saved in case the need arises to restore it.")
8298 (defvar org-open-link-marker (make-marker)
8299 "Marker pointing to the location where `org-open-at-point; was called.")
8301 ;;;###autoload
8302 (defun org-open-at-point-global ()
8303 "Follow a link like Org-mode does.
8304 This command can be called in any mode to follow a link that has
8305 Org-mode syntax."
8306 (interactive)
8307 (org-run-like-in-org-mode 'org-open-at-point))
8309 ;;;###autoload
8310 (defun org-open-link-from-string (s &optional arg reference-buffer)
8311 "Open a link in the string S, as if it was in Org-mode."
8312 (interactive "sLink: \nP")
8313 (let ((reference-buffer (or reference-buffer (current-buffer))))
8314 (with-temp-buffer
8315 (let ((org-inhibit-startup t))
8316 (org-mode)
8317 (insert s)
8318 (goto-char (point-min))
8319 (org-open-at-point arg reference-buffer)))))
8321 (defun org-open-at-point (&optional in-emacs reference-buffer)
8322 "Open link at or after point.
8323 If there is no link at point, this function will search forward up to
8324 the end of the current line.
8325 Normally, files will be opened by an appropriate application. If the
8326 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8327 With a double prefix argument, try to open outside of Emacs, in the
8328 application the system uses for this file type."
8329 (interactive "P")
8330 (org-load-modules-maybe)
8331 (move-marker org-open-link-marker (point))
8332 (setq org-window-config-before-follow-link (current-window-configuration))
8333 (org-remove-occur-highlights nil nil t)
8334 (cond
8335 ((and (org-on-heading-p)
8336 (not (org-in-regexp
8337 (concat org-plain-link-re "\\|"
8338 org-bracket-link-regexp "\\|"
8339 org-angle-link-re "\\|"
8340 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8341 (or (org-offer-links-in-entry in-emacs)
8342 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8343 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8344 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8345 (org-footnote-action))
8347 (let (type path link line search (pos (point)))
8348 (catch 'match
8349 (save-excursion
8350 (skip-chars-forward "^]\n\r")
8351 (when (org-in-regexp org-bracket-link-regexp 1)
8352 (setq link (org-extract-attributes
8353 (org-link-unescape (org-match-string-no-properties 1))))
8354 (while (string-match " *\n *" link)
8355 (setq link (replace-match " " t t link)))
8356 (setq link (org-link-expand-abbrev link))
8357 (cond
8358 ((or (file-name-absolute-p link)
8359 (string-match "^\\.\\.?/" link))
8360 (setq type "file" path link))
8361 ((string-match org-link-re-with-space3 link)
8362 (setq type (match-string 1 link) path (match-string 2 link)))
8363 (t (setq type "thisfile" path link)))
8364 (throw 'match t)))
8366 (when (get-text-property (point) 'org-linked-text)
8367 (setq type "thisfile"
8368 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8369 (1+ (point)) (point))
8370 path (buffer-substring
8371 (previous-single-property-change pos 'org-linked-text)
8372 (next-single-property-change pos 'org-linked-text)))
8373 (throw 'match t))
8375 (save-excursion
8376 (when (or (org-in-regexp org-angle-link-re)
8377 (org-in-regexp org-plain-link-re))
8378 (setq type (match-string 1) path (match-string 2))
8379 (throw 'match t)))
8380 (save-excursion
8381 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8382 (setq type "tags"
8383 path (match-string 1))
8384 (while (string-match ":" path)
8385 (setq path (replace-match "+" t t path)))
8386 (throw 'match t)))
8387 (when (org-in-regexp "<\\([^><\n]+\\)>")
8388 (setq type "tree-match"
8389 path (match-string 1))
8390 (throw 'match t)))
8391 (unless path
8392 (error "No link found"))
8394 ;; switch back to reference buffer
8395 ;; needed when if called in a temporary buffer through
8396 ;; org-open-link-from-string
8397 (with-current-buffer (or reference-buffer (current-buffer))
8399 ;; Remove any trailing spaces in path
8400 (if (string-match " +\\'" path)
8401 (setq path (replace-match "" t t path)))
8402 (if (and org-link-translation-function
8403 (fboundp org-link-translation-function))
8404 ;; Check if we need to translate the link
8405 (let ((tmp (funcall org-link-translation-function type path)))
8406 (setq type (car tmp) path (cdr tmp))))
8408 (cond
8410 ((assoc type org-link-protocols)
8411 (funcall (nth 1 (assoc type org-link-protocols)) path))
8413 ((equal type "mailto")
8414 (let ((cmd (car org-link-mailto-program))
8415 (args (cdr org-link-mailto-program)) args1
8416 (address path) (subject "") a)
8417 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8418 (setq address (match-string 1 path)
8419 subject (org-link-escape (match-string 2 path))))
8420 (while args
8421 (cond
8422 ((not (stringp (car args))) (push (pop args) args1))
8423 (t (setq a (pop args))
8424 (if (string-match "%a" a)
8425 (setq a (replace-match address t t a)))
8426 (if (string-match "%s" a)
8427 (setq a (replace-match subject t t a)))
8428 (push a args1))))
8429 (apply cmd (nreverse args1))))
8431 ((member type '("http" "https" "ftp" "news"))
8432 (browse-url (concat type ":" (org-link-escape
8433 path org-link-escape-chars-browser))))
8435 ((member type '("message"))
8436 (browse-url (concat type ":" path)))
8438 ((string= type "tags")
8439 (org-tags-view in-emacs path))
8440 ((string= type "thisfile")
8441 (if in-emacs
8442 (switch-to-buffer-other-window
8443 (org-get-buffer-for-internal-link (current-buffer)))
8444 (org-mark-ring-push))
8445 (let ((cmd `(org-link-search
8446 ,path
8447 ,(cond ((equal in-emacs '(4)) 'occur)
8448 ((equal in-emacs '(16)) 'org-occur)
8449 (t nil))
8450 ,pos)))
8451 (condition-case nil (eval cmd)
8452 (error (progn (widen) (eval cmd))))))
8454 ((string= type "tree-match")
8455 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8457 ((string= type "file")
8458 (if (string-match "::\\([0-9]+\\)\\'" path)
8459 (setq line (string-to-number (match-string 1 path))
8460 path (substring path 0 (match-beginning 0)))
8461 (if (string-match "::\\(.+\\)\\'" path)
8462 (setq search (match-string 1 path)
8463 path (substring path 0 (match-beginning 0)))))
8464 (if (string-match "[*?{]" (file-name-nondirectory path))
8465 (dired path)
8466 (org-open-file path in-emacs line search)))
8468 ((string= type "news")
8469 (require 'org-gnus)
8470 (org-gnus-follow-link path))
8472 ((string= type "shell")
8473 (let ((cmd path))
8474 (if (or (not org-confirm-shell-link-function)
8475 (funcall org-confirm-shell-link-function
8476 (format "Execute \"%s\" in shell? "
8477 (org-add-props cmd nil
8478 'face 'org-warning))))
8479 (progn
8480 (message "Executing %s" cmd)
8481 (shell-command cmd))
8482 (error "Abort"))))
8484 ((string= type "elisp")
8485 (let ((cmd path))
8486 (if (or (not org-confirm-elisp-link-function)
8487 (funcall org-confirm-elisp-link-function
8488 (format "Execute \"%s\" as elisp? "
8489 (org-add-props cmd nil
8490 'face 'org-warning))))
8491 (message "%s => %s" cmd
8492 (if (equal (string-to-char cmd) ?\()
8493 (eval (read cmd))
8494 (call-interactively (read cmd))))
8495 (error "Abort"))))
8498 (browse-url-at-point)))))))
8499 (move-marker org-open-link-marker nil)
8500 (run-hook-with-args 'org-follow-link-hook))
8502 (defun org-offer-links-in-entry (&optional nth zero)
8503 "Offer links in the current entry and follow the selected link.
8504 If there is only one link, follow it immediately as well.
8505 If NTH is an integer, immediately pick the NTH link found.
8506 If ZERO is a string, check also this string for a link, and if
8507 there is one, offer it as link number zero."
8508 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8509 "\\(" org-angle-link-re "\\)\\|"
8510 "\\(" org-plain-link-re "\\)"))
8511 (cnt ?0)
8512 (in-emacs (if (integerp nth) nil nth))
8513 have-zero end links link c)
8514 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8515 (push (match-string 0 zero) links)
8516 (setq cnt (1- cnt) have-zero t))
8517 (save-excursion
8518 (org-back-to-heading t)
8519 (setq end (save-excursion (outline-next-heading) (point)))
8520 (while (re-search-forward re end t)
8521 (push (match-string 0) links))
8522 (setq links (org-uniquify (reverse links))))
8524 (cond
8525 ((null links)
8526 (message "No links"))
8527 ((equal (length links) 1)
8528 (setq link (car links)))
8529 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8530 (setq link (nth (if have-zero nth (1- nth)) links)))
8531 (t ; we have to select a link
8532 (save-excursion
8533 (save-window-excursion
8534 (delete-other-windows)
8535 (with-output-to-temp-buffer "*Select Link*"
8536 (mapc (lambda (l)
8537 (if (not (string-match org-bracket-link-regexp l))
8538 (princ (format "[%c] %s\n" (incf cnt)
8539 (org-remove-angle-brackets l)))
8540 (if (match-end 3)
8541 (princ (format "[%c] %s (%s)\n" (incf cnt)
8542 (match-string 3 l) (match-string 1 l)))
8543 (princ (format "[%c] %s\n" (incf cnt)
8544 (match-string 1 l))))))
8545 links))
8546 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8547 (message "Select link to open:")
8548 (setq c (read-char-exclusive))
8549 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8550 (when (equal c ?q) (error "Abort"))
8551 (setq nth (- c ?0))
8552 (if have-zero (setq nth (1+ nth)))
8553 (unless (and (integerp nth) (>= (length links) nth))
8554 (error "Invalid link selection"))
8555 (setq link (nth (1- nth) links))))
8556 (if link
8557 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8558 nil)))
8560 ;;;; Time estimates
8562 (defun org-get-effort (&optional pom)
8563 "Get the effort estimate for the current entry."
8564 (org-entry-get pom org-effort-property))
8566 ;;; File search
8568 (defvar org-create-file-search-functions nil
8569 "List of functions to construct the right search string for a file link.
8570 These functions are called in turn with point at the location to
8571 which the link should point.
8573 A function in the hook should first test if it would like to
8574 handle this file type, for example by checking the major-mode or
8575 the file extension. If it decides not to handle this file, it
8576 should just return nil to give other functions a chance. If it
8577 does handle the file, it must return the search string to be used
8578 when following the link. The search string will be part of the
8579 file link, given after a double colon, and `org-open-at-point'
8580 will automatically search for it. If special measures must be
8581 taken to make the search successful, another function should be
8582 added to the companion hook `org-execute-file-search-functions',
8583 which see.
8585 A function in this hook may also use `setq' to set the variable
8586 `description' to provide a suggestion for the descriptive text to
8587 be used for this link when it gets inserted into an Org-mode
8588 buffer with \\[org-insert-link].")
8590 (defvar org-execute-file-search-functions nil
8591 "List of functions to execute a file search triggered by a link.
8593 Functions added to this hook must accept a single argument, the
8594 search string that was part of the file link, the part after the
8595 double colon. The function must first check if it would like to
8596 handle this search, for example by checking the major-mode or the
8597 file extension. If it decides not to handle this search, it
8598 should just return nil to give other functions a chance. If it
8599 does handle the search, it must return a non-nil value to keep
8600 other functions from trying.
8602 Each function can access the current prefix argument through the
8603 variable `current-prefix-argument'. Note that a single prefix is
8604 used to force opening a link in Emacs, so it may be good to only
8605 use a numeric or double prefix to guide the search function.
8607 In case this is needed, a function in this hook can also restore
8608 the window configuration before `org-open-at-point' was called using:
8610 (set-window-configuration org-window-config-before-follow-link)")
8612 (defun org-link-search (s &optional type avoid-pos)
8613 "Search for a link search option.
8614 If S is surrounded by forward slashes, it is interpreted as a
8615 regular expression. In org-mode files, this will create an `org-occur'
8616 sparse tree. In ordinary files, `occur' will be used to list matches.
8617 If the current buffer is in `dired-mode', grep will be used to search
8618 in all files. If AVOID-POS is given, ignore matches near that position."
8619 (let ((case-fold-search t)
8620 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8621 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8622 (append '(("") (" ") ("\t") ("\n"))
8623 org-emphasis-alist)
8624 "\\|") "\\)"))
8625 (pos (point))
8626 (pre nil) (post nil)
8627 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8628 (cond
8629 ;; First check if there are any special
8630 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8631 ;; Now try the builtin stuff
8632 ((and (equal (string-to-char s0) ?#)
8633 (> (length s0) 1)
8634 (save-excursion
8635 (goto-char (point-min))
8636 (and
8637 (re-search-forward
8638 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8639 (setq type 'dedicated
8640 pos (match-beginning 0))))
8641 ;; There is an exact target for this
8642 (goto-char pos)
8643 (org-back-to-heading t)))
8644 ((save-excursion
8645 (goto-char (point-min))
8646 (and
8647 (re-search-forward
8648 (concat "<<" (regexp-quote s0) ">>") nil t)
8649 (setq type 'dedicated
8650 pos (match-beginning 0))))
8651 ;; There is an exact target for this
8652 (goto-char pos))
8653 ((and (string-match "^(\\(.*\\))$" s0)
8654 (save-excursion
8655 (goto-char (point-min))
8656 (and
8657 (re-search-forward
8658 (concat "[^[]" (regexp-quote
8659 (format org-coderef-label-format
8660 (match-string 1 s0))))
8661 nil t)
8662 (setq type 'dedicated
8663 pos (1+ (match-beginning 0))))))
8664 ;; There is a coderef target for this
8665 (goto-char pos))
8666 ((string-match "^/\\(.*\\)/$" s)
8667 ;; A regular expression
8668 (cond
8669 ((org-mode-p)
8670 (org-occur (match-string 1 s)))
8671 ;;((eq major-mode 'dired-mode)
8672 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8673 (t (org-do-occur (match-string 1 s)))))
8675 ;; A normal search strings
8676 (when (equal (string-to-char s) ?*)
8677 ;; Anchor on headlines, post may include tags.
8678 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8679 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8680 s (substring s 1)))
8681 (remove-text-properties
8682 0 (length s)
8683 '(face nil mouse-face nil keymap nil fontified nil) s)
8684 ;; Make a series of regular expressions to find a match
8685 (setq words (org-split-string s "[ \n\r\t]+")
8687 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8688 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8689 "\\)" markers)
8690 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8691 re2a (concat "[ \t\r\n]" re2a_)
8692 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8693 re4 (concat "[^a-zA-Z_]" re4_)
8695 re1 (concat pre re2 post)
8696 re3 (concat pre (if pre re4_ re4) post)
8697 re5 (concat pre ".*" re4)
8698 re2 (concat pre re2)
8699 re2a (concat pre (if pre re2a_ re2a))
8700 re4 (concat pre (if pre re4_ re4))
8701 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8702 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8703 re5 "\\)"
8705 (cond
8706 ((eq type 'org-occur) (org-occur reall))
8707 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8708 (t (goto-char (point-min))
8709 (setq type 'fuzzy)
8710 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8711 (org-search-not-self 1 re1 nil t)
8712 (org-search-not-self 1 re2 nil t)
8713 (org-search-not-self 1 re2a nil t)
8714 (org-search-not-self 1 re3 nil t)
8715 (org-search-not-self 1 re4 nil t)
8716 (org-search-not-self 1 re5 nil t)
8718 (goto-char (match-beginning 1))
8719 (goto-char pos)
8720 (error "No match")))))
8722 ;; Normal string-search
8723 (goto-char (point-min))
8724 (if (search-forward s nil t)
8725 (goto-char (match-beginning 0))
8726 (error "No match"))))
8727 (and (org-mode-p) (org-show-context 'link-search))
8728 type))
8730 (defun org-search-not-self (group &rest args)
8731 "Execute `re-search-forward', but only accept matches that do not
8732 enclose the position of `org-open-link-marker'."
8733 (let ((m org-open-link-marker))
8734 (catch 'exit
8735 (while (apply 're-search-forward args)
8736 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8737 (goto-char (match-end group))
8738 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8739 (> (match-beginning 0) (marker-position m))
8740 (< (match-end 0) (marker-position m)))
8741 (save-match-data
8742 (or (not (org-in-regexp
8743 org-bracket-link-analytic-regexp 1))
8744 (not (match-end 4)) ; no description
8745 (and (<= (match-beginning 4) (point))
8746 (>= (match-end 4) (point))))))
8747 (throw 'exit (point))))))))
8749 (defun org-get-buffer-for-internal-link (buffer)
8750 "Return a buffer to be used for displaying the link target of internal links."
8751 (cond
8752 ((not org-display-internal-link-with-indirect-buffer)
8753 buffer)
8754 ((string-match "(Clone)$" (buffer-name buffer))
8755 (message "Buffer is already a clone, not making another one")
8756 ;; we also do not modify visibility in this case
8757 buffer)
8758 (t ; make a new indirect buffer for displaying the link
8759 (let* ((bn (buffer-name buffer))
8760 (ibn (concat bn "(Clone)"))
8761 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8762 (with-current-buffer ib (org-overview))
8763 ib))))
8765 (defun org-do-occur (regexp &optional cleanup)
8766 "Call the Emacs command `occur'.
8767 If CLEANUP is non-nil, remove the printout of the regular expression
8768 in the *Occur* buffer. This is useful if the regex is long and not useful
8769 to read."
8770 (occur regexp)
8771 (when cleanup
8772 (let ((cwin (selected-window)) win beg end)
8773 (when (setq win (get-buffer-window "*Occur*"))
8774 (select-window win))
8775 (goto-char (point-min))
8776 (when (re-search-forward "match[a-z]+" nil t)
8777 (setq beg (match-end 0))
8778 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8779 (setq end (1- (match-beginning 0)))))
8780 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8781 (goto-char (point-min))
8782 (select-window cwin))))
8784 ;;; The mark ring for links jumps
8786 (defvar org-mark-ring nil
8787 "Mark ring for positions before jumps in Org-mode.")
8788 (defvar org-mark-ring-last-goto nil
8789 "Last position in the mark ring used to go back.")
8790 ;; Fill and close the ring
8791 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8792 (loop for i from 1 to org-mark-ring-length do
8793 (push (make-marker) org-mark-ring))
8794 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8795 org-mark-ring)
8797 (defun org-mark-ring-push (&optional pos buffer)
8798 "Put the current position or POS into the mark ring and rotate it."
8799 (interactive)
8800 (setq pos (or pos (point)))
8801 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8802 (move-marker (car org-mark-ring)
8803 (or pos (point))
8804 (or buffer (current-buffer)))
8805 (message "%s"
8806 (substitute-command-keys
8807 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8809 (defun org-mark-ring-goto (&optional n)
8810 "Jump to the previous position in the mark ring.
8811 With prefix arg N, jump back that many stored positions. When
8812 called several times in succession, walk through the entire ring.
8813 Org-mode commands jumping to a different position in the current file,
8814 or to another Org-mode file, automatically push the old position
8815 onto the ring."
8816 (interactive "p")
8817 (let (p m)
8818 (if (eq last-command this-command)
8819 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8820 (setq p org-mark-ring))
8821 (setq org-mark-ring-last-goto p)
8822 (setq m (car p))
8823 (switch-to-buffer (marker-buffer m))
8824 (goto-char m)
8825 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8827 (defun org-remove-angle-brackets (s)
8828 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8829 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8831 (defun org-add-angle-brackets (s)
8832 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8833 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8835 (defun org-remove-double-quotes (s)
8836 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8837 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8840 ;;; Following specific links
8842 (defun org-follow-timestamp-link ()
8843 (cond
8844 ((org-at-date-range-p t)
8845 (let ((org-agenda-start-on-weekday)
8846 (t1 (match-string 1))
8847 (t2 (match-string 2)))
8848 (setq t1 (time-to-days (org-time-string-to-time t1))
8849 t2 (time-to-days (org-time-string-to-time t2)))
8850 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8851 ((org-at-timestamp-p t)
8852 (org-agenda-list nil (time-to-days (org-time-string-to-time
8853 (substring (match-string 1) 0 10)))
8855 (t (error "This should not happen"))))
8858 ;;; Following file links
8859 (defvar org-wait nil)
8860 (defun org-open-file (path &optional in-emacs line search)
8861 "Open the file at PATH.
8862 First, this expands any special file name abbreviations. Then the
8863 configuration variable `org-file-apps' is checked if it contains an
8864 entry for this file type, and if yes, the corresponding command is launched.
8866 If no application is found, Emacs simply visits the file.
8868 With optional prefix argument IN-EMACS, Emacs will visit the file.
8869 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8870 and o use an external application to visit the file.
8872 Optional LINE specifies a line to go to, optional SEARCH a string to
8873 search for. If LINE or SEARCH is given, the file will always be
8874 opened in Emacs.
8875 If the file does not exist, an error is thrown."
8876 (setq in-emacs (or in-emacs line search))
8877 (let* ((file (if (equal path "")
8878 buffer-file-name
8879 (substitute-in-file-name (expand-file-name path))))
8880 (apps (append org-file-apps (org-default-apps)))
8881 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8882 (dirp (if remp nil (file-directory-p file)))
8883 (file (if (and dirp org-open-directory-means-index-dot-org)
8884 (concat (file-name-as-directory file) "index.org")
8885 file))
8886 (a-m-a-p (assq 'auto-mode apps))
8887 (dfile (downcase file))
8888 (old-buffer (current-buffer))
8889 (old-pos (point))
8890 (old-mode major-mode)
8891 ext cmd)
8892 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8893 (setq ext (match-string 1 dfile))
8894 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8895 (setq ext (match-string 1 dfile))))
8896 (cond
8897 ((equal in-emacs '(16))
8898 (setq cmd (cdr (assoc 'system apps))))
8899 (in-emacs (setq cmd 'emacs))
8901 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8902 (and dirp (cdr (assoc 'directory apps)))
8903 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8904 'string-match)
8905 (cdr (assoc ext apps))
8906 (cdr (assoc t apps))))))
8907 (when (eq cmd 'system)
8908 (setq cmd (cdr (assoc 'system apps))))
8909 (when (eq cmd 'default)
8910 (setq cmd (cdr (assoc t apps))))
8911 (when (eq cmd 'mailcap)
8912 (require 'mailcap)
8913 (mailcap-parse-mailcaps)
8914 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8915 (command (mailcap-mime-info mime-type)))
8916 (if (stringp command)
8917 (setq cmd command)
8918 (setq cmd 'emacs))))
8919 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8920 (not (file-exists-p file))
8921 (not org-open-non-existing-files))
8922 (error "No such file: %s" file))
8923 (cond
8924 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8925 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8926 (while (string-match "['\"]%s['\"]" cmd)
8927 (setq cmd (replace-match "%s" t t cmd)))
8928 (while (string-match "%s" cmd)
8929 (setq cmd (replace-match
8930 (save-match-data
8931 (shell-quote-argument
8932 (convert-standard-filename file)))
8933 t t cmd)))
8934 (save-window-excursion
8935 (start-process-shell-command cmd nil cmd)
8936 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8938 ((or (stringp cmd)
8939 (eq cmd 'emacs))
8940 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8941 (widen)
8942 (if line (org-goto-line line)
8943 (if search (org-link-search search))))
8944 ((consp cmd)
8945 (let ((file (convert-standard-filename file)))
8946 (eval cmd)))
8947 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8948 (and (org-mode-p) (eq old-mode 'org-mode)
8949 (or (not (equal old-buffer (current-buffer)))
8950 (not (equal old-pos (point))))
8951 (org-mark-ring-push old-pos old-buffer))))
8953 (defun org-default-apps ()
8954 "Return the default applications for this operating system."
8955 (cond
8956 ((eq system-type 'darwin)
8957 org-file-apps-defaults-macosx)
8958 ((eq system-type 'windows-nt)
8959 org-file-apps-defaults-windowsnt)
8960 (t org-file-apps-defaults-gnu)))
8962 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8963 "Convert extensions to regular expressions in the cars of LIST.
8964 Also, weed out any non-string entries, because the return value is used
8965 only for regexp matching.
8966 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8967 point to the symbol `emacs', indicating that the file should
8968 be opened in Emacs."
8969 (append
8970 (delq nil
8971 (mapcar (lambda (x)
8972 (if (not (stringp (car x)))
8974 (if (string-match "\\W" (car x))
8976 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8977 list))
8978 (if add-auto-mode
8979 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8981 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8982 (defun org-file-remote-p (file)
8983 "Test whether FILE specifies a location on a remote system.
8984 Return non-nil if the location is indeed remote.
8986 For example, the filename \"/user@host:/foo\" specifies a location
8987 on the system \"/user@host:\"."
8988 (cond ((fboundp 'file-remote-p)
8989 (file-remote-p file))
8990 ((fboundp 'tramp-handle-file-remote-p)
8991 (tramp-handle-file-remote-p file))
8992 ((and (boundp 'ange-ftp-name-format)
8993 (string-match (car ange-ftp-name-format) file))
8995 (t nil)))
8998 ;;;; Refiling
9000 (defun org-get-org-file ()
9001 "Read a filename, with default directory `org-directory'."
9002 (let ((default (or org-default-notes-file remember-data-file)))
9003 (read-file-name (format "File name [%s]: " default)
9004 (file-name-as-directory org-directory)
9005 default)))
9007 (defun org-notes-order-reversed-p ()
9008 "Check if the current file should receive notes in reversed order."
9009 (cond
9010 ((not org-reverse-note-order) nil)
9011 ((eq t org-reverse-note-order) t)
9012 ((not (listp org-reverse-note-order)) nil)
9013 (t (catch 'exit
9014 (let ((all org-reverse-note-order)
9015 entry)
9016 (while (setq entry (pop all))
9017 (if (string-match (car entry) buffer-file-name)
9018 (throw 'exit (cdr entry))))
9019 nil)))))
9021 (defvar org-refile-target-table nil
9022 "The list of refile targets, created by `org-refile'.")
9024 (defvar org-agenda-new-buffers nil
9025 "Buffers created to visit agenda files.")
9027 (defun org-get-refile-targets (&optional default-buffer)
9028 "Produce a table with refile targets."
9029 (let ((case-fold-search nil)
9030 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9031 (entries (or org-refile-targets '((nil . (:level . 1)))))
9032 targets txt re files f desc descre fast-path-p level pos0)
9033 (message "Getting targets...")
9034 (with-current-buffer (or default-buffer (current-buffer))
9035 (while (setq entry (pop entries))
9036 (setq files (car entry) desc (cdr entry))
9037 (setq fast-path-p nil)
9038 (cond
9039 ((null files) (setq files (list (current-buffer))))
9040 ((eq files 'org-agenda-files)
9041 (setq files (org-agenda-files 'unrestricted)))
9042 ((and (symbolp files) (fboundp files))
9043 (setq files (funcall files)))
9044 ((and (symbolp files) (boundp files))
9045 (setq files (symbol-value files))))
9046 (if (stringp files) (setq files (list files)))
9047 (cond
9048 ((eq (car desc) :tag)
9049 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9050 ((eq (car desc) :todo)
9051 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9052 ((eq (car desc) :regexp)
9053 (setq descre (cdr desc)))
9054 ((eq (car desc) :level)
9055 (setq descre (concat "^\\*\\{" (number-to-string
9056 (if org-odd-levels-only
9057 (1- (* 2 (cdr desc)))
9058 (cdr desc)))
9059 "\\}[ \t]")))
9060 ((eq (car desc) :maxlevel)
9061 (setq fast-path-p t)
9062 (setq descre (concat "^\\*\\{1," (number-to-string
9063 (if org-odd-levels-only
9064 (1- (* 2 (cdr desc)))
9065 (cdr desc)))
9066 "\\}[ \t]")))
9067 (t (error "Bad refiling target description %s" desc)))
9068 (while (setq f (pop files))
9069 (with-current-buffer
9070 (if (bufferp f) f (org-get-agenda-file-buffer f))
9071 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9072 (setq f (and f (expand-file-name f)))
9073 (if (eq org-refile-use-outline-path 'file)
9074 (push (list (file-name-nondirectory f) f nil nil) targets))
9075 (save-excursion
9076 (save-restriction
9077 (widen)
9078 (goto-char (point-min))
9079 (while (re-search-forward descre nil t)
9080 (goto-char (setq pos0 (point-at-bol)))
9081 (catch 'next
9082 (when org-refile-target-verify-function
9083 (save-match-data
9084 (or (funcall org-refile-target-verify-function)
9085 (throw 'next t))))
9086 (when (looking-at org-complex-heading-regexp)
9087 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9088 txt (org-link-display-format (match-string 4))
9089 re (concat "^" (regexp-quote
9090 (buffer-substring (match-beginning 1)
9091 (match-end 4)))))
9092 (if (match-end 5) (setq re (concat re "[ \t]+"
9093 (regexp-quote
9094 (match-string 5)))))
9095 (setq re (concat re "[ \t]*$"))
9096 (when org-refile-use-outline-path
9097 (setq txt (mapconcat 'org-protect-slash
9098 (append
9099 (if (eq org-refile-use-outline-path 'file)
9100 (list (file-name-nondirectory
9101 (buffer-file-name (buffer-base-buffer))))
9102 (if (eq org-refile-use-outline-path 'full-file-path)
9103 (list (buffer-file-name (buffer-base-buffer)))))
9104 (org-get-outline-path fast-path-p level txt)
9105 (list txt))
9106 "/")))
9107 (push (list txt f re (point)) targets)))
9108 (when (= (point) pos0)
9109 ;; verification function has not moved point
9110 (goto-char (point-at-eol))))))))))
9111 (message "Getting targets...done")
9112 (nreverse targets)))
9114 (defun org-protect-slash (s)
9115 (while (string-match "/" s)
9116 (setq s (replace-match "\\" t t s)))
9119 (defvar org-olpa (make-vector 20 nil))
9121 (defun org-get-outline-path (&optional fastp level heading)
9122 "Return the outline path to the current entry, as a list.
9123 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9124 routine which makes outline path derivations for an entire file,
9125 avoiding backtracing."
9126 (if fastp
9127 (progn
9128 (if (> level 19)
9129 (error "Outline path failure, more than 19 levels."))
9130 (loop for i from level upto 19 do
9131 (aset org-olpa i nil))
9132 (prog1
9133 (delq nil (append org-olpa nil))
9134 (aset org-olpa level heading)))
9135 (let (rtn)
9136 (save-excursion
9137 (save-restriction
9138 (widen)
9139 (while (org-up-heading-safe)
9140 (when (looking-at org-complex-heading-regexp)
9141 (push (org-match-string-no-properties 4) rtn)))
9142 rtn)))))
9144 (defun org-format-outline-path (path &optional width prefix)
9145 "Format the outlie path PATH for display.
9146 Width is the maximum number of characters that is available.
9147 Prefix is a prefix to be included in the returned string,
9148 such as the file name."
9149 (setq width (or width 79))
9150 (if prefix (setq width (- width (length prefix))))
9151 (if (not path)
9152 (or prefix "")
9153 (let* ((nsteps (length path))
9154 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9155 (maxwidth (if (<= total-width width)
9156 10000 ;; everything fits
9157 ;; we need to shorten the level headings
9158 (/ (- width nsteps) nsteps)))
9159 (org-odd-levels-only nil)
9160 (n 0)
9161 (total (1+ (length prefix))))
9162 (setq maxwidth (max maxwidth 10))
9163 (concat prefix
9164 (mapconcat
9165 (lambda (h)
9166 (setq n (1+ n))
9167 (if (and (= n nsteps) (< maxwidth 10000))
9168 (setq maxwidth (- total-width total)))
9169 (if (< (length h) maxwidth)
9170 (progn (setq total (+ total (length h) 1)) h)
9171 (setq h (substring h 0 (- maxwidth 2))
9172 total (+ total maxwidth 1))
9173 (if (string-match "[ \t]+\\'" h)
9174 (setq h (substring h 0 (match-beginning 0))))
9175 (setq h (concat h "..")))
9176 (org-add-props h nil 'face
9177 (nth (% (1- n) org-n-level-faces)
9178 org-level-faces))
9180 path "/")))))
9182 (defun org-display-outline-path (&optional file current)
9183 "Display the current outline path in the echo area."
9184 (interactive "P")
9185 (let ((bfn (buffer-file-name (buffer-base-buffer)))
9186 (path (and (org-mode-p) (org-get-outline-path))))
9187 (if current (setq path (append path
9188 (save-excursion
9189 (org-back-to-heading t)
9190 (if (looking-at org-complex-heading-regexp)
9191 (list (match-string 4)))))))
9192 (message "%s"
9193 (org-format-outline-path
9194 path
9195 (1- (frame-width))
9196 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9198 (defvar org-refile-history nil
9199 "History for refiling operations.")
9201 (defvar org-after-refile-insert-hook nil
9202 "Hook run after `org-refile' has inserted its stuff at the new location.
9203 Note that this is still *before* the stuff will be removed from
9204 the *old* location.")
9206 (defun org-refile (&optional goto default-buffer rfloc)
9207 "Move the entry at point to another heading.
9208 The list of target headings is compiled using the information in
9209 `org-refile-targets', which see. This list is created before each use
9210 and will therefore always be up-to-date.
9212 At the target location, the entry is filed as a subitem of the target heading.
9213 Depending on `org-reverse-note-order', the new subitem will either be the
9214 first or the last subitem.
9216 If there is an active region, all entries in that region will be moved.
9217 However, the region must fulfil the requirement that the first heading
9218 is the first one sets the top-level of the moved text - at most siblings
9219 below it are allowed.
9221 With prefix arg GOTO, the command will only visit the target location,
9222 not actually move anything.
9223 With a double prefix `C-u C-u', go to the location where the last refiling
9224 operation has put the subtree.
9225 With a prefix argument of `2', refile to the running clock.
9227 RFLOC can be a refile location obtained in a different way.
9229 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9230 (interactive "P")
9231 (let* ((cbuf (current-buffer))
9232 (regionp (org-region-active-p))
9233 (region-start (and regionp (region-beginning)))
9234 (region-end (and regionp (region-end)))
9235 (region-length (and regionp (- region-end region-start)))
9236 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9237 pos it nbuf file re level reversed)
9238 (setq last-command nil)
9239 (when regionp
9240 (goto-char region-start)
9241 (or (bolp) (goto-char (point-at-bol)))
9242 (setq region-start (point))
9243 (unless (org-kill-is-subtree-p
9244 (buffer-substring region-start region-end))
9245 (error "The region is not a (sequence of) subtree(s)")))
9246 (if (equal goto '(16))
9247 (org-refile-goto-last-stored)
9248 (when (or
9249 (and (equal goto 2)
9250 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9251 (prog1
9252 (setq it (list (or org-clock-heading "running clock")
9253 (buffer-file-name
9254 (marker-buffer org-clock-hd-marker))
9256 (marker-position org-clock-hd-marker)))
9257 (setq goto nil)))
9258 (setq it (or rfloc
9259 (save-excursion
9260 (org-refile-get-location
9261 (if goto "Goto: " "Refile to: ") default-buffer
9262 org-refile-allow-creating-parent-nodes)))))
9263 (setq file (nth 1 it)
9264 re (nth 2 it)
9265 pos (nth 3 it))
9266 (if (and (not goto)
9268 (equal (buffer-file-name) file)
9269 (if regionp
9270 (and (>= pos region-start)
9271 (<= pos region-end))
9272 (and (>= pos (point))
9273 (< pos (save-excursion
9274 (org-end-of-subtree t t))))))
9275 (error "Cannot refile to position inside the tree or region"))
9277 (setq nbuf (or (find-buffer-visiting file)
9278 (find-file-noselect file)))
9279 (if goto
9280 (progn
9281 (switch-to-buffer nbuf)
9282 (goto-char pos)
9283 (org-show-context 'org-goto))
9284 (if regionp
9285 (progn
9286 (org-kill-new (buffer-substring region-start region-end))
9287 (org-save-markers-in-region region-start region-end))
9288 (org-copy-subtree 1 nil t))
9289 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9290 (find-file-noselect file)))
9291 (setq reversed (org-notes-order-reversed-p))
9292 (save-excursion
9293 (save-restriction
9294 (widen)
9295 (if pos
9296 (progn
9297 (goto-char pos)
9298 (looking-at outline-regexp)
9299 (setq level (org-get-valid-level (funcall outline-level) 1))
9300 (goto-char
9301 (if reversed
9302 (or (outline-next-heading) (point-max))
9303 (or (save-excursion (org-get-next-sibling))
9304 (org-end-of-subtree t t)
9305 (point-max)))))
9306 (setq level 1)
9307 (if (not reversed)
9308 (goto-char (point-max))
9309 (goto-char (point-min))
9310 (or (outline-next-heading) (goto-char (point-max)))))
9311 (if (not (bolp)) (newline))
9312 (bookmark-set "org-refile-last-stored")
9313 (org-paste-subtree level)
9314 (if (fboundp 'deactivate-mark) (deactivate-mark))
9315 (run-hooks 'org-after-refile-insert-hook))))
9316 (if regionp
9317 (delete-region (point) (+ (point) region-length))
9318 (org-cut-subtree))
9319 (when (featurep 'org-inlinetask)
9320 (org-inlinetask-remove-END-maybe))
9321 (setq org-markers-to-move nil)
9322 (message "Refiled to \"%s\"" (car it))))))
9323 (org-reveal))
9325 (defun org-refile-goto-last-stored ()
9326 "Go to the location where the last refile was stored."
9327 (interactive)
9328 (bookmark-jump "org-refile-last-stored")
9329 (message "This is the location of the last refile"))
9331 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9332 "Prompt the user for a refile location, using PROMPT."
9333 (let ((org-refile-targets org-refile-targets)
9334 (org-refile-use-outline-path org-refile-use-outline-path))
9335 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9336 (unless org-refile-target-table
9337 (error "No refile targets"))
9338 (let* ((cbuf (current-buffer))
9339 (partial-completion-mode nil)
9340 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9341 (cfunc (if (and org-refile-use-outline-path
9342 org-outline-path-complete-in-steps)
9343 'org-olpath-completing-read
9344 'org-icompleting-read))
9345 (extra (if org-refile-use-outline-path "/" ""))
9346 (filename (and cfn (expand-file-name cfn)))
9347 (tbl (mapcar
9348 (lambda (x)
9349 (if (and (not (member org-refile-use-outline-path
9350 '(file full-file-path)))
9351 (not (equal filename (nth 1 x))))
9352 (cons (concat (car x) extra " ("
9353 (file-name-nondirectory (nth 1 x)) ")")
9354 (cdr x))
9355 (cons (concat (car x) extra) (cdr x))))
9356 org-refile-target-table))
9357 (completion-ignore-case t)
9358 pa answ parent-target child parent old-hist)
9359 (setq old-hist org-refile-history)
9360 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9361 nil 'org-refile-history))
9362 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9363 (if pa
9364 (progn
9365 (when (or (not org-refile-history)
9366 (not (eq old-hist org-refile-history))
9367 (not (equal (car pa) (car org-refile-history))))
9368 (setq org-refile-history
9369 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9370 org-refile-history
9371 (cdr org-refile-history))))
9372 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9373 (pop org-refile-history)))
9375 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9376 (setq parent (match-string 1 answ)
9377 child (match-string 2 answ))
9378 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9379 (when (and parent-target
9380 (or (eq new-nodes t)
9381 (and (eq new-nodes 'confirm)
9382 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9383 (org-refile-new-child parent-target child))))))
9385 (defun org-refile-new-child (parent-target child)
9386 "Use refile target PARENT-TARGET to add new CHILD below it."
9387 (unless parent-target
9388 (error "Cannot find parent for new node"))
9389 (let ((file (nth 1 parent-target))
9390 (pos (nth 3 parent-target))
9391 level)
9392 (with-current-buffer (or (find-buffer-visiting file)
9393 (find-file-noselect file))
9394 (save-excursion
9395 (save-restriction
9396 (widen)
9397 (if pos
9398 (goto-char pos)
9399 (goto-char (point-max))
9400 (if (not (bolp)) (newline)))
9401 (when (looking-at outline-regexp)
9402 (setq level (funcall outline-level))
9403 (org-end-of-subtree t t))
9404 (org-back-over-empty-lines)
9405 (insert "\n" (make-string
9406 (if pos (org-get-valid-level level 1) 1) ?*)
9407 " " child "\n")
9408 (beginning-of-line 0)
9409 (list (concat (car parent-target) "/" child) file "" (point)))))))
9411 (defun org-olpath-completing-read (prompt collection &rest args)
9412 "Read an outline path like a file name."
9413 (let ((thetable collection)
9414 (org-completion-use-ido nil) ; does not work with ido.
9415 (org-completion-use-iswitchb nil)) ; or iswitchb
9416 (apply
9417 'org-icompleting-read prompt
9418 (lambda (string predicate &optional flag)
9419 (let (rtn r f (l (length string)))
9420 (cond
9421 ((eq flag nil)
9422 ;; try completion
9423 (try-completion string thetable))
9424 ((eq flag t)
9425 ;; all-completions
9426 (setq rtn (all-completions string thetable predicate))
9427 (mapcar
9428 (lambda (x)
9429 (setq r (substring x l))
9430 (if (string-match " ([^)]*)$" x)
9431 (setq f (match-string 0 x))
9432 (setq f ""))
9433 (if (string-match "/" r)
9434 (concat string (substring r 0 (match-end 0)) f)
9436 rtn))
9437 ((eq flag 'lambda)
9438 ;; exact match?
9439 (assoc string thetable)))
9441 args)))
9443 ;;;; Dynamic blocks
9445 (defun org-find-dblock (name)
9446 "Find the first dynamic block with name NAME in the buffer.
9447 If not found, stay at current position and return nil."
9448 (let (pos)
9449 (save-excursion
9450 (goto-char (point-min))
9451 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9452 nil t)
9453 (match-beginning 0))))
9454 (if pos (goto-char pos))
9455 pos))
9457 (defconst org-dblock-start-re
9458 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9459 "Matches the start line of a dynamic block, with parameters.")
9461 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9462 "Matches the end of a dynamic block.")
9464 (defun org-create-dblock (plist)
9465 "Create a dynamic block section, with parameters taken from PLIST.
9466 PLIST must contain a :name entry which is used as name of the block."
9467 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9468 (end-of-line 1)
9469 (newline))
9470 (let ((col (current-column))
9471 (name (plist-get plist :name)))
9472 (insert "#+BEGIN: " name)
9473 (while plist
9474 (if (eq (car plist) :name)
9475 (setq plist (cddr plist))
9476 (insert " " (prin1-to-string (pop plist)))))
9477 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9478 (beginning-of-line -2)))
9480 (defun org-prepare-dblock ()
9481 "Prepare dynamic block for refresh.
9482 This empties the block, puts the cursor at the insert position and returns
9483 the property list including an extra property :name with the block name."
9484 (unless (looking-at org-dblock-start-re)
9485 (error "Not at a dynamic block"))
9486 (let* ((begdel (1+ (match-end 0)))
9487 (name (org-no-properties (match-string 1)))
9488 (params (append (list :name name)
9489 (read (concat "(" (match-string 3) ")")))))
9490 (save-excursion
9491 (beginning-of-line 1)
9492 (skip-chars-forward " \t")
9493 (setq params (plist-put params :indentation-column (current-column))))
9494 (unless (re-search-forward org-dblock-end-re nil t)
9495 (error "Dynamic block not terminated"))
9496 (setq params
9497 (append params
9498 (list :content (buffer-substring
9499 begdel (match-beginning 0)))))
9500 (delete-region begdel (match-beginning 0))
9501 (goto-char begdel)
9502 (open-line 1)
9503 params))
9505 (defun org-map-dblocks (&optional command)
9506 "Apply COMMAND to all dynamic blocks in the current buffer.
9507 If COMMAND is not given, use `org-update-dblock'."
9508 (let ((cmd (or command 'org-update-dblock))
9509 pos)
9510 (save-excursion
9511 (goto-char (point-min))
9512 (while (re-search-forward org-dblock-start-re nil t)
9513 (goto-char (setq pos (match-beginning 0)))
9514 (condition-case nil
9515 (funcall cmd)
9516 (error (message "Error during update of dynamic block")))
9517 (goto-char pos)
9518 (unless (re-search-forward org-dblock-end-re nil t)
9519 (error "Dynamic block not terminated"))))))
9521 (defun org-dblock-update (&optional arg)
9522 "User command for updating dynamic blocks.
9523 Update the dynamic block at point. With prefix ARG, update all dynamic
9524 blocks in the buffer."
9525 (interactive "P")
9526 (if arg
9527 (org-update-all-dblocks)
9528 (or (looking-at org-dblock-start-re)
9529 (org-beginning-of-dblock))
9530 (org-update-dblock)))
9532 (defun org-update-dblock ()
9533 "Update the dynamic block at point
9534 This means to empty the block, parse for parameters and then call
9535 the correct writing function."
9536 (save-window-excursion
9537 (let* ((pos (point))
9538 (line (org-current-line))
9539 (params (org-prepare-dblock))
9540 (name (plist-get params :name))
9541 (indent (plist-get params :indentation-column))
9542 (cmd (intern (concat "org-dblock-write:" name))))
9543 (message "Updating dynamic block `%s' at line %d..." name line)
9544 (funcall cmd params)
9545 (message "Updating dynamic block `%s' at line %d...done" name line)
9546 (goto-char pos)
9547 (when (and indent (> indent 0))
9548 (setq indent (make-string indent ?\ ))
9549 (save-excursion
9550 (org-beginning-of-dblock)
9551 (forward-line 1)
9552 (while (not (looking-at org-dblock-end-re))
9553 (insert indent)
9554 (beginning-of-line 2))
9555 (when (looking-at org-dblock-end-re)
9556 (and (looking-at "[ \t]+")
9557 (replace-match ""))
9558 (insert indent)))))))
9560 (defun org-beginning-of-dblock ()
9561 "Find the beginning of the dynamic block at point.
9562 Error if there is no such block at point."
9563 (let ((pos (point))
9564 beg)
9565 (end-of-line 1)
9566 (if (and (re-search-backward org-dblock-start-re nil t)
9567 (setq beg (match-beginning 0))
9568 (re-search-forward org-dblock-end-re nil t)
9569 (> (match-end 0) pos))
9570 (goto-char beg)
9571 (goto-char pos)
9572 (error "Not in a dynamic block"))))
9574 (defun org-update-all-dblocks ()
9575 "Update all dynamic blocks in the buffer.
9576 This function can be used in a hook."
9577 (when (org-mode-p)
9578 (org-map-dblocks 'org-update-dblock)))
9581 ;;;; Completion
9583 (defconst org-additional-option-like-keywords
9584 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9585 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9586 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9587 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9588 "BEGIN:" "END:"
9589 "ORGTBL" "TBLFM:" "TBLNAME:"
9590 "BEGIN_EXAMPLE" "END_EXAMPLE"
9591 "BEGIN_QUOTE" "END_QUOTE"
9592 "BEGIN_VERSE" "END_VERSE"
9593 "BEGIN_CENTER" "END_CENTER"
9594 "BEGIN_SRC" "END_SRC"
9595 "CATEGORY" "COLUMNS"
9596 "CAPTION" "LABEL"
9597 "SETUPFILE"
9598 "BIND"
9599 "MACRO"))
9601 (defcustom org-structure-template-alist
9603 ("s" "#+begin_src ?\n\n#+end_src"
9604 "<src lang=\"?\">\n\n</src>")
9605 ("e" "#+begin_example\n?\n#+end_example"
9606 "<example>\n?\n</example>")
9607 ("q" "#+begin_quote\n?\n#+end_quote"
9608 "<quote>\n?\n</quote>")
9609 ("v" "#+begin_verse\n?\n#+end_verse"
9610 "<verse>\n?\n/verse>")
9611 ("c" "#+begin_center\n?\n#+end_center"
9612 "<center>\n?\n/center>")
9613 ("l" "#+begin_latex\n?\n#+end_latex"
9614 "<literal style=\"latex\">\n?\n</literal>")
9615 ("L" "#+latex: "
9616 "<literal style=\"latex\">?</literal>")
9617 ("h" "#+begin_html\n?\n#+end_html"
9618 "<literal style=\"html\">\n?\n</literal>")
9619 ("H" "#+html: "
9620 "<literal style=\"html\">?</literal>")
9621 ("a" "#+begin_ascii\n?\n#+end_ascii")
9622 ("A" "#+ascii: ")
9623 ("i" "#+include %file ?"
9624 "<include file=%file markup=\"?\">")
9626 "Structure completion elements.
9627 This is a list of abbreviation keys and values. The value gets inserted
9628 it you type @samp{.} followed by the key and then the completion key,
9629 usually `M-TAB'. %file will be replaced by a file name after prompting
9630 for the file using completion.
9631 There are two templates for each key, the first uses the original Org syntax,
9632 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9633 the default when the /org-mtags.el/ module has been loaded. See also the
9634 variable `org-mtags-prefer-muse-templates'.
9635 This is an experimental feature, it is undecided if it is going to stay in."
9636 :group 'org-completion
9637 :type '(repeat
9638 (string :tag "Key")
9639 (string :tag "Template")
9640 (string :tag "Muse Template")))
9642 (defun org-try-structure-completion ()
9643 "Try to complete a structure template before point.
9644 This looks for strings like \"<e\" on an otherwise empty line and
9645 expands them."
9646 (let ((l (buffer-substring (point-at-bol) (point)))
9648 (when (and (looking-at "[ \t]*$")
9649 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9650 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9651 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9652 (match-beginning 1)) a)
9653 t)))
9655 (defun org-complete-expand-structure-template (start cell)
9656 "Expand a structure template."
9657 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9658 (rpl (nth (if musep 2 1) cell))
9659 (ind ""))
9660 (delete-region start (point))
9661 (when (string-match "\\`#\\+" rpl)
9662 (cond
9663 ((bolp))
9664 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9665 (setq ind (buffer-substring (point-at-bol) (point))))
9666 (t (newline))))
9667 (setq start (point))
9668 (if (string-match "%file" rpl)
9669 (setq rpl (replace-match
9670 (concat
9671 "\""
9672 (save-match-data
9673 (abbreviate-file-name (read-file-name "Include file: ")))
9674 "\"")
9675 t t rpl)))
9676 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9677 (concat "\n" ind)))
9678 (insert rpl)
9679 (if (re-search-backward "\\?" start t) (delete-char 1))))
9682 (defun org-complete (&optional arg)
9683 "Perform completion on word at point.
9684 At the beginning of a headline, this completes TODO keywords as given in
9685 `org-todo-keywords'.
9686 If the current word is preceded by a backslash, completes the TeX symbols
9687 that are supported for HTML support.
9688 If the current word is preceded by \"#+\", completes special words for
9689 setting file options.
9690 In the line after \"#+STARTUP:, complete valid keywords.\"
9691 At all other locations, this simply calls the value of
9692 `org-completion-fallback-command'."
9693 (interactive "P")
9694 (org-without-partial-completion
9695 (catch 'exit
9696 (let* ((a nil)
9697 (end (point))
9698 (beg1 (save-excursion
9699 (skip-chars-backward (org-re "[:alnum:]_@"))
9700 (point)))
9701 (beg (save-excursion
9702 (skip-chars-backward "a-zA-Z0-9_:$")
9703 (point)))
9704 (confirm (lambda (x) (stringp (car x))))
9705 (searchhead (equal (char-before beg) ?*))
9706 (struct
9707 (when (and (member (char-before beg1) '(?. ?<))
9708 (setq a (assoc (buffer-substring beg1 (point))
9709 org-structure-template-alist)))
9710 (org-complete-expand-structure-template (1- beg1) a)
9711 (throw 'exit t)))
9712 (tag (and (equal (char-before beg1) ?:)
9713 (equal (char-after (point-at-bol)) ?*)))
9714 (prop (and (equal (char-before beg1) ?:)
9715 (not (equal (char-after (point-at-bol)) ?*))))
9716 (texp (equal (char-before beg) ?\\))
9717 (link (equal (char-before beg) ?\[))
9718 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9719 beg)
9720 "#+"))
9721 (startup (string-match "^#\\+STARTUP:.*"
9722 (buffer-substring (point-at-bol) (point))))
9723 (completion-ignore-case opt)
9724 (type nil)
9725 (tbl nil)
9726 (table (cond
9727 (opt
9728 (setq type :opt)
9729 (require 'org-exp)
9730 (append
9731 (delq nil
9732 (mapcar
9733 (lambda (x)
9734 (if (string-match
9735 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9736 (cons (match-string 2 x)
9737 (match-string 1 x))))
9738 (org-split-string (org-get-current-options) "\n")))
9739 (mapcar 'list org-additional-option-like-keywords)))
9740 (startup
9741 (setq type :startup)
9742 org-startup-options)
9743 (link (append org-link-abbrev-alist-local
9744 org-link-abbrev-alist))
9745 (texp
9746 (setq type :tex)
9747 org-html-entities)
9748 ((string-match "\\`\\*+[ \t]+\\'"
9749 (buffer-substring (point-at-bol) beg))
9750 (setq type :todo)
9751 (mapcar 'list org-todo-keywords-1))
9752 (searchhead
9753 (setq type :searchhead)
9754 (save-excursion
9755 (goto-char (point-min))
9756 (while (re-search-forward org-todo-line-regexp nil t)
9757 (push (list
9758 (org-make-org-heading-search-string
9759 (match-string 3) t))
9760 tbl)))
9761 tbl)
9762 (tag (setq type :tag beg beg1)
9763 (or org-tag-alist (org-get-buffer-tags)))
9764 (prop (setq type :prop beg beg1)
9765 (mapcar 'list (org-buffer-property-keys nil t t)))
9766 (t (progn
9767 (call-interactively org-completion-fallback-command)
9768 (throw 'exit nil)))))
9769 (pattern (buffer-substring-no-properties beg end))
9770 (completion (try-completion pattern table confirm)))
9771 (cond ((eq completion t)
9772 (if (not (assoc (upcase pattern) table))
9773 (message "Already complete")
9774 (if (and (equal type :opt)
9775 (not (member (car (assoc (upcase pattern) table))
9776 org-additional-option-like-keywords)))
9777 (insert (substring (cdr (assoc (upcase pattern) table))
9778 (length pattern)))
9779 (if (memq type '(:tag :prop)) (insert ":")))))
9780 ((null completion)
9781 (message "Can't find completion for \"%s\"" pattern)
9782 (ding))
9783 ((not (string= pattern completion))
9784 (delete-region beg end)
9785 (if (string-match " +$" completion)
9786 (setq completion (replace-match "" t t completion)))
9787 (insert completion)
9788 (if (get-buffer-window "*Completions*")
9789 (delete-window (get-buffer-window "*Completions*")))
9790 (if (assoc completion table)
9791 (if (eq type :todo) (insert " ")
9792 (if (memq type '(:tag :prop)) (insert ":"))))
9793 (if (and (equal type :opt) (assoc completion table))
9794 (message "%s" (substitute-command-keys
9795 "Press \\[org-complete] again to insert example settings"))))
9797 (message "Making completion list...")
9798 (let ((list (sort (all-completions pattern table confirm)
9799 'string<)))
9800 (with-output-to-temp-buffer "*Completions*"
9801 (condition-case nil
9802 ;; Protection needed for XEmacs and emacs 21
9803 (display-completion-list list pattern)
9804 (error (display-completion-list list)))))
9805 (message "Making completion list...%s" "done")))))))
9807 ;;;; TODO, DEADLINE, Comments
9809 (defun org-toggle-comment ()
9810 "Change the COMMENT state of an entry."
9811 (interactive)
9812 (save-excursion
9813 (org-back-to-heading)
9814 (let (case-fold-search)
9815 (if (looking-at (concat outline-regexp
9816 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9817 (replace-match "" t t nil 1)
9818 (if (looking-at outline-regexp)
9819 (progn
9820 (goto-char (match-end 0))
9821 (insert org-comment-string " ")))))))
9823 (defvar org-last-todo-state-is-todo nil
9824 "This is non-nil when the last TODO state change led to a TODO state.
9825 If the last change removed the TODO tag or switched to DONE, then
9826 this is nil.")
9828 (defvar org-setting-tags nil) ; dynamically skipped
9830 (defun org-parse-local-options (string var)
9831 "Parse STRING for startup setting relevant for variable VAR."
9832 (let ((rtn (symbol-value var))
9833 e opts)
9834 (save-match-data
9835 (if (or (not string) (not (string-match "\\S-" string)))
9837 (setq opts (delq nil (mapcar (lambda (x)
9838 (setq e (assoc x org-startup-options))
9839 (if (eq (nth 1 e) var) e nil))
9840 (org-split-string string "[ \t]+"))))
9841 (if (not opts)
9843 (setq rtn nil)
9844 (while (setq e (pop opts))
9845 (if (not (nth 3 e))
9846 (setq rtn (nth 2 e))
9847 (if (not (listp rtn)) (setq rtn nil))
9848 (push (nth 2 e) rtn)))
9849 rtn)))))
9851 (defvar org-todo-setup-filter-hook nil
9852 "Hook for functions that pre-filter todo specs.
9854 Each function takes a todo spec and returns either `nil' or the spec
9855 transformed into canonical form." )
9857 (defvar org-todo-get-default-hook nil
9858 "Hook for functions that get a default item for todo.
9860 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9861 `nil' or a string to be used for the todo mark." )
9863 (defvar org-agenda-headline-snapshot-before-repeat)
9865 (defun org-todo (&optional arg)
9866 "Change the TODO state of an item.
9867 The state of an item is given by a keyword at the start of the heading,
9868 like
9869 *** TODO Write paper
9870 *** DONE Call mom
9872 The different keywords are specified in the variable `org-todo-keywords'.
9873 By default the available states are \"TODO\" and \"DONE\".
9874 So for this example: when the item starts with TODO, it is changed to DONE.
9875 When it starts with DONE, the DONE is removed. And when neither TODO nor
9876 DONE are present, add TODO at the beginning of the heading.
9878 With C-u prefix arg, use completion to determine the new state.
9879 With numeric prefix arg, switch to that state.
9880 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9881 With a triple C-u prefix, circumvent any state blocking.
9883 For calling through lisp, arg is also interpreted in the following way:
9884 'none -> empty state
9885 \"\"(empty string) -> switch to empty state
9886 'done -> switch to DONE
9887 'nextset -> switch to the next set of keywords
9888 'previousset -> switch to the previous set of keywords
9889 \"WAITING\" -> switch to the specified keyword, but only if it
9890 really is a member of `org-todo-keywords'."
9891 (interactive "P")
9892 (if (equal arg '(16)) (setq arg 'nextset))
9893 (let ((org-blocker-hook org-blocker-hook)
9894 (case-fold-search nil))
9895 (when (equal arg '(64))
9896 (setq arg nil org-blocker-hook nil))
9897 (when (and org-blocker-hook
9898 (or org-inhibit-blocking
9899 (org-entry-get nil "NOBLOCKING")))
9900 (setq org-blocker-hook nil))
9901 (save-excursion
9902 (catch 'exit
9903 (org-back-to-heading t)
9904 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9905 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9906 (looking-at " *"))
9907 (let* ((match-data (match-data))
9908 (startpos (point-at-bol))
9909 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9910 (org-log-done org-log-done)
9911 (org-log-repeat org-log-repeat)
9912 (org-todo-log-states org-todo-log-states)
9913 (this (match-string 1))
9914 (hl-pos (match-beginning 0))
9915 (head (org-get-todo-sequence-head this))
9916 (ass (assoc head org-todo-kwd-alist))
9917 (interpret (nth 1 ass))
9918 (done-word (nth 3 ass))
9919 (final-done-word (nth 4 ass))
9920 (last-state (or this ""))
9921 (completion-ignore-case t)
9922 (member (member this org-todo-keywords-1))
9923 (tail (cdr member))
9924 (state (cond
9925 ((and org-todo-key-trigger
9926 (or (and (equal arg '(4))
9927 (eq org-use-fast-todo-selection 'prefix))
9928 (and (not arg) org-use-fast-todo-selection
9929 (not (eq org-use-fast-todo-selection
9930 'prefix)))))
9931 ;; Use fast selection
9932 (org-fast-todo-selection))
9933 ((and (equal arg '(4))
9934 (or (not org-use-fast-todo-selection)
9935 (not org-todo-key-trigger)))
9936 ;; Read a state with completion
9937 (org-icompleting-read
9938 "State: " (mapcar (lambda(x) (list x))
9939 org-todo-keywords-1)
9940 nil t))
9941 ((eq arg 'right)
9942 (if this
9943 (if tail (car tail) nil)
9944 (car org-todo-keywords-1)))
9945 ((eq arg 'left)
9946 (if (equal member org-todo-keywords-1)
9948 (if this
9949 (nth (- (length org-todo-keywords-1)
9950 (length tail) 2)
9951 org-todo-keywords-1)
9952 (org-last org-todo-keywords-1))))
9953 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9954 (setq arg nil))) ; hack to fall back to cycling
9955 (arg
9956 ;; user or caller requests a specific state
9957 (cond
9958 ((equal arg "") nil)
9959 ((eq arg 'none) nil)
9960 ((eq arg 'done) (or done-word (car org-done-keywords)))
9961 ((eq arg 'nextset)
9962 (or (car (cdr (member head org-todo-heads)))
9963 (car org-todo-heads)))
9964 ((eq arg 'previousset)
9965 (let ((org-todo-heads (reverse org-todo-heads)))
9966 (or (car (cdr (member head org-todo-heads)))
9967 (car org-todo-heads))))
9968 ((car (member arg org-todo-keywords-1)))
9969 ((stringp arg)
9970 (error "State `%s' not valid in this file" arg))
9971 ((nth (1- (prefix-numeric-value arg))
9972 org-todo-keywords-1))))
9973 ((null member) (or head (car org-todo-keywords-1)))
9974 ((equal this final-done-word) nil) ;; -> make empty
9975 ((null tail) nil) ;; -> first entry
9976 ((memq interpret '(type priority))
9977 (if (eq this-command last-command)
9978 (car tail)
9979 (if (> (length tail) 0)
9980 (or done-word (car org-done-keywords))
9981 nil)))
9983 (car tail))))
9984 (state (or
9985 (run-hook-with-args-until-success
9986 'org-todo-get-default-hook state last-state)
9987 state))
9988 (next (if state (concat " " state " ") " "))
9989 (change-plist (list :type 'todo-state-change :from this :to state
9990 :position startpos))
9991 dolog now-done-p)
9992 (when org-blocker-hook
9993 (setq org-last-todo-state-is-todo
9994 (not (member this org-done-keywords)))
9995 (unless (save-excursion
9996 (save-match-data
9997 (run-hook-with-args-until-failure
9998 'org-blocker-hook change-plist)))
9999 (if (interactive-p)
10000 (error "TODO state change from %s to %s blocked" this state)
10001 ;; fail silently
10002 (message "TODO state change from %s to %s blocked" this state)
10003 (throw 'exit nil))))
10004 (store-match-data match-data)
10005 (replace-match next t t)
10006 (unless (pos-visible-in-window-p hl-pos)
10007 (message "TODO state changed to %s" (org-trim next)))
10008 (unless head
10009 (setq head (org-get-todo-sequence-head state)
10010 ass (assoc head org-todo-kwd-alist)
10011 interpret (nth 1 ass)
10012 done-word (nth 3 ass)
10013 final-done-word (nth 4 ass)))
10014 (when (memq arg '(nextset previousset))
10015 (message "Keyword-Set %d/%d: %s"
10016 (- (length org-todo-sets) -1
10017 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10018 (length org-todo-sets)
10019 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10020 (setq org-last-todo-state-is-todo
10021 (not (member state org-done-keywords)))
10022 (setq now-done-p (and (member state org-done-keywords)
10023 (not (member this org-done-keywords))))
10024 (and logging (org-local-logging logging))
10025 (when (and (or org-todo-log-states org-log-done)
10026 (not (eq org-inhibit-logging t))
10027 (not (memq arg '(nextset previousset))))
10028 ;; we need to look at recording a time and note
10029 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10030 (nth 2 (assoc this org-todo-log-states))))
10031 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10032 (setq dolog 'time))
10033 (when (and state
10034 (member state org-not-done-keywords)
10035 (not (member this org-not-done-keywords)))
10036 ;; This is now a todo state and was not one before
10037 ;; If there was a CLOSED time stamp, get rid of it.
10038 (org-add-planning-info nil nil 'closed))
10039 (when (and now-done-p org-log-done)
10040 ;; It is now done, and it was not done before
10041 (org-add-planning-info 'closed (org-current-time))
10042 (if (and (not dolog) (eq 'note org-log-done))
10043 (org-add-log-setup 'done state this 'findpos 'note)))
10044 (when (and state dolog)
10045 ;; This is a non-nil state, and we need to log it
10046 (org-add-log-setup 'state state this 'findpos dolog)))
10047 ;; Fixup tag positioning
10048 (org-todo-trigger-tag-changes state)
10049 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10050 (when org-provide-todo-statistics
10051 (org-update-parent-todo-statistics))
10052 (run-hooks 'org-after-todo-state-change-hook)
10053 (if (and arg (not (member state org-done-keywords)))
10054 (setq head (org-get-todo-sequence-head state)))
10055 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10056 ;; Do we need to trigger a repeat?
10057 (when now-done-p
10058 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10059 ;; This is for the agenda, take a snapshot of the headline.
10060 (save-match-data
10061 (setq org-agenda-headline-snapshot-before-repeat
10062 (org-get-heading))))
10063 (org-auto-repeat-maybe state))
10064 ;; Fixup cursor location if close to the keyword
10065 (if (and (outline-on-heading-p)
10066 (not (bolp))
10067 (save-excursion (beginning-of-line 1)
10068 (looking-at org-todo-line-regexp))
10069 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10070 (progn
10071 (goto-char (or (match-end 2) (match-end 1)))
10072 (and (looking-at " ") (just-one-space))))
10073 (when org-trigger-hook
10074 (save-excursion
10075 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10077 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10078 "Block turning an entry into a TODO, using the hierarchy.
10079 This checks whether the current task should be blocked from state
10080 changes. Such blocking occurs when:
10082 1. The task has children which are not all in a completed state.
10084 2. A task has a parent with the property :ORDERED:, and there
10085 are siblings prior to the current task with incomplete
10086 status.
10088 3. The parent of the task is blocked because it has siblings that should
10089 be done first, or is child of a block grandparent TODO entry."
10091 (catch 'dont-block
10092 ;; If this is not a todo state change, or if this entry is already DONE,
10093 ;; do not block
10094 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10095 (member (plist-get change-plist :from)
10096 (cons 'done org-done-keywords))
10097 (member (plist-get change-plist :to)
10098 (cons 'todo org-not-done-keywords))
10099 (not (plist-get change-plist :to)))
10100 (throw 'dont-block t))
10101 ;; If this task has children, and any are undone, it's blocked
10102 (save-excursion
10103 (org-back-to-heading t)
10104 (let ((this-level (funcall outline-level)))
10105 (outline-next-heading)
10106 (let ((child-level (funcall outline-level)))
10107 (while (and (not (eobp))
10108 (> child-level this-level))
10109 ;; this todo has children, check whether they are all
10110 ;; completed
10111 (if (and (not (org-entry-is-done-p))
10112 (org-entry-is-todo-p))
10113 (throw 'dont-block nil))
10114 (outline-next-heading)
10115 (setq child-level (funcall outline-level))))))
10116 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10117 ;; any previous siblings are undone, it's blocked
10118 (save-excursion
10119 (org-back-to-heading t)
10120 (let* ((pos (point))
10121 (parent-pos (and (org-up-heading-safe) (point))))
10122 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10123 (when (and (org-entry-get (point) "ORDERED")
10124 (forward-line 1)
10125 (re-search-forward org-not-done-heading-regexp pos t))
10126 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10127 ;; Search further up the hierarchy, to see if an anchestor is blocked
10128 (while t
10129 (goto-char parent-pos)
10130 (if (not (looking-at org-not-done-heading-regexp))
10131 (throw 'dont-block t)) ; do not block, parent is not a TODO
10132 (setq pos (point))
10133 (setq parent-pos (and (org-up-heading-safe) (point)))
10134 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10135 (when (and (org-entry-get (point) "ORDERED")
10136 (forward-line 1)
10137 (re-search-forward org-not-done-heading-regexp pos t))
10138 (throw 'dont-block nil))))))) ; block, older sibling not done.
10140 (defcustom org-track-ordered-property-with-tag nil
10141 "Should the ORDERED property also be shown as a tag?
10142 The ORDERED property decides if an entry should require subtasks to be
10143 completed in sequence. Since a property is not very visible, setting
10144 this option means that toggling the ORDERED property with the command
10145 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10146 not relevant for the behavior, but it makes things more visible.
10148 Note that toggling the tag with tags commands will not change the property
10149 and therefore not influence behavior!
10151 This can be t, meaning the tag ORDERED should be used, It can also be a
10152 string to select a different tag for this task."
10153 :group 'org-todo
10154 :type '(choice
10155 (const :tag "No tracking" nil)
10156 (const :tag "Track with ORDERED tag" t)
10157 (string :tag "Use other tag")))
10159 (defun org-toggle-ordered-property ()
10160 "Toggle the ORDERED property of the current entry.
10161 For better visibility, you can track the value of this property with a tag.
10162 See variable `org-track-ordered-property-with-tag'."
10163 (interactive)
10164 (let* ((t1 org-track-ordered-property-with-tag)
10165 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10166 (save-excursion
10167 (org-back-to-heading)
10168 (if (org-entry-get nil "ORDERED")
10169 (progn
10170 (org-delete-property "ORDERED")
10171 (and tag (org-toggle-tag tag 'off))
10172 (message "Subtasks can be completed in arbitrary order"))
10173 (org-entry-put nil "ORDERED" "t")
10174 (and tag (org-toggle-tag tag 'on))
10175 (message "Subtasks must be completed in sequence")))))
10177 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10178 (defun org-block-todo-from-checkboxes (change-plist)
10179 "Block turning an entry into a TODO, using checkboxes.
10180 This checks whether the current task should be blocked from state
10181 changes because there are unchecked boxes in this entry."
10182 (catch 'dont-block
10183 ;; If this is not a todo state change, or if this entry is already DONE,
10184 ;; do not block
10185 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10186 (member (plist-get change-plist :from)
10187 (cons 'done org-done-keywords))
10188 (member (plist-get change-plist :to)
10189 (cons 'todo org-not-done-keywords))
10190 (not (plist-get change-plist :to)))
10191 (throw 'dont-block t))
10192 ;; If this task has checkboxes that are not checked, it's blocked
10193 (save-excursion
10194 (org-back-to-heading t)
10195 (let ((beg (point)) end)
10196 (outline-next-heading)
10197 (setq end (point))
10198 (goto-char beg)
10199 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10200 end t)
10201 (progn
10202 (if (boundp 'org-blocked-by-checkboxes)
10203 (setq org-blocked-by-checkboxes t))
10204 (throw 'dont-block nil)))))
10205 t)) ; do not block
10207 (defun org-update-statistics-cookies (all)
10208 "Update the statistics cookie, either from TODO or from checkboxes.
10209 This should be called with the cursor in a line with a statistics cookie."
10210 (interactive "P")
10211 (if all
10212 (progn
10213 (org-update-checkbox-count 'all)
10214 (org-map-entries 'org-update-parent-todo-statistics))
10215 (if (not (org-on-heading-p))
10216 (org-update-checkbox-count)
10217 (let ((pos (move-marker (make-marker) (point)))
10218 end l1 l2)
10219 (ignore-errors (org-back-to-heading t))
10220 (if (not (org-on-heading-p))
10221 (org-update-checkbox-count)
10222 (setq l1 (org-outline-level))
10223 (setq end (save-excursion
10224 (outline-next-heading)
10225 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10226 (point)))
10227 (if (and (save-excursion (re-search-forward
10228 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10229 (not (save-excursion (re-search-forward
10230 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10231 (org-update-checkbox-count)
10232 (if (and l2 (> l2 l1))
10233 (progn
10234 (goto-char end)
10235 (org-update-parent-todo-statistics))
10236 (error "No data for statistics cookie"))))
10237 (goto-char pos)
10238 (move-marker pos nil)))))
10240 (defvar org-entry-property-inherited-from) ;; defined below
10241 (defun org-update-parent-todo-statistics ()
10242 "Update any statistics cookie in the parent of the current headline.
10243 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10244 the entire subtree and this will travel up the hierarchy and update
10245 statistics everywhere."
10246 (interactive)
10247 (let* ((lim 0) prop
10248 (recursive (or (not org-hierarchical-todo-statistics)
10249 (string-match
10250 "\\<recursive\\>"
10251 (or (setq prop (org-entry-get
10252 nil "COOKIE_DATA" 'inherit)) ""))))
10253 (lim (or (and prop (marker-position
10254 org-entry-property-inherited-from))
10255 lim))
10256 (first t)
10257 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10258 level ltoggle l1 new ndel
10259 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10260 (catch 'exit
10261 (save-excursion
10262 (beginning-of-line 1)
10263 (if (org-at-heading-p)
10264 (setq ltoggle (funcall outline-level))
10265 (error "This should not happen"))
10266 (while (and (setq level (org-up-heading-safe))
10267 (or recursive first)
10268 (>= (point) lim))
10269 (setq first nil cookie-present nil)
10270 (unless (and level
10271 (not (string-match
10272 "\\<checkbox\\>"
10273 (downcase
10274 (or (org-entry-get
10275 nil "COOKIE_DATA")
10276 "")))))
10277 (throw 'exit nil))
10278 (while (re-search-forward box-re (point-at-eol) t)
10279 (setq cnt-all 0 cnt-done 0 cookie-present t)
10280 (setq is-percent (match-end 2))
10281 (save-match-data
10282 (unless (outline-next-heading) (throw 'exit nil))
10283 (while (and (looking-at org-complex-heading-regexp)
10284 (> (setq l1 (length (match-string 1))) level))
10285 (setq kwd (and (or recursive (= l1 ltoggle))
10286 (match-string 2)))
10287 (if (or (eq org-provide-todo-statistics 'all-headlines)
10288 (and (listp org-provide-todo-statistics)
10289 (or (member kwd org-provide-todo-statistics)
10290 (member kwd org-done-keywords))))
10291 (setq cnt-all (1+ cnt-all))
10292 (if (eq org-provide-todo-statistics t)
10293 (and kwd (setq cnt-all (1+ cnt-all)))))
10294 (and (member kwd org-done-keywords)
10295 (setq cnt-done (1+ cnt-done)))
10296 (outline-next-heading)))
10297 (setq new
10298 (if is-percent
10299 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10300 (format "[%d/%d]" cnt-done cnt-all))
10301 ndel (- (match-end 0) (match-beginning 0)))
10302 (goto-char (match-beginning 0))
10303 (insert new)
10304 (delete-region (point) (+ (point) ndel)))
10305 (when cookie-present
10306 (run-hook-with-args 'org-after-todo-statistics-hook
10307 cnt-done (- cnt-all cnt-done))))))
10308 (run-hooks 'org-todo-statistics-hook)))
10310 (defvar org-after-todo-statistics-hook nil
10311 "Hook that is called after a TODO statistics cookie has been updated.
10312 Each function is called with two arguments: the number of not-done entries
10313 and the number of done entries.
10315 For example, the following function, when added to this hook, will switch
10316 an entry to DONE when all children are done, and back to TODO when new
10317 entries are set to a TODO status. Note that this hook is only called
10318 when there is a statistics cookie in the headline!
10320 (defun org-summary-todo (n-done n-not-done)
10321 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10322 (let (org-log-done org-log-states) ; turn off logging
10323 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10326 (defvar org-todo-statistics-hook nil
10327 "Hook that is run whenever Org thinks TODO statistics should be updated.
10328 This hook runs even if there is no statistics cookie present, in which case
10329 `org-after-todo-statistics-hook' would not run.")
10331 (defun org-todo-trigger-tag-changes (state)
10332 "Apply the changes defined in `org-todo-state-tags-triggers'."
10333 (let ((l org-todo-state-tags-triggers)
10334 changes)
10335 (when (or (not state) (equal state ""))
10336 (setq changes (append changes (cdr (assoc "" l)))))
10337 (when (and (stringp state) (> (length state) 0))
10338 (setq changes (append changes (cdr (assoc state l)))))
10339 (when (member state org-not-done-keywords)
10340 (setq changes (append changes (cdr (assoc 'todo l)))))
10341 (when (member state org-done-keywords)
10342 (setq changes (append changes (cdr (assoc 'done l)))))
10343 (dolist (c changes)
10344 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10346 (defun org-local-logging (value)
10347 "Get logging settings from a property VALUE."
10348 (let* (words w a)
10349 ;; directly set the variables, they are already local.
10350 (setq org-log-done nil
10351 org-log-repeat nil
10352 org-todo-log-states nil)
10353 (setq words (org-split-string value))
10354 (while (setq w (pop words))
10355 (cond
10356 ((setq a (assoc w org-startup-options))
10357 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10358 (set (nth 1 a) (nth 2 a))))
10359 ((setq a (org-extract-log-state-settings w))
10360 (and (member (car a) org-todo-keywords-1)
10361 (push a org-todo-log-states)))))))
10363 (defun org-get-todo-sequence-head (kwd)
10364 "Return the head of the TODO sequence to which KWD belongs.
10365 If KWD is not set, check if there is a text property remembering the
10366 right sequence."
10367 (let (p)
10368 (cond
10369 ((not kwd)
10370 (or (get-text-property (point-at-bol) 'org-todo-head)
10371 (progn
10372 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10373 nil (point-at-eol)))
10374 (get-text-property p 'org-todo-head))))
10375 ((not (member kwd org-todo-keywords-1))
10376 (car org-todo-keywords-1))
10377 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10379 (defun org-fast-todo-selection ()
10380 "Fast TODO keyword selection with single keys.
10381 Returns the new TODO keyword, or nil if no state change should occur."
10382 (let* ((fulltable org-todo-key-alist)
10383 (done-keywords org-done-keywords) ;; needed for the faces.
10384 (maxlen (apply 'max (mapcar
10385 (lambda (x)
10386 (if (stringp (car x)) (string-width (car x)) 0))
10387 fulltable)))
10388 (expert nil)
10389 (fwidth (+ maxlen 3 1 3))
10390 (ncol (/ (- (window-width) 4) fwidth))
10391 tg cnt e c tbl
10392 groups ingroup)
10393 (save-excursion
10394 (save-window-excursion
10395 (if expert
10396 (set-buffer (get-buffer-create " *Org todo*"))
10397 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10398 (erase-buffer)
10399 (org-set-local 'org-done-keywords done-keywords)
10400 (setq tbl fulltable cnt 0)
10401 (while (setq e (pop tbl))
10402 (cond
10403 ((equal e '(:startgroup))
10404 (push '() groups) (setq ingroup t)
10405 (when (not (= cnt 0))
10406 (setq cnt 0)
10407 (insert "\n"))
10408 (insert "{ "))
10409 ((equal e '(:endgroup))
10410 (setq ingroup nil cnt 0)
10411 (insert "}\n"))
10412 ((equal e '(:newline))
10413 (when (not (= cnt 0))
10414 (setq cnt 0)
10415 (insert "\n")
10416 (setq e (car tbl))
10417 (while (equal (car tbl) '(:newline))
10418 (insert "\n")
10419 (setq tbl (cdr tbl)))))
10421 (setq tg (car e) c (cdr e))
10422 (if ingroup (push tg (car groups)))
10423 (setq tg (org-add-props tg nil 'face
10424 (org-get-todo-face tg)))
10425 (if (and (= cnt 0) (not ingroup)) (insert " "))
10426 (insert "[" c "] " tg (make-string
10427 (- fwidth 4 (length tg)) ?\ ))
10428 (when (= (setq cnt (1+ cnt)) ncol)
10429 (insert "\n")
10430 (if ingroup (insert " "))
10431 (setq cnt 0)))))
10432 (insert "\n")
10433 (goto-char (point-min))
10434 (if (not expert) (org-fit-window-to-buffer))
10435 (message "[a-z..]:Set [SPC]:clear")
10436 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10437 (cond
10438 ((or (= c ?\C-g)
10439 (and (= c ?q) (not (rassoc c fulltable))))
10440 (setq quit-flag t))
10441 ((= c ?\ ) nil)
10442 ((setq e (rassoc c fulltable) tg (car e))
10444 (t (setq quit-flag t)))))))
10446 (defun org-entry-is-todo-p ()
10447 (member (org-get-todo-state) org-not-done-keywords))
10449 (defun org-entry-is-done-p ()
10450 (member (org-get-todo-state) org-done-keywords))
10452 (defun org-get-todo-state ()
10453 (save-excursion
10454 (org-back-to-heading t)
10455 (and (looking-at org-todo-line-regexp)
10456 (match-end 2)
10457 (match-string 2))))
10459 (defun org-at-date-range-p (&optional inactive-ok)
10460 "Is the cursor inside a date range?"
10461 (interactive)
10462 (save-excursion
10463 (catch 'exit
10464 (let ((pos (point)))
10465 (skip-chars-backward "^[<\r\n")
10466 (skip-chars-backward "<[")
10467 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10468 (>= (match-end 0) pos)
10469 (throw 'exit t))
10470 (skip-chars-backward "^<[\r\n")
10471 (skip-chars-backward "<[")
10472 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10473 (>= (match-end 0) pos)
10474 (throw 'exit t)))
10475 nil)))
10477 (defun org-get-repeat (&optional tagline)
10478 "Check if there is a deadline/schedule with repeater in this entry."
10479 (save-match-data
10480 (save-excursion
10481 (org-back-to-heading t)
10482 (and (re-search-forward (if tagline
10483 (concat tagline "\\s-*" org-repeat-re)
10484 org-repeat-re)
10485 (org-entry-end-position) t)
10486 (match-string-no-properties 1)))))
10488 (defvar org-last-changed-timestamp)
10489 (defvar org-last-inserted-timestamp)
10490 (defvar org-log-post-message)
10491 (defvar org-log-note-purpose)
10492 (defvar org-log-note-how)
10493 (defvar org-log-note-extra)
10494 (defun org-auto-repeat-maybe (done-word)
10495 "Check if the current headline contains a repeated deadline/schedule.
10496 If yes, set TODO state back to what it was and change the base date
10497 of repeating deadline/scheduled time stamps to new date.
10498 This function is run automatically after each state change to a DONE state."
10499 ;; last-state is dynamically scoped into this function
10500 (let* ((repeat (org-get-repeat))
10501 (aa (assoc last-state org-todo-kwd-alist))
10502 (interpret (nth 1 aa))
10503 (head (nth 2 aa))
10504 (whata '(("d" . day) ("m" . month) ("y" . year)))
10505 (msg "Entry repeats: ")
10506 (org-log-done nil)
10507 (org-todo-log-states nil)
10508 (nshiftmax 10) (nshift 0)
10509 re type n what ts time)
10510 (when repeat
10511 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10512 (org-todo (if (eq interpret 'type) last-state head))
10513 (org-entry-put nil "LAST_REPEAT" (format-time-string
10514 (org-time-stamp-format t t)))
10515 (when org-log-repeat
10516 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10517 (memq 'org-add-log-note post-command-hook))
10518 ;; OK, we are already setup for some record
10519 (if (eq org-log-repeat 'note)
10520 ;; make sure we take a note, not only a time stamp
10521 (setq org-log-note-how 'note))
10522 ;; Set up for taking a record
10523 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10524 last-state
10525 'findpos org-log-repeat)))
10526 (org-back-to-heading t)
10527 (org-add-planning-info nil nil 'closed)
10528 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10529 org-deadline-time-regexp "\\)\\|\\("
10530 org-ts-regexp "\\)"))
10531 (while (re-search-forward
10532 re (save-excursion (outline-next-heading) (point)) t)
10533 (setq type (if (match-end 1) org-scheduled-string
10534 (if (match-end 3) org-deadline-string "Plain:"))
10535 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10536 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10537 (setq n (string-to-number (match-string 2 ts))
10538 what (match-string 3 ts))
10539 (if (equal what "w") (setq n (* n 7) what "d"))
10540 ;; Preparation, see if we need to modify the start date for the change
10541 (when (match-end 1)
10542 (setq time (save-match-data (org-time-string-to-time ts)))
10543 (cond
10544 ((equal (match-string 1 ts) ".")
10545 ;; Shift starting date to today
10546 (org-timestamp-change
10547 (- (time-to-days (current-time)) (time-to-days time))
10548 'day))
10549 ((equal (match-string 1 ts) "+")
10550 (while (or (= nshift 0)
10551 (<= (time-to-days time) (time-to-days (current-time))))
10552 (when (= (incf nshift) nshiftmax)
10553 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10554 (error "Abort")))
10555 (org-timestamp-change n (cdr (assoc what whata)))
10556 (org-at-timestamp-p t)
10557 (setq ts (match-string 1))
10558 (setq time (save-match-data (org-time-string-to-time ts))))
10559 (org-timestamp-change (- n) (cdr (assoc what whata)))
10560 ;; rematch, so that we have everything in place for the real shift
10561 (org-at-timestamp-p t)
10562 (setq ts (match-string 1))
10563 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10564 (org-timestamp-change n (cdr (assoc what whata)))
10565 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10566 (setq org-log-post-message msg)
10567 (message "%s" msg))))
10569 (defun org-show-todo-tree (arg)
10570 "Make a compact tree which shows all headlines marked with TODO.
10571 The tree will show the lines where the regexp matches, and all higher
10572 headlines above the match.
10573 With a \\[universal-argument] prefix, prompt for a regexp to match.
10574 With a numeric prefix N, construct a sparse tree for the Nth element
10575 of `org-todo-keywords-1'."
10576 (interactive "P")
10577 (let ((case-fold-search nil)
10578 (kwd-re
10579 (cond ((null arg) org-not-done-regexp)
10580 ((equal arg '(4))
10581 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10582 (mapcar 'list org-todo-keywords-1))))
10583 (concat "\\("
10584 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10585 "\\)\\>")))
10586 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10587 (regexp-quote (nth (1- (prefix-numeric-value arg))
10588 org-todo-keywords-1)))
10589 (t (error "Invalid prefix argument: %s" arg)))))
10590 (message "%d TODO entries found"
10591 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10593 (defun org-deadline (&optional remove time)
10594 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10595 With argument REMOVE, remove any deadline from the item.
10596 When TIME is set, it should be an internal time specification, and the
10597 scheduling will use the corresponding date."
10598 (interactive "P")
10599 (let ((old-date (org-entry-get nil "DEADLINE")))
10600 (if remove
10601 (progn
10602 (org-remove-timestamp-with-keyword org-deadline-string)
10603 (message "Item no longer has a deadline."))
10604 (if (org-get-repeat)
10605 (error "Cannot change deadline on task with repeater, please do that by hand")
10606 (org-add-planning-info 'deadline time 'closed)
10607 (when (and old-date org-log-redeadline
10608 (not (equal old-date
10609 (substring org-last-inserted-timestamp 1 -1))))
10610 (org-add-log-setup 'redeadline nil old-date 'findpos
10611 org-log-redeadline))
10612 (message "Deadline on %s" org-last-inserted-timestamp)))))
10614 (defun org-schedule (&optional remove time)
10615 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10616 With argument REMOVE, remove any scheduling date from the item.
10617 When TIME is set, it should be an internal time specification, and the
10618 scheduling will use the corresponding date."
10619 (interactive "P")
10620 (let ((old-date (org-entry-get nil "SCHEDULED")))
10621 (if remove
10622 (progn
10623 (org-remove-timestamp-with-keyword org-scheduled-string)
10624 (message "Item is no longer scheduled."))
10625 (if (org-get-repeat)
10626 (error "Cannot reschedule task with repeater, please do that by hand")
10627 (org-add-planning-info 'scheduled time 'closed)
10628 (when (and old-date org-log-reschedule
10629 (not (equal old-date
10630 (substring org-last-inserted-timestamp 1 -1))))
10631 (org-add-log-setup 'reschedule nil old-date 'findpos
10632 org-log-reschedule))
10633 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10635 (defun org-get-scheduled-time (pom &optional inherit)
10636 "Get the scheduled time as a time tuple, of a format suitable
10637 for calling org-schedule with, or if there is no scheduling,
10638 returns nil."
10639 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10640 (when time
10641 (apply 'encode-time (org-parse-time-string time)))))
10643 (defun org-get-deadline-time (pom &optional inherit)
10644 "Get the deadine as a time tuple, of a format suitable for
10645 calling org-deadline with, or if there is no scheduling, returns
10646 nil."
10647 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10648 (when time
10649 (apply 'encode-time (org-parse-time-string time)))))
10651 (defun org-remove-timestamp-with-keyword (keyword)
10652 "Remove all time stamps with KEYWORD in the current entry."
10653 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10654 beg)
10655 (save-excursion
10656 (org-back-to-heading t)
10657 (setq beg (point))
10658 (outline-next-heading)
10659 (while (re-search-backward re beg t)
10660 (replace-match "")
10661 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10662 (equal (char-before) ?\ ))
10663 (backward-delete-char 1)
10664 (if (string-match "^[ \t]*$" (buffer-substring
10665 (point-at-bol) (point-at-eol)))
10666 (delete-region (point-at-bol)
10667 (min (point-max) (1+ (point-at-eol))))))))))
10669 (defun org-add-planning-info (what &optional time &rest remove)
10670 "Insert new timestamp with keyword in the line directly after the headline.
10671 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10672 If non is given, the user is prompted for a date.
10673 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10674 be removed."
10675 (interactive)
10676 (let (org-time-was-given org-end-time-was-given ts
10677 end default-time default-input)
10679 (catch 'exit
10680 (when (and (not time) (memq what '(scheduled deadline)))
10681 ;; Try to get a default date/time from existing timestamp
10682 (save-excursion
10683 (org-back-to-heading t)
10684 (setq end (save-excursion (outline-next-heading) (point)))
10685 (when (re-search-forward (if (eq what 'scheduled)
10686 org-scheduled-time-regexp
10687 org-deadline-time-regexp)
10688 end t)
10689 (setq ts (match-string 1)
10690 default-time
10691 (apply 'encode-time (org-parse-time-string ts))
10692 default-input (and ts (org-get-compact-tod ts))))))
10693 (when what
10694 ;; If necessary, get the time from the user
10695 (setq time (or time (org-read-date nil 'to-time nil nil
10696 default-time default-input))))
10698 (when (and org-insert-labeled-timestamps-at-point
10699 (member what '(scheduled deadline)))
10700 (insert
10701 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10702 (org-insert-time-stamp time org-time-was-given
10703 nil nil nil (list org-end-time-was-given))
10704 (setq what nil))
10705 (save-excursion
10706 (save-restriction
10707 (let (col list elt ts buffer-invisibility-spec)
10708 (org-back-to-heading t)
10709 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10710 (goto-char (match-end 1))
10711 (setq col (current-column))
10712 (goto-char (match-end 0))
10713 (if (eobp) (insert "\n") (forward-char 1))
10714 (when (and (not what)
10715 (not (looking-at
10716 (concat "[ \t]*"
10717 org-keyword-time-not-clock-regexp))))
10718 ;; Nothing to add, nothing to remove...... :-)
10719 (throw 'exit nil))
10720 (if (and (not (looking-at outline-regexp))
10721 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10722 "[^\r\n]*"))
10723 (not (equal (match-string 1) org-clock-string)))
10724 (narrow-to-region (match-beginning 0) (match-end 0))
10725 (insert-before-markers "\n")
10726 (backward-char 1)
10727 (narrow-to-region (point) (point))
10728 (and org-adapt-indentation (org-indent-to-column col)))
10729 ;; Check if we have to remove something.
10730 (setq list (cons what remove))
10731 (while list
10732 (setq elt (pop list))
10733 (goto-char (point-min))
10734 (when (or (and (eq elt 'scheduled)
10735 (re-search-forward org-scheduled-time-regexp nil t))
10736 (and (eq elt 'deadline)
10737 (re-search-forward org-deadline-time-regexp nil t))
10738 (and (eq elt 'closed)
10739 (re-search-forward org-closed-time-regexp nil t)))
10740 (replace-match "")
10741 (if (looking-at "--+<[^>]+>") (replace-match ""))
10742 (skip-chars-backward " ")
10743 (if (looking-at " +") (replace-match ""))))
10744 (goto-char (point-max))
10745 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10746 (when what
10747 (insert
10748 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10749 (cond ((eq what 'scheduled) org-scheduled-string)
10750 ((eq what 'deadline) org-deadline-string)
10751 ((eq what 'closed) org-closed-string))
10752 " ")
10753 (setq ts (org-insert-time-stamp
10754 time
10755 (or org-time-was-given
10756 (and (eq what 'closed) org-log-done-with-time))
10757 (eq what 'closed)
10758 nil nil (list org-end-time-was-given)))
10759 (end-of-line 1))
10760 (goto-char (point-min))
10761 (widen)
10762 (if (and (looking-at "[ \t]+\n")
10763 (equal (char-before) ?\n))
10764 (delete-region (1- (point)) (point-at-eol)))
10765 ts))))))
10767 (defvar org-log-note-marker (make-marker))
10768 (defvar org-log-note-purpose nil)
10769 (defvar org-log-note-state nil)
10770 (defvar org-log-note-previous-state nil)
10771 (defvar org-log-note-how nil)
10772 (defvar org-log-note-extra nil)
10773 (defvar org-log-note-window-configuration nil)
10774 (defvar org-log-note-return-to (make-marker))
10775 (defvar org-log-post-message nil
10776 "Message to be displayed after a log note has been stored.
10777 The auto-repeater uses this.")
10779 (defun org-add-note ()
10780 "Add a note to the current entry.
10781 This is done in the same way as adding a state change note."
10782 (interactive)
10783 (org-add-log-setup 'note nil nil 'findpos nil))
10785 (defvar org-property-end-re)
10786 (defun org-add-log-setup (&optional purpose state prev-state
10787 findpos how &optional extra)
10788 "Set up the post command hook to take a note.
10789 If this is about to TODO state change, the new state is expected in STATE.
10790 When FINDPOS is non-nil, find the correct position for the note in
10791 the current entry. If not, assume that it can be inserted at point.
10792 HOW is an indicator what kind of note should be created.
10793 EXTRA is additional text that will be inserted into the notes buffer."
10794 (let* ((org-log-into-drawer (org-log-into-drawer))
10795 (drawer (cond ((stringp org-log-into-drawer)
10796 org-log-into-drawer)
10797 (org-log-into-drawer "LOGBOOK")
10798 (t nil))))
10799 (save-restriction
10800 (save-excursion
10801 (when findpos
10802 (org-back-to-heading t)
10803 (narrow-to-region (point) (save-excursion
10804 (outline-next-heading) (point)))
10805 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10806 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10807 "[^\r\n]*\\)?"))
10808 (goto-char (match-end 0))
10809 (cond
10810 (drawer
10811 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10812 nil t)
10813 (progn
10814 (goto-char (match-end 0))
10815 (or org-log-states-order-reversed
10816 (and (re-search-forward org-property-end-re nil t)
10817 (goto-char (1- (match-beginning 0))))))
10818 (insert "\n:" drawer ":\n:END:")
10819 (beginning-of-line 0)
10820 (org-indent-line-function)
10821 (beginning-of-line 2)
10822 (org-indent-line-function)
10823 (end-of-line 0)))
10824 ((and org-log-state-notes-insert-after-drawers
10825 (save-excursion
10826 (forward-line) (looking-at org-drawer-regexp)))
10827 (forward-line)
10828 (while (looking-at org-drawer-regexp)
10829 (goto-char (match-end 0))
10830 (re-search-forward org-property-end-re (point-max) t)
10831 (forward-line))
10832 (forward-line -1)))
10833 (unless org-log-states-order-reversed
10834 (and (= (char-after) ?\n) (forward-char 1))
10835 (org-skip-over-state-notes)
10836 (skip-chars-backward " \t\n\r")))
10837 (move-marker org-log-note-marker (point))
10838 (setq org-log-note-purpose purpose
10839 org-log-note-state state
10840 org-log-note-previous-state prev-state
10841 org-log-note-how how
10842 org-log-note-extra extra)
10843 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10845 (defun org-skip-over-state-notes ()
10846 "Skip past the list of State notes in an entry."
10847 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10848 (while (looking-at "[ \t]*- State")
10849 (condition-case nil
10850 (org-next-item)
10851 (error (org-end-of-item)))))
10853 (defun org-add-log-note (&optional purpose)
10854 "Pop up a window for taking a note, and add this note later at point."
10855 (remove-hook 'post-command-hook 'org-add-log-note)
10856 (setq org-log-note-window-configuration (current-window-configuration))
10857 (delete-other-windows)
10858 (move-marker org-log-note-return-to (point))
10859 (switch-to-buffer (marker-buffer org-log-note-marker))
10860 (goto-char org-log-note-marker)
10861 (org-switch-to-buffer-other-window "*Org Note*")
10862 (erase-buffer)
10863 (if (memq org-log-note-how '(time state))
10864 (let (current-prefix-arg) (org-store-log-note))
10865 (let ((org-inhibit-startup t)) (org-mode))
10866 (insert (format "# Insert note for %s.
10867 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10868 (cond
10869 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10870 ((eq org-log-note-purpose 'done) "closed todo item")
10871 ((eq org-log-note-purpose 'state)
10872 (format "state change from \"%s\" to \"%s\""
10873 (or org-log-note-previous-state "")
10874 (or org-log-note-state "")))
10875 ((eq org-log-note-purpose 'reschedule)
10876 "rescheduling")
10877 ((eq org-log-note-purpose 'redeadline)
10878 "changing deadline")
10879 ((eq org-log-note-purpose 'note)
10880 "this entry")
10881 (t (error "This should not happen")))))
10882 (if org-log-note-extra (insert org-log-note-extra))
10883 (org-set-local 'org-finish-function 'org-store-log-note)))
10885 (defvar org-note-abort nil) ; dynamically scoped
10886 (defun org-store-log-note ()
10887 "Finish taking a log note, and insert it to where it belongs."
10888 (let ((txt (buffer-string))
10889 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10890 lines ind)
10891 (kill-buffer (current-buffer))
10892 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10893 (setq txt (replace-match "" t t txt)))
10894 (if (string-match "\\s-+\\'" txt)
10895 (setq txt (replace-match "" t t txt)))
10896 (setq lines (org-split-string txt "\n"))
10897 (when (and note (string-match "\\S-" note))
10898 (setq note
10899 (org-replace-escapes
10900 note
10901 (list (cons "%u" (user-login-name))
10902 (cons "%U" user-full-name)
10903 (cons "%t" (format-time-string
10904 (org-time-stamp-format 'long 'inactive)
10905 (current-time)))
10906 (cons "%s" (if org-log-note-state
10907 (concat "\"" org-log-note-state "\"")
10908 ""))
10909 (cons "%S" (if org-log-note-previous-state
10910 (concat "\"" org-log-note-previous-state "\"")
10911 "\"\"")))))
10912 (if lines (setq note (concat note " \\\\")))
10913 (push note lines))
10914 (when (or current-prefix-arg org-note-abort)
10915 (when org-log-into-drawer
10916 (org-remove-empty-drawer-at
10917 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10918 org-log-note-marker))
10919 (setq lines nil))
10920 (when lines
10921 (with-current-buffer (marker-buffer org-log-note-marker)
10922 (save-excursion
10923 (goto-char org-log-note-marker)
10924 (move-marker org-log-note-marker nil)
10925 (end-of-line 1)
10926 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10927 (insert "- " (pop lines))
10928 (org-indent-line-function)
10929 (beginning-of-line 1)
10930 (looking-at "[ \t]*")
10931 (setq ind (concat (match-string 0) " "))
10932 (end-of-line 1)
10933 (while lines (insert "\n" ind (pop lines)))
10934 (message "Note stored")
10935 (org-back-to-heading t)
10936 (org-cycle-hide-drawers 'children)))))
10937 (set-window-configuration org-log-note-window-configuration)
10938 (with-current-buffer (marker-buffer org-log-note-return-to)
10939 (goto-char org-log-note-return-to))
10940 (move-marker org-log-note-return-to nil)
10941 (and org-log-post-message (message "%s" org-log-post-message)))
10943 (defun org-remove-empty-drawer-at (drawer pos)
10944 "Remove an empty drawer DRAWER at position POS.
10945 POS may also be a marker."
10946 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10947 (save-excursion
10948 (save-restriction
10949 (widen)
10950 (goto-char pos)
10951 (if (org-in-regexp
10952 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10953 (replace-match ""))))))
10955 (defun org-sparse-tree (&optional arg)
10956 "Create a sparse tree, prompt for the details.
10957 This command can create sparse trees. You first need to select the type
10958 of match used to create the tree:
10960 t Show entries with a specific TODO keyword.
10961 m Show entries selected by a tags/property match.
10962 p Enter a property name and its value (both with completion on existing
10963 names/values) and show entries with that property.
10964 / Show entries matching a regular expression (`r' can be used as well)
10965 d Show deadlines due within `org-deadline-warning-days'.
10966 b Show deadlines and scheduled items before a date.
10967 a Show deadlines and scheduled items after a date."
10968 (interactive "P")
10969 (let (ans kwd value)
10970 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10971 (setq ans (read-char-exclusive))
10972 (cond
10973 ((equal ans ?d)
10974 (call-interactively 'org-check-deadlines))
10975 ((equal ans ?b)
10976 (call-interactively 'org-check-before-date))
10977 ((equal ans ?a)
10978 (call-interactively 'org-check-after-date))
10979 ((equal ans ?t)
10980 (org-show-todo-tree '(4)))
10981 ((member ans '(?T ?m))
10982 (call-interactively 'org-match-sparse-tree))
10983 ((member ans '(?p ?P))
10984 (setq kwd (org-icompleting-read "Property: "
10985 (mapcar 'list (org-buffer-property-keys))))
10986 (setq value (org-icompleting-read "Value: "
10987 (mapcar 'list (org-property-values kwd))))
10988 (unless (string-match "\\`{.*}\\'" value)
10989 (setq value (concat "\"" value "\"")))
10990 (org-match-sparse-tree arg (concat kwd "=" value)))
10991 ((member ans '(?r ?R ?/))
10992 (call-interactively 'org-occur))
10993 (t (error "No such sparse tree command \"%c\"" ans)))))
10995 (defvar org-occur-highlights nil
10996 "List of overlays used for occur matches.")
10997 (make-variable-buffer-local 'org-occur-highlights)
10998 (defvar org-occur-parameters nil
10999 "Parameters of the active org-occur calls.
11000 This is a list, each call to org-occur pushes as cons cell,
11001 containing the regular expression and the callback, onto the list.
11002 The list can contain several entries if `org-occur' has been called
11003 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11004 will only contain one set of parameters. When the highlights are
11005 removed (for example with `C-c C-c', or with the next edit (depending
11006 on `org-remove-highlights-with-change'), this variable is emptied
11007 as well.")
11008 (make-variable-buffer-local 'org-occur-parameters)
11010 (defun org-occur (regexp &optional keep-previous callback)
11011 "Make a compact tree which shows all matches of REGEXP.
11012 The tree will show the lines where the regexp matches, and all higher
11013 headlines above the match. It will also show the heading after the match,
11014 to make sure editing the matching entry is easy.
11015 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11016 call to `org-occur' will be kept, to allow stacking of calls to this
11017 command.
11018 If CALLBACK is non-nil, it is a function which is called to confirm
11019 that the match should indeed be shown."
11020 (interactive "sRegexp: \nP")
11021 (when (equal regexp "")
11022 (error "Regexp cannot be empty"))
11023 (unless keep-previous
11024 (org-remove-occur-highlights nil nil t))
11025 (push (cons regexp callback) org-occur-parameters)
11026 (let ((cnt 0))
11027 (save-excursion
11028 (goto-char (point-min))
11029 (if (or (not keep-previous) ; do not want to keep
11030 (not org-occur-highlights)) ; no previous matches
11031 ;; hide everything
11032 (org-overview))
11033 (while (re-search-forward regexp nil t)
11034 (when (or (not callback)
11035 (save-match-data (funcall callback)))
11036 (setq cnt (1+ cnt))
11037 (when org-highlight-sparse-tree-matches
11038 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11039 (org-show-context 'occur-tree))))
11040 (when org-remove-highlights-with-change
11041 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11042 nil 'local))
11043 (unless org-sparse-tree-open-archived-trees
11044 (org-hide-archived-subtrees (point-min) (point-max)))
11045 (run-hooks 'org-occur-hook)
11046 (if (interactive-p)
11047 (message "%d match(es) for regexp %s" cnt regexp))
11048 cnt))
11050 (defun org-show-context (&optional key)
11051 "Make sure point and context and visible.
11052 How much context is shown depends upon the variables
11053 `org-show-hierarchy-above', `org-show-following-heading'. and
11054 `org-show-siblings'."
11055 (let ((heading-p (org-on-heading-p t))
11056 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11057 (following-p (org-get-alist-option org-show-following-heading key))
11058 (entry-p (org-get-alist-option org-show-entry-below key))
11059 (siblings-p (org-get-alist-option org-show-siblings key)))
11060 (catch 'exit
11061 ;; Show heading or entry text
11062 (if (and heading-p (not entry-p))
11063 (org-flag-heading nil) ; only show the heading
11064 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11065 (org-show-hidden-entry))) ; show entire entry
11066 (when following-p
11067 ;; Show next sibling, or heading below text
11068 (save-excursion
11069 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11070 (org-flag-heading nil))))
11071 (when siblings-p (org-show-siblings))
11072 (when hierarchy-p
11073 ;; show all higher headings, possibly with siblings
11074 (save-excursion
11075 (while (and (condition-case nil
11076 (progn (org-up-heading-all 1) t)
11077 (error nil))
11078 (not (bobp)))
11079 (org-flag-heading nil)
11080 (when siblings-p (org-show-siblings))))))))
11082 (defun org-reveal (&optional siblings)
11083 "Show current entry, hierarchy above it, and the following headline.
11084 This can be used to show a consistent set of context around locations
11085 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11086 not t for the search context.
11088 With optional argument SIBLINGS, on each level of the hierarchy all
11089 siblings are shown. This repairs the tree structure to what it would
11090 look like when opened with hierarchical calls to `org-cycle'."
11091 (interactive "P")
11092 (let ((org-show-hierarchy-above t)
11093 (org-show-following-heading t)
11094 (org-show-siblings (if siblings t org-show-siblings)))
11095 (org-show-context nil)))
11097 (defun org-highlight-new-match (beg end)
11098 "Highlight from BEG to END and mark the highlight is an occur headline."
11099 (let ((ov (org-make-overlay beg end)))
11100 (org-overlay-put ov 'face 'secondary-selection)
11101 (push ov org-occur-highlights)))
11103 (defun org-remove-occur-highlights (&optional beg end noremove)
11104 "Remove the occur highlights from the buffer.
11105 BEG and END are ignored. If NOREMOVE is nil, remove this function
11106 from the `before-change-functions' in the current buffer."
11107 (interactive)
11108 (unless org-inhibit-highlight-removal
11109 (mapc 'org-delete-overlay org-occur-highlights)
11110 (setq org-occur-highlights nil)
11111 (setq org-occur-parameters nil)
11112 (unless noremove
11113 (remove-hook 'before-change-functions
11114 'org-remove-occur-highlights 'local))))
11116 ;;;; Priorities
11118 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11119 "Regular expression matching the priority indicator.")
11121 (defvar org-remove-priority-next-time nil)
11123 (defun org-priority-up ()
11124 "Increase the priority of the current item."
11125 (interactive)
11126 (org-priority 'up))
11128 (defun org-priority-down ()
11129 "Decrease the priority of the current item."
11130 (interactive)
11131 (org-priority 'down))
11133 (defun org-priority (&optional action)
11134 "Change the priority of an item by ARG.
11135 ACTION can be `set', `up', `down', or a character."
11136 (interactive)
11137 (unless org-enable-priority-commands
11138 (error "Priority commands are disabled"))
11139 (setq action (or action 'set))
11140 (let (current new news have remove)
11141 (save-excursion
11142 (org-back-to-heading t)
11143 (if (looking-at org-priority-regexp)
11144 (setq current (string-to-char (match-string 2))
11145 have t)
11146 (setq current org-default-priority))
11147 (cond
11148 ((eq action 'remove)
11149 (setq remove t new ?\ ))
11150 ((or (eq action 'set)
11151 (if (featurep 'xemacs) (characterp action) (integerp action)))
11152 (if (not (eq action 'set))
11153 (setq new action)
11154 (message "Priority %c-%c, SPC to remove: "
11155 org-highest-priority org-lowest-priority)
11156 (setq new (read-char-exclusive)))
11157 (if (and (= (upcase org-highest-priority) org-highest-priority)
11158 (= (upcase org-lowest-priority) org-lowest-priority))
11159 (setq new (upcase new)))
11160 (cond ((equal new ?\ ) (setq remove t))
11161 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11162 (error "Priority must be between `%c' and `%c'"
11163 org-highest-priority org-lowest-priority))))
11164 ((eq action 'up)
11165 (if (and (not have) (eq last-command this-command))
11166 (setq new org-lowest-priority)
11167 (setq new (if (and org-priority-start-cycle-with-default (not have))
11168 org-default-priority (1- current)))))
11169 ((eq action 'down)
11170 (if (and (not have) (eq last-command this-command))
11171 (setq new org-highest-priority)
11172 (setq new (if (and org-priority-start-cycle-with-default (not have))
11173 org-default-priority (1+ current)))))
11174 (t (error "Invalid action")))
11175 (if (or (< (upcase new) org-highest-priority)
11176 (> (upcase new) org-lowest-priority))
11177 (setq remove t))
11178 (setq news (format "%c" new))
11179 (if have
11180 (if remove
11181 (replace-match "" t t nil 1)
11182 (replace-match news t t nil 2))
11183 (if remove
11184 (error "No priority cookie found in line")
11185 (let ((case-fold-search nil))
11186 (looking-at org-todo-line-regexp))
11187 (if (match-end 2)
11188 (progn
11189 (goto-char (match-end 2))
11190 (insert " [#" news "]"))
11191 (goto-char (match-beginning 3))
11192 (insert "[#" news "] "))))
11193 (org-preserve-lc (org-set-tags nil 'align)))
11194 (if remove
11195 (message "Priority removed")
11196 (message "Priority of current item set to %s" news))))
11198 (defun org-get-priority (s)
11199 "Find priority cookie and return priority."
11200 (save-match-data
11201 (if (not (string-match org-priority-regexp s))
11202 (* 1000 (- org-lowest-priority org-default-priority))
11203 (* 1000 (- org-lowest-priority
11204 (string-to-char (match-string 2 s)))))))
11206 ;;;; Tags
11208 (defvar org-agenda-archives-mode)
11209 (defvar org-map-continue-from nil
11210 "Position from where mapping should continue.
11211 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11213 (defvar org-scanner-tags nil
11214 "The current tag list while the tags scanner is running.")
11215 (defvar org-trust-scanner-tags nil
11216 "Should `org-get-tags-at' use the tags fro the scanner.
11217 This is for internal dynamical scoping only.
11218 When this is non-nil, the function `org-get-tags-at' will return the value
11219 of `org-scanner-tags' instead of building the list by itself. This
11220 can lead to large speed-ups when the tags scanner is used in a file with
11221 many entries, and when the list of tags is retrieved, for example to
11222 obtain a list of properties. Building the tags list for each entry in such
11223 a file becomes an N^2 operation - but with this variable set, it scales
11224 as N.")
11226 (defun org-scan-tags (action matcher &optional todo-only)
11227 "Scan headline tags with inheritance and produce output ACTION.
11229 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11230 or `agenda' to produce an entry list for an agenda view. It can also be
11231 a Lisp form or a function that should be called at each matched headline, in
11232 this case the return value is a list of all return values from these calls.
11234 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11235 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11236 only lines with a TODO keyword are included in the output."
11237 (require 'org-agenda)
11238 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11239 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11240 (org-re
11241 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11242 (props (list 'face 'default
11243 'done-face 'org-agenda-done
11244 'undone-face 'default
11245 'mouse-face 'highlight
11246 'org-not-done-regexp org-not-done-regexp
11247 'org-todo-regexp org-todo-regexp
11248 'help-echo
11249 (format "mouse-2 or RET jump to org file %s"
11250 (abbreviate-file-name
11251 (or (buffer-file-name (buffer-base-buffer))
11252 (buffer-name (buffer-base-buffer)))))))
11253 (case-fold-search nil)
11254 (org-map-continue-from nil)
11255 lspos tags tags-list
11256 (tags-alist (list (cons 0 org-file-tags)))
11257 (llast 0) rtn rtn1 level category i txt
11258 todo marker entry priority)
11259 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11260 (setq action (list 'lambda nil action)))
11261 (save-excursion
11262 (goto-char (point-min))
11263 (when (eq action 'sparse-tree)
11264 (org-overview)
11265 (org-remove-occur-highlights))
11266 (while (re-search-forward re nil t)
11267 (catch :skip
11268 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11269 tags (if (match-end 4) (org-match-string-no-properties 4)))
11270 (goto-char (setq lspos (match-beginning 0)))
11271 (setq level (org-reduced-level (funcall outline-level))
11272 category (org-get-category))
11273 (setq i llast llast level)
11274 ;; remove tag lists from same and sublevels
11275 (while (>= i level)
11276 (when (setq entry (assoc i tags-alist))
11277 (setq tags-alist (delete entry tags-alist)))
11278 (setq i (1- i)))
11279 ;; add the next tags
11280 (when tags
11281 (setq tags (org-split-string tags ":")
11282 tags-alist
11283 (cons (cons level tags) tags-alist)))
11284 ;; compile tags for current headline
11285 (setq tags-list
11286 (if org-use-tag-inheritance
11287 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11288 tags)
11289 org-scanner-tags tags-list)
11290 (when org-use-tag-inheritance
11291 (setcdr (car tags-alist)
11292 (mapcar (lambda (x)
11293 (setq x (copy-sequence x))
11294 (org-add-prop-inherited x))
11295 (cdar tags-alist))))
11296 (when (and tags org-use-tag-inheritance
11297 (or (not (eq t org-use-tag-inheritance))
11298 org-tags-exclude-from-inheritance))
11299 ;; selective inheritance, remove uninherited ones
11300 (setcdr (car tags-alist)
11301 (org-remove-uniherited-tags (cdar tags-alist))))
11302 (when (and (or (not todo-only)
11303 (and (member todo org-not-done-keywords)
11304 (or (not org-agenda-tags-todo-honor-ignore-options)
11305 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11306 (let ((case-fold-search t)) (eval matcher))
11308 (not (member org-archive-tag tags-list))
11309 ;; we have an archive tag, should we use this anyway?
11310 (or (not org-agenda-skip-archived-trees)
11311 (and (eq action 'agenda) org-agenda-archives-mode))))
11312 (unless (eq action 'sparse-tree) (org-agenda-skip))
11314 ;; select this headline
11316 (cond
11317 ((eq action 'sparse-tree)
11318 (and org-highlight-sparse-tree-matches
11319 (org-get-heading) (match-end 0)
11320 (org-highlight-new-match
11321 (match-beginning 0) (match-beginning 1)))
11322 (org-show-context 'tags-tree))
11323 ((eq action 'agenda)
11324 (setq txt (org-format-agenda-item
11326 (concat
11327 (if (eq org-tags-match-list-sublevels 'indented)
11328 (make-string (1- level) ?.) "")
11329 (org-get-heading))
11330 category
11331 tags-list
11333 priority (org-get-priority txt))
11334 (goto-char lspos)
11335 (setq marker (org-agenda-new-marker))
11336 (org-add-props txt props
11337 'org-marker marker 'org-hd-marker marker 'org-category category
11338 'todo-state todo
11339 'priority priority 'type "tagsmatch")
11340 (push txt rtn))
11341 ((functionp action)
11342 (setq org-map-continue-from nil)
11343 (save-excursion
11344 (setq rtn1 (funcall action))
11345 (push rtn1 rtn)))
11346 (t (error "Invalid action")))
11348 ;; if we are to skip sublevels, jump to end of subtree
11349 (unless org-tags-match-list-sublevels
11350 (org-end-of-subtree t)
11351 (backward-char 1))))
11352 ;; Get the correct position from where to continue
11353 (if org-map-continue-from
11354 (goto-char org-map-continue-from)
11355 (and (= (point) lspos) (end-of-line 1)))))
11356 (when (and (eq action 'sparse-tree)
11357 (not org-sparse-tree-open-archived-trees))
11358 (org-hide-archived-subtrees (point-min) (point-max)))
11359 (nreverse rtn)))
11361 (defun org-remove-uniherited-tags (tags)
11362 "Remove all tags that are not inherited from the list TAGS."
11363 (cond
11364 ((eq org-use-tag-inheritance t)
11365 (if org-tags-exclude-from-inheritance
11366 (org-delete-all org-tags-exclude-from-inheritance tags)
11367 tags))
11368 ((not org-use-tag-inheritance) nil)
11369 ((stringp org-use-tag-inheritance)
11370 (delq nil (mapcar
11371 (lambda (x)
11372 (if (and (string-match org-use-tag-inheritance x)
11373 (not (member x org-tags-exclude-from-inheritance)))
11374 x nil))
11375 tags)))
11376 ((listp org-use-tag-inheritance)
11377 (delq nil (mapcar
11378 (lambda (x)
11379 (if (member x org-use-tag-inheritance) x nil))
11380 tags)))))
11382 (defvar todo-only) ;; dynamically scoped
11384 (defun org-match-sparse-tree (&optional todo-only match)
11385 "Create a sparse tree according to tags string MATCH.
11386 MATCH can contain positive and negative selection of tags, like
11387 \"+WORK+URGENT-WITHBOSS\".
11388 If optional argument TODO-ONLY is non-nil, only select lines that are
11389 also TODO lines."
11390 (interactive "P")
11391 (org-prepare-agenda-buffers (list (current-buffer)))
11392 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11394 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11396 (defvar org-cached-props nil)
11397 (defun org-cached-entry-get (pom property)
11398 (if (or (eq t org-use-property-inheritance)
11399 (and (stringp org-use-property-inheritance)
11400 (string-match org-use-property-inheritance property))
11401 (and (listp org-use-property-inheritance)
11402 (member property org-use-property-inheritance)))
11403 ;; Caching is not possible, check it directly
11404 (org-entry-get pom property 'inherit)
11405 ;; Get all properties, so that we can do complicated checks easily
11406 (cdr (assoc property (or org-cached-props
11407 (setq org-cached-props
11408 (org-entry-properties pom)))))))
11410 (defun org-global-tags-completion-table (&optional files)
11411 "Return the list of all tags in all agenda buffer/files."
11412 (save-excursion
11413 (org-uniquify
11414 (delq nil
11415 (apply 'append
11416 (mapcar
11417 (lambda (file)
11418 (set-buffer (find-file-noselect file))
11419 (append (org-get-buffer-tags)
11420 (mapcar (lambda (x) (if (stringp (car-safe x))
11421 (list (car-safe x)) nil))
11422 org-tag-alist)))
11423 (if (and files (car files))
11424 files
11425 (org-agenda-files))))))))
11427 (defun org-make-tags-matcher (match)
11428 "Create the TAGS//TODO matcher form for the selection string MATCH."
11429 ;; todo-only is scoped dynamically into this function, and the function
11430 ;; may change it if the matcher asks for it.
11431 (unless match
11432 ;; Get a new match request, with completion
11433 (let ((org-last-tags-completion-table
11434 (org-global-tags-completion-table)))
11435 (setq match (org-completing-read-no-i
11436 "Match: " 'org-tags-completion-function nil nil nil
11437 'org-tags-history))))
11439 ;; Parse the string and create a lisp form
11440 (let ((match0 match)
11441 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11442 minus tag mm
11443 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11444 orterms term orlist re-p str-p level-p level-op time-p
11445 prop-p pn pv po cat-p gv rest)
11446 (if (string-match "/+" match)
11447 ;; match contains also a todo-matching request
11448 (progn
11449 (setq tagsmatch (substring match 0 (match-beginning 0))
11450 todomatch (substring match (match-end 0)))
11451 (if (string-match "^!" todomatch)
11452 (setq todo-only t todomatch (substring todomatch 1)))
11453 (if (string-match "^\\s-*$" todomatch)
11454 (setq todomatch nil)))
11455 ;; only matching tags
11456 (setq tagsmatch match todomatch nil))
11458 ;; Make the tags matcher
11459 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11460 (setq tagsmatcher t)
11461 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11462 (while (setq term (pop orterms))
11463 (while (and (equal (substring term -1) "\\") orterms)
11464 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11465 (while (string-match re term)
11466 (setq rest (substring term (match-end 0))
11467 minus (and (match-end 1)
11468 (equal (match-string 1 term) "-"))
11469 tag (match-string 2 term)
11470 re-p (equal (string-to-char tag) ?{)
11471 level-p (match-end 4)
11472 prop-p (match-end 5)
11473 mm (cond
11474 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11475 (level-p
11476 (setq level-op (org-op-to-function (match-string 3 term)))
11477 `(,level-op level ,(string-to-number
11478 (match-string 4 term))))
11479 (prop-p
11480 (setq pn (match-string 5 term)
11481 po (match-string 6 term)
11482 pv (match-string 7 term)
11483 cat-p (equal pn "CATEGORY")
11484 re-p (equal (string-to-char pv) ?{)
11485 str-p (equal (string-to-char pv) ?\")
11486 time-p (save-match-data
11487 (string-match "^\"[[<].*[]>]\"$" pv))
11488 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11489 (if time-p (setq pv (org-matcher-time pv)))
11490 (setq po (org-op-to-function po (if time-p 'time str-p)))
11491 (cond
11492 ((equal pn "CATEGORY")
11493 (setq gv '(get-text-property (point) 'org-category)))
11494 ((equal pn "TODO")
11495 (setq gv 'todo))
11497 (setq gv `(org-cached-entry-get nil ,pn))))
11498 (if re-p
11499 (if (eq po 'org<>)
11500 `(not (string-match ,pv (or ,gv "")))
11501 `(string-match ,pv (or ,gv "")))
11502 (if str-p
11503 `(,po (or ,gv "") ,pv)
11504 `(,po (string-to-number (or ,gv ""))
11505 ,(string-to-number pv) ))))
11506 (t `(member ,tag tags-list)))
11507 mm (if minus (list 'not mm) mm)
11508 term rest)
11509 (push mm tagsmatcher))
11510 (push (if (> (length tagsmatcher) 1)
11511 (cons 'and tagsmatcher)
11512 (car tagsmatcher))
11513 orlist)
11514 (setq tagsmatcher nil))
11515 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11516 (setq tagsmatcher
11517 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11518 ;; Make the todo matcher
11519 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11520 (setq todomatcher t)
11521 (setq orterms (org-split-string todomatch "|") orlist nil)
11522 (while (setq term (pop orterms))
11523 (while (string-match re term)
11524 (setq minus (and (match-end 1)
11525 (equal (match-string 1 term) "-"))
11526 kwd (match-string 2 term)
11527 re-p (equal (string-to-char kwd) ?{)
11528 term (substring term (match-end 0))
11529 mm (if re-p
11530 `(string-match ,(substring kwd 1 -1) todo)
11531 (list 'equal 'todo kwd))
11532 mm (if minus (list 'not mm) mm))
11533 (push mm todomatcher))
11534 (push (if (> (length todomatcher) 1)
11535 (cons 'and todomatcher)
11536 (car todomatcher))
11537 orlist)
11538 (setq todomatcher nil))
11539 (setq todomatcher (if (> (length orlist) 1)
11540 (cons 'or orlist) (car orlist))))
11542 ;; Return the string and lisp forms of the matcher
11543 (setq matcher (if todomatcher
11544 (list 'and tagsmatcher todomatcher)
11545 tagsmatcher))
11546 (cons match0 matcher)))
11548 (defun org-op-to-function (op &optional stringp)
11549 "Turn an operator into the appropriate function."
11550 (setq op
11551 (cond
11552 ((equal op "<" ) '(< string< org-time<))
11553 ((equal op ">" ) '(> org-string> org-time>))
11554 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11555 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11556 ((member op '("=" "==")) '(= string= org-time=))
11557 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11558 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11560 (defun org<> (a b) (not (= a b)))
11561 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11562 (defun org-string>= (a b) (not (string< a b)))
11563 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11564 (defun org-string<> (a b) (not (string= a b)))
11565 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11566 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11567 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11568 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11569 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11570 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11571 (defun org-2ft (s)
11572 "Convert S to a floating point time.
11573 If S is already a number, just return it. If it is a string, parse
11574 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11575 (cond
11576 ((numberp s) s)
11577 ((stringp s)
11578 (condition-case nil
11579 (float-time (apply 'encode-time (org-parse-time-string s)))
11580 (error 0.)))
11581 (t 0.)))
11583 (defun org-time-today ()
11584 "Time in seconds today at 0:00.
11585 Returns the float number of seconds since the beginning of the
11586 epoch to the beginning of today (00:00)."
11587 (float-time (apply 'encode-time
11588 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11590 (defun org-matcher-time (s)
11591 "Interpret a time comparison value."
11592 (save-match-data
11593 (cond
11594 ((string= s "<now>") (float-time))
11595 ((string= s "<today>") (org-time-today))
11596 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11597 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11598 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11599 (+ (org-time-today)
11600 (* (string-to-number (match-string 1 s))
11601 (cdr (assoc (match-string 2 s)
11602 '(("d" . 86400.0) ("w" . 604800.0)
11603 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11604 (t (org-2ft s)))))
11606 (defun org-match-any-p (re list)
11607 "Does re match any element of list?"
11608 (setq list (mapcar (lambda (x) (string-match re x)) list))
11609 (delq nil list))
11611 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11612 (defvar org-tags-overlay (org-make-overlay 1 1))
11613 (org-detach-overlay org-tags-overlay)
11615 (defun org-get-local-tags-at (&optional pos)
11616 "Get a list of tags defined in the current headline."
11617 (org-get-tags-at pos 'local))
11619 (defun org-get-local-tags ()
11620 "Get a list of tags defined in the current headline."
11621 (org-get-tags-at nil 'local))
11623 (defun org-get-tags-at (&optional pos local)
11624 "Get a list of all headline tags applicable at POS.
11625 POS defaults to point. If tags are inherited, the list contains
11626 the targets in the same sequence as the headlines appear, i.e.
11627 the tags of the current headline come last.
11628 When LOCAL is non-nil, only return tags from the current headline,
11629 ignore inherited ones."
11630 (interactive)
11631 (if (and org-trust-scanner-tags
11632 (or (not pos) (equal pos (point)))
11633 (not local))
11634 org-scanner-tags
11635 (let (tags ltags lastpos parent)
11636 (save-excursion
11637 (save-restriction
11638 (widen)
11639 (goto-char (or pos (point)))
11640 (save-match-data
11641 (catch 'done
11642 (condition-case nil
11643 (progn
11644 (org-back-to-heading t)
11645 (while (not (equal lastpos (point)))
11646 (setq lastpos (point))
11647 (when (looking-at
11648 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11649 (setq ltags (org-split-string
11650 (org-match-string-no-properties 1) ":"))
11651 (when parent
11652 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11653 (setq tags (append
11654 (if parent
11655 (org-remove-uniherited-tags ltags)
11656 ltags)
11657 tags)))
11658 (or org-use-tag-inheritance (throw 'done t))
11659 (if local (throw 'done t))
11660 (or (org-up-heading-safe) (error nil))
11661 (setq parent t)))
11662 (error nil)))))
11663 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11665 (defun org-add-prop-inherited (s)
11666 (add-text-properties 0 (length s) '(inherited t) s)
11669 (defun org-toggle-tag (tag &optional onoff)
11670 "Toggle the tag TAG for the current line.
11671 If ONOFF is `on' or `off', don't toggle but set to this state."
11672 (let (res current)
11673 (save-excursion
11674 (org-back-to-heading t)
11675 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11676 (point-at-eol) t)
11677 (progn
11678 (setq current (match-string 1))
11679 (replace-match ""))
11680 (setq current ""))
11681 (setq current (nreverse (org-split-string current ":")))
11682 (cond
11683 ((eq onoff 'on)
11684 (setq res t)
11685 (or (member tag current) (push tag current)))
11686 ((eq onoff 'off)
11687 (or (not (member tag current)) (setq current (delete tag current))))
11688 (t (if (member tag current)
11689 (setq current (delete tag current))
11690 (setq res t)
11691 (push tag current))))
11692 (end-of-line 1)
11693 (if current
11694 (progn
11695 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11696 (org-set-tags nil t))
11697 (delete-horizontal-space))
11698 (run-hooks 'org-after-tags-change-hook))
11699 res))
11701 (defun org-align-tags-here (to-col)
11702 ;; Assumes that this is a headline
11703 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11704 (beginning-of-line 1)
11705 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11706 (< pos (match-beginning 2)))
11707 (progn
11708 (setq tags-l (- (match-end 2) (match-beginning 2)))
11709 (goto-char (match-beginning 1))
11710 (insert " ")
11711 (delete-region (point) (1+ (match-beginning 2)))
11712 (setq ncol (max (1+ (current-column))
11713 (1+ col)
11714 (if (> to-col 0)
11715 to-col
11716 (- (abs to-col) tags-l))))
11717 (setq p (point))
11718 (insert (make-string (- ncol (current-column)) ?\ ))
11719 (setq ncol (current-column))
11720 (when indent-tabs-mode (tabify p (point-at-eol)))
11721 (org-move-to-column (min ncol col) t))
11722 (goto-char pos))))
11724 (defun org-set-tags-command (&optional arg just-align)
11725 "Call the set-tags command for the current entry."
11726 (interactive "P")
11727 (if (org-on-heading-p)
11728 (org-set-tags arg just-align)
11729 (save-excursion
11730 (org-back-to-heading t)
11731 (org-set-tags arg just-align))))
11733 (defun org-set-tags-to (data)
11734 "Set the tags of the current entry to DATA, replacing the current tags.
11735 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11736 If DATA is nil or the empty string, any tags will be removed."
11737 (interactive "sTags: ")
11738 (setq data
11739 (cond
11740 ((eq data nil) "")
11741 ((equal data "") "")
11742 ((stringp data)
11743 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11744 ":"))
11745 ((listp data)
11746 (concat ":" (mapconcat 'identity data ":") ":"))
11747 (t nil)))
11748 (when data
11749 (save-excursion
11750 (org-back-to-heading t)
11751 (when (looking-at org-complex-heading-regexp)
11752 (if (match-end 5)
11753 (progn
11754 (goto-char (match-beginning 5))
11755 (insert data)
11756 (delete-region (point) (point-at-eol))
11757 (org-set-tags nil 'align))
11758 (goto-char (point-at-eol))
11759 (insert " " data)
11760 (org-set-tags nil 'align)))
11761 (beginning-of-line 1)
11762 (if (looking-at ".*?\\([ \t]+\\)$")
11763 (delete-region (match-beginning 1) (match-end 1))))))
11765 (defun org-set-tags (&optional arg just-align)
11766 "Set the tags for the current headline.
11767 With prefix ARG, realign all tags in headings in the current buffer."
11768 (interactive "P")
11769 (let* ((re (concat "^" outline-regexp))
11770 (current (org-get-tags-string))
11771 (col (current-column))
11772 (org-setting-tags t)
11773 table current-tags inherited-tags ; computed below when needed
11774 tags p0 c0 c1 rpl)
11775 (if arg
11776 (save-excursion
11777 (goto-char (point-min))
11778 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11779 (while (re-search-forward re nil t)
11780 (org-set-tags nil t)
11781 (end-of-line 1)))
11782 (message "All tags realigned to column %d" org-tags-column))
11783 (if just-align
11784 (setq tags current)
11785 ;; Get a new set of tags from the user
11786 (save-excursion
11787 (setq table (append org-tag-persistent-alist
11788 (or org-tag-alist (org-get-buffer-tags))
11789 (and org-complete-tags-always-offer-all-agenda-tags
11790 (org-global-tags-completion-table (org-agenda-files))))
11791 org-last-tags-completion-table table
11792 current-tags (org-split-string current ":")
11793 inherited-tags (nreverse
11794 (nthcdr (length current-tags)
11795 (nreverse (org-get-tags-at))))
11796 tags
11797 (if (or (eq t org-use-fast-tag-selection)
11798 (and org-use-fast-tag-selection
11799 (delq nil (mapcar 'cdr table))))
11800 (org-fast-tag-selection
11801 current-tags inherited-tags table
11802 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11803 (let ((org-add-colon-after-tag-completion t))
11804 (org-trim
11805 (org-without-partial-completion
11806 (org-icompleting-read "Tags: " 'org-tags-completion-function
11807 nil nil current 'org-tags-history)))))))
11808 (while (string-match "[-+&]+" tags)
11809 ;; No boolean logic, just a list
11810 (setq tags (replace-match ":" t t tags))))
11812 (if org-tags-sort-function
11813 (setq tags (mapconcat 'identity
11814 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11815 org-tags-sort-function) ":")))
11817 (if (string-match "\\`[\t ]*\\'" tags)
11818 (setq tags "")
11819 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11820 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11822 ;; Insert new tags at the correct column
11823 (beginning-of-line 1)
11824 (cond
11825 ((and (equal current "") (equal tags "")))
11826 ((re-search-forward
11827 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11828 (point-at-eol) t)
11829 (if (equal tags "")
11830 (setq rpl "")
11831 (goto-char (match-beginning 0))
11832 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11833 (1+ (point)) (point))
11834 c1 (max (1+ c0) (if (> org-tags-column 0)
11835 org-tags-column
11836 (- (- org-tags-column) (length tags))))
11837 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11838 (replace-match rpl t t)
11839 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11840 tags)
11841 (t (error "Tags alignment failed")))
11842 (org-move-to-column col)
11843 (unless just-align
11844 (run-hooks 'org-after-tags-change-hook)))))
11846 (defun org-change-tag-in-region (beg end tag off)
11847 "Add or remove TAG for each entry in the region.
11848 This works in the agenda, and also in an org-mode buffer."
11849 (interactive
11850 (list (region-beginning) (region-end)
11851 (let ((org-last-tags-completion-table
11852 (if (org-mode-p)
11853 (org-get-buffer-tags)
11854 (org-global-tags-completion-table))))
11855 (org-icompleting-read
11856 "Tag: " 'org-tags-completion-function nil nil nil
11857 'org-tags-history))
11858 (progn
11859 (message "[s]et or [r]emove? ")
11860 (equal (read-char-exclusive) ?r))))
11861 (if (fboundp 'deactivate-mark) (deactivate-mark))
11862 (let ((agendap (equal major-mode 'org-agenda-mode))
11863 l1 l2 m buf pos newhead (cnt 0))
11864 (goto-char end)
11865 (setq l2 (1- (org-current-line)))
11866 (goto-char beg)
11867 (setq l1 (org-current-line))
11868 (loop for l from l1 to l2 do
11869 (org-goto-line l)
11870 (setq m (get-text-property (point) 'org-hd-marker))
11871 (when (or (and (org-mode-p) (org-on-heading-p))
11872 (and agendap m))
11873 (setq buf (if agendap (marker-buffer m) (current-buffer))
11874 pos (if agendap m (point)))
11875 (with-current-buffer buf
11876 (save-excursion
11877 (save-restriction
11878 (goto-char pos)
11879 (setq cnt (1+ cnt))
11880 (org-toggle-tag tag (if off 'off 'on))
11881 (setq newhead (org-get-heading)))))
11882 (and agendap (org-agenda-change-all-lines newhead m))))
11883 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11885 (defun org-tags-completion-function (string predicate &optional flag)
11886 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11887 (confirm (lambda (x) (stringp (car x)))))
11888 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11889 (setq s1 (match-string 1 string)
11890 s2 (match-string 2 string))
11891 (setq s1 "" s2 string))
11892 (cond
11893 ((eq flag nil)
11894 ;; try completion
11895 (setq rtn (try-completion s2 ctable confirm))
11896 (if (stringp rtn)
11897 (setq rtn
11898 (concat s1 s2 (substring rtn (length s2))
11899 (if (and org-add-colon-after-tag-completion
11900 (assoc rtn ctable))
11901 ":" ""))))
11902 rtn)
11903 ((eq flag t)
11904 ;; all-completions
11905 (all-completions s2 ctable confirm)
11907 ((eq flag 'lambda)
11908 ;; exact match?
11909 (assoc s2 ctable)))
11912 (defun org-fast-tag-insert (kwd tags face &optional end)
11913 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11914 (insert (format "%-12s" (concat kwd ":"))
11915 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11916 (or end "")))
11918 (defun org-fast-tag-show-exit (flag)
11919 (save-excursion
11920 (org-goto-line 3)
11921 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11922 (replace-match ""))
11923 (when flag
11924 (end-of-line 1)
11925 (org-move-to-column (- (window-width) 19) t)
11926 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11928 (defun org-set-current-tags-overlay (current prefix)
11929 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11930 (if (featurep 'xemacs)
11931 (org-overlay-display org-tags-overlay (concat prefix s)
11932 'secondary-selection)
11933 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11934 (org-overlay-display org-tags-overlay (concat prefix s)))))
11936 (defvar org-last-tag-selection-key nil)
11937 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11938 "Fast tag selection with single keys.
11939 CURRENT is the current list of tags in the headline, INHERITED is the
11940 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11941 possibly with grouping information. TODO-TABLE is a similar table with
11942 TODO keywords, should these have keys assigned to them.
11943 If the keys are nil, a-z are automatically assigned.
11944 Returns the new tags string, or nil to not change the current settings."
11945 (let* ((fulltable (append table todo-table))
11946 (maxlen (apply 'max (mapcar
11947 (lambda (x)
11948 (if (stringp (car x)) (string-width (car x)) 0))
11949 fulltable)))
11950 (buf (current-buffer))
11951 (expert (eq org-fast-tag-selection-single-key 'expert))
11952 (buffer-tags nil)
11953 (fwidth (+ maxlen 3 1 3))
11954 (ncol (/ (- (window-width) 4) fwidth))
11955 (i-face 'org-done)
11956 (c-face 'org-todo)
11957 tg cnt e c char c1 c2 ntable tbl rtn
11958 ov-start ov-end ov-prefix
11959 (exit-after-next org-fast-tag-selection-single-key)
11960 (done-keywords org-done-keywords)
11961 groups ingroup)
11962 (save-excursion
11963 (beginning-of-line 1)
11964 (if (looking-at
11965 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11966 (setq ov-start (match-beginning 1)
11967 ov-end (match-end 1)
11968 ov-prefix "")
11969 (setq ov-start (1- (point-at-eol))
11970 ov-end (1+ ov-start))
11971 (skip-chars-forward "^\n\r")
11972 (setq ov-prefix
11973 (concat
11974 (buffer-substring (1- (point)) (point))
11975 (if (> (current-column) org-tags-column)
11977 (make-string (- org-tags-column (current-column)) ?\ ))))))
11978 (org-move-overlay org-tags-overlay ov-start ov-end)
11979 (save-window-excursion
11980 (if expert
11981 (set-buffer (get-buffer-create " *Org tags*"))
11982 (delete-other-windows)
11983 (split-window-vertically)
11984 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11985 (erase-buffer)
11986 (org-set-local 'org-done-keywords done-keywords)
11987 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11988 (org-fast-tag-insert "Current" current c-face "\n\n")
11989 (org-fast-tag-show-exit exit-after-next)
11990 (org-set-current-tags-overlay current ov-prefix)
11991 (setq tbl fulltable char ?a cnt 0)
11992 (while (setq e (pop tbl))
11993 (cond
11994 ((equal (car e) :startgroup)
11995 (push '() groups) (setq ingroup t)
11996 (when (not (= cnt 0))
11997 (setq cnt 0)
11998 (insert "\n"))
11999 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12000 ((equal (car e) :endgroup)
12001 (setq ingroup nil cnt 0)
12002 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12003 ((equal e '(:newline))
12004 (when (not (= cnt 0))
12005 (setq cnt 0)
12006 (insert "\n")
12007 (setq e (car tbl))
12008 (while (equal (car tbl) '(:newline))
12009 (insert "\n")
12010 (setq tbl (cdr tbl)))))
12012 (setq tg (copy-sequence (car e)) c2 nil)
12013 (if (cdr e)
12014 (setq c (cdr e))
12015 ;; automatically assign a character.
12016 (setq c1 (string-to-char
12017 (downcase (substring
12018 tg (if (= (string-to-char tg) ?@) 1 0)))))
12019 (if (or (rassoc c1 ntable) (rassoc c1 table))
12020 (while (or (rassoc char ntable) (rassoc char table))
12021 (setq char (1+ char)))
12022 (setq c2 c1))
12023 (setq c (or c2 char)))
12024 (if ingroup (push tg (car groups)))
12025 (setq tg (org-add-props tg nil 'face
12026 (cond
12027 ((not (assoc tg table))
12028 (org-get-todo-face tg))
12029 ((member tg current) c-face)
12030 ((member tg inherited) i-face)
12031 (t nil))))
12032 (if (and (= cnt 0) (not ingroup)) (insert " "))
12033 (insert "[" c "] " tg (make-string
12034 (- fwidth 4 (length tg)) ?\ ))
12035 (push (cons tg c) ntable)
12036 (when (= (setq cnt (1+ cnt)) ncol)
12037 (insert "\n")
12038 (if ingroup (insert " "))
12039 (setq cnt 0)))))
12040 (setq ntable (nreverse ntable))
12041 (insert "\n")
12042 (goto-char (point-min))
12043 (if (not expert) (org-fit-window-to-buffer))
12044 (setq rtn
12045 (catch 'exit
12046 (while t
12047 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12048 (if (not groups) "no " "")
12049 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12050 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12051 (setq org-last-tag-selection-key c)
12052 (cond
12053 ((= c ?\r) (throw 'exit t))
12054 ((= c ?!)
12055 (setq groups (not groups))
12056 (goto-char (point-min))
12057 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12058 ((= c ?\C-c)
12059 (if (not expert)
12060 (org-fast-tag-show-exit
12061 (setq exit-after-next (not exit-after-next)))
12062 (setq expert nil)
12063 (delete-other-windows)
12064 (split-window-vertically)
12065 (org-switch-to-buffer-other-window " *Org tags*")
12066 (org-fit-window-to-buffer)))
12067 ((or (= c ?\C-g)
12068 (and (= c ?q) (not (rassoc c ntable))))
12069 (org-detach-overlay org-tags-overlay)
12070 (setq quit-flag t))
12071 ((= c ?\ )
12072 (setq current nil)
12073 (if exit-after-next (setq exit-after-next 'now)))
12074 ((= c ?\t)
12075 (condition-case nil
12076 (setq tg (org-icompleting-read
12077 "Tag: "
12078 (or buffer-tags
12079 (with-current-buffer buf
12080 (org-get-buffer-tags)))))
12081 (quit (setq tg "")))
12082 (when (string-match "\\S-" tg)
12083 (add-to-list 'buffer-tags (list tg))
12084 (if (member tg current)
12085 (setq current (delete tg current))
12086 (push tg current)))
12087 (if exit-after-next (setq exit-after-next 'now)))
12088 ((setq e (rassoc c todo-table) tg (car e))
12089 (with-current-buffer buf
12090 (save-excursion (org-todo tg)))
12091 (if exit-after-next (setq exit-after-next 'now)))
12092 ((setq e (rassoc c ntable) tg (car e))
12093 (if (member tg current)
12094 (setq current (delete tg current))
12095 (loop for g in groups do
12096 (if (member tg g)
12097 (mapc (lambda (x)
12098 (setq current (delete x current)))
12099 g)))
12100 (push tg current))
12101 (if exit-after-next (setq exit-after-next 'now))))
12103 ;; Create a sorted list
12104 (setq current
12105 (sort current
12106 (lambda (a b)
12107 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12108 (if (eq exit-after-next 'now) (throw 'exit t))
12109 (goto-char (point-min))
12110 (beginning-of-line 2)
12111 (delete-region (point) (point-at-eol))
12112 (org-fast-tag-insert "Current" current c-face)
12113 (org-set-current-tags-overlay current ov-prefix)
12114 (while (re-search-forward
12115 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12116 (setq tg (match-string 1))
12117 (add-text-properties
12118 (match-beginning 1) (match-end 1)
12119 (list 'face
12120 (cond
12121 ((member tg current) c-face)
12122 ((member tg inherited) i-face)
12123 (t (get-text-property (match-beginning 1) 'face))))))
12124 (goto-char (point-min)))))
12125 (org-detach-overlay org-tags-overlay)
12126 (if rtn
12127 (mapconcat 'identity current ":")
12128 nil))))
12130 (defun org-get-tags-string ()
12131 "Get the TAGS string in the current headline."
12132 (unless (org-on-heading-p t)
12133 (error "Not on a heading"))
12134 (save-excursion
12135 (beginning-of-line 1)
12136 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12137 (org-match-string-no-properties 1)
12138 "")))
12140 (defun org-get-tags ()
12141 "Get the list of tags specified in the current headline."
12142 (org-split-string (org-get-tags-string) ":"))
12144 (defun org-get-buffer-tags ()
12145 "Get a table of all tags used in the buffer, for completion."
12146 (let (tags)
12147 (save-excursion
12148 (goto-char (point-min))
12149 (while (re-search-forward
12150 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12151 (when (equal (char-after (point-at-bol 0)) ?*)
12152 (mapc (lambda (x) (add-to-list 'tags x))
12153 (org-split-string (org-match-string-no-properties 1) ":")))))
12154 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12155 (mapcar 'list tags)))
12157 ;;;; The mapping API
12159 ;;;###autoload
12160 (defun org-map-entries (func &optional match scope &rest skip)
12161 "Call FUNC at each headline selected by MATCH in SCOPE.
12163 FUNC is a function or a lisp form. The function will be called without
12164 arguments, with the cursor positioned at the beginning of the headline.
12165 The return values of all calls to the function will be collected and
12166 returned as a list.
12168 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12169 does not need to preserve point. After evaluation, the cursor will be
12170 moved to the end of the line (presumably of the headline of the
12171 processed entry) and search continues from there. Under some
12172 circumstances, this may not produce the wanted results. For example,
12173 if you have removed (e.g. archived) the current (sub)tree it could
12174 mean that the next entry will be skipped entirely. In such cases, you
12175 can specify the position from where search should continue by making
12176 FUNC set the variable `org-map-continue-from' to the desired buffer
12177 position.
12179 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12180 Only headlines that are matched by this query will be considered during
12181 the iteration. When MATCH is nil or t, all headlines will be
12182 visited by the iteration.
12184 SCOPE determines the scope of this command. It can be any of:
12186 nil The current buffer, respecting the restriction if any
12187 tree The subtree started with the entry at point
12188 file The current buffer, without restriction
12189 file-with-archives
12190 The current buffer, and any archives associated with it
12191 agenda All agenda files
12192 agenda-with-archives
12193 All agenda files with any archive files associated with them
12194 \(file1 file2 ...)
12195 If this is a list, all files in the list will be scanned
12197 The remaining args are treated as settings for the skipping facilities of
12198 the scanner. The following items can be given here:
12200 archive skip trees with the archive tag.
12201 comment skip trees with the COMMENT keyword
12202 function or Emacs Lisp form:
12203 will be used as value for `org-agenda-skip-function', so whenever
12204 the function returns t, FUNC will not be called for that
12205 entry and search will continue from the point where the
12206 function leaves it.
12208 If your function needs to retrieve the tags including inherited tags
12209 at the *current* entry, you can use the value of the variable
12210 `org-scanner-tags' which will be much faster than getting the value
12211 with `org-get-tags-at'. If your function gets properties with
12212 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12213 to t around the call to `org-entry-properties' to get the same speedup.
12214 Note that if your function moves around to retrieve tags and properties at
12215 a *different* entry, you cannot use these techniques."
12216 (let* ((org-agenda-archives-mode nil) ; just to make sure
12217 (org-agenda-skip-archived-trees (memq 'archive skip))
12218 (org-agenda-skip-comment-trees (memq 'comment skip))
12219 (org-agenda-skip-function
12220 (car (org-delete-all '(comment archive) skip)))
12221 (org-tags-match-list-sublevels t)
12222 matcher file res
12223 org-todo-keywords-for-agenda
12224 org-done-keywords-for-agenda
12225 org-todo-keyword-alist-for-agenda
12226 org-drawers-for-agenda
12227 org-tag-alist-for-agenda)
12229 (cond
12230 ((eq match t) (setq matcher t))
12231 ((eq match nil) (setq matcher t))
12232 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12234 (save-excursion
12235 (save-restriction
12236 (when (eq scope 'tree)
12237 (org-back-to-heading t)
12238 (org-narrow-to-subtree)
12239 (setq scope nil))
12241 (if (not scope)
12242 (progn
12243 (org-prepare-agenda-buffers
12244 (list (buffer-file-name (current-buffer))))
12245 (setq res (org-scan-tags func matcher)))
12246 ;; Get the right scope
12247 (cond
12248 ((and scope (listp scope) (symbolp (car scope)))
12249 (setq scope (eval scope)))
12250 ((eq scope 'agenda)
12251 (setq scope (org-agenda-files t)))
12252 ((eq scope 'agenda-with-archives)
12253 (setq scope (org-agenda-files t))
12254 (setq scope (org-add-archive-files scope)))
12255 ((eq scope 'file)
12256 (setq scope (list (buffer-file-name))))
12257 ((eq scope 'file-with-archives)
12258 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12259 (org-prepare-agenda-buffers scope)
12260 (while (setq file (pop scope))
12261 (with-current-buffer (org-find-base-buffer-visiting file)
12262 (save-excursion
12263 (save-restriction
12264 (widen)
12265 (goto-char (point-min))
12266 (setq res (append res (org-scan-tags func matcher))))))))))
12267 res))
12269 ;;;; Properties
12271 ;;; Setting and retrieving properties
12273 (defconst org-special-properties
12274 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12275 "TIMESTAMP" "TIMESTAMP_IA")
12276 "The special properties valid in Org-mode.
12278 These are properties that are not defined in the property drawer,
12279 but in some other way.")
12281 (defconst org-default-properties
12282 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12283 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12284 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12285 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12286 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12287 "CLOCK_MODELINE_TOTAL" "STYLE")
12288 "Some properties that are used by Org-mode for various purposes.
12289 Being in this list makes sure that they are offered for completion.")
12291 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12292 "Regular expression matching the first line of a property drawer.")
12294 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12295 "Regular expression matching the first line of a property drawer.")
12297 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12298 "Regular expression matching the first line of a property drawer.")
12300 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12301 "Regular expression matching the first line of a property drawer.")
12303 (defconst org-property-drawer-re
12304 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12305 org-property-end-re "\\)\n?")
12306 "Matches an entire property drawer.")
12308 (defconst org-clock-drawer-re
12309 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12310 org-property-end-re "\\)\n?")
12311 "Matches an entire clock drawer.")
12313 (defun org-property-action ()
12314 "Do an action on properties."
12315 (interactive)
12316 (let (c)
12317 (org-at-property-p)
12318 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12319 (setq c (read-char-exclusive))
12320 (cond
12321 ((equal c ?s)
12322 (call-interactively 'org-set-property))
12323 ((equal c ?d)
12324 (call-interactively 'org-delete-property))
12325 ((equal c ?D)
12326 (call-interactively 'org-delete-property-globally))
12327 ((equal c ?c)
12328 (call-interactively 'org-compute-property-at-point))
12329 (t (error "No such property action %c" c)))))
12331 (defun org-set-effort (&optional value)
12332 "Set the effort property of the current entry.
12333 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12334 allowed value."
12335 (interactive "P")
12336 (if (equal value 0) (setq value 10))
12337 (let* ((completion-ignore-case t)
12338 (prop org-effort-property)
12339 (cur (org-entry-get nil prop))
12340 (allowed (org-property-get-allowed-values nil prop 'table))
12341 (existing (mapcar 'list (org-property-values prop)))
12343 (val (cond
12344 ((stringp value) value)
12345 ((and allowed (integerp value))
12346 (or (car (nth (1- value) allowed))
12347 (car (org-last allowed))))
12348 (allowed
12349 (message "Select 1-9,0, [RET%s]: %s"
12350 (if cur (concat "=" cur) "")
12351 (mapconcat 'car allowed " "))
12352 (setq rpl (read-char-exclusive))
12353 (if (equal rpl ?\r)
12355 (setq rpl (- rpl ?0))
12356 (if (equal rpl 0) (setq rpl 10))
12357 (if (and (> rpl 0) (<= rpl (length allowed)))
12358 (car (nth (1- rpl) allowed))
12359 (org-completing-read "Effort: " allowed nil))))
12361 (let (org-completion-use-ido org-completion-use-iswitchb)
12362 (org-completing-read
12363 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12364 (concat "[" cur "]") "")
12365 ": ")
12366 existing nil nil "" nil cur))))))
12367 (unless (equal (org-entry-get nil prop) val)
12368 (org-entry-put nil prop val))
12369 (message "%s is now %s" prop val)))
12371 (defun org-at-property-p ()
12372 "Is the cursor in a property line?"
12373 ;; FIXME: Does not check if we are actually in the drawer.
12374 ;; FIXME: also returns true on any drawers.....
12375 ;; This is used by C-c C-c for property action.
12376 (save-excursion
12377 (beginning-of-line 1)
12378 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12380 (defun org-get-property-block (&optional beg end force)
12381 "Return the (beg . end) range of the body of the property drawer.
12382 BEG and END can be beginning and end of subtree, if not given
12383 they will be found.
12384 If the drawer does not exist and FORCE is non-nil, create the drawer."
12385 (catch 'exit
12386 (save-excursion
12387 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12388 (end (or end (progn (outline-next-heading) (point)))))
12389 (goto-char beg)
12390 (if (re-search-forward org-property-start-re end t)
12391 (setq beg (1+ (match-end 0)))
12392 (if force
12393 (save-excursion
12394 (org-insert-property-drawer)
12395 (setq end (progn (outline-next-heading) (point))))
12396 (throw 'exit nil))
12397 (goto-char beg)
12398 (if (re-search-forward org-property-start-re end t)
12399 (setq beg (1+ (match-end 0)))))
12400 (if (re-search-forward org-property-end-re end t)
12401 (setq end (match-beginning 0))
12402 (or force (throw 'exit nil))
12403 (goto-char beg)
12404 (setq end beg)
12405 (org-indent-line-function)
12406 (insert ":END:\n"))
12407 (cons beg end)))))
12409 (defun org-entry-properties (&optional pom which)
12410 "Get all properties of the entry at point-or-marker POM.
12411 This includes the TODO keyword, the tags, time strings for deadline,
12412 scheduled, and clocking, and any additional properties defined in the
12413 entry. The return value is an alist, keys may occur multiple times
12414 if the property key was used several times.
12415 POM may also be nil, in which case the current entry is used.
12416 If WHICH is nil or `all', get all properties. If WHICH is
12417 `special' or `standard', only get that subclass."
12418 (setq which (or which 'all))
12419 (org-with-point-at pom
12420 (let ((clockstr (substring org-clock-string 0 -1))
12421 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12422 beg end range props sum-props key value string clocksum)
12423 (save-excursion
12424 (when (condition-case nil
12425 (and (org-mode-p) (org-back-to-heading t))
12426 (error nil))
12427 (setq beg (point))
12428 (setq sum-props (get-text-property (point) 'org-summaries))
12429 (setq clocksum (get-text-property (point) :org-clock-minutes))
12430 (outline-next-heading)
12431 (setq end (point))
12432 (when (memq which '(all special))
12433 ;; Get the special properties, like TODO and tags
12434 (goto-char beg)
12435 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12436 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12437 (when (looking-at org-priority-regexp)
12438 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12439 (when (and (setq value (org-get-tags-string))
12440 (string-match "\\S-" value))
12441 (push (cons "TAGS" value) props))
12442 (when (setq value (org-get-tags-at))
12443 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12444 props))
12445 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12446 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12447 string (if (equal key clockstr)
12448 (org-no-properties
12449 (org-trim
12450 (buffer-substring
12451 (match-beginning 3) (goto-char (point-at-eol)))))
12452 (substring (org-match-string-no-properties 3) 1 -1)))
12453 (unless key
12454 (if (= (char-after (match-beginning 3)) ?\[)
12455 (setq key "TIMESTAMP_IA")
12456 (setq key "TIMESTAMP")))
12457 (when (or (equal key clockstr) (not (assoc key props)))
12458 (push (cons key string) props)))
12462 (when (memq which '(all standard))
12463 ;; Get the standard properties, like :PROP: ...
12464 (setq range (org-get-property-block beg end))
12465 (when range
12466 (goto-char (car range))
12467 (while (re-search-forward
12468 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12469 (cdr range) t)
12470 (setq key (org-match-string-no-properties 1)
12471 value (org-trim (or (org-match-string-no-properties 2) "")))
12472 (unless (member key excluded)
12473 (push (cons key (or value "")) props)))))
12474 (if clocksum
12475 (push (cons "CLOCKSUM"
12476 (org-columns-number-to-string (/ (float clocksum) 60.)
12477 'add_times))
12478 props))
12479 (unless (assoc "CATEGORY" props)
12480 (setq value (or (org-get-category)
12481 (progn (org-refresh-category-properties)
12482 (org-get-category))))
12483 (push (cons "CATEGORY" value) props))
12484 (append sum-props (nreverse props)))))))
12486 (defun org-entry-get (pom property &optional inherit)
12487 "Get value of PROPERTY for entry at point-or-marker POM.
12488 If INHERIT is non-nil and the entry does not have the property,
12489 then also check higher levels of the hierarchy.
12490 If INHERIT is the symbol `selective', use inheritance only if the setting
12491 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12492 If the property is present but empty, the return value is the empty string.
12493 If the property is not present at all, nil is returned."
12494 (org-with-point-at pom
12495 (if (and inherit (if (eq inherit 'selective)
12496 (org-property-inherit-p property)
12498 (org-entry-get-with-inheritance property)
12499 (if (member property org-special-properties)
12500 ;; We need a special property. Use brute force, get all properties.
12501 (cdr (assoc property (org-entry-properties nil 'special)))
12502 (let ((range (org-get-property-block)))
12503 (if (and range
12504 (goto-char (car range))
12505 (re-search-forward
12506 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12507 (cdr range) t))
12508 ;; Found the property, return it.
12509 (if (match-end 1)
12510 (org-match-string-no-properties 1)
12511 "")))))))
12513 (defun org-property-or-variable-value (var &optional inherit)
12514 "Check if there is a property fixing the value of VAR.
12515 If yes, return this value. If not, return the current value of the variable."
12516 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12517 (if (and prop (stringp prop) (string-match "\\S-" prop))
12518 (read prop)
12519 (symbol-value var))))
12521 (defun org-entry-delete (pom property)
12522 "Delete the property PROPERTY from entry at point-or-marker POM."
12523 (org-with-point-at pom
12524 (if (member property org-special-properties)
12525 nil ; cannot delete these properties.
12526 (let ((range (org-get-property-block)))
12527 (if (and range
12528 (goto-char (car range))
12529 (re-search-forward
12530 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12531 (cdr range) t))
12532 (progn
12533 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12535 nil)))))
12537 ;; Multi-values properties are properties that contain multiple values
12538 ;; These values are assumed to be single words, separated by whitespace.
12539 (defun org-entry-add-to-multivalued-property (pom property value)
12540 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12541 (let* ((old (org-entry-get pom property))
12542 (values (and old (org-split-string old "[ \t]"))))
12543 (setq value (org-entry-protect-space value))
12544 (unless (member value values)
12545 (setq values (cons value values))
12546 (org-entry-put pom property
12547 (mapconcat 'identity values " ")))))
12549 (defun org-entry-remove-from-multivalued-property (pom property value)
12550 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12551 (let* ((old (org-entry-get pom property))
12552 (values (and old (org-split-string old "[ \t]"))))
12553 (setq value (org-entry-protect-space value))
12554 (when (member value values)
12555 (setq values (delete value values))
12556 (org-entry-put pom property
12557 (mapconcat 'identity values " ")))))
12559 (defun org-entry-member-in-multivalued-property (pom property value)
12560 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12561 (let* ((old (org-entry-get pom property))
12562 (values (and old (org-split-string old "[ \t]"))))
12563 (setq value (org-entry-protect-space value))
12564 (member value values)))
12566 (defun org-entry-get-multivalued-property (pom property)
12567 "Return a list of values in a multivalued property."
12568 (let* ((value (org-entry-get pom property))
12569 (values (and value (org-split-string value "[ \t]"))))
12570 (mapcar 'org-entry-restore-space values)))
12572 (defun org-entry-put-multivalued-property (pom property &rest values)
12573 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12574 VALUES should be a list of strings. Spaces will be protected."
12575 (org-entry-put pom property
12576 (mapconcat 'org-entry-protect-space values " "))
12577 (let* ((value (org-entry-get pom property))
12578 (values (and value (org-split-string value "[ \t]"))))
12579 (mapcar 'org-entry-restore-space values)))
12581 (defun org-entry-protect-space (s)
12582 "Protect spaces and newline in string S."
12583 (while (string-match " " s)
12584 (setq s (replace-match "%20" t t s)))
12585 (while (string-match "\n" s)
12586 (setq s (replace-match "%0A" t t s)))
12589 (defun org-entry-restore-space (s)
12590 "Restore spaces and newline in string S."
12591 (while (string-match "%20" s)
12592 (setq s (replace-match " " t t s)))
12593 (while (string-match "%0A" s)
12594 (setq s (replace-match "\n" t t s)))
12597 (defvar org-entry-property-inherited-from (make-marker)
12598 "Marker pointing to the entry from where a property was inherited.
12599 Each call to `org-entry-get-with-inheritance' will set this marker to the
12600 location of the entry where the inheritance search matched. If there was
12601 no match, the marker will point nowhere.
12602 Note that also `org-entry-get' calls this function, if the INHERIT flag
12603 is set.")
12605 (defun org-entry-get-with-inheritance (property)
12606 "Get entry property, and search higher levels if not present."
12607 (move-marker org-entry-property-inherited-from nil)
12608 (let (tmp)
12609 (save-excursion
12610 (save-restriction
12611 (widen)
12612 (catch 'ex
12613 (while t
12614 (when (setq tmp (org-entry-get nil property))
12615 (org-back-to-heading t)
12616 (move-marker org-entry-property-inherited-from (point))
12617 (throw 'ex tmp))
12618 (or (org-up-heading-safe) (throw 'ex nil)))))
12619 (or tmp
12620 (cdr (assoc property org-file-properties))
12621 (cdr (assoc property org-global-properties))
12622 (cdr (assoc property org-global-properties-fixed))))))
12624 (defvar org-property-changed-functions nil
12625 "Hook called when the value of a property has changed.
12626 Each hook function should accept two arguments, the name of the property
12627 and the new value.")
12629 (defun org-entry-put (pom property value)
12630 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12631 (org-with-point-at pom
12632 (org-back-to-heading t)
12633 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12634 range)
12635 (cond
12636 ((equal property "TODO")
12637 (when (and (stringp value) (string-match "\\S-" value)
12638 (not (member value org-todo-keywords-1)))
12639 (error "\"%s\" is not a valid TODO state" value))
12640 (if (or (not value)
12641 (not (string-match "\\S-" value)))
12642 (setq value 'none))
12643 (org-todo value)
12644 (org-set-tags nil 'align))
12645 ((equal property "PRIORITY")
12646 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12647 (string-to-char value) ?\ ))
12648 (org-set-tags nil 'align))
12649 ((equal property "SCHEDULED")
12650 (if (re-search-forward org-scheduled-time-regexp end t)
12651 (cond
12652 ((eq value 'earlier) (org-timestamp-change -1 'day))
12653 ((eq value 'later) (org-timestamp-change 1 'day))
12654 (t (call-interactively 'org-schedule)))
12655 (call-interactively 'org-schedule)))
12656 ((equal property "DEADLINE")
12657 (if (re-search-forward org-deadline-time-regexp end t)
12658 (cond
12659 ((eq value 'earlier) (org-timestamp-change -1 'day))
12660 ((eq value 'later) (org-timestamp-change 1 'day))
12661 (t (call-interactively 'org-deadline)))
12662 (call-interactively 'org-deadline)))
12663 ((member property org-special-properties)
12664 (error "The %s property can not yet be set with `org-entry-put'"
12665 property))
12666 (t ; a non-special property
12667 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12668 (setq range (org-get-property-block beg end 'force))
12669 (goto-char (car range))
12670 (if (re-search-forward
12671 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12672 (progn
12673 (delete-region (match-beginning 1) (match-end 1))
12674 (goto-char (match-beginning 1)))
12675 (goto-char (cdr range))
12676 (insert "\n")
12677 (backward-char 1)
12678 (org-indent-line-function)
12679 (insert ":" property ":"))
12680 (and value (insert " " value))
12681 (org-indent-line-function)))))
12682 (run-hook-with-args 'org-property-changed-functions property value)))
12684 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12685 "Get all property keys in the current buffer.
12686 With INCLUDE-SPECIALS, also list the special properties that reflect things
12687 like tags and TODO state.
12688 With INCLUDE-DEFAULTS, also include properties that has special meaning
12689 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12690 With INCLUDE-COLUMNS, also include property names given in COLUMN
12691 formats in the current buffer."
12692 (let (rtn range cfmt s p)
12693 (save-excursion
12694 (save-restriction
12695 (widen)
12696 (goto-char (point-min))
12697 (while (re-search-forward org-property-start-re nil t)
12698 (setq range (org-get-property-block))
12699 (goto-char (car range))
12700 (while (re-search-forward
12701 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12702 (cdr range) t)
12703 (add-to-list 'rtn (org-match-string-no-properties 1)))
12704 (outline-next-heading))))
12706 (when include-specials
12707 (setq rtn (append org-special-properties rtn)))
12709 (when include-defaults
12710 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12711 (add-to-list 'rtn org-effort-property))
12713 (when include-columns
12714 (save-excursion
12715 (save-restriction
12716 (widen)
12717 (goto-char (point-min))
12718 (while (re-search-forward
12719 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12720 nil t)
12721 (setq cfmt (match-string 2) s 0)
12722 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12723 cfmt s)
12724 (setq s (match-end 0)
12725 p (match-string 1 cfmt))
12726 (unless (or (equal p "ITEM")
12727 (member p org-special-properties))
12728 (add-to-list 'rtn (match-string 1 cfmt))))))))
12730 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12732 (defun org-property-values (key)
12733 "Return a list of all values of property KEY."
12734 (save-excursion
12735 (save-restriction
12736 (widen)
12737 (goto-char (point-min))
12738 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12739 values)
12740 (while (re-search-forward re nil t)
12741 (add-to-list 'values (org-trim (match-string 1))))
12742 (delete "" values)))))
12744 (defun org-insert-property-drawer ()
12745 "Insert a property drawer into the current entry."
12746 (interactive)
12747 (org-back-to-heading t)
12748 (looking-at outline-regexp)
12749 (let ((indent (if org-adapt-indentation
12750 (- (match-end 0)(match-beginning 0))
12752 (beg (point))
12753 (re (concat "^[ \t]*" org-keyword-time-regexp))
12754 end hiddenp)
12755 (outline-next-heading)
12756 (setq end (point))
12757 (goto-char beg)
12758 (while (re-search-forward re end t))
12759 (setq hiddenp (org-invisible-p))
12760 (end-of-line 1)
12761 (and (equal (char-after) ?\n) (forward-char 1))
12762 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12763 (if (member (match-string 1) '("CLOCK:" ":END:"))
12764 ;; just skip this line
12765 (beginning-of-line 2)
12766 ;; Drawer start, find the end
12767 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12768 (beginning-of-line 1)))
12769 (org-skip-over-state-notes)
12770 (skip-chars-backward " \t\n\r")
12771 (if (eq (char-before) ?*) (forward-char 1))
12772 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12773 (beginning-of-line 0)
12774 (org-indent-to-column indent)
12775 (beginning-of-line 2)
12776 (org-indent-to-column indent)
12777 (beginning-of-line 0)
12778 (if hiddenp
12779 (save-excursion
12780 (org-back-to-heading t)
12781 (hide-entry))
12782 (org-flag-drawer t))))
12784 (defun org-set-property (property value)
12785 "In the current entry, set PROPERTY to VALUE.
12786 When called interactively, this will prompt for a property name, offering
12787 completion on existing and default properties. And then it will prompt
12788 for a value, offering completion either on allowed values (via an inherited
12789 xxx_ALL property) or on existing values in other instances of this property
12790 in the current file."
12791 (interactive
12792 (let* ((completion-ignore-case t)
12793 (keys (org-buffer-property-keys nil t t))
12794 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12795 (prop (if (member prop0 keys)
12796 prop0
12797 (or (cdr (assoc (downcase prop0)
12798 (mapcar (lambda (x) (cons (downcase x) x))
12799 keys)))
12800 prop0)))
12801 (cur (org-entry-get nil prop))
12802 (allowed (org-property-get-allowed-values nil prop 'table))
12803 (existing (mapcar 'list (org-property-values prop)))
12804 (val (if allowed
12805 (org-completing-read "Value: " allowed nil
12806 (not (get-text-property 0 'org-unrestricted
12807 (caar allowed))))
12808 (let (org-completion-use-ido org-completion-use-iswitchb)
12809 (org-completing-read
12810 (concat "Value " (if (and cur (string-match "\\S-" cur))
12811 (concat "[" cur "]") "")
12812 ": ")
12813 existing nil nil "" nil cur)))))
12814 (list prop (if (equal val "") cur val))))
12815 (unless (equal (org-entry-get nil property) value)
12816 (org-entry-put nil property value)))
12818 (defun org-delete-property (property)
12819 "In the current entry, delete PROPERTY."
12820 (interactive
12821 (let* ((completion-ignore-case t)
12822 (prop (org-icompleting-read
12823 "Property: " (org-entry-properties nil 'standard))))
12824 (list prop)))
12825 (message "Property %s %s" property
12826 (if (org-entry-delete nil property)
12827 "deleted"
12828 "was not present in the entry")))
12830 (defun org-delete-property-globally (property)
12831 "Remove PROPERTY globally, from all entries."
12832 (interactive
12833 (let* ((completion-ignore-case t)
12834 (prop (org-icompleting-read
12835 "Globally remove property: "
12836 (mapcar 'list (org-buffer-property-keys)))))
12837 (list prop)))
12838 (save-excursion
12839 (save-restriction
12840 (widen)
12841 (goto-char (point-min))
12842 (let ((cnt 0))
12843 (while (re-search-forward
12844 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12845 nil t)
12846 (setq cnt (1+ cnt))
12847 (replace-match ""))
12848 (message "Property \"%s\" removed from %d entries" property cnt)))))
12850 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12852 (defun org-compute-property-at-point ()
12853 "Compute the property at point.
12854 This looks for an enclosing column format, extracts the operator and
12855 then applies it to the property in the column format's scope."
12856 (interactive)
12857 (unless (org-at-property-p)
12858 (error "Not at a property"))
12859 (let ((prop (org-match-string-no-properties 2)))
12860 (org-columns-get-format-and-top-level)
12861 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12862 (error "No operator defined for property %s" prop))
12863 (org-columns-compute prop)))
12865 (defvar org-property-allowed-value-functions nil
12866 "Hook for functions supplying allowed values for specific.
12867 The functions must take a single argument, the name of the property, and
12868 return a flat list of allowed values. If \":ETC\" is one of
12869 the values, this means that these values are intended as defaults for
12870 completion, but that other values should be allowed too.
12871 The functions must return nil if they are now responsible for this
12872 prioerty.")
12874 (defun org-property-get-allowed-values (pom property &optional table)
12875 "Get allowed values for the property PROPERTY.
12876 When TABLE is non-nil, return an alist that can directly be used for
12877 completion."
12878 (let (vals)
12879 (cond
12880 ((equal property "TODO")
12881 (setq vals (org-with-point-at pom
12882 (append org-todo-keywords-1 '("")))))
12883 ((equal property "PRIORITY")
12884 (let ((n org-lowest-priority))
12885 (while (>= n org-highest-priority)
12886 (push (char-to-string n) vals)
12887 (setq n (1- n)))))
12888 ((member property org-special-properties))
12889 ((setq vals (run-hook-with-args-until-success
12890 'org-property-allowed-value-functions property)))
12892 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12893 (when (and vals (string-match "\\S-" vals))
12894 (setq vals (car (read-from-string (concat "(" vals ")"))))
12895 (setq vals (mapcar (lambda (x)
12896 (cond ((stringp x) x)
12897 ((numberp x) (number-to-string x))
12898 ((symbolp x) (symbol-name x))
12899 (t "???")))
12900 vals)))))
12901 (when (member ":ETC" vals)
12902 (setq vals (remove ":ETC" vals))
12903 (org-add-props (car vals) '(org-unrestricted t)))
12904 (if table (mapcar 'list vals) vals)))
12906 (defun org-property-previous-allowed-value (&optional previous)
12907 "Switch to the next allowed value for this property."
12908 (interactive)
12909 (org-property-next-allowed-value t))
12911 (defun org-property-next-allowed-value (&optional previous)
12912 "Switch to the next allowed value for this property."
12913 (interactive)
12914 (unless (org-at-property-p)
12915 (error "Not at a property"))
12916 (let* ((key (match-string 2))
12917 (value (match-string 3))
12918 (allowed (or (org-property-get-allowed-values (point) key)
12919 (and (member value '("[ ]" "[-]" "[X]"))
12920 '("[ ]" "[X]"))))
12921 nval)
12922 (unless allowed
12923 (error "Allowed values for this property have not been defined"))
12924 (if previous (setq allowed (reverse allowed)))
12925 (if (member value allowed)
12926 (setq nval (car (cdr (member value allowed)))))
12927 (setq nval (or nval (car allowed)))
12928 (if (equal nval value)
12929 (error "Only one allowed value for this property"))
12930 (org-at-property-p)
12931 (replace-match (concat " :" key ": " nval) t t)
12932 (org-indent-line-function)
12933 (beginning-of-line 1)
12934 (skip-chars-forward " \t")
12935 (run-hook-with-args 'org-property-changed-functions key nval)))
12937 (defun org-find-entry-with-id (ident)
12938 "Locate the entry that contains the ID property with exact value IDENT.
12939 IDENT can be a string, a symbol or a number, this function will search for
12940 the string representation of it.
12941 Return the position where this entry starts, or nil if there is no such entry."
12942 (interactive "sID: ")
12943 (let ((id (cond
12944 ((stringp ident) ident)
12945 ((symbol-name ident) (symbol-name ident))
12946 ((numberp ident) (number-to-string ident))
12947 (t (error "IDENT %s must be a string, symbol or number" ident))))
12948 (case-fold-search nil))
12949 (save-excursion
12950 (save-restriction
12951 (widen)
12952 (goto-char (point-min))
12953 (when (re-search-forward
12954 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12955 nil t)
12956 (org-back-to-heading t)
12957 (point))))))
12959 ;;;; Timestamps
12961 (defvar org-last-changed-timestamp nil)
12962 (defvar org-last-inserted-timestamp nil
12963 "The last time stamp inserted with `org-insert-time-stamp'.")
12964 (defvar org-time-was-given) ; dynamically scoped parameter
12965 (defvar org-end-time-was-given) ; dynamically scoped parameter
12966 (defvar org-ts-what) ; dynamically scoped parameter
12968 (defun org-time-stamp (arg &optional inactive)
12969 "Prompt for a date/time and insert a time stamp.
12970 If the user specifies a time like HH:MM, or if this command is called
12971 with a prefix argument, the time stamp will contain date and time.
12972 Otherwise, only the date will be included. All parts of a date not
12973 specified by the user will be filled in from the current date/time.
12974 So if you press just return without typing anything, the time stamp
12975 will represent the current date/time. If there is already a timestamp
12976 at the cursor, it will be modified."
12977 (interactive "P")
12978 (let* ((ts nil)
12979 (default-time
12980 ;; Default time is either today, or, when entering a range,
12981 ;; the range start.
12982 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12983 (save-excursion
12984 (re-search-backward
12985 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12986 (- (point) 20) t)))
12987 (apply 'encode-time (org-parse-time-string (match-string 1)))
12988 (current-time)))
12989 (default-input (and ts (org-get-compact-tod ts)))
12990 org-time-was-given org-end-time-was-given time)
12991 (cond
12992 ((and (org-at-timestamp-p t)
12993 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12994 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12995 (insert "--")
12996 (setq time (let ((this-command this-command))
12997 (org-read-date arg 'totime nil nil
12998 default-time default-input)))
12999 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13000 ((org-at-timestamp-p t)
13001 (setq time (let ((this-command this-command))
13002 (org-read-date arg 'totime nil nil default-time default-input)))
13003 (when (org-at-timestamp-p t) ; just to get the match data
13004 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13005 (replace-match "")
13006 (setq org-last-changed-timestamp
13007 (org-insert-time-stamp
13008 time (or org-time-was-given arg)
13009 inactive nil nil (list org-end-time-was-given))))
13010 (message "Timestamp updated"))
13012 (setq time (let ((this-command this-command))
13013 (org-read-date arg 'totime nil nil default-time default-input)))
13014 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13015 nil nil (list org-end-time-was-given))))))
13017 ;; FIXME: can we use this for something else, like computing time differences?
13018 (defun org-get-compact-tod (s)
13019 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13020 (let* ((t1 (match-string 1 s))
13021 (h1 (string-to-number (match-string 2 s)))
13022 (m1 (string-to-number (match-string 3 s)))
13023 (t2 (and (match-end 4) (match-string 5 s)))
13024 (h2 (and t2 (string-to-number (match-string 6 s))))
13025 (m2 (and t2 (string-to-number (match-string 7 s))))
13026 dh dm)
13027 (if (not t2)
13029 (setq dh (- h2 h1) dm (- m2 m1))
13030 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13031 (concat t1 "+" (number-to-string dh)
13032 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13034 (defun org-time-stamp-inactive (&optional arg)
13035 "Insert an inactive time stamp.
13036 An inactive time stamp is enclosed in square brackets instead of angle
13037 brackets. It is inactive in the sense that it does not trigger agenda entries,
13038 does not link to the calendar and cannot be changed with the S-cursor keys.
13039 So these are more for recording a certain time/date."
13040 (interactive "P")
13041 (org-time-stamp arg 'inactive))
13043 (defvar org-date-ovl (org-make-overlay 1 1))
13044 (org-overlay-put org-date-ovl 'face 'org-warning)
13045 (org-detach-overlay org-date-ovl)
13047 (defvar org-ans1) ; dynamically scoped parameter
13048 (defvar org-ans2) ; dynamically scoped parameter
13050 (defvar org-plain-time-of-day-regexp) ; defined below
13052 (defvar org-overriding-default-time nil) ; dynamically scoped
13053 (defvar org-read-date-overlay nil)
13054 (defvar org-dcst nil) ; dynamically scoped
13055 (defvar org-read-date-history nil)
13056 (defvar org-read-date-final-answer nil)
13058 (defun org-read-date (&optional with-time to-time from-string prompt
13059 default-time default-input)
13060 "Read a date, possibly a time, and make things smooth for the user.
13061 The prompt will suggest to enter an ISO date, but you can also enter anything
13062 which will at least partially be understood by `parse-time-string'.
13063 Unrecognized parts of the date will default to the current day, month, year,
13064 hour and minute. If this command is called to replace a timestamp at point,
13065 of to enter the second timestamp of a range, the default time is taken from the
13066 existing stamp. For example,
13067 3-2-5 --> 2003-02-05
13068 feb 15 --> currentyear-02-15
13069 sep 12 9 --> 2009-09-12
13070 12:45 --> today 12:45
13071 22 sept 0:34 --> currentyear-09-22 0:34
13072 12 --> currentyear-currentmonth-12
13073 Fri --> nearest Friday (today or later)
13074 etc.
13076 Furthermore you can specify a relative date by giving, as the *first* thing
13077 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13078 change in days weeks, months, years.
13079 With a single plus or minus, the date is relative to today. With a double
13080 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13081 +4d --> four days from today
13082 +4 --> same as above
13083 +2w --> two weeks from today
13084 ++5 --> five days from default date
13086 The function understands only English month and weekday abbreviations,
13087 but this can be configured with the variables `parse-time-months' and
13088 `parse-time-weekdays'.
13090 While prompting, a calendar is popped up - you can also select the
13091 date with the mouse (button 1). The calendar shows a period of three
13092 months. To scroll it to other months, use the keys `>' and `<'.
13093 If you don't like the calendar, turn it off with
13094 \(setq org-read-date-popup-calendar nil)
13096 With optional argument TO-TIME, the date will immediately be converted
13097 to an internal time.
13098 With an optional argument WITH-TIME, the prompt will suggest to also
13099 insert a time. Note that when WITH-TIME is not set, you can still
13100 enter a time, and this function will inform the calling routine about
13101 this change. The calling routine may then choose to change the format
13102 used to insert the time stamp into the buffer to include the time.
13103 With optional argument FROM-STRING, read from this string instead from
13104 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13105 the time/date that is used for everything that is not specified by the
13106 user."
13107 (require 'parse-time)
13108 (let* ((org-time-stamp-rounding-minutes
13109 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13110 (org-dcst org-display-custom-times)
13111 (ct (org-current-time))
13112 (def (or org-overriding-default-time default-time ct))
13113 (defdecode (decode-time def))
13114 (dummy (progn
13115 (when (< (nth 2 defdecode) org-extend-today-until)
13116 (setcar (nthcdr 2 defdecode) -1)
13117 (setcar (nthcdr 1 defdecode) 59)
13118 (setq def (apply 'encode-time defdecode)
13119 defdecode (decode-time def)))))
13120 (calendar-frame-setup nil)
13121 (calendar-move-hook nil)
13122 (calendar-view-diary-initially-flag nil)
13123 (view-diary-entries-initially nil)
13124 (calendar-view-holidays-initially-flag nil)
13125 (view-calendar-holidays-initially nil)
13126 (timestr (format-time-string
13127 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13128 (prompt (concat (if prompt (concat prompt " ") "")
13129 (format "Date+time [%s]: " timestr)))
13130 ans (org-ans0 "") org-ans1 org-ans2 final)
13132 (cond
13133 (from-string (setq ans from-string))
13134 (org-read-date-popup-calendar
13135 (save-excursion
13136 (save-window-excursion
13137 (calendar)
13138 (calendar-forward-day (- (time-to-days def)
13139 (calendar-absolute-from-gregorian
13140 (calendar-current-date))))
13141 (org-eval-in-calendar nil t)
13142 (let* ((old-map (current-local-map))
13143 (map (copy-keymap calendar-mode-map))
13144 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13145 (org-defkey map (kbd "RET") 'org-calendar-select)
13146 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13147 'org-calendar-select-mouse)
13148 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13149 'org-calendar-select-mouse)
13150 (org-defkey minibuffer-local-map [(meta shift left)]
13151 (lambda () (interactive)
13152 (org-eval-in-calendar '(calendar-backward-month 1))))
13153 (org-defkey minibuffer-local-map [(meta shift right)]
13154 (lambda () (interactive)
13155 (org-eval-in-calendar '(calendar-forward-month 1))))
13156 (org-defkey minibuffer-local-map [(meta shift up)]
13157 (lambda () (interactive)
13158 (org-eval-in-calendar '(calendar-backward-year 1))))
13159 (org-defkey minibuffer-local-map [(meta shift down)]
13160 (lambda () (interactive)
13161 (org-eval-in-calendar '(calendar-forward-year 1))))
13162 (org-defkey minibuffer-local-map [?\e (shift left)]
13163 (lambda () (interactive)
13164 (org-eval-in-calendar '(calendar-backward-month 1))))
13165 (org-defkey minibuffer-local-map [?\e (shift right)]
13166 (lambda () (interactive)
13167 (org-eval-in-calendar '(calendar-forward-month 1))))
13168 (org-defkey minibuffer-local-map [?\e (shift up)]
13169 (lambda () (interactive)
13170 (org-eval-in-calendar '(calendar-backward-year 1))))
13171 (org-defkey minibuffer-local-map [?\e (shift down)]
13172 (lambda () (interactive)
13173 (org-eval-in-calendar '(calendar-forward-year 1))))
13174 (org-defkey minibuffer-local-map [(shift up)]
13175 (lambda () (interactive)
13176 (org-eval-in-calendar '(calendar-backward-week 1))))
13177 (org-defkey minibuffer-local-map [(shift down)]
13178 (lambda () (interactive)
13179 (org-eval-in-calendar '(calendar-forward-week 1))))
13180 (org-defkey minibuffer-local-map [(shift left)]
13181 (lambda () (interactive)
13182 (org-eval-in-calendar '(calendar-backward-day 1))))
13183 (org-defkey minibuffer-local-map [(shift right)]
13184 (lambda () (interactive)
13185 (org-eval-in-calendar '(calendar-forward-day 1))))
13186 (org-defkey minibuffer-local-map ">"
13187 (lambda () (interactive)
13188 (org-eval-in-calendar '(scroll-calendar-left 1))))
13189 (org-defkey minibuffer-local-map "<"
13190 (lambda () (interactive)
13191 (org-eval-in-calendar '(scroll-calendar-right 1))))
13192 (run-hooks 'org-read-date-minibuffer-setup-hook)
13193 (unwind-protect
13194 (progn
13195 (use-local-map map)
13196 (add-hook 'post-command-hook 'org-read-date-display)
13197 (setq org-ans0 (read-string prompt default-input
13198 'org-read-date-history nil))
13199 ;; org-ans0: from prompt
13200 ;; org-ans1: from mouse click
13201 ;; org-ans2: from calendar motion
13202 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13203 (remove-hook 'post-command-hook 'org-read-date-display)
13204 (use-local-map old-map)
13205 (when org-read-date-overlay
13206 (org-delete-overlay org-read-date-overlay)
13207 (setq org-read-date-overlay nil)))))))
13209 (t ; Naked prompt only
13210 (unwind-protect
13211 (setq ans (read-string prompt default-input
13212 'org-read-date-history timestr))
13213 (when org-read-date-overlay
13214 (org-delete-overlay org-read-date-overlay)
13215 (setq org-read-date-overlay nil)))))
13217 (setq final (org-read-date-analyze ans def defdecode))
13218 (setq org-read-date-final-answer ans)
13220 (if to-time
13221 (apply 'encode-time final)
13222 (if (and (boundp 'org-time-was-given) org-time-was-given)
13223 (format "%04d-%02d-%02d %02d:%02d"
13224 (nth 5 final) (nth 4 final) (nth 3 final)
13225 (nth 2 final) (nth 1 final))
13226 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13228 (defvar def)
13229 (defvar defdecode)
13230 (defvar with-time)
13231 (defvar org-read-date-analyze-futurep nil)
13232 (defun org-read-date-display ()
13233 "Display the current date prompt interpretation in the minibuffer."
13234 (when org-read-date-display-live
13235 (when org-read-date-overlay
13236 (org-delete-overlay org-read-date-overlay))
13237 (let ((p (point)))
13238 (end-of-line 1)
13239 (while (not (equal (buffer-substring
13240 (max (point-min) (- (point) 4)) (point))
13241 " "))
13242 (insert " "))
13243 (goto-char p))
13244 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13245 " " (or org-ans1 org-ans2)))
13246 (org-end-time-was-given nil)
13247 (f (org-read-date-analyze ans def defdecode))
13248 (fmts (if org-dcst
13249 org-time-stamp-custom-formats
13250 org-time-stamp-formats))
13251 (fmt (if (or with-time
13252 (and (boundp 'org-time-was-given) org-time-was-given))
13253 (cdr fmts)
13254 (car fmts)))
13255 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13256 (when (and org-end-time-was-given
13257 (string-match org-plain-time-of-day-regexp txt))
13258 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13259 org-end-time-was-given
13260 (substring txt (match-end 0)))))
13261 (when org-read-date-analyze-futurep
13262 (setq txt (concat txt " (=>F)")))
13263 (setq org-read-date-overlay
13264 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13265 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13267 (defun org-read-date-analyze (ans def defdecode)
13268 "Analyse the combined answer of the date prompt."
13269 ;; FIXME: cleanup and comment
13270 (let (delta deltan deltaw deltadef year month day
13271 hour minute second wday pm h2 m2 tl wday1
13272 iso-year iso-weekday iso-week iso-year iso-date futurep)
13273 (setq org-read-date-analyze-futurep nil)
13274 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13275 (setq ans "+0"))
13277 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13278 (setq ans (replace-match "" t t ans)
13279 deltan (car delta)
13280 deltaw (nth 1 delta)
13281 deltadef (nth 2 delta)))
13283 ;; Check if there is an iso week date in there
13284 ;; If yes, store the info and postpone interpreting it until the rest
13285 ;; of the parsing is done
13286 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13287 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13288 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13289 iso-week (string-to-number (match-string 2 ans)))
13290 (setq ans (replace-match "" t t ans)))
13292 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13293 (when (string-match
13294 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13295 (setq year (if (match-end 2)
13296 (string-to-number (match-string 2 ans))
13297 (string-to-number (format-time-string "%Y")))
13298 month (string-to-number (match-string 3 ans))
13299 day (string-to-number (match-string 4 ans)))
13300 (if (< year 100) (setq year (+ 2000 year)))
13301 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13302 t nil ans)))
13303 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13304 ;; If there is a time with am/pm, and *no* time without it, we convert
13305 ;; so that matching will be successful.
13306 (loop for i from 1 to 2 do ; twice, for end time as well
13307 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13308 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13309 (setq hour (string-to-number (match-string 1 ans))
13310 minute (if (match-end 3)
13311 (string-to-number (match-string 3 ans))
13313 pm (equal ?p
13314 (string-to-char (downcase (match-string 4 ans)))))
13315 (if (and (= hour 12) (not pm))
13316 (setq hour 0)
13317 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13318 (setq ans (replace-match (format "%02d:%02d" hour minute)
13319 t t ans))))
13321 ;; Check if a time range is given as a duration
13322 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13323 (setq hour (string-to-number (match-string 1 ans))
13324 h2 (+ hour (string-to-number (match-string 3 ans)))
13325 minute (string-to-number (match-string 2 ans))
13326 m2 (+ minute (if (match-end 5) (string-to-number
13327 (match-string 5 ans))0)))
13328 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13329 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13330 t t ans)))
13332 ;; Check if there is a time range
13333 (when (boundp 'org-end-time-was-given)
13334 (setq org-time-was-given nil)
13335 (when (and (string-match org-plain-time-of-day-regexp ans)
13336 (match-end 8))
13337 (setq org-end-time-was-given (match-string 8 ans))
13338 (setq ans (concat (substring ans 0 (match-beginning 7))
13339 (substring ans (match-end 7))))))
13341 (setq tl (parse-time-string ans)
13342 day (or (nth 3 tl) (nth 3 defdecode))
13343 month (or (nth 4 tl)
13344 (if (and org-read-date-prefer-future
13345 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13346 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13347 (nth 4 defdecode)))
13348 year (or (nth 5 tl)
13349 (if (and org-read-date-prefer-future
13350 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13351 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13352 (nth 5 defdecode)))
13353 hour (or (nth 2 tl) (nth 2 defdecode))
13354 minute (or (nth 1 tl) (nth 1 defdecode))
13355 second (or (nth 0 tl) 0)
13356 wday (nth 6 tl))
13358 (when (and (eq org-read-date-prefer-future 'time)
13359 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13360 (equal day (nth 3 defdecode))
13361 (equal month (nth 4 defdecode))
13362 (equal year (nth 5 defdecode))
13363 (nth 2 tl)
13364 (or (< (nth 2 tl) (nth 2 defdecode))
13365 (and (= (nth 2 tl) (nth 2 defdecode))
13366 (nth 1 tl)
13367 (< (nth 1 tl) (nth 1 defdecode)))))
13368 (setq day (1+ day)
13369 futurep t))
13371 ;; Special date definitions below
13372 (cond
13373 (iso-week
13374 ;; There was an iso week
13375 (setq futurep nil)
13376 (setq year (or iso-year year)
13377 day (or iso-weekday wday 1)
13378 wday nil ; to make sure that the trigger below does not match
13379 iso-date (calendar-gregorian-from-absolute
13380 (calendar-absolute-from-iso
13381 (list iso-week day year))))
13382 ; FIXME: Should we also push ISO weeks into the future?
13383 ; (when (and org-read-date-prefer-future
13384 ; (not iso-year)
13385 ; (< (calendar-absolute-from-gregorian iso-date)
13386 ; (time-to-days (current-time))))
13387 ; (setq year (1+ year)
13388 ; iso-date (calendar-gregorian-from-absolute
13389 ; (calendar-absolute-from-iso
13390 ; (list iso-week day year)))))
13391 (setq month (car iso-date)
13392 year (nth 2 iso-date)
13393 day (nth 1 iso-date)))
13394 (deltan
13395 (setq futurep nil)
13396 (unless deltadef
13397 (let ((now (decode-time (current-time))))
13398 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13399 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13400 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13401 ((equal deltaw "m") (setq month (+ month deltan)))
13402 ((equal deltaw "y") (setq year (+ year deltan)))))
13403 ((and wday (not (nth 3 tl)))
13404 (setq futurep nil)
13405 ;; Weekday was given, but no day, so pick that day in the week
13406 ;; on or after the derived date.
13407 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13408 (unless (equal wday wday1)
13409 (setq day (+ day (% (- wday wday1 -7) 7))))))
13410 (if (and (boundp 'org-time-was-given)
13411 (nth 2 tl))
13412 (setq org-time-was-given t))
13413 (if (< year 100) (setq year (+ 2000 year)))
13414 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13415 (setq org-read-date-analyze-futurep futurep)
13416 (list second minute hour day month year)))
13418 (defvar parse-time-weekdays)
13420 (defun org-read-date-get-relative (s today default)
13421 "Check string S for special relative date string.
13422 TODAY and DEFAULT are internal times, for today and for a default.
13423 Return shift list (N what def-flag)
13424 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13425 N is the number of WHATs to shift.
13426 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13427 the DEFAULT date rather than TODAY."
13428 (when (and
13429 (string-match
13430 (concat
13431 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13432 "\\([0-9]+\\)?"
13433 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13434 "\\([ \t]\\|$\\)") s)
13435 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13436 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13437 (string-to-char (substring (match-string 1 s) -1))
13438 ?+))
13439 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13440 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13441 (what (if (match-end 3) (match-string 3 s) "d"))
13442 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13443 (date (if rel default today))
13444 (wday (nth 6 (decode-time date)))
13445 delta)
13446 (if wday1
13447 (progn
13448 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13449 (if (= dir ?-) (setq delta (- delta 7)))
13450 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13451 (list delta "d" rel))
13452 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13454 (defun org-eval-in-calendar (form &optional keepdate)
13455 "Eval FORM in the calendar window and return to current window.
13456 Also, store the cursor date in variable org-ans2."
13457 (let ((sf (selected-frame))
13458 (sw (selected-window)))
13459 (select-window (get-buffer-window "*Calendar*" t))
13460 (eval form)
13461 (when (and (not keepdate) (calendar-cursor-to-date))
13462 (let* ((date (calendar-cursor-to-date))
13463 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13464 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13465 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13466 (select-window sw)
13467 (org-select-frame-set-input-focus sf)))
13469 (defun org-calendar-select ()
13470 "Return to `org-read-date' with the date currently selected.
13471 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13472 (interactive)
13473 (when (calendar-cursor-to-date)
13474 (let* ((date (calendar-cursor-to-date))
13475 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13476 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13477 (if (active-minibuffer-window) (exit-minibuffer))))
13479 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13480 "Insert a date stamp for the date given by the internal TIME.
13481 WITH-HM means, use the stamp format that includes the time of the day.
13482 INACTIVE means use square brackets instead of angular ones, so that the
13483 stamp will not contribute to the agenda.
13484 PRE and POST are optional strings to be inserted before and after the
13485 stamp.
13486 The command returns the inserted time stamp."
13487 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13488 stamp)
13489 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13490 (insert-before-markers (or pre ""))
13491 (insert-before-markers (setq stamp (format-time-string fmt time)))
13492 (when (listp extra)
13493 (setq extra (car extra))
13494 (if (and (stringp extra)
13495 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13496 (setq extra (format "-%02d:%02d"
13497 (string-to-number (match-string 1 extra))
13498 (string-to-number (match-string 2 extra))))
13499 (setq extra nil)))
13500 (when extra
13501 (backward-char 1)
13502 (insert-before-markers extra)
13503 (forward-char 1))
13504 (insert-before-markers (or post ""))
13505 (setq org-last-inserted-timestamp stamp)))
13507 (defun org-toggle-time-stamp-overlays ()
13508 "Toggle the use of custom time stamp formats."
13509 (interactive)
13510 (setq org-display-custom-times (not org-display-custom-times))
13511 (unless org-display-custom-times
13512 (let ((p (point-min)) (bmp (buffer-modified-p)))
13513 (while (setq p (next-single-property-change p 'display))
13514 (if (and (get-text-property p 'display)
13515 (eq (get-text-property p 'face) 'org-date))
13516 (remove-text-properties
13517 p (setq p (next-single-property-change p 'display))
13518 '(display t))))
13519 (set-buffer-modified-p bmp)))
13520 (if (featurep 'xemacs)
13521 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13522 (org-restart-font-lock)
13523 (setq org-table-may-need-update t)
13524 (if org-display-custom-times
13525 (message "Time stamps are overlayed with custom format")
13526 (message "Time stamp overlays removed")))
13528 (defun org-display-custom-time (beg end)
13529 "Overlay modified time stamp format over timestamp between BEG and END."
13530 (let* ((ts (buffer-substring beg end))
13531 t1 w1 with-hm tf time str w2 (off 0))
13532 (save-match-data
13533 (setq t1 (org-parse-time-string ts t))
13534 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13535 (setq off (- (match-end 0) (match-beginning 0)))))
13536 (setq end (- end off))
13537 (setq w1 (- end beg)
13538 with-hm (and (nth 1 t1) (nth 2 t1))
13539 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13540 time (org-fix-decoded-time t1)
13541 str (org-add-props
13542 (format-time-string
13543 (substring tf 1 -1) (apply 'encode-time time))
13544 nil 'mouse-face 'highlight)
13545 w2 (length str))
13546 (if (not (= w2 w1))
13547 (add-text-properties (1+ beg) (+ 2 beg)
13548 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13549 (if (featurep 'xemacs)
13550 (progn
13551 (put-text-property beg end 'invisible t)
13552 (put-text-property beg end 'end-glyph (make-glyph str)))
13553 (put-text-property beg end 'display str))))
13555 (defun org-translate-time (string)
13556 "Translate all timestamps in STRING to custom format.
13557 But do this only if the variable `org-display-custom-times' is set."
13558 (when org-display-custom-times
13559 (save-match-data
13560 (let* ((start 0)
13561 (re org-ts-regexp-both)
13562 t1 with-hm inactive tf time str beg end)
13563 (while (setq start (string-match re string start))
13564 (setq beg (match-beginning 0)
13565 end (match-end 0)
13566 t1 (save-match-data
13567 (org-parse-time-string (substring string beg end) t))
13568 with-hm (and (nth 1 t1) (nth 2 t1))
13569 inactive (equal (substring string beg (1+ beg)) "[")
13570 tf (funcall (if with-hm 'cdr 'car)
13571 org-time-stamp-custom-formats)
13572 time (org-fix-decoded-time t1)
13573 str (format-time-string
13574 (concat
13575 (if inactive "[" "<") (substring tf 1 -1)
13576 (if inactive "]" ">"))
13577 (apply 'encode-time time))
13578 string (replace-match str t t string)
13579 start (+ start (length str)))))))
13580 string)
13582 (defun org-fix-decoded-time (time)
13583 "Set 0 instead of nil for the first 6 elements of time.
13584 Don't touch the rest."
13585 (let ((n 0))
13586 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13588 (defun org-days-to-time (timestamp-string)
13589 "Difference between TIMESTAMP-STRING and now in days."
13590 (- (time-to-days (org-time-string-to-time timestamp-string))
13591 (time-to-days (current-time))))
13593 (defun org-deadline-close (timestamp-string &optional ndays)
13594 "Is the time in TIMESTAMP-STRING close to the current date?"
13595 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13596 (and (< (org-days-to-time timestamp-string) ndays)
13597 (not (org-entry-is-done-p))))
13599 (defun org-get-wdays (ts)
13600 "Get the deadline lead time appropriate for timestring TS."
13601 (cond
13602 ((<= org-deadline-warning-days 0)
13603 ;; 0 or negative, enforce this value no matter what
13604 (- org-deadline-warning-days))
13605 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13606 ;; lead time is specified.
13607 (floor (* (string-to-number (match-string 1 ts))
13608 (cdr (assoc (match-string 2 ts)
13609 '(("d" . 1) ("w" . 7)
13610 ("m" . 30.4) ("y" . 365.25)))))))
13611 ;; go for the default.
13612 (t org-deadline-warning-days)))
13614 (defun org-calendar-select-mouse (ev)
13615 "Return to `org-read-date' with the date currently selected.
13616 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13617 (interactive "e")
13618 (mouse-set-point ev)
13619 (when (calendar-cursor-to-date)
13620 (let* ((date (calendar-cursor-to-date))
13621 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13622 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13623 (if (active-minibuffer-window) (exit-minibuffer))))
13625 (defun org-check-deadlines (ndays)
13626 "Check if there are any deadlines due or past due.
13627 A deadline is considered due if it happens within `org-deadline-warning-days'
13628 days from today's date. If the deadline appears in an entry marked DONE,
13629 it is not shown. The prefix arg NDAYS can be used to test that many
13630 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13631 (interactive "P")
13632 (let* ((org-warn-days
13633 (cond
13634 ((equal ndays '(4)) 100000)
13635 (ndays (prefix-numeric-value ndays))
13636 (t (abs org-deadline-warning-days))))
13637 (case-fold-search nil)
13638 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13639 (callback
13640 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13642 (message "%d deadlines past-due or due within %d days"
13643 (org-occur regexp nil callback)
13644 org-warn-days)))
13646 (defun org-check-before-date (date)
13647 "Check if there are deadlines or scheduled entries before DATE."
13648 (interactive (list (org-read-date)))
13649 (let ((case-fold-search nil)
13650 (regexp (concat "\\<\\(" org-deadline-string
13651 "\\|" org-scheduled-string
13652 "\\) *<\\([^>]+\\)>"))
13653 (callback
13654 (lambda () (time-less-p
13655 (org-time-string-to-time (match-string 2))
13656 (org-time-string-to-time date)))))
13657 (message "%d entries before %s"
13658 (org-occur regexp nil callback) date)))
13660 (defun org-check-after-date (date)
13661 "Check if there are deadlines or scheduled entries after DATE."
13662 (interactive (list (org-read-date)))
13663 (let ((case-fold-search nil)
13664 (regexp (concat "\\<\\(" org-deadline-string
13665 "\\|" org-scheduled-string
13666 "\\) *<\\([^>]+\\)>"))
13667 (callback
13668 (lambda () (not
13669 (time-less-p
13670 (org-time-string-to-time (match-string 2))
13671 (org-time-string-to-time date))))))
13672 (message "%d entries after %s"
13673 (org-occur regexp nil callback) date)))
13675 (defun org-evaluate-time-range (&optional to-buffer)
13676 "Evaluate a time range by computing the difference between start and end.
13677 Normally the result is just printed in the echo area, but with prefix arg
13678 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13679 If the time range is actually in a table, the result is inserted into the
13680 next column.
13681 For time difference computation, a year is assumed to be exactly 365
13682 days in order to avoid rounding problems."
13683 (interactive "P")
13685 (org-clock-update-time-maybe)
13686 (save-excursion
13687 (unless (org-at-date-range-p t)
13688 (goto-char (point-at-bol))
13689 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13690 (if (not (org-at-date-range-p t))
13691 (error "Not at a time-stamp range, and none found in current line")))
13692 (let* ((ts1 (match-string 1))
13693 (ts2 (match-string 2))
13694 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13695 (match-end (match-end 0))
13696 (time1 (org-time-string-to-time ts1))
13697 (time2 (org-time-string-to-time ts2))
13698 (t1 (org-float-time time1))
13699 (t2 (org-float-time time2))
13700 (diff (abs (- t2 t1)))
13701 (negative (< (- t2 t1) 0))
13702 ;; (ys (floor (* 365 24 60 60)))
13703 (ds (* 24 60 60))
13704 (hs (* 60 60))
13705 (fy "%dy %dd %02d:%02d")
13706 (fy1 "%dy %dd")
13707 (fd "%dd %02d:%02d")
13708 (fd1 "%dd")
13709 (fh "%02d:%02d")
13710 y d h m align)
13711 (if havetime
13712 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13714 d (floor (/ diff ds)) diff (mod diff ds)
13715 h (floor (/ diff hs)) diff (mod diff hs)
13716 m (floor (/ diff 60)))
13717 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13719 d (floor (+ (/ diff ds) 0.5))
13720 h 0 m 0))
13721 (if (not to-buffer)
13722 (message "%s" (org-make-tdiff-string y d h m))
13723 (if (org-at-table-p)
13724 (progn
13725 (goto-char match-end)
13726 (setq align t)
13727 (and (looking-at " *|") (goto-char (match-end 0))))
13728 (goto-char match-end))
13729 (if (looking-at
13730 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13731 (replace-match ""))
13732 (if negative (insert " -"))
13733 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13734 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13735 (insert " " (format fh h m))))
13736 (if align (org-table-align))
13737 (message "Time difference inserted")))))
13739 (defun org-make-tdiff-string (y d h m)
13740 (let ((fmt "")
13741 (l nil))
13742 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13743 l (push y l)))
13744 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13745 l (push d l)))
13746 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13747 l (push h l)))
13748 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13749 l (push m l)))
13750 (apply 'format fmt (nreverse l))))
13752 (defun org-time-string-to-time (s)
13753 (apply 'encode-time (org-parse-time-string s)))
13754 (defun org-time-string-to-seconds (s)
13755 (org-float-time (org-time-string-to-time s)))
13757 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13758 "Convert a time stamp to an absolute day number.
13759 If there is a specifyer for a cyclic time stamp, get the closest date to
13760 DAYNR.
13761 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13762 the variable date is bound by the calendar when this is called."
13763 (cond
13764 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13765 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13766 daynr
13767 (+ daynr 1000)))
13768 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13769 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13770 (time-to-days (current-time))) (match-string 0 s)
13771 prefer show-all))
13772 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13774 (defun org-days-to-iso-week (days)
13775 "Return the iso week number."
13776 (require 'cal-iso)
13777 (car (calendar-iso-from-absolute days)))
13779 (defun org-small-year-to-year (year)
13780 "Convert 2-digit years into 4-digit years.
13781 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13782 The year 2000 cannot be abbreviated. Any year larger than 99
13783 is returned unchanged."
13784 (if (< year 38)
13785 (setq year (+ 2000 year))
13786 (if (< year 100)
13787 (setq year (+ 1900 year))))
13788 year)
13790 (defun org-time-from-absolute (d)
13791 "Return the time corresponding to date D.
13792 D may be an absolute day number, or a calendar-type list (month day year)."
13793 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13794 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13796 (defun org-calendar-holiday ()
13797 "List of holidays, for Diary display in Org-mode."
13798 (require 'holidays)
13799 (let ((hl (funcall
13800 (if (fboundp 'calendar-check-holidays)
13801 'calendar-check-holidays 'check-calendar-holidays) date)))
13802 (if hl (mapconcat 'identity hl "; "))))
13804 (defun org-diary-sexp-entry (sexp entry date)
13805 "Process a SEXP diary ENTRY for DATE."
13806 (require 'diary-lib)
13807 (let ((result (if calendar-debug-sexp
13808 (let ((stack-trace-on-error t))
13809 (eval (car (read-from-string sexp))))
13810 (condition-case nil
13811 (eval (car (read-from-string sexp)))
13812 (error
13813 (beep)
13814 (message "Bad sexp at line %d in %s: %s"
13815 (org-current-line)
13816 (buffer-file-name) sexp)
13817 (sleep-for 2))))))
13818 (cond ((stringp result) result)
13819 ((and (consp result)
13820 (stringp (cdr result))) (cdr result))
13821 (result entry)
13822 (t nil))))
13824 (defun org-diary-to-ical-string (frombuf)
13825 "Get iCalendar entries from diary entries in buffer FROMBUF.
13826 This uses the icalendar.el library."
13827 (let* ((tmpdir (if (featurep 'xemacs)
13828 (temp-directory)
13829 temporary-file-directory))
13830 (tmpfile (make-temp-name
13831 (expand-file-name "orgics" tmpdir)))
13832 buf rtn b e)
13833 (with-current-buffer frombuf
13834 (icalendar-export-region (point-min) (point-max) tmpfile)
13835 (setq buf (find-buffer-visiting tmpfile))
13836 (set-buffer buf)
13837 (goto-char (point-min))
13838 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13839 (setq b (match-beginning 0)))
13840 (goto-char (point-max))
13841 (if (re-search-backward "^END:VEVENT" nil t)
13842 (setq e (match-end 0)))
13843 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13844 (kill-buffer buf)
13845 (delete-file tmpfile)
13846 rtn))
13848 (defun org-closest-date (start current change prefer show-all)
13849 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13850 When PREFER is `past' return a date that is either CURRENT or past.
13851 When PREFER is `future', return a date that is either CURRENT or future.
13852 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13853 ;; Make the proper lists from the dates
13854 (catch 'exit
13855 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13856 dn dw sday cday n1 n2 n0
13857 d m y y1 y2 date1 date2 nmonths nm ny m2)
13859 (setq start (org-date-to-gregorian start)
13860 current (org-date-to-gregorian
13861 (if show-all
13862 current
13863 (time-to-days (current-time))))
13864 sday (calendar-absolute-from-gregorian start)
13865 cday (calendar-absolute-from-gregorian current))
13867 (if (<= cday sday) (throw 'exit sday))
13869 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13870 (setq dn (string-to-number (match-string 1 change))
13871 dw (cdr (assoc (match-string 2 change) a1)))
13872 (error "Invalid change specifyer: %s" change))
13873 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13874 (cond
13875 ((eq dw 'day)
13876 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13877 n2 (+ n1 dn)))
13878 ((eq dw 'year)
13879 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13880 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13881 (setq date1 (list m d y1)
13882 n1 (calendar-absolute-from-gregorian date1)
13883 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13884 n2 (calendar-absolute-from-gregorian date2)))
13885 ((eq dw 'month)
13886 ;; approx number of month between the two dates
13887 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13888 ;; How often does dn fit in there?
13889 (setq d (nth 1 start) m (car start) y (nth 2 start)
13890 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13891 m (+ m nm)
13892 ny (floor (/ m 12))
13893 y (+ y ny)
13894 m (- m (* ny 12)))
13895 (while (> m 12) (setq m (- m 12) y (1+ y)))
13896 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13897 (setq m2 (+ m dn) y2 y)
13898 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13899 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13900 (while (<= n2 cday)
13901 (setq n1 n2 m m2 y y2)
13902 (setq m2 (+ m dn) y2 y)
13903 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13904 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13905 ;; Make sure n1 is the earlier date
13906 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13907 (if show-all
13908 (cond
13909 ((eq prefer 'past) (if (= cday n2) n2 n1))
13910 ((eq prefer 'future) (if (= cday n1) n1 n2))
13911 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13912 (cond
13913 ((eq prefer 'past) (if (= cday n2) n2 n1))
13914 ((eq prefer 'future) (if (= cday n1) n1 n2))
13915 (t (if (= cday n1) n1 n2)))))))
13917 (defun org-date-to-gregorian (date)
13918 "Turn any specification of DATE into a gregorian date for the calendar."
13919 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13920 ((and (listp date) (= (length date) 3)) date)
13921 ((stringp date)
13922 (setq date (org-parse-time-string date))
13923 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13924 ((listp date)
13925 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13927 (defun org-parse-time-string (s &optional nodefault)
13928 "Parse the standard Org-mode time string.
13929 This should be a lot faster than the normal `parse-time-string'.
13930 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13931 hour and minute fields will be nil if not given."
13932 (if (string-match org-ts-regexp0 s)
13933 (list 0
13934 (if (or (match-beginning 8) (not nodefault))
13935 (string-to-number (or (match-string 8 s) "0")))
13936 (if (or (match-beginning 7) (not nodefault))
13937 (string-to-number (or (match-string 7 s) "0")))
13938 (string-to-number (match-string 4 s))
13939 (string-to-number (match-string 3 s))
13940 (string-to-number (match-string 2 s))
13941 nil nil nil)
13942 (error "Not a standard Org-mode time string: %s" s)))
13944 (defun org-timestamp-up (&optional arg)
13945 "Increase the date item at the cursor by one.
13946 If the cursor is on the year, change the year. If it is on the month or
13947 the day, change that.
13948 With prefix ARG, change by that many units."
13949 (interactive "p")
13950 (org-timestamp-change (prefix-numeric-value arg)))
13952 (defun org-timestamp-down (&optional arg)
13953 "Decrease the date item at the cursor by one.
13954 If the cursor is on the year, change the year. If it is on the month or
13955 the day, change that.
13956 With prefix ARG, change by that many units."
13957 (interactive "p")
13958 (org-timestamp-change (- (prefix-numeric-value arg))))
13960 (defun org-timestamp-up-day (&optional arg)
13961 "Increase the date in the time stamp by one day.
13962 With prefix ARG, change that many days."
13963 (interactive "p")
13964 (if (and (not (org-at-timestamp-p t))
13965 (org-on-heading-p))
13966 (org-todo 'up)
13967 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13969 (defun org-timestamp-down-day (&optional arg)
13970 "Decrease the date in the time stamp by one day.
13971 With prefix ARG, change that many days."
13972 (interactive "p")
13973 (if (and (not (org-at-timestamp-p t))
13974 (org-on-heading-p))
13975 (org-todo 'down)
13976 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13978 (defun org-at-timestamp-p (&optional inactive-ok)
13979 "Determine if the cursor is in or at a timestamp."
13980 (interactive)
13981 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13982 (pos (point))
13983 (ans (or (looking-at tsr)
13984 (save-excursion
13985 (skip-chars-backward "^[<\n\r\t")
13986 (if (> (point) (point-min)) (backward-char 1))
13987 (and (looking-at tsr)
13988 (> (- (match-end 0) pos) -1))))))
13989 (and ans
13990 (boundp 'org-ts-what)
13991 (setq org-ts-what
13992 (cond
13993 ((= pos (match-beginning 0)) 'bracket)
13994 ((= pos (1- (match-end 0))) 'bracket)
13995 ((org-pos-in-match-range pos 2) 'year)
13996 ((org-pos-in-match-range pos 3) 'month)
13997 ((org-pos-in-match-range pos 7) 'hour)
13998 ((org-pos-in-match-range pos 8) 'minute)
13999 ((or (org-pos-in-match-range pos 4)
14000 (org-pos-in-match-range pos 5)) 'day)
14001 ((and (> pos (or (match-end 8) (match-end 5)))
14002 (< pos (match-end 0)))
14003 (- pos (or (match-end 8) (match-end 5))))
14004 (t 'day))))
14005 ans))
14007 (defun org-toggle-timestamp-type ()
14008 "Toggle the type (<active> or [inactive]) of a time stamp."
14009 (interactive)
14010 (when (org-at-timestamp-p t)
14011 (let ((beg (match-beginning 0)) (end (match-end 0))
14012 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14013 (save-excursion
14014 (goto-char beg)
14015 (while (re-search-forward "[][<>]" end t)
14016 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14017 t t)))
14018 (message "Timestamp is now %sactive"
14019 (if (equal (char-after beg) ?<) "" "in")))))
14021 (defun org-timestamp-change (n &optional what)
14022 "Change the date in the time stamp at point.
14023 The date will be changed by N times WHAT. WHAT can be `day', `month',
14024 `year', `minute', `second'. If WHAT is not given, the cursor position
14025 in the timestamp determines what will be changed."
14026 (let ((pos (point))
14027 with-hm inactive
14028 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14029 org-ts-what
14030 extra rem
14031 ts time time0)
14032 (if (not (org-at-timestamp-p t))
14033 (error "Not at a timestamp"))
14034 (if (and (not what) (eq org-ts-what 'bracket))
14035 (org-toggle-timestamp-type)
14036 (if (and (not what) (not (eq org-ts-what 'day))
14037 org-display-custom-times
14038 (get-text-property (point) 'display)
14039 (not (get-text-property (1- (point)) 'display)))
14040 (setq org-ts-what 'day))
14041 (setq org-ts-what (or what org-ts-what)
14042 inactive (= (char-after (match-beginning 0)) ?\[)
14043 ts (match-string 0))
14044 (replace-match "")
14045 (if (string-match
14046 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14048 (setq extra (match-string 1 ts)))
14049 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14050 (setq with-hm t))
14051 (setq time0 (org-parse-time-string ts))
14052 (when (and (eq org-ts-what 'minute)
14053 (eq current-prefix-arg nil))
14054 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14055 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14056 (setcar (cdr time0) (+ (nth 1 time0)
14057 (if (> n 0) (- rem) (- dm rem))))))
14058 (setq time
14059 (encode-time (or (car time0) 0)
14060 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14061 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14062 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14063 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14064 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14065 (nthcdr 6 time0)))
14066 (when (and (member org-ts-what '(hour minute))
14067 extra
14068 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14069 (setq extra (org-modify-ts-extra
14070 extra
14071 (if (eq org-ts-what 'hour) 2 5)
14072 n dm)))
14073 (when (integerp org-ts-what)
14074 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14075 (if (eq what 'calendar)
14076 (let ((cal-date (org-get-date-from-calendar)))
14077 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14078 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14079 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14080 (setcar time0 (or (car time0) 0))
14081 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14082 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14083 (setq time (apply 'encode-time time0))))
14084 (setq org-last-changed-timestamp
14085 (org-insert-time-stamp time with-hm inactive nil nil extra))
14086 (org-clock-update-time-maybe)
14087 (goto-char pos)
14088 ;; Try to recenter the calendar window, if any
14089 (if (and org-calendar-follow-timestamp-change
14090 (get-buffer-window "*Calendar*" t)
14091 (memq org-ts-what '(day month year)))
14092 (org-recenter-calendar (time-to-days time))))))
14094 (defun org-modify-ts-extra (s pos n dm)
14095 "Change the different parts of the lead-time and repeat fields in timestamp."
14096 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14097 ng h m new rem)
14098 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14099 (cond
14100 ((or (org-pos-in-match-range pos 2)
14101 (org-pos-in-match-range pos 3))
14102 (setq m (string-to-number (match-string 3 s))
14103 h (string-to-number (match-string 2 s)))
14104 (if (org-pos-in-match-range pos 2)
14105 (setq h (+ h n))
14106 (setq n (* dm (org-no-warnings (signum n))))
14107 (when (not (= 0 (setq rem (% m dm))))
14108 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14109 (setq m (+ m n)))
14110 (if (< m 0) (setq m (+ m 60) h (1- h)))
14111 (if (> m 59) (setq m (- m 60) h (1+ h)))
14112 (setq h (min 24 (max 0 h)))
14113 (setq ng 1 new (format "-%02d:%02d" h m)))
14114 ((org-pos-in-match-range pos 6)
14115 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14116 ((org-pos-in-match-range pos 5)
14117 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14119 ((org-pos-in-match-range pos 9)
14120 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14121 ((org-pos-in-match-range pos 8)
14122 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14124 (when ng
14125 (setq s (concat
14126 (substring s 0 (match-beginning ng))
14128 (substring s (match-end ng))))))
14131 (defun org-recenter-calendar (date)
14132 "If the calendar is visible, recenter it to DATE."
14133 (let* ((win (selected-window))
14134 (cwin (get-buffer-window "*Calendar*" t))
14135 (calendar-move-hook nil))
14136 (when cwin
14137 (select-window cwin)
14138 (calendar-goto-date (if (listp date) date
14139 (calendar-gregorian-from-absolute date)))
14140 (select-window win))))
14142 (defun org-goto-calendar (&optional arg)
14143 "Go to the Emacs calendar at the current date.
14144 If there is a time stamp in the current line, go to that date.
14145 A prefix ARG can be used to force the current date."
14146 (interactive "P")
14147 (let ((tsr org-ts-regexp) diff
14148 (calendar-move-hook nil)
14149 (calendar-view-holidays-initially-flag nil)
14150 (view-calendar-holidays-initially nil)
14151 (calendar-view-diary-initially-flag nil)
14152 (view-diary-entries-initially nil))
14153 (if (or (org-at-timestamp-p)
14154 (save-excursion
14155 (beginning-of-line 1)
14156 (looking-at (concat ".*" tsr))))
14157 (let ((d1 (time-to-days (current-time)))
14158 (d2 (time-to-days
14159 (org-time-string-to-time (match-string 1)))))
14160 (setq diff (- d2 d1))))
14161 (calendar)
14162 (calendar-goto-today)
14163 (if (and diff (not arg)) (calendar-forward-day diff))))
14165 (defun org-get-date-from-calendar ()
14166 "Return a list (month day year) of date at point in calendar."
14167 (with-current-buffer "*Calendar*"
14168 (save-match-data
14169 (calendar-cursor-to-date))))
14171 (defun org-date-from-calendar ()
14172 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14173 If there is already a time stamp at the cursor position, update it."
14174 (interactive)
14175 (if (org-at-timestamp-p t)
14176 (org-timestamp-change 0 'calendar)
14177 (let ((cal-date (org-get-date-from-calendar)))
14178 (org-insert-time-stamp
14179 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14181 (defun org-minutes-to-hh:mm-string (m)
14182 "Compute H:MM from a number of minutes."
14183 (let ((h (/ m 60)))
14184 (setq m (- m (* 60 h)))
14185 (format org-time-clocksum-format h m)))
14187 (defun org-hh:mm-string-to-minutes (s)
14188 "Convert a string H:MM to a number of minutes.
14189 If the string is just a number, interpret it as minutes.
14190 In fact, the first hh:mm or number in the string will be taken,
14191 there can be extra stuff in the string.
14192 If no number is found, the return value is 0."
14193 (cond
14194 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14195 (+ (* (string-to-number (match-string 1 s)) 60)
14196 (string-to-number (match-string 2 s))))
14197 ((string-match "\\([0-9]+\\)" s)
14198 (string-to-number (match-string 1 s)))
14199 (t 0)))
14201 ;;;; Files
14203 (defun org-save-all-org-buffers ()
14204 "Save all Org-mode buffers without user confirmation."
14205 (interactive)
14206 (message "Saving all Org-mode buffers...")
14207 (save-some-buffers t 'org-mode-p)
14208 (when (featurep 'org-id) (org-id-locations-save))
14209 (message "Saving all Org-mode buffers... done"))
14211 (defun org-revert-all-org-buffers ()
14212 "Revert all Org-mode buffers.
14213 Prompt for confirmation when there are unsaved changes.
14214 Be sure you know what you are doing before letting this function
14215 overwrite your changes.
14217 This function is useful in a setup where one tracks org files
14218 with a version control system, to revert on one machine after pulling
14219 changes from another. I believe the procedure must be like this:
14221 1. M-x org-save-all-org-buffers
14222 2. Pull changes from the other machine, resolve conflicts
14223 3. M-x org-revert-all-org-buffers"
14224 (interactive)
14225 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14226 (error "Abort"))
14227 (save-excursion
14228 (save-window-excursion
14229 (mapc
14230 (lambda (b)
14231 (when (and (with-current-buffer b (org-mode-p))
14232 (with-current-buffer b buffer-file-name))
14233 (switch-to-buffer b)
14234 (revert-buffer t 'no-confirm)))
14235 (buffer-list))
14236 (when (and (featurep 'org-id) org-id-track-globally)
14237 (org-id-locations-load)))))
14239 ;;;; Agenda files
14241 ;;;###autoload
14242 (defun org-iswitchb (&optional arg)
14243 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14244 With a prefix argument, restrict available to files.
14245 With two prefix arguments, restrict available buffers to agenda files."
14246 (interactive "P")
14247 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14248 ((equal arg '(16)) (org-buffer-list 'agenda))
14249 (t (org-buffer-list)))))
14250 (switch-to-buffer
14251 (org-icompleting-read "Org buffer: "
14252 (mapcar 'list (mapcar 'buffer-name blist))
14253 nil t))))
14255 ;;;###autoload
14256 (defalias 'org-ido-switchb 'org-iswitchb)
14258 (defun org-buffer-list (&optional predicate exclude-tmp)
14259 "Return a list of Org buffers.
14260 PREDICATE can be `export', `files' or `agenda'.
14262 export restrict the list to Export buffers.
14263 files restrict the list to buffers visiting Org files.
14264 agenda restrict the list to buffers visiting agenda files.
14266 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14267 (let* ((bfn nil)
14268 (agenda-files (and (eq predicate 'agenda)
14269 (mapcar 'file-truename (org-agenda-files t))))
14270 (filter
14271 (cond
14272 ((eq predicate 'files)
14273 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14274 ((eq predicate 'export)
14275 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14276 ((eq predicate 'agenda)
14277 (lambda (b)
14278 (with-current-buffer b
14279 (and (eq major-mode 'org-mode)
14280 (setq bfn (buffer-file-name b))
14281 (member (file-truename bfn) agenda-files)))))
14282 (t (lambda (b) (with-current-buffer b
14283 (or (eq major-mode 'org-mode)
14284 (string-match "\*Org .*Export"
14285 (buffer-name b)))))))))
14286 (delq nil
14287 (mapcar
14288 (lambda(b)
14289 (if (and (funcall filter b)
14290 (or (not exclude-tmp)
14291 (not (string-match "tmp" (buffer-name b)))))
14293 nil))
14294 (buffer-list)))))
14296 (defun org-agenda-files (&optional unrestricted archives)
14297 "Get the list of agenda files.
14298 Optional UNRESTRICTED means return the full list even if a restriction
14299 is currently in place.
14300 When ARCHIVES is t, include all archive files hat are really being
14301 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14302 `org-agenda-archives-mode' is t."
14303 (let ((files
14304 (cond
14305 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14306 ((stringp org-agenda-files) (org-read-agenda-file-list))
14307 ((listp org-agenda-files) org-agenda-files)
14308 (t (error "Invalid value of `org-agenda-files'")))))
14309 (setq files (apply 'append
14310 (mapcar (lambda (f)
14311 (if (file-directory-p f)
14312 (directory-files
14313 f t org-agenda-file-regexp)
14314 (list f)))
14315 files)))
14316 (when org-agenda-skip-unavailable-files
14317 (setq files (delq nil
14318 (mapcar (function
14319 (lambda (file)
14320 (and (file-readable-p file) file)))
14321 files))))
14322 (when (or (eq archives t)
14323 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14324 (setq files (org-add-archive-files files)))
14325 files))
14327 (defun org-edit-agenda-file-list ()
14328 "Edit the list of agenda files.
14329 Depending on setup, this either uses customize to edit the variable
14330 `org-agenda-files', or it visits the file that is holding the list. In the
14331 latter case, the buffer is set up in a way that saving it automatically kills
14332 the buffer and restores the previous window configuration."
14333 (interactive)
14334 (if (stringp org-agenda-files)
14335 (let ((cw (current-window-configuration)))
14336 (find-file org-agenda-files)
14337 (org-set-local 'org-window-configuration cw)
14338 (org-add-hook 'after-save-hook
14339 (lambda ()
14340 (set-window-configuration
14341 (prog1 org-window-configuration
14342 (kill-buffer (current-buffer))))
14343 (org-install-agenda-files-menu)
14344 (message "New agenda file list installed"))
14345 nil 'local)
14346 (message "%s" (substitute-command-keys
14347 "Edit list and finish with \\[save-buffer]")))
14348 (customize-variable 'org-agenda-files)))
14350 (defun org-store-new-agenda-file-list (list)
14351 "Set new value for the agenda file list and save it correctly."
14352 (if (stringp org-agenda-files)
14353 (let ((f org-agenda-files) b)
14354 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14355 (with-temp-file f
14356 (insert (mapconcat 'identity list "\n") "\n")))
14357 (let ((org-mode-hook nil) (org-inhibit-startup t)
14358 (org-insert-mode-line-in-empty-file nil))
14359 (setq org-agenda-files list)
14360 (customize-save-variable 'org-agenda-files org-agenda-files))))
14362 (defun org-read-agenda-file-list ()
14363 "Read the list of agenda files from a file."
14364 (when (file-directory-p org-agenda-files)
14365 (error "`org-agenda-files' cannot be a single directory"))
14366 (when (stringp org-agenda-files)
14367 (with-temp-buffer
14368 (insert-file-contents org-agenda-files)
14369 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14372 ;;;###autoload
14373 (defun org-cycle-agenda-files ()
14374 "Cycle through the files in `org-agenda-files'.
14375 If the current buffer visits an agenda file, find the next one in the list.
14376 If the current buffer does not, find the first agenda file."
14377 (interactive)
14378 (let* ((fs (org-agenda-files t))
14379 (files (append fs (list (car fs))))
14380 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14381 file)
14382 (unless files (error "No agenda files"))
14383 (catch 'exit
14384 (while (setq file (pop files))
14385 (if (equal (file-truename file) tcf)
14386 (when (car files)
14387 (find-file (car files))
14388 (throw 'exit t))))
14389 (find-file (car fs)))
14390 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14392 (defun org-agenda-file-to-front (&optional to-end)
14393 "Move/add the current file to the top of the agenda file list.
14394 If the file is not present in the list, it is added to the front. If it is
14395 present, it is moved there. With optional argument TO-END, add/move to the
14396 end of the list."
14397 (interactive "P")
14398 (let ((org-agenda-skip-unavailable-files nil)
14399 (file-alist (mapcar (lambda (x)
14400 (cons (file-truename x) x))
14401 (org-agenda-files t)))
14402 (ctf (file-truename buffer-file-name))
14403 x had)
14404 (setq x (assoc ctf file-alist) had x)
14406 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14407 (if to-end
14408 (setq file-alist (append (delq x file-alist) (list x)))
14409 (setq file-alist (cons x (delq x file-alist))))
14410 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14411 (org-install-agenda-files-menu)
14412 (message "File %s to %s of agenda file list"
14413 (if had "moved" "added") (if to-end "end" "front"))))
14415 (defun org-remove-file (&optional file)
14416 "Remove current file from the list of files in variable `org-agenda-files'.
14417 These are the files which are being checked for agenda entries.
14418 Optional argument FILE means, use this file instead of the current."
14419 (interactive)
14420 (let* ((org-agenda-skip-unavailable-files nil)
14421 (file (or file buffer-file-name))
14422 (true-file (file-truename file))
14423 (afile (abbreviate-file-name file))
14424 (files (delq nil (mapcar
14425 (lambda (x)
14426 (if (equal true-file
14427 (file-truename x))
14428 nil x))
14429 (org-agenda-files t)))))
14430 (if (not (= (length files) (length (org-agenda-files t))))
14431 (progn
14432 (org-store-new-agenda-file-list files)
14433 (org-install-agenda-files-menu)
14434 (message "Removed file: %s" afile))
14435 (message "File was not in list: %s (not removed)" afile))))
14437 (defun org-file-menu-entry (file)
14438 (vector file (list 'find-file file) t))
14440 (defun org-check-agenda-file (file)
14441 "Make sure FILE exists. If not, ask user what to do."
14442 (when (not (file-exists-p file))
14443 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14444 (abbreviate-file-name file))
14445 (let ((r (downcase (read-char-exclusive))))
14446 (cond
14447 ((equal r ?r)
14448 (org-remove-file file)
14449 (throw 'nextfile t))
14450 (t (error "Abort"))))))
14452 (defun org-get-agenda-file-buffer (file)
14453 "Get a buffer visiting FILE. If the buffer needs to be created, add
14454 it to the list of buffers which might be released later."
14455 (let ((buf (org-find-base-buffer-visiting file)))
14456 (if buf
14457 buf ; just return it
14458 ;; Make a new buffer and remember it
14459 (setq buf (find-file-noselect file))
14460 (if buf (push buf org-agenda-new-buffers))
14461 buf)))
14463 (defun org-release-buffers (blist)
14464 "Release all buffers in list, asking the user for confirmation when needed.
14465 When a buffer is unmodified, it is just killed. When modified, it is saved
14466 \(if the user agrees) and then killed."
14467 (let (buf file)
14468 (while (setq buf (pop blist))
14469 (setq file (buffer-file-name buf))
14470 (when (and (buffer-modified-p buf)
14471 file
14472 (y-or-n-p (format "Save file %s? " file)))
14473 (with-current-buffer buf (save-buffer)))
14474 (kill-buffer buf))))
14476 (defun org-prepare-agenda-buffers (files)
14477 "Create buffers for all agenda files, protect archived trees and comments."
14478 (interactive)
14479 (let ((pa '(:org-archived t))
14480 (pc '(:org-comment t))
14481 (pall '(:org-archived t :org-comment t))
14482 (inhibit-read-only t)
14483 (rea (concat ":" org-archive-tag ":"))
14484 bmp file re)
14485 (save-excursion
14486 (save-restriction
14487 (while (setq file (pop files))
14488 (catch 'nextfile
14489 (if (bufferp file)
14490 (set-buffer file)
14491 (org-check-agenda-file file)
14492 (set-buffer (org-get-agenda-file-buffer file)))
14493 (widen)
14494 (setq bmp (buffer-modified-p))
14495 (org-refresh-category-properties)
14496 (setq org-todo-keywords-for-agenda
14497 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14498 (setq org-done-keywords-for-agenda
14499 (append org-done-keywords-for-agenda org-done-keywords))
14500 (setq org-todo-keyword-alist-for-agenda
14501 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14502 (setq org-drawers-for-agenda
14503 (append org-drawers-for-agenda org-drawers))
14504 (setq org-tag-alist-for-agenda
14505 (append org-tag-alist-for-agenda org-tag-alist))
14507 (save-excursion
14508 (remove-text-properties (point-min) (point-max) pall)
14509 (when org-agenda-skip-archived-trees
14510 (goto-char (point-min))
14511 (while (re-search-forward rea nil t)
14512 (if (org-on-heading-p t)
14513 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14514 (goto-char (point-min))
14515 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14516 (while (re-search-forward re nil t)
14517 (add-text-properties
14518 (match-beginning 0) (org-end-of-subtree t) pc)))
14519 (set-buffer-modified-p bmp)))))
14520 (setq org-todo-keyword-alist-for-agenda
14521 (org-uniquify org-todo-keyword-alist-for-agenda)
14522 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14524 ;;;; Embedded LaTeX
14526 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14527 "Keymap for the minor `org-cdlatex-mode'.")
14529 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14530 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14531 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14532 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14533 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14535 (defvar org-cdlatex-texmathp-advice-is-done nil
14536 "Flag remembering if we have applied the advice to texmathp already.")
14538 (define-minor-mode org-cdlatex-mode
14539 "Toggle the minor `org-cdlatex-mode'.
14540 This mode supports entering LaTeX environment and math in LaTeX fragments
14541 in Org-mode.
14542 \\{org-cdlatex-mode-map}"
14543 nil " OCDL" nil
14544 (when org-cdlatex-mode (require 'cdlatex))
14545 (unless org-cdlatex-texmathp-advice-is-done
14546 (setq org-cdlatex-texmathp-advice-is-done t)
14547 (defadvice texmathp (around org-math-always-on activate)
14548 "Always return t in org-mode buffers.
14549 This is because we want to insert math symbols without dollars even outside
14550 the LaTeX math segments. If Orgmode thinks that point is actually inside
14551 an embedded LaTeX fragment, let texmathp do its job.
14552 \\[org-cdlatex-mode-map]"
14553 (interactive)
14554 (let (p)
14555 (cond
14556 ((not (org-mode-p)) ad-do-it)
14557 ((eq this-command 'cdlatex-math-symbol)
14558 (setq ad-return-value t
14559 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14561 (let ((p (org-inside-LaTeX-fragment-p)))
14562 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14563 (setq ad-return-value t
14564 texmathp-why '("Org-mode embedded math" . 0))
14565 (if p ad-do-it)))))))))
14567 (defun turn-on-org-cdlatex ()
14568 "Unconditionally turn on `org-cdlatex-mode'."
14569 (org-cdlatex-mode 1))
14571 (defun org-inside-LaTeX-fragment-p ()
14572 "Test if point is inside a LaTeX fragment.
14573 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14574 sequence appearing also before point.
14575 Even though the matchers for math are configurable, this function assumes
14576 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14577 delimiters are skipped when they have been removed by customization.
14578 The return value is nil, or a cons cell with the delimiter and
14579 and the position of this delimiter.
14581 This function does a reasonably good job, but can locally be fooled by
14582 for example currency specifications. For example it will assume being in
14583 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14584 fragments that are properly closed, but during editing, we have to live
14585 with the uncertainty caused by missing closing delimiters. This function
14586 looks only before point, not after."
14587 (catch 'exit
14588 (let ((pos (point))
14589 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14590 (lim (progn
14591 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14592 (point)))
14593 dd-on str (start 0) m re)
14594 (goto-char pos)
14595 (when dodollar
14596 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14597 re (nth 1 (assoc "$" org-latex-regexps)))
14598 (while (string-match re str start)
14599 (cond
14600 ((= (match-end 0) (length str))
14601 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14602 ((= (match-end 0) (- (length str) 5))
14603 (throw 'exit nil))
14604 (t (setq start (match-end 0))))))
14605 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14606 (goto-char pos)
14607 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14608 (and (match-beginning 2) (throw 'exit nil))
14609 ;; count $$
14610 (while (re-search-backward "\\$\\$" lim t)
14611 (setq dd-on (not dd-on)))
14612 (goto-char pos)
14613 (if dd-on (cons "$$" m))))))
14615 (defun org-inside-latex-macro-p ()
14616 "Is point inside a LaTeX macro or its arguments?"
14617 (save-match-data
14618 (org-in-regexp
14619 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14621 (defun org-try-cdlatex-tab ()
14622 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14623 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14624 - inside a LaTeX fragment, or
14625 - after the first word in a line, where an abbreviation expansion could
14626 insert a LaTeX environment."
14627 (when org-cdlatex-mode
14628 (cond
14629 ((save-excursion
14630 (skip-chars-backward "a-zA-Z0-9*")
14631 (skip-chars-backward " \t")
14632 (bolp))
14633 (cdlatex-tab) t)
14634 ((org-inside-LaTeX-fragment-p)
14635 (cdlatex-tab) t)
14636 (t nil))))
14638 (defun org-cdlatex-underscore-caret (&optional arg)
14639 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14640 Revert to the normal definition outside of these fragments."
14641 (interactive "P")
14642 (if (org-inside-LaTeX-fragment-p)
14643 (call-interactively 'cdlatex-sub-superscript)
14644 (let (org-cdlatex-mode)
14645 (call-interactively (key-binding (vector last-input-event))))))
14647 (defun org-cdlatex-math-modify (&optional arg)
14648 "Execute `cdlatex-math-modify' in LaTeX fragments.
14649 Revert to the normal definition outside of these fragments."
14650 (interactive "P")
14651 (if (org-inside-LaTeX-fragment-p)
14652 (call-interactively 'cdlatex-math-modify)
14653 (let (org-cdlatex-mode)
14654 (call-interactively (key-binding (vector last-input-event))))))
14656 (defvar org-latex-fragment-image-overlays nil
14657 "List of overlays carrying the images of latex fragments.")
14658 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14660 (defun org-remove-latex-fragment-image-overlays ()
14661 "Remove all overlays with LaTeX fragment images in current buffer."
14662 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14663 (setq org-latex-fragment-image-overlays nil))
14665 (defun org-preview-latex-fragment (&optional subtree)
14666 "Preview the LaTeX fragment at point, or all locally or globally.
14667 If the cursor is in a LaTeX fragment, create the image and overlay
14668 it over the source code. If there is no fragment at point, display
14669 all fragments in the current text, from one headline to the next. With
14670 prefix SUBTREE, display all fragments in the current subtree. With a
14671 double prefix `C-u C-u', or when the cursor is before the first headline,
14672 display all fragments in the buffer.
14673 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14674 (interactive "P")
14675 (org-remove-latex-fragment-image-overlays)
14676 (save-excursion
14677 (save-restriction
14678 (let (beg end at msg)
14679 (cond
14680 ((or (equal subtree '(16))
14681 (not (save-excursion
14682 (re-search-backward (concat "^" outline-regexp) nil t))))
14683 (setq beg (point-min) end (point-max)
14684 msg "Creating images for buffer...%s"))
14685 ((equal subtree '(4))
14686 (org-back-to-heading)
14687 (setq beg (point) end (org-end-of-subtree t)
14688 msg "Creating images for subtree...%s"))
14690 (if (setq at (org-inside-LaTeX-fragment-p))
14691 (goto-char (max (point-min) (- (cdr at) 2)))
14692 (org-back-to-heading))
14693 (setq beg (point) end (progn (outline-next-heading) (point))
14694 msg (if at "Creating image...%s"
14695 "Creating images for entry...%s"))))
14696 (message msg "")
14697 (narrow-to-region beg end)
14698 (goto-char beg)
14699 (org-format-latex
14700 (concat "ltxpng/" (file-name-sans-extension
14701 (file-name-nondirectory
14702 buffer-file-name)))
14703 default-directory 'overlays msg at 'forbuffer)
14704 (message msg "done. Use `C-c C-c' to remove images.")))))
14706 (defvar org-latex-regexps
14707 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14708 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14709 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14710 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14711 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14712 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14713 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14714 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14715 "Regular expressions for matching embedded LaTeX.")
14717 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14718 "Replace LaTeX fragments with links to an image, and produce images.
14719 Some of the options can be changed using the variable
14720 `org-format-latex-options'."
14721 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14722 (let* ((prefixnodir (file-name-nondirectory prefix))
14723 (absprefix (expand-file-name prefix dir))
14724 (todir (file-name-directory absprefix))
14725 (opt org-format-latex-options)
14726 (matchers (plist-get opt :matchers))
14727 (re-list org-latex-regexps)
14728 (cnt 0) txt hash link beg end re e checkdir
14729 executables-checked
14730 m n block linkfile movefile ov)
14731 ;; Check the different regular expressions
14732 (while (setq e (pop re-list))
14733 (setq m (car e) re (nth 1 e) n (nth 2 e)
14734 block (if (nth 3 e) "\n\n" ""))
14735 (when (member m matchers)
14736 (goto-char (point-min))
14737 (while (re-search-forward re nil t)
14738 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14739 (not (get-text-property (match-beginning n)
14740 'org-protected))
14741 (or (not overlays)
14742 (not (eq (get-char-property (match-beginning n)
14743 'org-overlay-type)
14744 'org-latex-overlay))))
14745 (setq txt (match-string n)
14746 beg (match-beginning n) end (match-end n)
14747 cnt (1+ cnt))
14748 (let (print-length print-level) ; make sure full list is printed
14749 (setq hash (sha1 (prin1-to-string
14750 (list org-format-latex-header
14751 org-export-latex-packages-alist
14752 org-format-latex-options
14753 forbuffer txt)))
14754 linkfile (format "%s_%s.png" prefix hash)
14755 movefile (format "%s_%s.png" absprefix hash)))
14756 (setq link (concat block "[[file:" linkfile "]]" block))
14757 (if msg (message msg cnt))
14758 (goto-char beg)
14759 (unless checkdir ; make sure the directory exists
14760 (setq checkdir t)
14761 (or (file-directory-p todir) (make-directory todir)))
14763 (unless executables-checked
14764 (org-check-external-command
14765 "latex" "needed to convert LaTeX fragments to images")
14766 (org-check-external-command
14767 "dvipng" "needed to convert LaTeX fragments to images")
14768 (setq executables-checked t))
14770 (unless (file-exists-p movefile)
14771 (org-create-formula-image
14772 txt movefile opt forbuffer))
14773 (if overlays
14774 (progn
14775 (mapc (lambda (o)
14776 (if (eq (org-overlay-get o 'org-overlay-type)
14777 'org-latex-overlay)
14778 (org-delete-overlay o)))
14779 (org-overlays-in beg end))
14780 (setq ov (org-make-overlay beg end))
14781 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14782 (if (featurep 'xemacs)
14783 (progn
14784 (org-overlay-put ov 'invisible t)
14785 (org-overlay-put
14786 ov 'end-glyph
14787 (make-glyph (vector 'png :file movefile))))
14788 (org-overlay-put
14789 ov 'display
14790 (list 'image :type 'png :file movefile :ascent 'center)))
14791 (push ov org-latex-fragment-image-overlays)
14792 (goto-char end))
14793 (delete-region beg end)
14794 (insert link))))))))
14796 ;; This function borrows from Ganesh Swami's latex2png.el
14797 (defun org-create-formula-image (string tofile options buffer)
14798 "This calls dvipng."
14799 (require 'org-latex)
14800 (let* ((tmpdir (if (featurep 'xemacs)
14801 (temp-directory)
14802 temporary-file-directory))
14803 (texfilebase (make-temp-name
14804 (expand-file-name "orgtex" tmpdir)))
14805 (texfile (concat texfilebase ".tex"))
14806 (dvifile (concat texfilebase ".dvi"))
14807 (pngfile (concat texfilebase ".png"))
14808 (fnh (if (featurep 'xemacs)
14809 (font-height (get-face-font 'default))
14810 (face-attribute 'default :height nil)))
14811 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14812 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14813 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14814 "Black"))
14815 (bg (or (plist-get options (if buffer :background :html-background))
14816 "Transparent")))
14817 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14818 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14819 (with-temp-file texfile
14820 (insert org-format-latex-header
14821 (if org-export-latex-packages-alist
14822 (concat "\n"
14823 (mapconcat (lambda(p)
14824 (if (equal "" (car p))
14825 (format "\\usepackage{%s}" (cadr p))
14826 (format "\\usepackage[%s]{%s}"
14827 (car p) (cadr p))))
14828 org-export-latex-packages-alist "\n"))
14830 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14831 (let ((dir default-directory))
14832 (condition-case nil
14833 (progn
14834 (cd tmpdir)
14835 (call-process "latex" nil nil nil texfile))
14836 (error nil))
14837 (cd dir))
14838 (if (not (file-exists-p dvifile))
14839 (progn (message "Failed to create dvi file from %s" texfile) nil)
14840 (condition-case nil
14841 (call-process "dvipng" nil nil nil
14842 "-fg" fg "-bg" bg
14843 "-D" dpi
14844 ;;"-x" scale "-y" scale
14845 "-T" "tight"
14846 "-o" pngfile
14847 dvifile)
14848 (error nil))
14849 (if (not (file-exists-p pngfile))
14850 (progn (message "Failed to create png file from %s" texfile) nil)
14851 ;; Use the requested file name and clean up
14852 (copy-file pngfile tofile 'replace)
14853 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14854 (delete-file (concat texfilebase e)))
14855 pngfile))))
14857 (defun org-dvipng-color (attr)
14858 "Return an rgb color specification for dvipng."
14859 (apply 'format "rgb %s %s %s"
14860 (mapcar 'org-normalize-color
14861 (color-values (face-attribute 'default attr nil)))))
14863 (defun org-normalize-color (value)
14864 "Return string to be used as color value for an RGB component."
14865 (format "%g" (/ value 65535.0)))
14867 ;;;; Key bindings
14869 ;; Make `C-c C-x' a prefix key
14870 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14872 ;; TAB key with modifiers
14873 (org-defkey org-mode-map "\C-i" 'org-cycle)
14874 (org-defkey org-mode-map [(tab)] 'org-cycle)
14875 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14876 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14877 (org-defkey org-mode-map "\M-\t" 'org-complete)
14878 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14879 ;; The following line is necessary under Suse GNU/Linux
14880 (unless (featurep 'xemacs)
14881 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14882 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14883 (define-key org-mode-map [backtab] 'org-shifttab)
14885 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14886 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14887 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14889 ;; Cursor keys with modifiers
14890 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14891 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14892 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14893 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14895 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14896 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14897 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14898 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14900 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14901 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14902 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14903 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14905 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14906 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14908 ;;; Extra keys for tty access.
14909 ;; We only set them when really needed because otherwise the
14910 ;; menus don't show the simple keys
14912 (when (or org-use-extra-keys
14913 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14914 (not window-system))
14915 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14916 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14917 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14918 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14919 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14920 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14921 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14922 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14923 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14924 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14925 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14926 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14927 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14928 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14929 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14930 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14931 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14932 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14933 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14934 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14935 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14936 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14937 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14938 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14939 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14940 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14941 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14942 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14944 ;; All the other keys
14946 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14947 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14948 (if (boundp 'narrow-map)
14949 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14950 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14951 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14952 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14953 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14954 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14955 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14956 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14957 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14958 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14959 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14960 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14961 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14962 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14963 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14964 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14965 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14966 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14967 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14968 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14969 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14970 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14971 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14972 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14973 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14974 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14975 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14976 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14977 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14978 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14979 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14980 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14981 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14982 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14983 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14984 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14985 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14986 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14987 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14988 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14989 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14990 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14991 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14992 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14993 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14994 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14995 (org-defkey org-mode-map "\C-c^" 'org-sort)
14996 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14997 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14998 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14999 (org-defkey org-mode-map "\C-m" 'org-return)
15000 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15001 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15002 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15003 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15004 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15005 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15006 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15007 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15008 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15009 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15010 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15011 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15012 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15013 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15014 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15015 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15016 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15017 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15018 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15019 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15020 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15022 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15023 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15024 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15025 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15027 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15028 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15029 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15030 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15031 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15032 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15033 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15034 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15035 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15036 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15037 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15038 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15039 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15040 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15041 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15043 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15044 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15045 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15046 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15048 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15050 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15052 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15053 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15055 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15058 (when (featurep 'xemacs)
15059 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15062 (defconst org-speed-commands-default
15064 ("Outline Navigation")
15065 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15066 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15067 ("f" . (org-speed-move-safe 'org-forward-same-level))
15068 ("b" . (org-speed-move-safe 'org-backward-same-level))
15069 ("u" . (org-speed-move-safe 'outline-up-heading))
15070 ("j" . org-goto)
15071 ("g" . (org-refile t))
15072 ("Outline Visibility")
15073 ("c" . org-cycle)
15074 ("C" . org-shifttab)
15075 (" " . org-display-outline-path)
15076 ("Outline Structure Editing")
15077 ("U" . org-shiftmetaup)
15078 ("D" . org-shiftmetadown)
15079 ("r" . org-metaright)
15080 ("l" . org-metaleft)
15081 ("R" . org-shiftmetaright)
15082 ("L" . org-shiftmetaleft)
15083 ("i" . (progn (forward-char 1) (call-interactively
15084 'org-insert-heading-respect-content)))
15085 ("^" . org-sort)
15086 ("w" . org-refile)
15087 ("a" . org-archive-subtree-default-with-confirmation)
15088 ("." . outline-mark-subtree)
15089 ("Clock Commands")
15090 ("I" . org-clock-in)
15091 ("O" . org-clock-out)
15092 ("Meta Data Editing")
15093 ("t" . org-todo)
15094 ("0" . (org-priority ?\ ))
15095 ("1" . (org-priority ?A))
15096 ("2" . (org-priority ?B))
15097 ("3" . (org-priority ?C))
15098 (";" . org-set-tags-command)
15099 ("e" . org-set-effort)
15100 ("Agenda Views etc")
15101 ("v" . org-agenda)
15102 ("/" . org-sparse-tree)
15103 ("Misc")
15104 ("o" . org-open-at-point)
15105 ("?" . org-speed-command-help)
15107 "The default speed commands.")
15109 (defun org-print-speed-command (e)
15110 (if (> (length (car e)) 1)
15111 (progn
15112 (princ "\n")
15113 (princ (car e))
15114 (princ "\n")
15115 (princ (make-string (length (car e)) ?-))
15116 (princ "\n"))
15117 (princ (car e))
15118 (princ " ")
15119 (if (symbolp (cdr e))
15120 (princ (symbol-name (cdr e)))
15121 (prin1 (cdr e)))
15122 (princ "\n")))
15124 (defun org-speed-command-help ()
15125 "Show the available speed commands."
15126 (interactive)
15127 (if (not org-use-speed-commands)
15128 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15129 (with-output-to-temp-buffer "*Help*"
15130 (princ "User-defined Speed commands\n===========================\n")
15131 (mapc 'org-print-speed-command org-speed-commands-user)
15132 (princ "\n")
15133 (princ "Built-in Speed commands\n=======================\n")
15134 (mapc 'org-print-speed-command org-speed-commands-default))
15135 (with-current-buffer "*Help*"
15136 (setq truncate-lines t))))
15138 (defun org-speed-move-safe (cmd)
15139 "Execute CMD, but make sure that the cursor always ends up in a headline.
15140 If not, return to the original position and throw an error."
15141 (interactive)
15142 (let ((pos (point)))
15143 (call-interactively cmd)
15144 (unless (and (bolp) (org-on-heading-p))
15145 (goto-char pos)
15146 (error "Boundary reached while executing %s" cmd))))
15148 (defvar org-self-insert-command-undo-counter 0)
15150 (defvar org-table-auto-blank-field) ; defined in org-table.el
15151 (defvar org-speed-command nil)
15152 (defun org-self-insert-command (N)
15153 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15154 If the cursor is in a table looking at whitespace, the whitespace is
15155 overwritten, and the table is not marked as requiring realignment."
15156 (interactive "p")
15157 (cond
15158 ((and org-use-speed-commands
15159 (or (and (bolp) (looking-at outline-regexp))
15160 (and (functionp org-use-speed-commands)
15161 (funcall org-use-speed-commands)))
15162 (setq
15163 org-speed-command
15164 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15165 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15166 (cond
15167 ((commandp org-speed-command)
15168 (setq this-command org-speed-command)
15169 (call-interactively org-speed-command))
15170 ((functionp org-speed-command)
15171 (funcall org-speed-command))
15172 ((and org-speed-command (listp org-speed-command))
15173 (eval org-speed-command))
15174 (t (let (org-use-speed-commands)
15175 (call-interactively 'org-self-insert-command)))))
15176 ((and
15177 (org-table-p)
15178 (progn
15179 ;; check if we blank the field, and if that triggers align
15180 (and (featurep 'org-table) org-table-auto-blank-field
15181 (member last-command
15182 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15183 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15184 ;; got extra space, this field does not determine column width
15185 (let (org-table-may-need-update) (org-table-blank-field))
15186 ;; no extra space, this field may determine column width
15187 (org-table-blank-field)))
15189 (eq N 1)
15190 (looking-at "[^|\n]* |"))
15191 (let (org-table-may-need-update)
15192 (goto-char (1- (match-end 0)))
15193 (delete-backward-char 1)
15194 (goto-char (match-beginning 0))
15195 (self-insert-command N)))
15197 (setq org-table-may-need-update t)
15198 (self-insert-command N)
15199 (org-fix-tags-on-the-fly)
15200 (if org-self-insert-cluster-for-undo
15201 (if (not (eq last-command 'org-self-insert-command))
15202 (setq org-self-insert-command-undo-counter 1)
15203 (if (>= org-self-insert-command-undo-counter 20)
15204 (setq org-self-insert-command-undo-counter 1)
15205 (and (> org-self-insert-command-undo-counter 0)
15206 buffer-undo-list
15207 (not (cadr buffer-undo-list)) ; remove nil entry
15208 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15209 (setq org-self-insert-command-undo-counter
15210 (1+ org-self-insert-command-undo-counter))))))))
15212 (defun org-fix-tags-on-the-fly ()
15213 (when (and (equal (char-after (point-at-bol)) ?*)
15214 (org-on-heading-p))
15215 (org-align-tags-here org-tags-column)))
15217 (defun org-delete-backward-char (N)
15218 "Like `delete-backward-char', insert whitespace at field end in tables.
15219 When deleting backwards, in tables this function will insert whitespace in
15220 front of the next \"|\" separator, to keep the table aligned. The table will
15221 still be marked for re-alignment if the field did fill the entire column,
15222 because, in this case the deletion might narrow the column."
15223 (interactive "p")
15224 (if (and (org-table-p)
15225 (eq N 1)
15226 (string-match "|" (buffer-substring (point-at-bol) (point)))
15227 (looking-at ".*?|"))
15228 (let ((pos (point))
15229 (noalign (looking-at "[^|\n\r]* |"))
15230 (c org-table-may-need-update))
15231 (backward-delete-char N)
15232 (skip-chars-forward "^|")
15233 (insert " ")
15234 (goto-char (1- pos))
15235 ;; noalign: if there were two spaces at the end, this field
15236 ;; does not determine the width of the column.
15237 (if noalign (setq org-table-may-need-update c)))
15238 (backward-delete-char N)
15239 (org-fix-tags-on-the-fly)))
15241 (defun org-delete-char (N)
15242 "Like `delete-char', but insert whitespace at field end in tables.
15243 When deleting characters, in tables this function will insert whitespace in
15244 front of the next \"|\" separator, to keep the table aligned. The table will
15245 still be marked for re-alignment if the field did fill the entire column,
15246 because, in this case the deletion might narrow the column."
15247 (interactive "p")
15248 (if (and (org-table-p)
15249 (not (bolp))
15250 (not (= (char-after) ?|))
15251 (eq N 1))
15252 (if (looking-at ".*?|")
15253 (let ((pos (point))
15254 (noalign (looking-at "[^|\n\r]* |"))
15255 (c org-table-may-need-update))
15256 (replace-match (concat
15257 (substring (match-string 0) 1 -1)
15258 " |"))
15259 (goto-char pos)
15260 ;; noalign: if there were two spaces at the end, this field
15261 ;; does not determine the width of the column.
15262 (if noalign (setq org-table-may-need-update c)))
15263 (delete-char N))
15264 (delete-char N)
15265 (org-fix-tags-on-the-fly)))
15267 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15268 (put 'org-self-insert-command 'delete-selection t)
15269 (put 'orgtbl-self-insert-command 'delete-selection t)
15270 (put 'org-delete-char 'delete-selection 'supersede)
15271 (put 'org-delete-backward-char 'delete-selection 'supersede)
15272 (put 'org-yank 'delete-selection 'yank)
15274 ;; Make `flyspell-mode' delay after some commands
15275 (put 'org-self-insert-command 'flyspell-delayed t)
15276 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15277 (put 'org-delete-char 'flyspell-delayed t)
15278 (put 'org-delete-backward-char 'flyspell-delayed t)
15280 ;; Make pabbrev-mode expand after org-mode commands
15281 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15282 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15284 ;; How to do this: Measure non-white length of current string
15285 ;; If equal to column width, we should realign.
15287 (defun org-remap (map &rest commands)
15288 "In MAP, remap the functions given in COMMANDS.
15289 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15290 (let (new old)
15291 (while commands
15292 (setq old (pop commands) new (pop commands))
15293 (if (fboundp 'command-remapping)
15294 (org-defkey map (vector 'remap old) new)
15295 (substitute-key-definition old new map global-map)))))
15297 (when (eq org-enable-table-editor 'optimized)
15298 ;; If the user wants maximum table support, we need to hijack
15299 ;; some standard editing functions
15300 (org-remap org-mode-map
15301 'self-insert-command 'org-self-insert-command
15302 'delete-char 'org-delete-char
15303 'delete-backward-char 'org-delete-backward-char)
15304 (org-defkey org-mode-map "|" 'org-force-self-insert))
15306 (defvar org-ctrl-c-ctrl-c-hook nil
15307 "Hook for functions attaching themselves to `C-c C-c'.
15308 This can be used to add additional functionality to the C-c C-c key which
15309 executes context-dependent commands.
15310 Each function will be called with no arguments. The function must check
15311 if the context is appropriate for it to act. If yes, it should do its
15312 thing and then return a non-nil value. If the context is wrong,
15313 just do nothing and return nil.")
15315 (defvar org-tab-first-hook nil
15316 "Hook for functions to attach themselves to TAB.
15317 See `org-ctrl-c-ctrl-c-hook' for more information.
15318 This hook runs as the first action when TAB is pressed, even before
15319 `org-cycle' messes around with the `outline-regexp' to cater for
15320 inline tasks and plain list item folding.
15321 If any function in this hook returns t, not other actions like table
15322 field motion visibility cycling will be done.")
15324 (defvar org-tab-after-check-for-table-hook nil
15325 "Hook for functions to attach themselves to TAB.
15326 See `org-ctrl-c-ctrl-c-hook' for more information.
15327 This hook runs after it has been established that the cursor is not in a
15328 table, but before checking if the cursor is in a headline or if global cycling
15329 should be done.
15330 If any function in this hook returns t, not other actions like visibility
15331 cycling will be done.")
15333 (defvar org-tab-after-check-for-cycling-hook nil
15334 "Hook for functions to attach themselves to TAB.
15335 See `org-ctrl-c-ctrl-c-hook' for more information.
15336 This hook runs after it has been established that not table field motion and
15337 not visibility should be done because of current context. This is probably
15338 the place where a package like yasnippets can hook in.")
15340 (defvar org-tab-before-tab-emulation-hook nil
15341 "Hook for functions to attach themselves to TAB.
15342 See `org-ctrl-c-ctrl-c-hook' for more information.
15343 This hook runs after every other options for TAB have been exhausted, but
15344 before indentation and \t insertion takes place.")
15346 (defvar org-metaleft-hook nil
15347 "Hook for functions attaching themselves to `M-left'.
15348 See `org-ctrl-c-ctrl-c-hook' for more information.")
15349 (defvar org-metaright-hook nil
15350 "Hook for functions attaching themselves to `M-right'.
15351 See `org-ctrl-c-ctrl-c-hook' for more information.")
15352 (defvar org-metaup-hook nil
15353 "Hook for functions attaching themselves to `M-up'.
15354 See `org-ctrl-c-ctrl-c-hook' for more information.")
15355 (defvar org-metadown-hook nil
15356 "Hook for functions attaching themselves to `M-down'.
15357 See `org-ctrl-c-ctrl-c-hook' for more information.")
15358 (defvar org-shiftmetaleft-hook nil
15359 "Hook for functions attaching themselves to `M-S-left'.
15360 See `org-ctrl-c-ctrl-c-hook' for more information.")
15361 (defvar org-shiftmetaright-hook nil
15362 "Hook for functions attaching themselves to `M-S-right'.
15363 See `org-ctrl-c-ctrl-c-hook' for more information.")
15364 (defvar org-shiftmetaup-hook nil
15365 "Hook for functions attaching themselves to `M-S-up'.
15366 See `org-ctrl-c-ctrl-c-hook' for more information.")
15367 (defvar org-shiftmetadown-hook nil
15368 "Hook for functions attaching themselves to `M-S-down'.
15369 See `org-ctrl-c-ctrl-c-hook' for more information.")
15370 (defvar org-metareturn-hook nil
15371 "Hook for functions attaching themselves to `M-RET'.
15372 See `org-ctrl-c-ctrl-c-hook' for more information.")
15374 (defun org-modifier-cursor-error ()
15375 "Throw an error, a modified cursor command was applied in wrong context."
15376 (error "This command is active in special context like tables, headlines or items"))
15378 (defun org-shiftselect-error ()
15379 "Throw an error because Shift-Cursor command was applied in wrong context."
15380 (if (and (boundp 'shift-select-mode) shift-select-mode)
15381 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15382 (error "This command works only in special context like headlines or timestamps")))
15384 (defun org-call-for-shift-select (cmd)
15385 (let ((this-command-keys-shift-translated t))
15386 (call-interactively cmd)))
15388 (defun org-shifttab (&optional arg)
15389 "Global visibility cycling or move to previous table field.
15390 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15391 on context.
15392 See the individual commands for more information."
15393 (interactive "P")
15394 (cond
15395 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15396 ((integerp arg)
15397 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15398 (message "Content view to level: %d" arg)
15399 (org-content (prefix-numeric-value arg2))
15400 (setq org-cycle-global-status 'overview)))
15401 (t (call-interactively 'org-global-cycle))))
15403 (defun org-shiftmetaleft ()
15404 "Promote subtree or delete table column.
15405 Calls `org-promote-subtree', `org-outdent-item',
15406 or `org-table-delete-column', depending on context.
15407 See the individual commands for more information."
15408 (interactive)
15409 (cond
15410 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15411 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15412 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15413 ((org-at-item-p) (call-interactively 'org-outdent-item))
15414 (t (org-modifier-cursor-error))))
15416 (defun org-shiftmetaright ()
15417 "Demote subtree or insert table column.
15418 Calls `org-demote-subtree', `org-indent-item',
15419 or `org-table-insert-column', depending on context.
15420 See the individual commands for more information."
15421 (interactive)
15422 (cond
15423 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15424 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15425 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15426 ((org-at-item-p) (call-interactively 'org-indent-item))
15427 (t (org-modifier-cursor-error))))
15429 (defun org-shiftmetaup (&optional arg)
15430 "Move subtree up or kill table row.
15431 Calls `org-move-subtree-up' or `org-table-kill-row' or
15432 `org-move-item-up' depending on context. See the individual commands
15433 for more information."
15434 (interactive "P")
15435 (cond
15436 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15437 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15438 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15439 ((org-at-item-p) (call-interactively 'org-move-item-up))
15440 (t (org-modifier-cursor-error))))
15442 (defun org-shiftmetadown (&optional arg)
15443 "Move subtree down or insert table row.
15444 Calls `org-move-subtree-down' or `org-table-insert-row' or
15445 `org-move-item-down', depending on context. See the individual
15446 commands for more information."
15447 (interactive "P")
15448 (cond
15449 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15450 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15451 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15452 ((org-at-item-p) (call-interactively 'org-move-item-down))
15453 (t (org-modifier-cursor-error))))
15455 (defun org-metaleft (&optional arg)
15456 "Promote heading or move table column to left.
15457 Calls `org-do-promote' or `org-table-move-column', depending on context.
15458 With no specific context, calls the Emacs default `backward-word'.
15459 See the individual commands for more information."
15460 (interactive "P")
15461 (cond
15462 ((run-hook-with-args-until-success 'org-metaleft-hook))
15463 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15464 ((or (org-on-heading-p)
15465 (and (org-region-active-p)
15466 (save-excursion
15467 (goto-char (region-beginning))
15468 (org-on-heading-p))))
15469 (call-interactively 'org-do-promote))
15470 ((or (org-at-item-p)
15471 (and (org-region-active-p)
15472 (save-excursion
15473 (goto-char (region-beginning))
15474 (org-at-item-p))))
15475 (call-interactively 'org-outdent-item))
15476 (t (call-interactively 'backward-word))))
15478 (defun org-metaright (&optional arg)
15479 "Demote subtree or move table column to right.
15480 Calls `org-do-demote' or `org-table-move-column', depending on context.
15481 With no specific context, calls the Emacs default `forward-word'.
15482 See the individual commands for more information."
15483 (interactive "P")
15484 (cond
15485 ((run-hook-with-args-until-success 'org-metaright-hook))
15486 ((org-at-table-p) (call-interactively 'org-table-move-column))
15487 ((or (org-on-heading-p)
15488 (and (org-region-active-p)
15489 (save-excursion
15490 (goto-char (region-beginning))
15491 (org-on-heading-p))))
15492 (call-interactively 'org-do-demote))
15493 ((or (org-at-item-p)
15494 (and (org-region-active-p)
15495 (save-excursion
15496 (goto-char (region-beginning))
15497 (org-at-item-p))))
15498 (call-interactively 'org-indent-item))
15499 (t (call-interactively 'forward-word))))
15501 (defun org-metaup (&optional arg)
15502 "Move subtree up or move table row up.
15503 Calls `org-move-subtree-up' or `org-table-move-row' or
15504 `org-move-item-up', depending on context. See the individual commands
15505 for more information."
15506 (interactive "P")
15507 (cond
15508 ((run-hook-with-args-until-success 'org-metaup-hook))
15509 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15510 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15511 ((org-at-item-p) (call-interactively 'org-move-item-up))
15512 (t (transpose-lines 1) (beginning-of-line -1))))
15514 (defun org-metadown (&optional arg)
15515 "Move subtree down or move table row down.
15516 Calls `org-move-subtree-down' or `org-table-move-row' or
15517 `org-move-item-down', depending on context. See the individual
15518 commands for more information."
15519 (interactive "P")
15520 (cond
15521 ((run-hook-with-args-until-success 'org-metadown-hook))
15522 ((org-at-table-p) (call-interactively 'org-table-move-row))
15523 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15524 ((org-at-item-p) (call-interactively 'org-move-item-down))
15525 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15527 (defun org-shiftup (&optional arg)
15528 "Increase item in timestamp or increase priority of current headline.
15529 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15530 depending on context. See the individual commands for more information."
15531 (interactive "P")
15532 (cond
15533 ((and org-support-shift-select (org-region-active-p))
15534 (org-call-for-shift-select 'previous-line))
15535 ((org-at-timestamp-p t)
15536 (call-interactively (if org-edit-timestamp-down-means-later
15537 'org-timestamp-down 'org-timestamp-up)))
15538 ((and (not (eq org-support-shift-select 'always))
15539 org-enable-priority-commands
15540 (org-on-heading-p))
15541 (call-interactively 'org-priority-up))
15542 ((and (not org-support-shift-select) (org-at-item-p))
15543 (call-interactively 'org-previous-item))
15544 ((org-clocktable-try-shift 'up arg))
15545 (org-support-shift-select
15546 (org-call-for-shift-select 'previous-line))
15547 (t (org-shiftselect-error))))
15549 (defun org-shiftdown (&optional arg)
15550 "Decrease item in timestamp or decrease priority of current headline.
15551 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15552 depending on context. See the individual commands for more information."
15553 (interactive "P")
15554 (cond
15555 ((and org-support-shift-select (org-region-active-p))
15556 (org-call-for-shift-select 'next-line))
15557 ((org-at-timestamp-p t)
15558 (call-interactively (if org-edit-timestamp-down-means-later
15559 'org-timestamp-up 'org-timestamp-down)))
15560 ((and (not (eq org-support-shift-select 'always))
15561 org-enable-priority-commands
15562 (org-on-heading-p))
15563 (call-interactively 'org-priority-down))
15564 ((and (not org-support-shift-select) (org-at-item-p))
15565 (call-interactively 'org-next-item))
15566 ((org-clocktable-try-shift 'down arg))
15567 (org-support-shift-select
15568 (org-call-for-shift-select 'next-line))
15569 (t (org-shiftselect-error))))
15571 (defun org-shiftright (&optional arg)
15572 "Cycle the thing at point or in the current line, depending on context.
15573 Depending on context, this does one of the following:
15575 - switch a timestamp at point one day into the future
15576 - on a headline, switch to the next TODO keyword.
15577 - on an item, switch entire list to the next bullet type
15578 - on a property line, switch to the next allowed value
15579 - on a clocktable definition line, move time block into the future"
15580 (interactive "P")
15581 (cond
15582 ((and org-support-shift-select (org-region-active-p))
15583 (org-call-for-shift-select 'forward-char))
15584 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15585 ((and (not (eq org-support-shift-select 'always))
15586 (org-on-heading-p))
15587 (let ((org-inhibit-logging
15588 (not org-treat-S-cursor-todo-selection-as-state-change))
15589 (org-inhibit-blocking
15590 (not org-treat-S-cursor-todo-selection-as-state-change)))
15591 (org-call-with-arg 'org-todo 'right)))
15592 ((or (and org-support-shift-select
15593 (not (eq org-support-shift-select 'always))
15594 (org-at-item-bullet-p))
15595 (and (not org-support-shift-select) (org-at-item-p)))
15596 (org-call-with-arg 'org-cycle-list-bullet nil))
15597 ((and (not (eq org-support-shift-select 'always))
15598 (org-at-property-p))
15599 (call-interactively 'org-property-next-allowed-value))
15600 ((org-clocktable-try-shift 'right arg))
15601 (org-support-shift-select
15602 (org-call-for-shift-select 'forward-char))
15603 (t (org-shiftselect-error))))
15605 (defun org-shiftleft (&optional arg)
15606 "Cycle the thing at point or in the current line, depending on context.
15607 Depending on context, this does one of the following:
15609 - switch a timestamp at point one day into the past
15610 - on a headline, switch to the previous TODO keyword.
15611 - on an item, switch entire list to the previous bullet type
15612 - on a property line, switch to the previous allowed value
15613 - on a clocktable definition line, move time block into the past"
15614 (interactive "P")
15615 (cond
15616 ((and org-support-shift-select (org-region-active-p))
15617 (org-call-for-shift-select 'backward-char))
15618 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15619 ((and (not (eq org-support-shift-select 'always))
15620 (org-on-heading-p))
15621 (let ((org-inhibit-logging
15622 (not org-treat-S-cursor-todo-selection-as-state-change))
15623 (org-inhibit-blocking
15624 (not org-treat-S-cursor-todo-selection-as-state-change)))
15625 (org-call-with-arg 'org-todo 'left)))
15626 ((or (and org-support-shift-select
15627 (not (eq org-support-shift-select 'always))
15628 (org-at-item-bullet-p))
15629 (and (not org-support-shift-select) (org-at-item-p)))
15630 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15631 ((and (not (eq org-support-shift-select 'always))
15632 (org-at-property-p))
15633 (call-interactively 'org-property-previous-allowed-value))
15634 ((org-clocktable-try-shift 'left arg))
15635 (org-support-shift-select
15636 (org-call-for-shift-select 'backward-char))
15637 (t (org-shiftselect-error))))
15639 (defun org-shiftcontrolright ()
15640 "Switch to next TODO set."
15641 (interactive)
15642 (cond
15643 ((and org-support-shift-select (org-region-active-p))
15644 (org-call-for-shift-select 'forward-word))
15645 ((and (not (eq org-support-shift-select 'always))
15646 (org-on-heading-p))
15647 (org-call-with-arg 'org-todo 'nextset))
15648 (org-support-shift-select
15649 (org-call-for-shift-select 'forward-word))
15650 (t (org-shiftselect-error))))
15652 (defun org-shiftcontrolleft ()
15653 "Switch to previous TODO set."
15654 (interactive)
15655 (cond
15656 ((and org-support-shift-select (org-region-active-p))
15657 (org-call-for-shift-select 'backward-word))
15658 ((and (not (eq org-support-shift-select 'always))
15659 (org-on-heading-p))
15660 (org-call-with-arg 'org-todo 'previousset))
15661 (org-support-shift-select
15662 (org-call-for-shift-select 'backward-word))
15663 (t (org-shiftselect-error))))
15665 (defun org-ctrl-c-ret ()
15666 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15667 (interactive)
15668 (cond
15669 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15670 (t (call-interactively 'org-insert-heading))))
15672 (defun org-copy-special ()
15673 "Copy region in table or copy current subtree.
15674 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15675 See the individual commands for more information."
15676 (interactive)
15677 (call-interactively
15678 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15680 (defun org-cut-special ()
15681 "Cut region in table or cut current subtree.
15682 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15683 See the individual commands for more information."
15684 (interactive)
15685 (call-interactively
15686 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15688 (defun org-paste-special (arg)
15689 "Paste rectangular region into table, or past subtree relative to level.
15690 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15691 See the individual commands for more information."
15692 (interactive "P")
15693 (if (org-at-table-p)
15694 (org-table-paste-rectangle)
15695 (org-paste-subtree arg)))
15697 (defun org-edit-special ()
15698 "Call a special editor for the stuff at point.
15699 When at a table, call the formula editor with `org-table-edit-formulas'.
15700 When at the first line of an src example, call `org-edit-src-code'.
15701 When in an #+include line, visit the include file. Otherwise call
15702 `ffap' to visit the file at point."
15703 (interactive)
15704 (cond
15705 ((org-at-table-p)
15706 (call-interactively 'org-table-edit-formulas))
15707 ((save-excursion
15708 (beginning-of-line 1)
15709 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15710 (find-file (org-trim (match-string 1))))
15711 ((org-edit-src-code))
15712 ((org-edit-fixed-width-region))
15713 (t (call-interactively 'ffap))))
15716 (defun org-ctrl-c-ctrl-c (&optional arg)
15717 "Set tags in headline, or update according to changed information at point.
15719 This command does many different things, depending on context:
15721 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15722 this is what we do.
15724 - If the cursor is on a statistics cookie, update it.
15726 - If the cursor is in a headline, prompt for tags and insert them
15727 into the current line, aligned to `org-tags-column'. When called
15728 with prefix arg, realign all tags in the current buffer.
15730 - If the cursor is in one of the special #+KEYWORD lines, this
15731 triggers scanning the buffer for these lines and updating the
15732 information.
15734 - If the cursor is inside a table, realign the table. This command
15735 works even if the automatic table editor has been turned off.
15737 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15738 the entire table.
15740 - If the cursor is at a footnote reference or definition, jump to
15741 the corresponding definition or references, respectively.
15743 - If the cursor is a the beginning of a dynamic block, update it.
15745 - If the cursor is inside a table created by the table.el package,
15746 activate that table.
15748 - If the current buffer is a remember buffer, close note and file
15749 it. A prefix argument of 1 files to the default location
15750 without further interaction. A prefix argument of 2 files to
15751 the currently clocking task.
15753 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15754 links in this buffer.
15756 - If the cursor is on a numbered item in a plain list, renumber the
15757 ordered list.
15759 - If the cursor is on a checkbox, toggle it."
15760 (interactive "P")
15761 (let ((org-enable-table-editor t))
15762 (cond
15763 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15764 org-occur-highlights
15765 org-latex-fragment-image-overlays)
15766 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15767 (org-remove-occur-highlights)
15768 (org-remove-latex-fragment-image-overlays)
15769 (message "Temporary highlights/overlays removed from current buffer"))
15770 ((and (local-variable-p 'org-finish-function (current-buffer))
15771 (fboundp org-finish-function))
15772 (funcall org-finish-function))
15773 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15774 ((org-at-property-p)
15775 (call-interactively 'org-property-action))
15776 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15777 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15778 (or (org-on-heading-p) (org-at-item-p)))
15779 (call-interactively 'org-update-statistics-cookies))
15780 ((org-on-heading-p) (call-interactively 'org-set-tags))
15781 ((org-at-table.el-p)
15782 (require 'table)
15783 (beginning-of-line 1)
15784 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15785 (call-interactively 'table-recognize-table))
15786 ((org-at-table-p)
15787 (org-table-maybe-eval-formula)
15788 (if arg
15789 (call-interactively 'org-table-recalculate)
15790 (org-table-maybe-recalculate-line))
15791 (call-interactively 'org-table-align))
15792 ((or (org-footnote-at-reference-p)
15793 (org-footnote-at-definition-p))
15794 (call-interactively 'org-footnote-action))
15795 ((org-at-item-checkbox-p)
15796 (call-interactively 'org-toggle-checkbox))
15797 ((org-at-item-p)
15798 (if arg
15799 (call-interactively 'org-toggle-checkbox)
15800 (call-interactively 'org-maybe-renumber-ordered-list)))
15801 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15802 ;; Dynamic block
15803 (beginning-of-line 1)
15804 (save-excursion (org-update-dblock)))
15805 ((save-excursion
15806 (beginning-of-line 1)
15807 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15808 (cond
15809 ((equal (match-string 1) "TBLFM")
15810 ;; Recalculate the table before this line
15811 (save-excursion
15812 (beginning-of-line 1)
15813 (skip-chars-backward " \r\n\t")
15814 (if (org-at-table-p)
15815 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15817 (let ((org-inhibit-startup-visibility-stuff t)
15818 (org-startup-align-all-tables nil))
15819 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15820 (message "Local setup has been refreshed"))))
15821 ((org-clock-update-time-maybe))
15822 (t (error "C-c C-c can do nothing useful at this location")))))
15824 (defun org-mode-restart ()
15825 "Restart Org-mode, to scan again for special lines.
15826 Also updates the keyword regular expressions."
15827 (interactive)
15828 (org-mode)
15829 (message "Org-mode restarted"))
15831 (defun org-kill-note-or-show-branches ()
15832 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15833 (interactive)
15834 (if (not org-finish-function)
15835 (call-interactively 'show-branches)
15836 (let ((org-note-abort t))
15837 (funcall org-finish-function))))
15839 (defun org-return (&optional indent)
15840 "Goto next table row or insert a newline.
15841 Calls `org-table-next-row' or `newline', depending on context.
15842 See the individual commands for more information."
15843 (interactive)
15844 (cond
15845 ((bobp) (if indent (newline-and-indent) (newline)))
15846 ((org-at-table-p)
15847 (org-table-justify-field-maybe)
15848 (call-interactively 'org-table-next-row))
15849 ((and org-return-follows-link
15850 (eq (get-text-property (point) 'face) 'org-link))
15851 (call-interactively 'org-open-at-point))
15852 ((and (org-at-heading-p)
15853 (looking-at
15854 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15855 (org-show-entry)
15856 (end-of-line 1)
15857 (newline))
15858 (t (if indent (newline-and-indent) (newline)))))
15860 (defun org-return-indent ()
15861 "Goto next table row or insert a newline and indent.
15862 Calls `org-table-next-row' or `newline-and-indent', depending on
15863 context. See the individual commands for more information."
15864 (interactive)
15865 (org-return t))
15867 (defun org-ctrl-c-star ()
15868 "Compute table, or change heading status of lines.
15869 Calls `org-table-recalculate' or `org-toggle-heading',
15870 depending on context."
15871 (interactive)
15872 (cond
15873 ((org-at-table-p)
15874 (call-interactively 'org-table-recalculate))
15876 ;; Convert all lines in region to list items
15877 (call-interactively 'org-toggle-heading))))
15879 (defun org-ctrl-c-minus ()
15880 "Insert separator line in table or modify bullet status of line.
15881 Also turns a plain line or a region of lines into list items.
15882 Calls `org-table-insert-hline', `org-toggle-item', or
15883 `org-cycle-list-bullet', depending on context."
15884 (interactive)
15885 (cond
15886 ((org-at-table-p)
15887 (call-interactively 'org-table-insert-hline))
15888 ((org-region-active-p)
15889 (call-interactively 'org-toggle-item))
15890 ((org-in-item-p)
15891 (call-interactively 'org-cycle-list-bullet))
15893 (call-interactively 'org-toggle-item))))
15895 (defun org-toggle-item ()
15896 "Convert headings or normal lines to items, items to normal lines.
15897 If there is no active region, only the current line is considered.
15899 If the first line in the region is a headline, convert all headlines to items.
15901 If the first line in the region is an item, convert all items to normal lines.
15903 If the first line is normal text, add an item bullet to each line."
15904 (interactive)
15905 (let (l2 l beg end)
15906 (if (org-region-active-p)
15907 (setq beg (region-beginning) end (region-end))
15908 (setq beg (point-at-bol)
15909 end (min (1+ (point-at-eol)) (point-max))))
15910 (save-excursion
15911 (goto-char end)
15912 (setq l2 (org-current-line))
15913 (goto-char beg)
15914 (beginning-of-line 1)
15915 (setq l (1- (org-current-line)))
15916 (if (org-at-item-p)
15917 ;; We already have items, de-itemize
15918 (while (< (setq l (1+ l)) l2)
15919 (when (org-at-item-p)
15920 (goto-char (match-beginning 2))
15921 (delete-region (match-beginning 2) (match-end 2))
15922 (and (looking-at "[ \t]+") (replace-match "")))
15923 (beginning-of-line 2))
15924 (if (org-on-heading-p)
15925 ;; Headings, convert to items
15926 (while (< (setq l (1+ l)) l2)
15927 (if (looking-at org-outline-regexp)
15928 (replace-match "- " t t))
15929 (beginning-of-line 2))
15930 ;; normal lines, turn them into items
15931 (while (< (setq l (1+ l)) l2)
15932 (unless (org-at-item-p)
15933 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15934 (replace-match "\\1- \\2")))
15935 (beginning-of-line 2)))))))
15937 (defun org-toggle-heading (&optional nstars)
15938 "Convert headings to normal text, or items or text to headings.
15939 If there is no active region, only the current line is considered.
15941 If the first line is a heading, remove the stars from all headlines
15942 in the region.
15944 If the first line is a plain list item, turn all plain list items
15945 into headings.
15947 If the first line is a normal line, turn each and every line in the
15948 region into a heading.
15950 When converting a line into a heading, the number of stars is chosen
15951 such that the lines become children of the current entry. However,
15952 when a prefix argument is given, its value determines the number of
15953 stars to add."
15954 (interactive "P")
15955 (let (l2 l itemp beg end)
15956 (if (org-region-active-p)
15957 (setq beg (region-beginning) end (region-end))
15958 (setq beg (point-at-bol)
15959 end (min (1+ (point-at-eol)) (point-max))))
15960 (save-excursion
15961 (goto-char end)
15962 (setq l2 (org-current-line))
15963 (goto-char beg)
15964 (beginning-of-line 1)
15965 (setq l (1- (org-current-line)))
15966 (if (org-on-heading-p)
15967 ;; We already have headlines, de-star them
15968 (while (< (setq l (1+ l)) l2)
15969 (when (org-on-heading-p t)
15970 (and (looking-at outline-regexp) (replace-match "")))
15971 (beginning-of-line 2))
15972 (setq itemp (org-at-item-p))
15973 (let* ((stars
15974 (if nstars
15975 (make-string (prefix-numeric-value current-prefix-arg)
15977 (save-excursion
15978 (if (re-search-backward org-complex-heading-regexp nil t)
15979 (match-string 1) ""))))
15980 (add-stars (cond (nstars "")
15981 ((equal stars "") "*")
15982 (org-odd-levels-only "**")
15983 (t "*")))
15984 (rpl (concat stars add-stars " ")))
15985 (while (< (setq l (1+ l)) l2)
15986 (if itemp
15987 (and (org-at-item-p) (replace-match rpl t t))
15988 (unless (org-on-heading-p)
15989 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15990 (replace-match (concat rpl (match-string 2))))))
15991 (beginning-of-line 2)))))))
15993 (defun org-meta-return (&optional arg)
15994 "Insert a new heading or wrap a region in a table.
15995 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15996 See the individual commands for more information."
15997 (interactive "P")
15998 (cond
15999 ((run-hook-with-args-until-success 'org-metareturn-hook))
16000 ((org-at-table-p)
16001 (call-interactively 'org-table-wrap-region))
16002 (t (call-interactively 'org-insert-heading))))
16004 ;;; Menu entries
16006 ;; Define the Org-mode menus
16007 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16008 '("Tbl"
16009 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16010 ["Next Field" org-cycle (org-at-table-p)]
16011 ["Previous Field" org-shifttab (org-at-table-p)]
16012 ["Next Row" org-return (org-at-table-p)]
16013 "--"
16014 ["Blank Field" org-table-blank-field (org-at-table-p)]
16015 ["Edit Field" org-table-edit-field (org-at-table-p)]
16016 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16017 "--"
16018 ("Column"
16019 ["Move Column Left" org-metaleft (org-at-table-p)]
16020 ["Move Column Right" org-metaright (org-at-table-p)]
16021 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16022 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16023 ("Row"
16024 ["Move Row Up" org-metaup (org-at-table-p)]
16025 ["Move Row Down" org-metadown (org-at-table-p)]
16026 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16027 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16028 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16029 "--"
16030 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16031 ("Rectangle"
16032 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16033 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16034 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16035 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16036 "--"
16037 ("Calculate"
16038 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16039 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16040 ["Edit Formulas" org-edit-special (org-at-table-p)]
16041 "--"
16042 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16043 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16044 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16045 "--"
16046 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16047 "--"
16048 ["Sum Column/Rectangle" org-table-sum
16049 (or (org-at-table-p) (org-region-active-p))]
16050 ["Which Column?" org-table-current-column (org-at-table-p)])
16051 ["Debug Formulas"
16052 org-table-toggle-formula-debugger
16053 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16054 ["Show Col/Row Numbers"
16055 org-table-toggle-coordinate-overlays
16056 :style toggle
16057 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16058 "--"
16059 ["Create" org-table-create (and (not (org-at-table-p))
16060 org-enable-table-editor)]
16061 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16062 ["Import from File" org-table-import (not (org-at-table-p))]
16063 ["Export to File" org-table-export (org-at-table-p)]
16064 "--"
16065 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16067 (easy-menu-define org-org-menu org-mode-map "Org menu"
16068 '("Org"
16069 ("Show/Hide"
16070 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16071 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16072 ["Sparse Tree..." org-sparse-tree t]
16073 ["Reveal Context" org-reveal t]
16074 ["Show All" show-all t]
16075 "--"
16076 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16077 "--"
16078 ["New Heading" org-insert-heading t]
16079 ("Navigate Headings"
16080 ["Up" outline-up-heading t]
16081 ["Next" outline-next-visible-heading t]
16082 ["Previous" outline-previous-visible-heading t]
16083 ["Next Same Level" outline-forward-same-level t]
16084 ["Previous Same Level" outline-backward-same-level t]
16085 "--"
16086 ["Jump" org-goto t])
16087 ("Edit Structure"
16088 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16089 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16090 "--"
16091 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16092 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16093 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16094 "--"
16095 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16096 "--"
16097 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16098 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16099 ["Demote Heading" org-metaright (not (org-at-table-p))]
16100 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16101 "--"
16102 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16103 "--"
16104 ["Convert to odd levels" org-convert-to-odd-levels t]
16105 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16106 ("Editing"
16107 ["Emphasis..." org-emphasize t]
16108 ["Edit Source Example" org-edit-special t]
16109 "--"
16110 ["Footnote new/jump" org-footnote-action t]
16111 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16112 ("Archive"
16113 ["Archive (default method)" org-archive-subtree-default t]
16114 "--"
16115 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16116 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16117 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16119 "--"
16120 ("Hyperlinks"
16121 ["Store Link (Global)" org-store-link t]
16122 ["Find existing link to here" org-occur-link-in-agenda-files t]
16123 ["Insert Link" org-insert-link t]
16124 ["Follow Link" org-open-at-point t]
16125 "--"
16126 ["Next link" org-next-link t]
16127 ["Previous link" org-previous-link t]
16128 "--"
16129 ["Descriptive Links"
16130 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16131 :style radio
16132 :selected (member '(org-link) buffer-invisibility-spec)]
16133 ["Literal Links"
16134 (progn
16135 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16136 :style radio
16137 :selected (not (member '(org-link) buffer-invisibility-spec))])
16138 "--"
16139 ("TODO Lists"
16140 ["TODO/DONE/-" org-todo t]
16141 ("Select keyword"
16142 ["Next keyword" org-shiftright (org-on-heading-p)]
16143 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16144 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16145 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16146 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16147 ["Show TODO Tree" org-show-todo-tree t]
16148 ["Global TODO list" org-todo-list t]
16149 "--"
16150 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16151 :selected org-enforce-todo-dependencies :style toggle :active t]
16152 "Settings for tree at point"
16153 ["Do Children sequentially" org-toggle-ordered-property :style radio
16154 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16155 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16156 ["Do Children parallel" org-toggle-ordered-property :style radio
16157 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16158 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16159 "--"
16160 ["Set Priority" org-priority t]
16161 ["Priority Up" org-shiftup t]
16162 ["Priority Down" org-shiftdown t]
16163 "--"
16164 ["Get news from all feeds" org-feed-update-all t]
16165 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16166 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16167 ("TAGS and Properties"
16168 ["Set Tags" org-set-tags-command t]
16169 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16170 "--"
16171 ["Set property" org-set-property t]
16172 ["Column view of properties" org-columns t]
16173 ["Insert Column View DBlock" org-insert-columns-dblock t])
16174 ("Dates and Scheduling"
16175 ["Timestamp" org-time-stamp t]
16176 ["Timestamp (inactive)" org-time-stamp-inactive t]
16177 ("Change Date"
16178 ["1 Day Later" org-shiftright t]
16179 ["1 Day Earlier" org-shiftleft t]
16180 ["1 ... Later" org-shiftup t]
16181 ["1 ... Earlier" org-shiftdown t])
16182 ["Compute Time Range" org-evaluate-time-range t]
16183 ["Schedule Item" org-schedule t]
16184 ["Deadline" org-deadline t]
16185 "--"
16186 ["Custom time format" org-toggle-time-stamp-overlays
16187 :style radio :selected org-display-custom-times]
16188 "--"
16189 ["Goto Calendar" org-goto-calendar t]
16190 ["Date from Calendar" org-date-from-calendar t]
16191 "--"
16192 ["Start/Restart Timer" org-timer-start t]
16193 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16194 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16195 ["Insert Timer String" org-timer t]
16196 ["Insert Timer Item" org-timer-item t])
16197 ("Logging work"
16198 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16199 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16200 ["Clock out" org-clock-out t]
16201 ["Clock cancel" org-clock-cancel t]
16202 "--"
16203 ["Mark as default task" org-clock-mark-default-task t]
16204 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16205 ["Goto running clock" org-clock-goto t]
16206 "--"
16207 ["Display times" org-clock-display t]
16208 ["Create clock table" org-clock-report t]
16209 "--"
16210 ["Record DONE time"
16211 (progn (setq org-log-done (not org-log-done))
16212 (message "Switching to %s will %s record a timestamp"
16213 (car org-done-keywords)
16214 (if org-log-done "automatically" "not")))
16215 :style toggle :selected org-log-done])
16216 "--"
16217 ["Agenda Command..." org-agenda t]
16218 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16219 ("File List for Agenda")
16220 ("Special views current file"
16221 ["TODO Tree" org-show-todo-tree t]
16222 ["Check Deadlines" org-check-deadlines t]
16223 ["Timeline" org-timeline t]
16224 ["Tags/Property tree" org-match-sparse-tree t])
16225 "--"
16226 ["Export/Publish..." org-export t]
16227 ("LaTeX"
16228 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16229 :selected org-cdlatex-mode]
16230 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16231 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16232 ["Modify math symbol" org-cdlatex-math-modify
16233 (org-inside-LaTeX-fragment-p)]
16234 ["Insert citation" org-reftex-citation t]
16235 "--"
16236 ["Export LaTeX fragments as images"
16237 (if (featurep 'org-exp)
16238 (setq org-export-with-LaTeX-fragments
16239 (not org-export-with-LaTeX-fragments))
16240 (require 'org-exp))
16241 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16242 org-export-with-LaTeX-fragments)]
16243 "--"
16244 ["Template for BEAMER" org-beamer-settings-template t])
16245 "--"
16246 ("MobileOrg"
16247 ["Push Files and Views" org-mobile-push t]
16248 ["Get Captured and Flagged" org-mobile-pull t]
16249 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16250 "--"
16251 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16252 "--"
16253 ("Documentation"
16254 ["Show Version" org-version t]
16255 ["Info Documentation" org-info t])
16256 ("Customize"
16257 ["Browse Org Group" org-customize t]
16258 "--"
16259 ["Expand This Menu" org-create-customize-menu
16260 (fboundp 'customize-menu-create)])
16261 ["Send bug report" org-submit-bug-report t]
16262 "--"
16263 ("Refresh/Reload"
16264 ["Refresh setup current buffer" org-mode-restart t]
16265 ["Reload Org (after update)" org-reload t]
16266 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16269 (defun org-info (&optional node)
16270 "Read documentation for Org-mode in the info system.
16271 With optional NODE, go directly to that node."
16272 (interactive)
16273 (info (format "(org)%s" (or node ""))))
16275 ;;;###autoload
16276 (defun org-submit-bug-report ()
16277 "Submit a bug report on Org-mode via mail.
16279 Don't hesitate to report any problems or inaccurate documentation.
16281 If you don't have setup sending mail from (X)Emacs, please copy the
16282 output buffer into your mail program, as it gives us important
16283 information about your Org-mode version and configuration."
16284 (interactive)
16285 (require 'reporter)
16286 (org-load-modules-maybe)
16287 (org-require-autoloaded-modules)
16288 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16289 (reporter-submit-bug-report
16290 "emacs-orgmode@gnu.org"
16291 (org-version)
16292 (let (list)
16293 (save-window-excursion
16294 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16295 (delete-other-windows)
16296 (erase-buffer)
16297 (insert "You are about to submit a bug report to the Org-mode mailing list.
16299 We would like to add your full Org-mode and Outline configuration to the
16300 bug report. This greatly simplifies the work of the maintainer and
16301 other experts on the mailing list.
16303 HOWEVER, some variables you have customized may contain private
16304 information. The names of customers, colleagues, or friends, might
16305 appear in the form of file names, tags, todo states, or search strings.
16306 If you answer yes to the prompt, you might want to check and remove
16307 such private information before sending the email.")
16308 (add-text-properties (point-min) (point-max) '(face org-warning))
16309 (when (yes-or-no-p "Include your Org-mode configuration ")
16310 (mapatoms
16311 (lambda (v)
16312 (and (boundp v)
16313 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16314 (or (and (symbol-value v)
16315 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16316 (and
16317 (get v 'custom-type) (get v 'standard-value)
16318 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16319 (push v list)))))
16320 (kill-buffer (get-buffer "*Warn about privacy*"))
16321 list))
16322 nil nil
16323 "Remember to cover the basics, that is, what you expected to happen and
16324 what in fact did happen. You don't know how to make a good report? See
16326 http://orgmode.org/manual/Feedback.html#Feedback
16328 Your bug report will be posted to the Org-mode mailing list.
16329 ------------------------------------------------------------------------")
16330 (save-excursion
16331 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16332 (replace-match "\\1Bug: \\3 [\\2]")))))
16335 (defun org-install-agenda-files-menu ()
16336 (let ((bl (buffer-list)))
16337 (save-excursion
16338 (while bl
16339 (set-buffer (pop bl))
16340 (if (org-mode-p) (setq bl nil)))
16341 (when (org-mode-p)
16342 (easy-menu-change
16343 '("Org") "File List for Agenda"
16344 (append
16345 (list
16346 ["Edit File List" (org-edit-agenda-file-list) t]
16347 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16348 ["Remove Current File from List" org-remove-file t]
16349 ["Cycle through agenda files" org-cycle-agenda-files t]
16350 ["Occur in all agenda files" org-occur-in-agenda-files t]
16351 "--")
16352 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16354 ;;;; Documentation
16356 ;;;###autoload
16357 (defun org-require-autoloaded-modules ()
16358 (interactive)
16359 (mapc 'require
16360 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16361 org-docbook org-exp org-html org-icalendar
16362 org-id org-latex
16363 org-publish org-remember org-table
16364 org-timer org-xoxo)))
16366 ;;;###autoload
16367 (defun org-reload (&optional uncompiled)
16368 "Reload all org lisp files.
16369 With prefix arg UNCOMPILED, load the uncompiled versions."
16370 (interactive "P")
16371 (require 'find-func)
16372 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16373 (dir-org (file-name-directory (org-find-library-name "org")))
16374 (dir-org-contrib (ignore-errors
16375 (file-name-directory
16376 (org-find-library-name "org-contribdir"))))
16377 (files
16378 (append (directory-files dir-org t file-re)
16379 (and dir-org-contrib
16380 (directory-files dir-org-contrib t file-re))))
16381 (remove-re (concat (if (featurep 'xemacs)
16382 "org-colview" "org-colview-xemacs")
16383 "\\'")))
16384 (setq files (mapcar 'file-name-sans-extension files))
16385 (setq files (mapcar
16386 (lambda (x) (if (string-match remove-re x) nil x))
16387 files))
16388 (setq files (delq nil files))
16389 (mapc
16390 (lambda (f)
16391 (when (featurep (intern (file-name-nondirectory f)))
16392 (if (and (not uncompiled)
16393 (file-exists-p (concat f ".elc")))
16394 (load (concat f ".elc") nil nil t)
16395 (load (concat f ".el") nil nil t))))
16396 files))
16397 (org-version))
16399 ;;;###autoload
16400 (defun org-customize ()
16401 "Call the customize function with org as argument."
16402 (interactive)
16403 (org-load-modules-maybe)
16404 (org-require-autoloaded-modules)
16405 (customize-browse 'org))
16407 (defun org-create-customize-menu ()
16408 "Create a full customization menu for Org-mode, insert it into the menu."
16409 (interactive)
16410 (org-load-modules-maybe)
16411 (org-require-autoloaded-modules)
16412 (if (fboundp 'customize-menu-create)
16413 (progn
16414 (easy-menu-change
16415 '("Org") "Customize"
16416 `(["Browse Org group" org-customize t]
16417 "--"
16418 ,(customize-menu-create 'org)
16419 ["Set" Custom-set t]
16420 ["Save" Custom-save t]
16421 ["Reset to Current" Custom-reset-current t]
16422 ["Reset to Saved" Custom-reset-saved t]
16423 ["Reset to Standard Settings" Custom-reset-standard t]))
16424 (message "\"Org\"-menu now contains full customization menu"))
16425 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16427 ;;;; Miscellaneous stuff
16429 ;;; Generally useful functions
16431 (defun org-get-at-bol (property)
16432 "Get text property PROPERTY at beginning of line."
16433 (get-text-property (point-at-bol) property))
16435 (defun org-find-text-property-in-string (prop s)
16436 "Return the first non-nil value of property PROP in string S."
16437 (or (get-text-property 0 prop s)
16438 (get-text-property (or (next-single-property-change 0 prop s) 0)
16439 prop s)))
16441 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16442 "Display the given MESSAGE as a warning."
16443 (if (fboundp 'display-warning)
16444 (display-warning 'org message
16445 (if (featurep 'xemacs)
16446 'warning
16447 :warning))
16448 (let ((buf (get-buffer-create "*Org warnings*")))
16449 (with-current-buffer buf
16450 (goto-char (point-max))
16451 (insert "Warning (Org): " message)
16452 (unless (bolp)
16453 (newline)))
16454 (display-buffer buf)
16455 (sit-for 0))))
16457 (defun org-in-commented-line ()
16458 "Is point in a line starting with `#'?"
16459 (equal (char-after (point-at-bol)) ?#))
16461 (defun org-in-verbatim-emphasis ()
16462 (save-match-data
16463 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16465 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16466 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16467 (if (and marker (marker-buffer marker)
16468 (buffer-live-p (marker-buffer marker)))
16469 (progn
16470 (switch-to-buffer (marker-buffer marker))
16471 (if (or (> marker (point-max)) (< marker (point-min)))
16472 (widen))
16473 (goto-char marker)
16474 (org-show-context 'org-goto))
16475 (if bookmark
16476 (bookmark-jump bookmark)
16477 (error "Cannot find location"))))
16479 (defun org-quote-csv-field (s)
16480 "Quote field for inclusion in CSV material."
16481 (if (string-match "[\",]" s)
16482 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16485 (defun org-plist-delete (plist property)
16486 "Delete PROPERTY from PLIST.
16487 This is in contrast to merely setting it to 0."
16488 (let (p)
16489 (while plist
16490 (if (not (eq property (car plist)))
16491 (setq p (plist-put p (car plist) (nth 1 plist))))
16492 (setq plist (cddr plist)))
16495 (defun org-force-self-insert (N)
16496 "Needed to enforce self-insert under remapping."
16497 (interactive "p")
16498 (self-insert-command N))
16500 (defun org-string-width (s)
16501 "Compute width of string, ignoring invisible characters.
16502 This ignores character with invisibility property `org-link', and also
16503 characters with property `org-cwidth', because these will become invisible
16504 upon the next fontification round."
16505 (let (b l)
16506 (when (or (eq t buffer-invisibility-spec)
16507 (assq 'org-link buffer-invisibility-spec))
16508 (while (setq b (text-property-any 0 (length s)
16509 'invisible 'org-link s))
16510 (setq s (concat (substring s 0 b)
16511 (substring s (or (next-single-property-change
16512 b 'invisible s) (length s)))))))
16513 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16514 (setq s (concat (substring s 0 b)
16515 (substring s (or (next-single-property-change
16516 b 'org-cwidth s) (length s))))))
16517 (setq l (string-width s) b -1)
16518 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16519 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16522 (defun org-get-indentation (&optional line)
16523 "Get the indentation of the current line, interpreting tabs.
16524 When LINE is given, assume it represents a line and compute its indentation."
16525 (if line
16526 (if (string-match "^ *" (org-remove-tabs line))
16527 (match-end 0))
16528 (save-excursion
16529 (beginning-of-line 1)
16530 (skip-chars-forward " \t")
16531 (current-column))))
16533 (defun org-remove-tabs (s &optional width)
16534 "Replace tabulators in S with spaces.
16535 Assumes that s is a single line, starting in column 0."
16536 (setq width (or width tab-width))
16537 (while (string-match "\t" s)
16538 (setq s (replace-match
16539 (make-string
16540 (- (* width (/ (+ (match-beginning 0) width) width))
16541 (match-beginning 0)) ?\ )
16542 t t s)))
16545 (defun org-fix-indentation (line ind)
16546 "Fix indentation in LINE.
16547 IND is a cons cell with target and minimum indentation.
16548 If the current indentation in LINE is smaller than the minimum,
16549 leave it alone. If it is larger than ind, set it to the target."
16550 (let* ((l (org-remove-tabs line))
16551 (i (org-get-indentation l))
16552 (i1 (car ind)) (i2 (cdr ind)))
16553 (if (>= i i2) (setq l (substring line i2)))
16554 (if (> i1 0)
16555 (concat (make-string i1 ?\ ) l)
16556 l)))
16558 (defun org-remove-indentation (code &optional n)
16559 "Remove the maximum common indentation from the lines in CODE.
16560 N may optionally be the number of spaces to remove."
16561 (with-temp-buffer
16562 (insert code)
16563 (org-do-remove-indentation n)
16564 (buffer-string)))
16566 (defun org-do-remove-indentation (&optional n)
16567 "Remove the maximum common indentation from the buffer."
16568 (untabify (point-min) (point-max))
16569 (let ((min 10000) re)
16570 (if n
16571 (setq min n)
16572 (goto-char (point-min))
16573 (while (re-search-forward "^ *[^ \n]" nil t)
16574 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16575 (unless (or (= min 0) (= min 10000))
16576 (setq re (format "^ \\{%d\\}" min))
16577 (goto-char (point-min))
16578 (while (re-search-forward re nil t)
16579 (replace-match "")
16580 (end-of-line 1))
16581 min)))
16583 (defun org-fill-template (template alist)
16584 "Find each %key of ALIST in TEMPLATE and replace it."
16585 (let ((case-fold-search nil)
16586 entry key value)
16587 (setq alist (sort (copy-sequence alist)
16588 (lambda (a b) (< (length (car a)) (length (car b))))))
16589 (while (setq entry (pop alist))
16590 (setq template
16591 (replace-regexp-in-string
16592 (concat "%" (regexp-quote (car entry)))
16593 (cdr entry) template t t)))
16594 template))
16596 (defun org-base-buffer (buffer)
16597 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16598 (if (not buffer)
16599 buffer
16600 (or (buffer-base-buffer buffer)
16601 buffer)))
16603 (defun org-trim (s)
16604 "Remove whitespace at beginning and end of string."
16605 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16606 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16609 (defun org-wrap (string &optional width lines)
16610 "Wrap string to either a number of lines, or a width in characters.
16611 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16612 that costs. If there is a word longer than WIDTH, the text is actually
16613 wrapped to the length of that word.
16614 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16615 many lines, whatever width that takes.
16616 The return value is a list of lines, without newlines at the end."
16617 (let* ((words (org-split-string string "[ \t\n]+"))
16618 (maxword (apply 'max (mapcar 'org-string-width words)))
16619 w ll)
16620 (cond (width
16621 (org-do-wrap words (max maxword width)))
16622 (lines
16623 (setq w maxword)
16624 (setq ll (org-do-wrap words maxword))
16625 (if (<= (length ll) lines)
16627 (setq ll words)
16628 (while (> (length ll) lines)
16629 (setq w (1+ w))
16630 (setq ll (org-do-wrap words w)))
16631 ll))
16632 (t (error "Cannot wrap this")))))
16634 (defun org-do-wrap (words width)
16635 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16636 (let (lines line)
16637 (while words
16638 (setq line (pop words))
16639 (while (and words (< (+ (length line) (length (car words))) width))
16640 (setq line (concat line " " (pop words))))
16641 (setq lines (push line lines)))
16642 (nreverse lines)))
16644 (defun org-split-string (string &optional separators)
16645 "Splits STRING into substrings at SEPARATORS.
16646 No empty strings are returned if there are matches at the beginning
16647 and end of string."
16648 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16649 (start 0)
16650 notfirst
16651 (list nil))
16652 (while (and (string-match rexp string
16653 (if (and notfirst
16654 (= start (match-beginning 0))
16655 (< start (length string)))
16656 (1+ start) start))
16657 (< (match-beginning 0) (length string)))
16658 (setq notfirst t)
16659 (or (eq (match-beginning 0) 0)
16660 (and (eq (match-beginning 0) (match-end 0))
16661 (eq (match-beginning 0) start))
16662 (setq list
16663 (cons (substring string start (match-beginning 0))
16664 list)))
16665 (setq start (match-end 0)))
16666 (or (eq start (length string))
16667 (setq list
16668 (cons (substring string start)
16669 list)))
16670 (nreverse list)))
16672 (defun org-quote-vert (s)
16673 "Replace \"|\" with \"\\vert\"."
16674 (while (string-match "|" s)
16675 (setq s (replace-match "\\vert" t t s)))
16678 (defun org-uuidgen-p (s)
16679 "Is S an ID created by UUIDGEN?"
16680 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16682 (defun org-context ()
16683 "Return a list of contexts of the current cursor position.
16684 If several contexts apply, all are returned.
16685 Each context entry is a list with a symbol naming the context, and
16686 two positions indicating start and end of the context. Possible
16687 contexts are:
16689 :headline anywhere in a headline
16690 :headline-stars on the leading stars in a headline
16691 :todo-keyword on a TODO keyword (including DONE) in a headline
16692 :tags on the TAGS in a headline
16693 :priority on the priority cookie in a headline
16694 :item on the first line of a plain list item
16695 :item-bullet on the bullet/number of a plain list item
16696 :checkbox on the checkbox in a plain list item
16697 :table in an org-mode table
16698 :table-special on a special filed in a table
16699 :table-table in a table.el table
16700 :link on a hyperlink
16701 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16702 :target on a <<target>>
16703 :radio-target on a <<<radio-target>>>
16704 :latex-fragment on a LaTeX fragment
16705 :latex-preview on a LaTeX fragment with overlayed preview image
16707 This function expects the position to be visible because it uses font-lock
16708 faces as a help to recognize the following contexts: :table-special, :link,
16709 and :keyword."
16710 (let* ((f (get-text-property (point) 'face))
16711 (faces (if (listp f) f (list f)))
16712 (p (point)) clist o)
16713 ;; First the large context
16714 (cond
16715 ((org-on-heading-p t)
16716 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16717 (when (progn
16718 (beginning-of-line 1)
16719 (looking-at org-todo-line-tags-regexp))
16720 (push (org-point-in-group p 1 :headline-stars) clist)
16721 (push (org-point-in-group p 2 :todo-keyword) clist)
16722 (push (org-point-in-group p 4 :tags) clist))
16723 (goto-char p)
16724 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16725 (if (looking-at "\\[#[A-Z0-9]\\]")
16726 (push (org-point-in-group p 0 :priority) clist)))
16728 ((org-at-item-p)
16729 (push (org-point-in-group p 2 :item-bullet) clist)
16730 (push (list :item (point-at-bol)
16731 (save-excursion (org-end-of-item) (point)))
16732 clist)
16733 (and (org-at-item-checkbox-p)
16734 (push (org-point-in-group p 0 :checkbox) clist)))
16736 ((org-at-table-p)
16737 (push (list :table (org-table-begin) (org-table-end)) clist)
16738 (if (memq 'org-formula faces)
16739 (push (list :table-special
16740 (previous-single-property-change p 'face)
16741 (next-single-property-change p 'face)) clist)))
16742 ((org-at-table-p 'any)
16743 (push (list :table-table) clist)))
16744 (goto-char p)
16746 ;; Now the small context
16747 (cond
16748 ((org-at-timestamp-p)
16749 (push (org-point-in-group p 0 :timestamp) clist))
16750 ((memq 'org-link faces)
16751 (push (list :link
16752 (previous-single-property-change p 'face)
16753 (next-single-property-change p 'face)) clist))
16754 ((memq 'org-special-keyword faces)
16755 (push (list :keyword
16756 (previous-single-property-change p 'face)
16757 (next-single-property-change p 'face)) clist))
16758 ((org-on-target-p)
16759 (push (org-point-in-group p 0 :target) clist)
16760 (goto-char (1- (match-beginning 0)))
16761 (if (looking-at org-radio-target-regexp)
16762 (push (org-point-in-group p 0 :radio-target) clist))
16763 (goto-char p))
16764 ((setq o (car (delq nil
16765 (mapcar
16766 (lambda (x)
16767 (if (memq x org-latex-fragment-image-overlays) x))
16768 (org-overlays-at (point))))))
16769 (push (list :latex-fragment
16770 (org-overlay-start o) (org-overlay-end o)) clist)
16771 (push (list :latex-preview
16772 (org-overlay-start o) (org-overlay-end o)) clist))
16773 ((org-inside-LaTeX-fragment-p)
16774 ;; FIXME: positions wrong.
16775 (push (list :latex-fragment (point) (point)) clist)))
16777 (setq clist (nreverse (delq nil clist)))
16778 clist))
16780 ;; FIXME: Compare with at-regexp-p Do we need both?
16781 (defun org-in-regexp (re &optional nlines visually)
16782 "Check if point is inside a match of regexp.
16783 Normally only the current line is checked, but you can include NLINES extra
16784 lines both before and after point into the search.
16785 If VISUALLY is set, require that the cursor is not after the match but
16786 really on, so that the block visually is on the match."
16787 (catch 'exit
16788 (let ((pos (point))
16789 (eol (point-at-eol (+ 1 (or nlines 0))))
16790 (inc (if visually 1 0)))
16791 (save-excursion
16792 (beginning-of-line (- 1 (or nlines 0)))
16793 (while (re-search-forward re eol t)
16794 (if (and (<= (match-beginning 0) pos)
16795 (>= (+ inc (match-end 0)) pos))
16796 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16798 (defun org-at-regexp-p (regexp)
16799 "Is point inside a match of REGEXP in the current line?"
16800 (catch 'exit
16801 (save-excursion
16802 (let ((pos (point)) (end (point-at-eol)))
16803 (beginning-of-line 1)
16804 (while (re-search-forward regexp end t)
16805 (if (and (<= (match-beginning 0) pos)
16806 (>= (match-end 0) pos))
16807 (throw 'exit t)))
16808 nil))))
16810 (defun org-occur-in-agenda-files (regexp &optional nlines)
16811 "Call `multi-occur' with buffers for all agenda files."
16812 (interactive "sOrg-files matching: \np")
16813 (let* ((files (org-agenda-files))
16814 (tnames (mapcar 'file-truename files))
16815 (extra org-agenda-text-search-extra-files)
16817 (when (eq (car extra) 'agenda-archives)
16818 (setq extra (cdr extra))
16819 (setq files (org-add-archive-files files)))
16820 (while (setq f (pop extra))
16821 (unless (member (file-truename f) tnames)
16822 (add-to-list 'files f 'append)
16823 (add-to-list 'tnames (file-truename f) 'append)))
16824 (multi-occur
16825 (mapcar (lambda (x)
16826 (with-current-buffer
16827 (or (get-file-buffer x) (find-file-noselect x))
16828 (widen)
16829 (current-buffer)))
16830 files)
16831 regexp)))
16833 (if (boundp 'occur-mode-find-occurrence-hook)
16834 ;; Emacs 23
16835 (add-hook 'occur-mode-find-occurrence-hook
16836 (lambda ()
16837 (when (org-mode-p)
16838 (org-reveal))))
16839 ;; Emacs 22
16840 (defadvice occur-mode-goto-occurrence
16841 (after org-occur-reveal activate)
16842 (and (org-mode-p) (org-reveal)))
16843 (defadvice occur-mode-goto-occurrence-other-window
16844 (after org-occur-reveal activate)
16845 (and (org-mode-p) (org-reveal)))
16846 (defadvice occur-mode-display-occurrence
16847 (after org-occur-reveal activate)
16848 (when (org-mode-p)
16849 (let ((pos (occur-mode-find-occurrence)))
16850 (with-current-buffer (marker-buffer pos)
16851 (save-excursion
16852 (goto-char pos)
16853 (org-reveal)))))))
16855 (defun org-occur-link-in-agenda-files ()
16856 "Create a link and search for it in the agendas.
16857 The link is not stored in `org-stored-links', it is just created
16858 for the search purpose."
16859 (interactive)
16860 (let ((link (condition-case nil
16861 (org-store-link nil)
16862 (error "Unable to create a link to here"))))
16863 (org-occur-in-agenda-files (regexp-quote link))))
16865 (defun org-uniquify (list)
16866 "Remove duplicate elements from LIST."
16867 (let (res)
16868 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16869 res))
16871 (defun org-delete-all (elts list)
16872 "Remove all elements in ELTS from LIST."
16873 (while elts
16874 (setq list (delete (pop elts) list)))
16875 list)
16877 (defun org-back-over-empty-lines ()
16878 "Move backwards over whitespace, to the beginning of the first empty line.
16879 Returns the number of empty lines passed."
16880 (let ((pos (point)))
16881 (skip-chars-backward " \t\n\r")
16882 (beginning-of-line 2)
16883 (goto-char (min (point) pos))
16884 (count-lines (point) pos)))
16886 (defun org-skip-whitespace ()
16887 (skip-chars-forward " \t\n\r"))
16889 (defun org-point-in-group (point group &optional context)
16890 "Check if POINT is in match-group GROUP.
16891 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16892 match. If the match group does ot exist or point is not inside it,
16893 return nil."
16894 (and (match-beginning group)
16895 (>= point (match-beginning group))
16896 (<= point (match-end group))
16897 (if context
16898 (list context (match-beginning group) (match-end group))
16899 t)))
16901 (defun org-switch-to-buffer-other-window (&rest args)
16902 "Switch to buffer in a second window on the current frame.
16903 In particular, do not allow pop-up frames."
16904 (let (pop-up-frames special-display-buffer-names special-display-regexps
16905 special-display-function)
16906 (apply 'switch-to-buffer-other-window args)))
16908 (defun org-combine-plists (&rest plists)
16909 "Create a single property list from all plists in PLISTS.
16910 The process starts by copying the first list, and then setting properties
16911 from the other lists. Settings in the last list are the most significant
16912 ones and overrule settings in the other lists."
16913 (let ((rtn (copy-sequence (pop plists)))
16914 p v ls)
16915 (while plists
16916 (setq ls (pop plists))
16917 (while ls
16918 (setq p (pop ls) v (pop ls))
16919 (setq rtn (plist-put rtn p v))))
16920 rtn))
16922 (defun org-move-line-down (arg)
16923 "Move the current line down. With prefix argument, move it past ARG lines."
16924 (interactive "p")
16925 (let ((col (current-column))
16926 beg end pos)
16927 (beginning-of-line 1) (setq beg (point))
16928 (beginning-of-line 2) (setq end (point))
16929 (beginning-of-line (+ 1 arg))
16930 (setq pos (move-marker (make-marker) (point)))
16931 (insert (delete-and-extract-region beg end))
16932 (goto-char pos)
16933 (org-move-to-column col)))
16935 (defun org-move-line-up (arg)
16936 "Move the current line up. With prefix argument, move it past ARG lines."
16937 (interactive "p")
16938 (let ((col (current-column))
16939 beg end pos)
16940 (beginning-of-line 1) (setq beg (point))
16941 (beginning-of-line 2) (setq end (point))
16942 (beginning-of-line (- arg))
16943 (setq pos (move-marker (make-marker) (point)))
16944 (insert (delete-and-extract-region beg end))
16945 (goto-char pos)
16946 (org-move-to-column col)))
16948 (defun org-replace-escapes (string table)
16949 "Replace %-escapes in STRING with values in TABLE.
16950 TABLE is an association list with keys like \"%a\" and string values.
16951 The sequences in STRING may contain normal field width and padding information,
16952 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16953 so values can contain further %-escapes if they are define later in TABLE."
16954 (let ((case-fold-search nil)
16955 e re rpl)
16956 (while (setq e (pop table))
16957 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16958 (while (string-match re string)
16959 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16960 (cdr e)))
16961 (setq string (replace-match rpl t t string))))
16962 string))
16965 (defun org-sublist (list start end)
16966 "Return a section of LIST, from START to END.
16967 Counting starts at 1."
16968 (let (rtn (c start))
16969 (setq list (nthcdr (1- start) list))
16970 (while (and list (<= c end))
16971 (push (pop list) rtn)
16972 (setq c (1+ c)))
16973 (nreverse rtn)))
16975 (defun org-find-base-buffer-visiting (file)
16976 "Like `find-buffer-visiting' but always return the base buffer and
16977 not an indirect buffer."
16978 (let ((buf (or (get-file-buffer file)
16979 (find-buffer-visiting file))))
16980 (if buf
16981 (or (buffer-base-buffer buf) buf)
16982 nil)))
16984 (defun org-image-file-name-regexp (&optional extensions)
16985 "Return regexp matching the file names of images.
16986 If EXTENSIONS is given, only match these."
16987 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16988 (image-file-name-regexp)
16989 (let ((image-file-name-extensions
16990 (or extensions
16991 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16992 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16993 (concat "\\."
16994 (regexp-opt (nconc (mapcar 'upcase
16995 image-file-name-extensions)
16996 image-file-name-extensions)
16998 "\\'"))))
17000 (defun org-file-image-p (file &optional extensions)
17001 "Return non-nil if FILE is an image."
17002 (save-match-data
17003 (string-match (org-image-file-name-regexp extensions) file)))
17005 (defun org-get-cursor-date ()
17006 "Return the date at cursor in as a time.
17007 This works in the calendar and in the agenda, anywhere else it just
17008 returns the current time."
17009 (let (date day defd)
17010 (cond
17011 ((eq major-mode 'calendar-mode)
17012 (setq date (calendar-cursor-to-date)
17013 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17014 ((eq major-mode 'org-agenda-mode)
17015 (setq day (get-text-property (point) 'day))
17016 (if day
17017 (setq date (calendar-gregorian-from-absolute day)
17018 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17019 (nth 2 date))))))
17020 (or defd (current-time))))
17022 (defvar org-agenda-action-marker (make-marker)
17023 "Marker pointing to the entry for the next agenda action.")
17025 (defun org-mark-entry-for-agenda-action ()
17026 "Mark the current entry as target of an agenda action.
17027 Agenda actions are actions executed from the agenda with the key `k',
17028 which make use of the date at the cursor."
17029 (interactive)
17030 (move-marker org-agenda-action-marker
17031 (save-excursion (org-back-to-heading t) (point))
17032 (current-buffer))
17033 (message
17034 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17036 ;;; Paragraph filling stuff.
17037 ;; We want this to be just right, so use the full arsenal.
17039 (defun org-indent-line-function ()
17040 "Indent line like previous, but further if previous was headline or item."
17041 (interactive)
17042 (let* ((pos (point))
17043 (itemp (org-at-item-p))
17044 (case-fold-search t)
17045 (org-drawer-regexp (or org-drawer-regexp "\000"))
17046 column bpos bcol tpos tcol bullet btype bullet-type)
17047 ;; Find the previous relevant line
17048 (beginning-of-line 1)
17049 (cond
17050 ((looking-at "#") (setq column 0))
17051 ((looking-at "\\*+ ") (setq column 0))
17052 ((and (looking-at "[ \t]*:END:")
17053 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17054 (save-excursion
17055 (goto-char (1- (match-beginning 1)))
17056 (setq column (current-column))))
17057 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17058 (save-excursion
17059 (re-search-backward
17060 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17061 (setq column (org-get-indentation (match-string 0))))
17063 (beginning-of-line 0)
17064 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17065 (not (looking-at "[ \t]*:END:"))
17066 (not (looking-at org-drawer-regexp)))
17067 (beginning-of-line 0))
17068 (cond
17069 ((looking-at "\\*+[ \t]+")
17070 (if (not org-adapt-indentation)
17071 (setq column 0)
17072 (goto-char (match-end 0))
17073 (setq column (current-column))))
17074 ((looking-at org-drawer-regexp)
17075 (goto-char (1- (match-beginning 1)))
17076 (setq column (current-column)))
17077 ((looking-at "\\([ \t]*\\):END:")
17078 (goto-char (match-end 1))
17079 (setq column (current-column)))
17080 ((org-in-item-p)
17081 (org-beginning-of-item)
17082 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17083 (setq bpos (match-beginning 1) tpos (match-end 0)
17084 bcol (progn (goto-char bpos) (current-column))
17085 tcol (progn (goto-char tpos) (current-column))
17086 bullet (match-string 1)
17087 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17088 (if (> tcol (+ bcol org-description-max-indent))
17089 (setq tcol (+ bcol 5)))
17090 (if (not itemp)
17091 (setq column tcol)
17092 (goto-char pos)
17093 (beginning-of-line 1)
17094 (if (looking-at "\\S-")
17095 (progn
17096 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17097 (setq bullet (match-string 1)
17098 btype (if (string-match "[0-9]" bullet) "n" bullet))
17099 (setq column (if (equal btype bullet-type) bcol tcol)))
17100 (setq column (org-get-indentation)))))
17101 (t (setq column (org-get-indentation))))))
17102 (goto-char pos)
17103 (if (<= (current-column) (current-indentation))
17104 (org-indent-line-to column)
17105 (save-excursion (org-indent-line-to column)))
17106 (setq column (current-column))
17107 (beginning-of-line 1)
17108 (if (looking-at
17109 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17110 (replace-match (concat (match-string 1)
17111 (format org-property-format
17112 (match-string 2) (match-string 3)))
17113 t t))
17114 (org-move-to-column column)))
17116 (defun org-set-autofill-regexps ()
17117 (interactive)
17118 ;; In the paragraph separator we include headlines, because filling
17119 ;; text in a line directly attached to a headline would otherwise
17120 ;; fill the headline as well.
17121 (org-set-local 'comment-start-skip "^#+[ \t]*")
17122 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17123 ;; The paragraph starter includes hand-formatted lists.
17124 (org-set-local
17125 'paragraph-start
17126 (concat
17127 "\f" "\\|"
17128 "[ ]*$" "\\|"
17129 "\\*+ " "\\|"
17130 "[ \t]*#" "\\|"
17131 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17132 "[ \t]*[:|]" "\\|"
17133 "\\$\\$" "\\|"
17134 "\\\\\\(begin\\|end\\|[][]\\)"))
17135 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17136 ;; But only if the user has not turned off tables or fixed-width regions
17137 (org-set-local
17138 'auto-fill-inhibit-regexp
17139 (concat "\\*+ \\|#\\+"
17140 "\\|[ \t]*" org-keyword-time-regexp
17141 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17142 (concat
17143 "\\|[ \t]*["
17144 (if org-enable-table-editor "|" "")
17145 (if org-enable-fixed-width-editor ":" "")
17146 "]"))))
17147 ;; We use our own fill-paragraph function, to make sure that tables
17148 ;; and fixed-width regions are not wrapped. That function will pass
17149 ;; through to `fill-paragraph' when appropriate.
17150 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17151 ; Adaptive filling: To get full control, first make sure that
17152 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17153 (org-set-local 'adaptive-fill-regexp "\000")
17154 (org-set-local 'adaptive-fill-function
17155 'org-adaptive-fill-function)
17156 (org-set-local
17157 'align-mode-rules-list
17158 '((org-in-buffer-settings
17159 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17160 (modes . '(org-mode))))))
17162 (defun org-fill-paragraph (&optional justify)
17163 "Re-align a table, pass through to fill-paragraph if no table."
17164 (let ((table-p (org-at-table-p))
17165 (table.el-p (org-at-table.el-p)))
17166 (cond ((and (equal (char-after (point-at-bol)) ?*)
17167 (save-excursion (goto-char (point-at-bol))
17168 (looking-at outline-regexp)))
17169 t) ; skip headlines
17170 (table.el-p t) ; skip table.el tables
17171 (table-p (org-table-align) t) ; align org-mode tables
17172 (t nil)))) ; call paragraph-fill
17174 ;; For reference, this is the default value of adaptive-fill-regexp
17175 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17177 (defun org-adaptive-fill-function ()
17178 "Return a fill prefix for org-mode files.
17179 In particular, this makes sure hanging paragraphs for hand-formatted lists
17180 work correctly."
17181 (cond ((looking-at "#[ \t]+")
17182 (match-string 0))
17183 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17184 (save-excursion
17185 (if (> (match-end 1) (+ (match-beginning 1)
17186 org-description-max-indent))
17187 (goto-char (+ (match-beginning 1) 5))
17188 (goto-char (match-end 0)))
17189 (make-string (current-column) ?\ )))
17190 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17191 (save-excursion
17192 (goto-char (match-end 0))
17193 (make-string (current-column) ?\ )))
17194 (t nil)))
17196 ;;; Other stuff.
17198 (defun org-toggle-fixed-width-section (arg)
17199 "Toggle the fixed-width export.
17200 If there is no active region, the QUOTE keyword at the current headline is
17201 inserted or removed. When present, it causes the text between this headline
17202 and the next to be exported as fixed-width text, and unmodified.
17203 If there is an active region, this command adds or removes a colon as the
17204 first character of this line. If the first character of a line is a colon,
17205 this line is also exported in fixed-width font."
17206 (interactive "P")
17207 (let* ((cc 0)
17208 (regionp (org-region-active-p))
17209 (beg (if regionp (region-beginning) (point)))
17210 (end (if regionp (region-end)))
17211 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17212 (case-fold-search nil)
17213 (re "[ \t]*\\(: \\)")
17214 off)
17215 (if regionp
17216 (save-excursion
17217 (goto-char beg)
17218 (setq cc (current-column))
17219 (beginning-of-line 1)
17220 (setq off (looking-at re))
17221 (while (> nlines 0)
17222 (setq nlines (1- nlines))
17223 (beginning-of-line 1)
17224 (cond
17225 (arg
17226 (org-move-to-column cc t)
17227 (insert ": \n")
17228 (forward-line -1))
17229 ((and off (looking-at re))
17230 (replace-match "" t t nil 1))
17231 ((not off) (org-move-to-column cc t) (insert ": ")))
17232 (forward-line 1)))
17233 (save-excursion
17234 (org-back-to-heading)
17235 (if (looking-at (concat outline-regexp
17236 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17237 (replace-match "" t t nil 1)
17238 (if (looking-at outline-regexp)
17239 (progn
17240 (goto-char (match-end 0))
17241 (insert org-quote-string " "))))))))
17243 (defun org-reftex-citation ()
17244 "Use reftex-citation to insert a citation into the buffer.
17245 This looks for a line like
17247 #+BIBLIOGRAPHY: foo plain option:-d
17249 and derives from it that foo.bib is the bibliography file relevant
17250 for this document. It then installs the necessary environment for RefTeX
17251 to work in this buffer and calls `reftex-citation' to insert a citation
17252 into the buffer.
17254 Export of such citations to both LaTeX and HTML is handled by the contributed
17255 package org-exp-bibtex by Taru Karttunen."
17256 (interactive)
17257 (let ((reftex-docstruct-symbol 'rds)
17258 (reftex-cite-format "\\cite{%l}")
17259 rds bib)
17260 (save-excursion
17261 (save-restriction
17262 (widen)
17263 (let ((case-fold-search t)
17264 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17265 (if (not (save-excursion
17266 (or (re-search-forward re nil t)
17267 (re-search-backward re nil t))))
17268 (error "No bibliography defined in file")
17269 (setq bib (concat (match-string 1) ".bib")
17270 rds (list (list 'bib bib)))))))
17271 (call-interactively 'reftex-citation)))
17273 ;;;; Functions extending outline functionality
17275 (defun org-beginning-of-line (&optional arg)
17276 "Go to the beginning of the current line. If that is invisible, continue
17277 to a visible line beginning. This makes the function of C-a more intuitive.
17278 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17279 first attempt, and only move to after the tags when the cursor is already
17280 beyond the end of the headline."
17281 (interactive "P")
17282 (let ((pos (point))
17283 (special (if (consp org-special-ctrl-a/e)
17284 (car org-special-ctrl-a/e)
17285 org-special-ctrl-a/e))
17286 refpos)
17287 (if (org-bound-and-true-p line-move-visual)
17288 (beginning-of-visual-line 1)
17289 (beginning-of-line 1))
17290 (if (and arg (fboundp 'move-beginning-of-line))
17291 (call-interactively 'move-beginning-of-line)
17292 (if (bobp)
17294 (backward-char 1)
17295 (if (org-invisible-p)
17296 (while (and (not (bobp)) (org-invisible-p))
17297 (backward-char 1)
17298 (beginning-of-line 1))
17299 (forward-char 1))))
17300 (when special
17301 (cond
17302 ((and (looking-at org-complex-heading-regexp)
17303 (= (char-after (match-end 1)) ?\ ))
17304 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17305 (point-at-eol)))
17306 (goto-char
17307 (if (eq special t)
17308 (cond ((> pos refpos) refpos)
17309 ((= pos (point)) refpos)
17310 (t (point)))
17311 (cond ((> pos (point)) (point))
17312 ((not (eq last-command this-command)) (point))
17313 (t refpos)))))
17314 ((org-at-item-p)
17315 (goto-char
17316 (if (eq special t)
17317 (cond ((> pos (match-end 4)) (match-end 4))
17318 ((= pos (point)) (match-end 4))
17319 (t (point)))
17320 (cond ((> pos (point)) (point))
17321 ((not (eq last-command this-command)) (point))
17322 (t (match-end 4))))))))
17323 (org-no-warnings
17324 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17326 (defun org-end-of-line (&optional arg)
17327 "Go to the end of the line.
17328 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17329 first attempt, and only move to after the tags when the cursor is already
17330 beyond the end of the headline."
17331 (interactive "P")
17332 (let ((special (if (consp org-special-ctrl-a/e)
17333 (cdr org-special-ctrl-a/e)
17334 org-special-ctrl-a/e)))
17335 (if (or (not special)
17336 (not (org-on-heading-p))
17337 arg)
17338 (call-interactively
17339 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17340 ((fboundp 'move-end-of-line) 'move-end-of-line)
17341 (t 'end-of-line)))
17342 (let ((pos (point)))
17343 (beginning-of-line 1)
17344 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17345 (if (eq special t)
17346 (if (or (< pos (match-beginning 1))
17347 (= pos (match-end 0)))
17348 (goto-char (match-beginning 1))
17349 (goto-char (match-end 0)))
17350 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17351 (goto-char (match-end 0))
17352 (goto-char (match-beginning 1))))
17353 (call-interactively (if (fboundp 'move-end-of-line)
17354 'move-end-of-line
17355 'end-of-line)))))
17356 (org-no-warnings
17357 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17359 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17360 (define-key org-mode-map "\C-e" 'org-end-of-line)
17361 (define-key org-mode-map [home] 'org-beginning-of-line)
17362 (define-key org-mode-map [end] 'org-end-of-line)
17364 (defun org-backward-sentence (&optional arg)
17365 "Go to beginning of sentence, or beginning of table field.
17366 This will call `backward-sentence' or `org-table-beginning-of-field',
17367 depending on context."
17368 (interactive "P")
17369 (cond
17370 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17371 (t (call-interactively 'backward-sentence))))
17373 (defun org-forward-sentence (&optional arg)
17374 "Go to end of sentence, or end of table field.
17375 This will call `forward-sentence' or `org-table-end-of-field',
17376 depending on context."
17377 (interactive "P")
17378 (cond
17379 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17380 (t (call-interactively 'forward-sentence))))
17382 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17383 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17385 (defun org-kill-line (&optional arg)
17386 "Kill line, to tags or end of line."
17387 (interactive "P")
17388 (cond
17389 ((or (not org-special-ctrl-k)
17390 (bolp)
17391 (not (org-on-heading-p)))
17392 (call-interactively 'kill-line))
17393 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17394 (kill-region (point) (match-beginning 1))
17395 (org-set-tags nil t))
17396 (t (kill-region (point) (point-at-eol)))))
17398 (define-key org-mode-map "\C-k" 'org-kill-line)
17400 (defun org-yank (&optional arg)
17401 "Yank. If the kill is a subtree, treat it specially.
17402 This command will look at the current kill and check if is a single
17403 subtree, or a series of subtrees[1]. If it passes the test, and if the
17404 cursor is at the beginning of a line or after the stars of a currently
17405 empty headline, then the yank is handled specially. How exactly depends
17406 on the value of the following variables, both set by default.
17408 org-yank-folded-subtrees
17409 When set, the subtree(s) will be folded after insertion, but only
17410 if doing so would now swallow text after the yanked text.
17412 org-yank-adjusted-subtrees
17413 When set, the subtree will be promoted or demoted in order to
17414 fit into the local outline tree structure, which means that the level
17415 will be adjusted so that it becomes the smaller one of the two
17416 *visible* surrounding headings.
17418 Any prefix to this command will cause `yank' to be called directly with
17419 no special treatment. In particular, a simple `C-u' prefix will just
17420 plainly yank the text as it is.
17422 \[1] The test checks if the first non-white line is a heading
17423 and if there are no other headings with fewer stars."
17424 (interactive "P")
17425 (org-yank-generic 'yank arg))
17427 (defun org-yank-generic (command arg)
17428 "Perform some yank-like command.
17430 This function implements the behavior described in the `org-yank'
17431 documentation. However, it has been generalized to work for any
17432 interactive command with similar behavior."
17434 ;; pretend to be command COMMAND
17435 (setq this-command command)
17437 (if arg
17438 (call-interactively command)
17440 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17441 (and (org-kill-is-subtree-p)
17442 (or (bolp)
17443 (and (looking-at "[ \t]*$")
17444 (string-match
17445 "\\`\\*+\\'"
17446 (buffer-substring (point-at-bol) (point)))))))
17447 swallowp)
17448 (cond
17449 ((and subtreep org-yank-folded-subtrees)
17450 (let ((beg (point))
17451 end)
17452 (if (and subtreep org-yank-adjusted-subtrees)
17453 (org-paste-subtree nil nil 'for-yank)
17454 (call-interactively command))
17456 (setq end (point))
17457 (goto-char beg)
17458 (when (and (bolp) subtreep
17459 (not (setq swallowp
17460 (org-yank-folding-would-swallow-text beg end))))
17461 (or (looking-at outline-regexp)
17462 (re-search-forward (concat "^" outline-regexp) end t))
17463 (while (and (< (point) end) (looking-at outline-regexp))
17464 (hide-subtree)
17465 (org-cycle-show-empty-lines 'folded)
17466 (condition-case nil
17467 (outline-forward-same-level 1)
17468 (error (goto-char end)))))
17469 (when swallowp
17470 (message
17471 "Inserted text not folded because that would swallow text"))
17473 (goto-char end)
17474 (skip-chars-forward " \t\n\r")
17475 (beginning-of-line 1)
17476 (push-mark beg 'nomsg)))
17477 ((and subtreep org-yank-adjusted-subtrees)
17478 (let ((beg (point-at-bol)))
17479 (org-paste-subtree nil nil 'for-yank)
17480 (push-mark beg 'nomsg)))
17482 (call-interactively command))))))
17484 (defun org-yank-folding-would-swallow-text (beg end)
17485 "Would hide-subtree at BEG swallow any text after END?"
17486 (let (level)
17487 (save-excursion
17488 (goto-char beg)
17489 (when (or (looking-at outline-regexp)
17490 (re-search-forward (concat "^" outline-regexp) end t))
17491 (setq level (org-outline-level)))
17492 (goto-char end)
17493 (skip-chars-forward " \t\r\n\v\f")
17494 (if (or (eobp)
17495 (and (bolp) (looking-at org-outline-regexp)
17496 (<= (org-outline-level) level)))
17497 nil ; Nothing would be swallowed
17498 t)))) ; something would swallow
17500 (define-key org-mode-map "\C-y" 'org-yank)
17502 (defun org-invisible-p ()
17503 "Check if point is at a character currently not visible."
17504 ;; Early versions of noutline don't have `outline-invisible-p'.
17505 (if (fboundp 'outline-invisible-p)
17506 (outline-invisible-p)
17507 (get-char-property (point) 'invisible)))
17509 (defun org-invisible-p2 ()
17510 "Check if point is at a character currently not visible."
17511 (save-excursion
17512 (if (and (eolp) (not (bobp))) (backward-char 1))
17513 ;; Early versions of noutline don't have `outline-invisible-p'.
17514 (if (fboundp 'outline-invisible-p)
17515 (outline-invisible-p)
17516 (get-char-property (point) 'invisible))))
17518 (defun org-back-to-heading (&optional invisible-ok)
17519 "Call `outline-back-to-heading', but provide a better error message."
17520 (condition-case nil
17521 (outline-back-to-heading invisible-ok)
17522 (error (error "Before first headline at position %d in buffer %s"
17523 (point) (current-buffer)))))
17525 (defun org-before-first-heading-p ()
17526 "Before first heading?"
17527 (save-excursion
17528 (null (re-search-backward "^\\*+ " nil t))))
17530 (defun org-on-heading-p (&optional ignored)
17531 (outline-on-heading-p t))
17532 (defun org-at-heading-p (&optional ignored)
17533 (outline-on-heading-p t))
17535 (defun org-at-heading-or-item-p ()
17536 (or (org-on-heading-p) (org-at-item-p)))
17538 (defun org-on-target-p ()
17539 (or (org-in-regexp org-radio-target-regexp)
17540 (org-in-regexp org-target-regexp)))
17542 (defun org-up-heading-all (arg)
17543 "Move to the heading line of which the present line is a subheading.
17544 This function considers both visible and invisible heading lines.
17545 With argument, move up ARG levels."
17546 (if (fboundp 'outline-up-heading-all)
17547 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17548 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17550 (defun org-up-heading-safe ()
17551 "Move to the heading line of which the present line is a subheading.
17552 This version will not throw an error. It will return the level of the
17553 headline found, or nil if no higher level is found.
17555 Also, this function will be a lot faster than `outline-up-heading',
17556 because it relies on stars being the outline starters. This can really
17557 make a significant difference in outlines with very many siblings."
17558 (let (start-level re)
17559 (org-back-to-heading t)
17560 (setq start-level (funcall outline-level))
17561 (if (equal start-level 1)
17563 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17564 (if (re-search-backward re nil t)
17565 (funcall outline-level)))))
17567 (defun org-first-sibling-p ()
17568 "Is this heading the first child of its parents?"
17569 (interactive)
17570 (let ((re (concat "^" outline-regexp))
17571 level l)
17572 (unless (org-at-heading-p t)
17573 (error "Not at a heading"))
17574 (setq level (funcall outline-level))
17575 (save-excursion
17576 (if (not (re-search-backward re nil t))
17578 (setq l (funcall outline-level))
17579 (< l level)))))
17581 (defun org-goto-sibling (&optional previous)
17582 "Goto the next sibling, even if it is invisible.
17583 When PREVIOUS is set, go to the previous sibling instead. Returns t
17584 when a sibling was found. When none is found, return nil and don't
17585 move point."
17586 (let ((fun (if previous 're-search-backward 're-search-forward))
17587 (pos (point))
17588 (re (concat "^" outline-regexp))
17589 level l)
17590 (when (condition-case nil (org-back-to-heading t) (error nil))
17591 (setq level (funcall outline-level))
17592 (catch 'exit
17593 (or previous (forward-char 1))
17594 (while (funcall fun re nil t)
17595 (setq l (funcall outline-level))
17596 (when (< l level) (goto-char pos) (throw 'exit nil))
17597 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17598 (goto-char pos)
17599 nil))))
17601 (defun org-show-siblings ()
17602 "Show all siblings of the current headline."
17603 (save-excursion
17604 (while (org-goto-sibling) (org-flag-heading nil)))
17605 (save-excursion
17606 (while (org-goto-sibling 'previous)
17607 (org-flag-heading nil))))
17609 (defun org-show-hidden-entry ()
17610 "Show an entry where even the heading is hidden."
17611 (save-excursion
17612 (org-show-entry)))
17614 (defun org-flag-heading (flag &optional entry)
17615 "Flag the current heading. FLAG non-nil means make invisible.
17616 When ENTRY is non-nil, show the entire entry."
17617 (save-excursion
17618 (org-back-to-heading t)
17619 ;; Check if we should show the entire entry
17620 (if entry
17621 (progn
17622 (org-show-entry)
17623 (save-excursion
17624 (and (outline-next-heading)
17625 (org-flag-heading nil))))
17626 (outline-flag-region (max (point-min) (1- (point)))
17627 (save-excursion (outline-end-of-heading) (point))
17628 flag))))
17630 (defun org-get-next-sibling ()
17631 "Move to next heading of the same level, and return point.
17632 If there is no such heading, return nil.
17633 This is like outline-next-sibling, but invisible headings are ok."
17634 (let ((level (funcall outline-level)))
17635 (outline-next-heading)
17636 (while (and (not (eobp)) (> (funcall outline-level) level))
17637 (outline-next-heading))
17638 (if (or (eobp) (< (funcall outline-level) level))
17640 (point))))
17642 (defun org-get-last-sibling ()
17643 "Move to previous heading of the same level, and return point.
17644 If there is no such heading, return nil."
17645 (let ((opoint (point))
17646 (level (funcall outline-level)))
17647 (outline-previous-heading)
17648 (when (and (/= (point) opoint) (outline-on-heading-p t))
17649 (while (and (> (funcall outline-level) level)
17650 (not (bobp)))
17651 (outline-previous-heading))
17652 (if (< (funcall outline-level) level)
17654 (point)))))
17656 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17657 ;; This contains an exact copy of the original function, but it uses
17658 ;; `org-back-to-heading', to make it work also in invisible
17659 ;; trees. And is uses an invisible-OK argument.
17660 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17661 ;; Furthermore, when used inside Org, finding the end of a large subtree
17662 ;; with many children and grandchildren etc, this can be much faster
17663 ;; than the outline version.
17664 (org-back-to-heading invisible-OK)
17665 (let ((first t)
17666 (level (funcall outline-level)))
17667 (if (and (org-mode-p) (< level 1000))
17668 ;; A true heading (not a plain list item), in Org-mode
17669 ;; This means we can easily find the end by looking
17670 ;; only for the right number of stars. Using a regexp to do
17671 ;; this is so much faster than using a Lisp loop.
17672 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17673 (forward-char 1)
17674 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17675 ;; something else, do it the slow way
17676 (while (and (not (eobp))
17677 (or first (> (funcall outline-level) level)))
17678 (setq first nil)
17679 (outline-next-heading)))
17680 (unless to-heading
17681 (if (memq (preceding-char) '(?\n ?\^M))
17682 (progn
17683 ;; Go to end of line before heading
17684 (forward-char -1)
17685 (if (memq (preceding-char) '(?\n ?\^M))
17686 ;; leave blank line before heading
17687 (forward-char -1))))))
17688 (point))
17690 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17691 "Use Org version in org-mode, for dramatic speed-up."
17692 (if (eq major-mode 'org-mode)
17693 (progn
17694 (org-end-of-subtree nil t)
17695 (unless (eobp) (backward-char 1)))
17696 ad-do-it))
17698 (defun org-forward-same-level (arg &optional invisible-ok)
17699 "Move forward to the arg'th subheading at same level as this one.
17700 Stop at the first and last subheadings of a superior heading."
17701 (interactive "p")
17702 (org-back-to-heading invisible-ok)
17703 (org-on-heading-p)
17704 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17705 (re (format "^\\*\\{1,%d\\} " level))
17707 (forward-char 1)
17708 (while (> arg 0)
17709 (while (and (re-search-forward re nil 'move)
17710 (setq l (- (match-end 0) (match-beginning 0) 1))
17711 (= l level)
17712 (not invisible-ok)
17713 (progn (backward-char 1) (org-invisible-p)))
17714 (if (< l level) (setq arg 1)))
17715 (setq arg (1- arg)))
17716 (beginning-of-line 1)))
17718 (defun org-backward-same-level (arg &optional invisible-ok)
17719 "Move backward to the arg'th subheading at same level as this one.
17720 Stop at the first and last subheadings of a superior heading."
17721 (interactive "p")
17722 (org-back-to-heading)
17723 (org-on-heading-p)
17724 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17725 (re (format "^\\*\\{1,%d\\} " level))
17727 (while (> arg 0)
17728 (while (and (re-search-backward re nil 'move)
17729 (setq l (- (match-end 0) (match-beginning 0) 1))
17730 (= l level)
17731 (not invisible-ok)
17732 (org-invisible-p))
17733 (if (< l level) (setq arg 1)))
17734 (setq arg (1- arg)))))
17736 (defun org-show-subtree ()
17737 "Show everything after this heading at deeper levels."
17738 (outline-flag-region
17739 (point)
17740 (save-excursion
17741 (org-end-of-subtree t t))
17742 nil))
17744 (defun org-show-entry ()
17745 "Show the body directly following this heading.
17746 Show the heading too, if it is currently invisible."
17747 (interactive)
17748 (save-excursion
17749 (condition-case nil
17750 (progn
17751 (org-back-to-heading t)
17752 (outline-flag-region
17753 (max (point-min) (1- (point)))
17754 (save-excursion
17755 (if (re-search-forward
17756 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17757 (match-beginning 1)
17758 (point-max)))
17759 nil)
17760 (org-cycle-hide-drawers 'children))
17761 (error nil))))
17763 (defun org-make-options-regexp (kwds &optional extra)
17764 "Make a regular expression for keyword lines."
17765 (concat
17767 "#?[ \t]*\\+\\("
17768 (mapconcat 'regexp-quote kwds "\\|")
17769 (if extra (concat "\\|" extra))
17770 "\\):[ \t]*"
17771 "\\(.*\\)"))
17773 ;; Make isearch reveal the necessary context
17774 (defun org-isearch-end ()
17775 "Reveal context after isearch exits."
17776 (when isearch-success ; only if search was successful
17777 (if (featurep 'xemacs)
17778 ;; Under XEmacs, the hook is run in the correct place,
17779 ;; we directly show the context.
17780 (org-show-context 'isearch)
17781 ;; In Emacs the hook runs *before* restoring the overlays.
17782 ;; So we have to use a one-time post-command-hook to do this.
17783 ;; (Emacs 22 has a special variable, see function `org-mode')
17784 (unless (and (boundp 'isearch-mode-end-hook-quit)
17785 isearch-mode-end-hook-quit)
17786 ;; Only when the isearch was not quitted.
17787 (org-add-hook 'post-command-hook 'org-isearch-post-command
17788 'append 'local)))))
17790 (defun org-isearch-post-command ()
17791 "Remove self from hook, and show context."
17792 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17793 (org-show-context 'isearch))
17796 ;;;; Integration with and fixes for other packages
17798 ;;; Imenu support
17800 (defvar org-imenu-markers nil
17801 "All markers currently used by Imenu.")
17802 (make-variable-buffer-local 'org-imenu-markers)
17804 (defun org-imenu-new-marker (&optional pos)
17805 "Return a new marker for use by Imenu, and remember the marker."
17806 (let ((m (make-marker)))
17807 (move-marker m (or pos (point)))
17808 (push m org-imenu-markers)
17811 (defun org-imenu-get-tree ()
17812 "Produce the index for Imenu."
17813 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17814 (setq org-imenu-markers nil)
17815 (let* ((n org-imenu-depth)
17816 (re (concat "^" outline-regexp))
17817 (subs (make-vector (1+ n) nil))
17818 (last-level 0)
17819 m level head)
17820 (save-excursion
17821 (save-restriction
17822 (widen)
17823 (goto-char (point-max))
17824 (while (re-search-backward re nil t)
17825 (setq level (org-reduced-level (funcall outline-level)))
17826 (when (<= level n)
17827 (looking-at org-complex-heading-regexp)
17828 (setq head (org-link-display-format
17829 (org-match-string-no-properties 4))
17830 m (org-imenu-new-marker))
17831 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17832 (if (>= level last-level)
17833 (push (cons head m) (aref subs level))
17834 (push (cons head (aref subs (1+ level))) (aref subs level))
17835 (loop for i from (1+ level) to n do (aset subs i nil)))
17836 (setq last-level level)))))
17837 (aref subs 1)))
17839 (eval-after-load "imenu"
17840 '(progn
17841 (add-hook 'imenu-after-jump-hook
17842 (lambda ()
17843 (if (eq major-mode 'org-mode)
17844 (org-show-context 'org-goto))))))
17846 (defun org-link-display-format (link)
17847 "Replace a link with either the description, or the link target
17848 if no description is present"
17849 (save-match-data
17850 (if (string-match org-bracket-link-analytic-regexp link)
17851 (replace-match (if (match-end 5)
17852 (match-string 5 link)
17853 (concat (match-string 1 link)
17854 (match-string 3 link)))
17855 nil t link)
17856 link)))
17858 ;; Speedbar support
17860 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17861 "Overlay marking the agenda restriction line in speedbar.")
17862 (org-overlay-put org-speedbar-restriction-lock-overlay
17863 'face 'org-agenda-restriction-lock)
17864 (org-overlay-put org-speedbar-restriction-lock-overlay
17865 'help-echo "Agendas are currently limited to this item.")
17866 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17868 (defun org-speedbar-set-agenda-restriction ()
17869 "Restrict future agenda commands to the location at point in speedbar.
17870 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17871 (interactive)
17872 (require 'org-agenda)
17873 (let (p m tp np dir txt)
17874 (cond
17875 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17876 'org-imenu t))
17877 (setq m (get-text-property p 'org-imenu-marker))
17878 (with-current-buffer (marker-buffer m)
17879 (goto-char m)
17880 (org-agenda-set-restriction-lock 'subtree)))
17881 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17882 'speedbar-function 'speedbar-find-file))
17883 (setq tp (previous-single-property-change
17884 (1+ p) 'speedbar-function)
17885 np (next-single-property-change
17886 tp 'speedbar-function)
17887 dir (speedbar-line-directory)
17888 txt (buffer-substring-no-properties (or tp (point-min))
17889 (or np (point-max))))
17890 (with-current-buffer (find-file-noselect
17891 (let ((default-directory dir))
17892 (expand-file-name txt)))
17893 (unless (org-mode-p)
17894 (error "Cannot restrict to non-Org-mode file"))
17895 (org-agenda-set-restriction-lock 'file)))
17896 (t (error "Don't know how to restrict Org-mode's agenda")))
17897 (org-move-overlay org-speedbar-restriction-lock-overlay
17898 (point-at-bol) (point-at-eol))
17899 (setq current-prefix-arg nil)
17900 (org-agenda-maybe-redo)))
17902 (eval-after-load "speedbar"
17903 '(progn
17904 (speedbar-add-supported-extension ".org")
17905 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17906 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17907 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17908 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17909 (add-hook 'speedbar-visiting-tag-hook
17910 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17913 ;;; Fixes and Hacks for problems with other packages
17915 ;; Make flyspell not check words in links, to not mess up our keymap
17916 (defun org-mode-flyspell-verify ()
17917 "Don't let flyspell put overlays at active buttons."
17918 (and (not (get-text-property (point) 'keymap))
17919 (not (get-text-property (point) 'org-no-flyspell))))
17921 (defun org-remove-flyspell-overlays-in (beg end)
17922 "Remove flyspell overlays in region."
17923 (and (org-bound-and-true-p flyspell-mode)
17924 (fboundp 'flyspell-delete-region-overlays)
17925 (flyspell-delete-region-overlays beg end))
17926 (add-text-properties beg end '(org-no-flyspell t)))
17928 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17929 (eval-after-load "bookmark"
17930 '(if (boundp 'bookmark-after-jump-hook)
17931 ;; We can use the hook
17932 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17933 ;; Hook not available, use advice
17934 (defadvice bookmark-jump (after org-make-visible activate)
17935 "Make the position visible."
17936 (org-bookmark-jump-unhide))))
17938 ;; Make sure saveplace shows the location if it was hidden
17939 (eval-after-load "saveplace"
17940 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17941 "Make the position visible."
17942 (org-bookmark-jump-unhide)))
17944 ;; Make sure ecb shows the location if it was hidden
17945 (eval-after-load "ecb"
17946 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17947 "Make hierarchy visible when jumping into location from ECB tree buffer."
17948 (if (eq major-mode 'org-mode)
17949 (org-show-context))))
17951 (defun org-bookmark-jump-unhide ()
17952 "Unhide the current position, to show the bookmark location."
17953 (and (org-mode-p)
17954 (or (org-invisible-p)
17955 (save-excursion (goto-char (max (point-min) (1- (point))))
17956 (org-invisible-p)))
17957 (org-show-context 'bookmark-jump)))
17959 ;; Make session.el ignore our circular variable
17960 (eval-after-load "session"
17961 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17963 ;;;; Experimental code
17965 (defun org-closed-in-range ()
17966 "Sparse tree of items closed in a certain time range.
17967 Still experimental, may disappear in the future."
17968 (interactive)
17969 ;; Get the time interval from the user.
17970 (let* ((time1 (org-float-time
17971 (org-read-date nil 'to-time nil "Starting date: ")))
17972 (time2 (org-float-time
17973 (org-read-date nil 'to-time nil "End date:")))
17974 ;; callback function
17975 (callback (lambda ()
17976 (let ((time
17977 (org-float-time
17978 (apply 'encode-time
17979 (org-parse-time-string
17980 (match-string 1))))))
17981 ;; check if time in interval
17982 (and (>= time time1) (<= time time2))))))
17983 ;; make tree, check each match with the callback
17984 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17986 ;;;; Finish up
17988 (provide 'org)
17990 (run-hooks 'org-load-hook)
17992 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17994 ;;; org.el ends here