Fix recent bug with timestamp properties
[org-mode.git] / lisp / org.el
blob27af308e77ce789698e29da0e7351b26755466f8
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.33trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.33trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message version)))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " docview: Links to doc-view buffers" org-docview)
193 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
194 (const :tag " id: Global IDs for identifying entries" org-id)
195 (const :tag " info: Links to Info nodes" org-info)
196 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
197 (const :tag " habit: Track your consistency with habits" org-habit)
198 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
199 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
200 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
201 (const :tag " mew Links to Mew folders/messages" org-mew)
202 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
203 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
204 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
205 (const :tag " vm: Links to VM folders/messages" org-vm)
206 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
207 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
208 (const :tag " mouse: Additional mouse support" org-mouse)
210 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
211 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
212 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
213 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
214 (const :tag "C collector: Collect properties into tables" org-collector)
215 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
216 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
217 (const :tag "C eval: Include command output as text" org-eval)
218 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
219 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
220 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
221 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
222 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
224 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
226 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
227 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
228 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
229 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
230 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
231 (const :tag "C mtags: Support for muse-like tags" org-mtags)
232 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
233 (const :tag "C R: Computation using the R language" org-R)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
238 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
239 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
240 (const :tag "C track: Keep up with Org-mode development" org-track)
241 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
243 (defcustom org-support-shift-select nil
244 "Non-nil means, make shift-cursor commands select text when possible.
246 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
247 selecting a region, or enlarge thusly regions started in this way.
248 In Org-mode, in special contexts, these same keys are used for other
249 purposes, important enough to compete with shift selection. Org tries
250 to balance these needs by supporting `shift-select-mode' outside these
251 special contexts, under control of this variable.
253 The default of this variable is nil, to avoid confusing behavior. Shifted
254 cursor keys will then execute Org commands in the following contexts:
255 - on a headline, changing TODO state (left/right) and priority (up/down)
256 - on a time stamp, changing the time
257 - in a plain list item, changing the bullet type
258 - in a property definition line, switching between allowed values
259 - in the BEGIN line of a clock table (changing the time block).
260 Outside these contexts, the commands will throw an error.
262 When this variable is t and the cursor is not in a special context,
263 Org-mode will support shift-selection for making and enlarging regions.
264 To make this more effective, the bullet cycling will no longer happen
265 anywhere in an item line, but only if the cursor is exactly on the bullet.
267 If you set this variable to the symbol `always', then the keys
268 will not be special in headlines, property lines, and item lines, to make
269 shift selection work there as well. If this is what you want, you can
270 use the following alternative commands: `C-c C-t' and `C-c ,' to
271 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
272 TODO sets, `C-c -' to cycle item bullet types, and properties can be
273 edited by hand or in column view.
275 However, when the cursor is on a timestamp, shift-cursor commands
276 will still edit the time stamp - this is just too good to give up.
278 XEmacs user should have this variable set to nil, because shift-select-mode
279 is Emacs 23 only."
280 :group 'org
281 :type '(choice
282 (const :tag "Never" nil)
283 (const :tag "When outside special context" t)
284 (const :tag "Everywhere except timestamps" always)))
286 (defgroup org-startup nil
287 "Options concerning startup of Org-mode."
288 :tag "Org Startup"
289 :group 'org)
291 (defcustom org-startup-folded t
292 "Non-nil means, entering Org-mode will switch to OVERVIEW.
293 This can also be configured on a per-file basis by adding one of
294 the following lines anywhere in the buffer:
296 #+STARTUP: fold (or `overview', this is equivalent)
297 #+STARTUP: nofold (or `showall', this is equivalent)
298 #+STARTUP: content
299 #+STARTUP: showeverything"
300 :group 'org-startup
301 :type '(choice
302 (const :tag "nofold: show all" nil)
303 (const :tag "fold: overview" t)
304 (const :tag "content: all headlines" content)
305 (const :tag "show everything, even drawers" showeverything)))
307 (defcustom org-startup-truncated t
308 "Non-nil means, entering Org-mode will set `truncate-lines'.
309 This is useful since some lines containing links can be very long and
310 uninteresting. Also tables look terrible when wrapped."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-startup-indented nil
315 "Non-nil means, turn on `org-indent-mode' on startup.
316 This can also be configured on a per-file basis by adding one of
317 the following lines anywhere in the buffer:
319 #+STARTUP: indent
320 #+STARTUP: noindent"
321 :group 'org-structure
322 :type '(choice
323 (const :tag "Not" nil)
324 (const :tag "Globally (slow on startup in large files)" t)))
326 (defcustom org-startup-with-beamer-mode nil
327 "Non-nil means, turn on `org-beamer-mode' on startup.
328 This can also be configured on a per-file basis by adding one of
329 the following lines anywhere in the buffer:
331 #+STARTUP: beamer"
332 :group 'org-startup
333 :type 'boolean)
335 (defcustom org-startup-align-all-tables nil
336 "Non-nil means, align all tables when visiting a file.
337 This is useful when the column width in tables is forced with <N> cookies
338 in table fields. Such tables will look correct only after the first re-align.
339 This can also be configured on a per-file basis by adding one of
340 the following lines anywhere in the buffer:
341 #+STARTUP: align
342 #+STARTUP: noalign"
343 :group 'org-startup
344 :type 'boolean)
346 (defcustom org-insert-mode-line-in-empty-file nil
347 "Non-nil means insert the first line setting Org-mode in empty files.
348 When the function `org-mode' is called interactively in an empty file, this
349 normally means that the file name does not automatically trigger Org-mode.
350 To ensure that the file will always be in Org-mode in the future, a
351 line enforcing Org-mode will be inserted into the buffer, if this option
352 has been set."
353 :group 'org-startup
354 :type 'boolean)
356 (defcustom org-replace-disputed-keys nil
357 "Non-nil means use alternative key bindings for some keys.
358 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
359 These keys are also used by other packages like shift-selection-mode'
360 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
361 If you want to use Org-mode together with one of these other modes,
362 or more generally if you would like to move some Org-mode commands to
363 other keys, set this variable and configure the keys with the variable
364 `org-disputed-keys'.
366 This option is only relevant at load-time of Org-mode, and must be set
367 *before* org.el is loaded. Changing it requires a restart of Emacs to
368 become effective."
369 :group 'org-startup
370 :type 'boolean)
372 (defcustom org-use-extra-keys nil
373 "Non-nil means use extra key sequence definitions for certain
374 commands. This happens automatically if you run XEmacs or if
375 window-system is nil. This variable lets you do the same
376 manually. You must set it before loading org.
378 Example: on Carbon Emacs 22 running graphically, with an external
379 keyboard on a Powerbook, the default way of setting M-left might
380 not work for either Alt or ESC. Setting this variable will make
381 it work for ESC."
382 :group 'org-startup
383 :type 'boolean)
385 (if (fboundp 'defvaralias)
386 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
388 (defcustom org-disputed-keys
389 '(([(shift up)] . [(meta p)])
390 ([(shift down)] . [(meta n)])
391 ([(shift left)] . [(meta -)])
392 ([(shift right)] . [(meta +)])
393 ([(control shift right)] . [(meta shift +)])
394 ([(control shift left)] . [(meta shift -)]))
395 "Keys for which Org-mode and other modes compete.
396 This is an alist, cars are the default keys, second element specifies
397 the alternative to use when `org-replace-disputed-keys' is t.
399 Keys can be specified in any syntax supported by `define-key'.
400 The value of this option takes effect only at Org-mode's startup,
401 therefore you'll have to restart Emacs to apply it after changing."
402 :group 'org-startup
403 :type 'alist)
405 (defun org-key (key)
406 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
407 Or return the original if not disputed."
408 (if org-replace-disputed-keys
409 (let* ((nkey (key-description key))
410 (x (org-find-if (lambda (x)
411 (equal (key-description (car x)) nkey))
412 org-disputed-keys)))
413 (if x (cdr x) key))
414 key))
416 (defun org-find-if (predicate seq)
417 (catch 'exit
418 (while seq
419 (if (funcall predicate (car seq))
420 (throw 'exit (car seq))
421 (pop seq)))))
423 (defun org-defkey (keymap key def)
424 "Define a key, possibly translated, as returned by `org-key'."
425 (define-key keymap (org-key key) def))
427 (defcustom org-ellipsis nil
428 "The ellipsis to use in the Org-mode outline.
429 When nil, just use the standard three dots. When a string, use that instead,
430 When a face, use the standard 3 dots, but with the specified face.
431 The change affects only Org-mode (which will then use its own display table).
432 Changing this requires executing `M-x org-mode' in a buffer to become
433 effective."
434 :group 'org-startup
435 :type '(choice (const :tag "Default" nil)
436 (face :tag "Face" :value org-warning)
437 (string :tag "String" :value "...#")))
439 (defvar org-display-table nil
440 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
442 (defgroup org-keywords nil
443 "Keywords in Org-mode."
444 :tag "Org Keywords"
445 :group 'org)
447 (defcustom org-deadline-string "DEADLINE:"
448 "String to mark deadline entries.
449 A deadline is this string, followed by a time stamp. Should be a word,
450 terminated by a colon. You can insert a schedule keyword and
451 a timestamp with \\[org-deadline].
452 Changes become only effective after restarting Emacs."
453 :group 'org-keywords
454 :type 'string)
456 (defcustom org-scheduled-string "SCHEDULED:"
457 "String to mark scheduled TODO entries.
458 A schedule is this string, followed by a time stamp. Should be a word,
459 terminated by a colon. You can insert a schedule keyword and
460 a timestamp with \\[org-schedule].
461 Changes become only effective after restarting Emacs."
462 :group 'org-keywords
463 :type 'string)
465 (defcustom org-closed-string "CLOSED:"
466 "String used as the prefix for timestamps logging closing a TODO entry."
467 :group 'org-keywords
468 :type 'string)
470 (defcustom org-clock-string "CLOCK:"
471 "String used as prefix for timestamps clocking work hours on an item."
472 :group 'org-keywords
473 :type 'string)
475 (defcustom org-comment-string "COMMENT"
476 "Entries starting with this keyword will never be exported.
477 An entry can be toggled between COMMENT and normal with
478 \\[org-toggle-comment].
479 Changes become only effective after restarting Emacs."
480 :group 'org-keywords
481 :type 'string)
483 (defcustom org-quote-string "QUOTE"
484 "Entries starting with this keyword will be exported in fixed-width font.
485 Quoting applies only to the text in the entry following the headline, and does
486 not extend beyond the next headline, even if that is lower level.
487 An entry can be toggled between QUOTE and normal with
488 \\[org-toggle-fixed-width-section]."
489 :group 'org-keywords
490 :type 'string)
492 (defconst org-repeat-re
493 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
494 "Regular expression for specifying repeated events.
495 After a match, group 1 contains the repeat expression.")
497 (defgroup org-structure nil
498 "Options concerning the general structure of Org-mode files."
499 :tag "Org Structure"
500 :group 'org)
502 (defgroup org-reveal-location nil
503 "Options about how to make context of a location visible."
504 :tag "Org Reveal Location"
505 :group 'org-structure)
507 (defconst org-context-choice
508 '(choice
509 (const :tag "Always" t)
510 (const :tag "Never" nil)
511 (repeat :greedy t :tag "Individual contexts"
512 (cons
513 (choice :tag "Context"
514 (const agenda)
515 (const org-goto)
516 (const occur-tree)
517 (const tags-tree)
518 (const link-search)
519 (const mark-goto)
520 (const bookmark-jump)
521 (const isearch)
522 (const default))
523 (boolean))))
524 "Contexts for the reveal options.")
526 (defcustom org-show-hierarchy-above '((default . t))
527 "Non-nil means, show full hierarchy when revealing a location.
528 Org-mode often shows locations in an org-mode file which might have
529 been invisible before. When this is set, the hierarchy of headings
530 above the exposed location is shown.
531 Turning this off for example for sparse trees makes them very compact.
532 Instead of t, this can also be an alist specifying this option for different
533 contexts. Valid contexts are
534 agenda when exposing an entry from the agenda
535 org-goto when using the command `org-goto' on key C-c C-j
536 occur-tree when using the command `org-occur' on key C-c /
537 tags-tree when constructing a sparse tree based on tags matches
538 link-search when exposing search matches associated with a link
539 mark-goto when exposing the jump goal of a mark
540 bookmark-jump when exposing a bookmark location
541 isearch when exiting from an incremental search
542 default default for all contexts not set explicitly"
543 :group 'org-reveal-location
544 :type org-context-choice)
546 (defcustom org-show-following-heading '((default . nil))
547 "Non-nil means, show following heading when revealing a location.
548 Org-mode often shows locations in an org-mode file which might have
549 been invisible before. When this is set, the heading following the
550 match is shown.
551 Turning this off for example for sparse trees makes them very compact,
552 but makes it harder to edit the location of the match. In such a case,
553 use the command \\[org-reveal] to show more context.
554 Instead of t, this can also be an alist specifying this option for different
555 contexts. See `org-show-hierarchy-above' for valid contexts."
556 :group 'org-reveal-location
557 :type org-context-choice)
559 (defcustom org-show-siblings '((default . nil) (isearch t))
560 "Non-nil means, show all sibling heading when revealing a location.
561 Org-mode often shows locations in an org-mode file which might have
562 been invisible before. When this is set, the sibling of the current entry
563 heading are all made visible. If `org-show-hierarchy-above' is t,
564 the same happens on each level of the hierarchy above the current entry.
566 By default this is on for the isearch context, off for all other contexts.
567 Turning this off for example for sparse trees makes them very compact,
568 but makes it harder to edit the location of the match. In such a case,
569 use the command \\[org-reveal] to show more context.
570 Instead of t, this can also be an alist specifying this option for different
571 contexts. See `org-show-hierarchy-above' for valid contexts."
572 :group 'org-reveal-location
573 :type org-context-choice)
575 (defcustom org-show-entry-below '((default . nil))
576 "Non-nil means, show the entry below a headline when revealing a location.
577 Org-mode often shows locations in an org-mode file which might have
578 been invisible before. When this is set, the text below the headline that is
579 exposed is also shown.
581 By default this is off for all contexts.
582 Instead of t, this can also be an alist specifying this option for different
583 contexts. See `org-show-hierarchy-above' for valid contexts."
584 :group 'org-reveal-location
585 :type org-context-choice)
587 (defcustom org-indirect-buffer-display 'other-window
588 "How should indirect tree buffers be displayed?
589 This applies to indirect buffers created with the commands
590 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
591 Valid values are:
592 current-window Display in the current window
593 other-window Just display in another window.
594 dedicated-frame Create one new frame, and re-use it each time.
595 new-frame Make a new frame each time. Note that in this case
596 previously-made indirect buffers are kept, and you need to
597 kill these buffers yourself."
598 :group 'org-structure
599 :group 'org-agenda-windows
600 :type '(choice
601 (const :tag "In current window" current-window)
602 (const :tag "In current frame, other window" other-window)
603 (const :tag "Each time a new frame" new-frame)
604 (const :tag "One dedicated frame" dedicated-frame)))
606 (defcustom org-use-speed-commands nil
607 "Non-nil means, activate single letter commands at beginning of a headline.
608 This may also be a function to test for appropriate locations where speed
609 commands should be active."
610 :group 'org-structure
611 :type '(choice
612 (const :tag "Never" nil)
613 (const :tag "At beginning of headline stars" t)
614 (function)))
616 (defcustom org-speed-commands-user nil
617 "Alist of additional speed commands.
618 This list will be checked before `org-speed-commands-default'
619 when the variable `org-use-speed-commands' is non-nil
620 and when the cursor is at the beginning of a headline.
621 The car if each entry is a string with a single letter, which must
622 be assigned to `self-insert-command' in the global map.
623 The cdr is either a command to be called interactively, a function
624 to be called, or a form to be evaluated.
625 An entry that is just a list with a single string will be interpreted
626 as a descriptive headline that will be added when listing the speed
627 copmmands in the Help buffer using the `?' speed command."
628 :group 'org-structure
629 :type '(repeat :value ("k" . ignore)
630 (choice :value ("k" . ignore)
631 (list :tag "Descriptive Headline" (string :tag "Headline"))
632 (cons :tag "Letter and Command"
633 (string :tag "Command letter")
634 (choice
635 (function)
636 (sexp))))))
638 (defgroup org-cycle nil
639 "Options concerning visibility cycling in Org-mode."
640 :tag "Org Cycle"
641 :group 'org-structure)
643 (defcustom org-cycle-skip-children-state-if-no-children t
644 "Non-nil means, skip CHILDREN state in entries that don't have any."
645 :group 'org-cycle
646 :type 'boolean)
648 (defcustom org-cycle-max-level nil
649 "Maximum level which should still be subject to visibility cycling.
650 Levels higher than this will, for cycling, be treated as text, not a headline.
651 When `org-odd-levels-only' is set, a value of N in this variable actually
652 means 2N-1 stars as the limiting headline.
653 When nil, cycle all levels.
654 Note that the limiting level of cycling is also influenced by
655 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
656 `org-inlinetask-min-level' is, cycling will be limited to levels one less
657 than its value."
658 :group 'org-cycle
659 :type '(choice
660 (const :tag "No limit" nil)
661 (integer :tag "Maximum level")))
663 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
664 "Names of drawers. Drawers are not opened by cycling on the headline above.
665 Drawers only open with a TAB on the drawer line itself. A drawer looks like
666 this:
667 :DRAWERNAME:
668 .....
669 :END:
670 The drawer \"PROPERTIES\" is special for capturing properties through
671 the property API.
673 Drawers can be defined on the per-file basis with a line like:
675 #+DRAWERS: HIDDEN STATE PROPERTIES"
676 :group 'org-structure
677 :group 'org-cycle
678 :type '(repeat (string :tag "Drawer Name")))
680 (defcustom org-hide-block-startup nil
681 "Non-nil means, , entering Org-mode will fold all blocks.
682 This can also be set in on a per-file basis with
684 #+STARTUP: hideblocks
685 #+STARTUP: showblocks"
686 :group 'org-startup
687 :group 'org-cycle
688 :type 'boolean)
690 (defcustom org-cycle-global-at-bob nil
691 "Cycle globally if cursor is at beginning of buffer and not at a headline.
692 This makes it possible to do global cycling without having to use S-TAB or
693 C-u TAB. For this special case to work, the first line of the buffer
694 must not be a headline - it may be empty or some other text. When used in
695 this way, `org-cycle-hook' is disables temporarily, to make sure the
696 cursor stays at the beginning of the buffer.
697 When this option is nil, don't do anything special at the beginning
698 of the buffer."
699 :group 'org-cycle
700 :type 'boolean)
702 (defcustom org-cycle-level-after-item/entry-creation t
703 "Non-nil means, cycle entry level or item indentation in new empty entries.
705 When the cursor is at the end of an empty headline, i.e with only stars
706 and maybe a TODO keyword, TAB will then switch the entry to become a child,
707 and then all possible anchestor states, before returning to the original state.
708 This makes data entry extremely fast: M-RET to create a new headline,
709 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
711 When the cursor is at the end of an empty plain list item, one TAB will
712 make it a subitem, two or more tabs will back up to make this an item
713 higher up in the item hierarchy."
714 :group 'org-cycle
715 :type 'boolean)
717 (defcustom org-cycle-emulate-tab t
718 "Where should `org-cycle' emulate TAB.
719 nil Never
720 white Only in completely white lines
721 whitestart Only at the beginning of lines, before the first non-white char
722 t Everywhere except in headlines
723 exc-hl-bol Everywhere except at the start of a headline
724 If TAB is used in a place where it does not emulate TAB, the current subtree
725 visibility is cycled."
726 :group 'org-cycle
727 :type '(choice (const :tag "Never" nil)
728 (const :tag "Only in completely white lines" white)
729 (const :tag "Before first char in a line" whitestart)
730 (const :tag "Everywhere except in headlines" t)
731 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
734 (defcustom org-cycle-separator-lines 2
735 "Number of empty lines needed to keep an empty line between collapsed trees.
736 If you leave an empty line between the end of a subtree and the following
737 headline, this empty line is hidden when the subtree is folded.
738 Org-mode will leave (exactly) one empty line visible if the number of
739 empty lines is equal or larger to the number given in this variable.
740 So the default 2 means, at least 2 empty lines after the end of a subtree
741 are needed to produce free space between a collapsed subtree and the
742 following headline.
744 If the number is negative, and the number of empty lines is at least -N,
745 all empty lines are shown.
747 Special case: when 0, never leave empty lines in collapsed view."
748 :group 'org-cycle
749 :type 'integer)
750 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
752 (defcustom org-pre-cycle-hook nil
753 "Hook that is run before visibility cycling is happening.
754 The function(s) in this hook must accept a single argument which indicates
755 the new state that will be set right after running this hook. The
756 argument is a symbol. Before a global state change, it can have the values
757 `overview', `content', or `all'. Before a local state change, it can have
758 the values `folded', `children', or `subtree'."
759 :group 'org-cycle
760 :type 'hook)
762 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
763 org-cycle-hide-drawers
764 org-cycle-show-empty-lines
765 org-optimize-window-after-visibility-change)
766 "Hook that is run after `org-cycle' has changed the buffer visibility.
767 The function(s) in this hook must accept a single argument which indicates
768 the new state that was set by the most recent `org-cycle' command. The
769 argument is a symbol. After a global state change, it can have the values
770 `overview', `content', or `all'. After a local state change, it can have
771 the values `folded', `children', or `subtree'."
772 :group 'org-cycle
773 :type 'hook)
775 (defgroup org-edit-structure nil
776 "Options concerning structure editing in Org-mode."
777 :tag "Org Edit Structure"
778 :group 'org-structure)
780 (defcustom org-odd-levels-only nil
781 "Non-nil means, skip even levels and only use odd levels for the outline.
782 This has the effect that two stars are being added/taken away in
783 promotion/demotion commands. It also influences how levels are
784 handled by the exporters.
785 Changing it requires restart of `font-lock-mode' to become effective
786 for fontification also in regions already fontified.
787 You may also set this on a per-file basis by adding one of the following
788 lines to the buffer:
790 #+STARTUP: odd
791 #+STARTUP: oddeven"
792 :group 'org-edit-structure
793 :group 'org-font-lock
794 :type 'boolean)
796 (defcustom org-adapt-indentation t
797 "Non-nil means, adapt indentation to outline node level.
799 When this variable is set, Org assumes that you write outlines by
800 indenting text in each node to align with the headline (after the stars).
801 The following issues are influenced by this variable:
803 - When this is set and the *entire* text in an entry is indented, the
804 indentation is increased by one space in a demotion command, and
805 decreased by one in a promotion command. If any line in the entry
806 body starts with text at column 0, indentation is not changed at all.
808 - Property drawers and planning information is inserted indented when
809 this variable s set. When nil, they will not be indented.
811 - TAB indents a line relative to context. The lines below a headline
812 will be indented when this variable is set.
814 Note that this is all about true indentation, by adding and removing
815 space characters. See also `org-indent.el' which does level-dependent
816 indentation in a virtual way, i.e. at display time in Emacs."
817 :group 'org-edit-structure
818 :type 'boolean)
820 (defcustom org-special-ctrl-a/e nil
821 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
823 When t, `C-a' will bring back the cursor to the beginning of the
824 headline text, i.e. after the stars and after a possible TODO keyword.
825 In an item, this will be the position after the bullet.
826 When the cursor is already at that position, another `C-a' will bring
827 it to the beginning of the line.
829 `C-e' will jump to the end of the headline, ignoring the presence of tags
830 in the headline. A second `C-e' will then jump to the true end of the
831 line, after any tags. This also means that, when this variable is
832 non-nil, `C-e' also will never jump beyond the end of the heading of a
833 folded section, i.e. not after the ellipses.
835 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
836 going to the true line boundary first. Only a directly following, identical
837 keypress will bring the cursor to the special positions.
839 This may also be a cons cell where the behavior for `C-a' and `C-e' is
840 set separately."
841 :group 'org-edit-structure
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on: after stars/bullet and before tags first" t)
845 (const :tag "reversed: true line boundary first" reversed)
846 (cons :tag "Set C-a and C-e separately"
847 (choice :tag "Special C-a"
848 (const :tag "off" nil)
849 (const :tag "on: after stars/bullet first" t)
850 (const :tag "reversed: before stars/bullet first" reversed))
851 (choice :tag "Special C-e"
852 (const :tag "off" nil)
853 (const :tag "on: before tags first" t)
854 (const :tag "reversed: after tags first" reversed)))))
855 (if (fboundp 'defvaralias)
856 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
858 (defcustom org-special-ctrl-k nil
859 "Non-nil means `C-k' will behave specially in headlines.
860 When nil, `C-k' will call the default `kill-line' command.
861 When t, the following will happen while the cursor is in the headline:
863 - When the cursor is at the beginning of a headline, kill the entire
864 line and possible the folded subtree below the line.
865 - When in the middle of the headline text, kill the headline up to the tags.
866 - When after the headline text, kill the tags."
867 :group 'org-edit-structure
868 :type 'boolean)
870 (defcustom org-yank-folded-subtrees t
871 "Non-nil means, when yanking subtrees, fold them.
872 If the kill is a single subtree, or a sequence of subtrees, i.e. if
873 it starts with a heading and all other headings in it are either children
874 or siblings, then fold all the subtrees. However, do this only if no
875 text after the yank would be swallowed into a folded tree by this action."
876 :group 'org-edit-structure
877 :type 'boolean)
879 (defcustom org-yank-adjusted-subtrees nil
880 "Non-nil means, when yanking subtrees, adjust the level.
881 With this setting, `org-paste-subtree' is used to insert the subtree, see
882 this function for details."
883 :group 'org-edit-structure
884 :type 'boolean)
886 (defcustom org-M-RET-may-split-line '((default . t))
887 "Non-nil means, M-RET will split the line at the cursor position.
888 When nil, it will go to the end of the line before making a
889 new line.
890 You may also set this option in a different way for different
891 contexts. Valid contexts are:
893 headline when creating a new headline
894 item when creating a new item
895 table in a table field
896 default the value to be used for all contexts not explicitly
897 customized"
898 :group 'org-structure
899 :group 'org-table
900 :type '(choice
901 (const :tag "Always" t)
902 (const :tag "Never" nil)
903 (repeat :greedy t :tag "Individual contexts"
904 (cons
905 (choice :tag "Context"
906 (const headline)
907 (const item)
908 (const table)
909 (const default))
910 (boolean)))))
913 (defcustom org-insert-heading-respect-content nil
914 "Non-nil means, insert new headings after the current subtree.
915 When nil, the new heading is created directly after the current line.
916 The commands \\[org-insert-heading-respect-content] and
917 \\[org-insert-todo-heading-respect-content] turn this variable on
918 for the duration of the command."
919 :group 'org-structure
920 :type 'boolean)
922 (defcustom org-blank-before-new-entry '((heading . auto)
923 (plain-list-item . auto))
924 "Should `org-insert-heading' leave a blank line before new heading/item?
925 The value is an alist, with `heading' and `plain-list-item' as car,
926 and a boolean flag as cdr. For plain lists, if the variable
927 `org-empty-line-terminates-plain-lists' is set, the setting here
928 is ignored and no empty line is inserted, to keep the list in tact."
929 :group 'org-edit-structure
930 :type '(list
931 (cons (const heading)
932 (choice (const :tag "Never" nil)
933 (const :tag "Always" t)
934 (const :tag "Auto" auto)))
935 (cons (const plain-list-item)
936 (choice (const :tag "Never" nil)
937 (const :tag "Always" t)
938 (const :tag "Auto" auto)))))
940 (defcustom org-insert-heading-hook nil
941 "Hook being run after inserting a new heading."
942 :group 'org-edit-structure
943 :type 'hook)
945 (defcustom org-enable-fixed-width-editor t
946 "Non-nil means, lines starting with \":\" are treated as fixed-width.
947 This currently only means, they are never auto-wrapped.
948 When nil, such lines will be treated like ordinary lines.
949 See also the QUOTE keyword."
950 :group 'org-edit-structure
951 :type 'boolean)
954 (defcustom org-goto-auto-isearch t
955 "Non-nil means, typing characters in org-goto starts incremental search."
956 :group 'org-edit-structure
957 :type 'boolean)
959 (defgroup org-sparse-trees nil
960 "Options concerning sparse trees in Org-mode."
961 :tag "Org Sparse Trees"
962 :group 'org-structure)
964 (defcustom org-highlight-sparse-tree-matches t
965 "Non-nil means, highlight all matches that define a sparse tree.
966 The highlights will automatically disappear the next time the buffer is
967 changed by an edit command."
968 :group 'org-sparse-trees
969 :type 'boolean)
971 (defcustom org-remove-highlights-with-change t
972 "Non-nil means, any change to the buffer will remove temporary highlights.
973 Such highlights are created by `org-occur' and `org-clock-display'.
974 When nil, `C-c C-c needs to be used to get rid of the highlights.
975 The highlights created by `org-preview-latex-fragment' always need
976 `C-c C-c' to be removed."
977 :group 'org-sparse-trees
978 :group 'org-time
979 :type 'boolean)
982 (defcustom org-occur-hook '(org-first-headline-recenter)
983 "Hook that is run after `org-occur' has constructed a sparse tree.
984 This can be used to recenter the window to show as much of the structure
985 as possible."
986 :group 'org-sparse-trees
987 :type 'hook)
989 (defgroup org-imenu-and-speedbar nil
990 "Options concerning imenu and speedbar in Org-mode."
991 :tag "Org Imenu and Speedbar"
992 :group 'org-structure)
994 (defcustom org-imenu-depth 2
995 "The maximum level for Imenu access to Org-mode headlines.
996 This also applied for speedbar access."
997 :group 'org-imenu-and-speedbar
998 :type 'integer)
1000 (defgroup org-table nil
1001 "Options concerning tables in Org-mode."
1002 :tag "Org Table"
1003 :group 'org)
1005 (defcustom org-enable-table-editor 'optimized
1006 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1007 When nil, such lines will be treated like ordinary lines.
1009 When equal to the symbol `optimized', the table editor will be optimized to
1010 do the following:
1011 - Automatic overwrite mode in front of whitespace in table fields.
1012 This makes the structure of the table stay in tact as long as the edited
1013 field does not exceed the column width.
1014 - Minimize the number of realigns. Normally, the table is aligned each time
1015 TAB or RET are pressed to move to another field. With optimization this
1016 happens only if changes to a field might have changed the column width.
1017 Optimization requires replacing the functions `self-insert-command',
1018 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1019 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1020 very good at guessing when a re-align will be necessary, but you can always
1021 force one with \\[org-ctrl-c-ctrl-c].
1023 If you would like to use the optimized version in Org-mode, but the
1024 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1026 This variable can be used to turn on and off the table editor during a session,
1027 but in order to toggle optimization, a restart is required.
1029 See also the variable `org-table-auto-blank-field'."
1030 :group 'org-table
1031 :type '(choice
1032 (const :tag "off" nil)
1033 (const :tag "on" t)
1034 (const :tag "on, optimized" optimized)))
1036 (defcustom org-self-insert-cluster-for-undo t
1037 "Non-nil means cluster self-insert commands for undo when possible.
1038 If this is set, then, like in the Emacs command loop, 20 consecutive
1039 characters will be undone together.
1040 This is configurable, because there is some impact on typing performance."
1041 :group 'org-table
1042 :type 'boolean)
1044 (defcustom org-table-tab-recognizes-table.el t
1045 "Non-nil means, TAB will automatically notice a table.el table.
1046 When it sees such a table, it moves point into it and - if necessary -
1047 calls `table-recognize-table'."
1048 :group 'org-table-editing
1049 :type 'boolean)
1051 (defgroup org-link nil
1052 "Options concerning links in Org-mode."
1053 :tag "Org Link"
1054 :group 'org)
1056 (defvar org-link-abbrev-alist-local nil
1057 "Buffer-local version of `org-link-abbrev-alist', which see.
1058 The value of this is taken from the #+LINK lines.")
1059 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1061 (defcustom org-link-abbrev-alist nil
1062 "Alist of link abbreviations.
1063 The car of each element is a string, to be replaced at the start of a link.
1064 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1065 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1067 [[linkkey:tag][description]]
1069 The 'linkkey' must be a word word, starting with a letter, followed
1070 by letters, numbers, '-' or '_'.
1072 If REPLACE is a string, the tag will simply be appended to create the link.
1073 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1074 the placeholder \"%h\" will cause a url-encoded version of the tag to
1075 be inserted at that point (see the function `url-hexify-string').
1077 REPLACE may also be a function that will be called with the tag as the
1078 only argument to create the link, which should be returned as a string.
1080 See the manual for examples."
1081 :group 'org-link
1082 :type '(repeat
1083 (cons
1084 (string :tag "Protocol")
1085 (choice
1086 (string :tag "Format")
1087 (function)))))
1089 (defcustom org-descriptive-links t
1090 "Non-nil means, hide link part and only show description of bracket links.
1091 Bracket links are like [[link][description]]. This variable sets the initial
1092 state in new org-mode buffers. The setting can then be toggled on a
1093 per-buffer basis from the Org->Hyperlinks menu."
1094 :group 'org-link
1095 :type 'boolean)
1097 (defcustom org-link-file-path-type 'adaptive
1098 "How the path name in file links should be stored.
1099 Valid values are:
1101 relative Relative to the current directory, i.e. the directory of the file
1102 into which the link is being inserted.
1103 absolute Absolute path, if possible with ~ for home directory.
1104 noabbrev Absolute path, no abbreviation of home directory.
1105 adaptive Use relative path for files in the current directory and sub-
1106 directories of it. For other files, use an absolute path."
1107 :group 'org-link
1108 :type '(choice
1109 (const relative)
1110 (const absolute)
1111 (const noabbrev)
1112 (const adaptive)))
1114 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1115 "Types of links that should be activated in Org-mode files.
1116 This is a list of symbols, each leading to the activation of a certain link
1117 type. In principle, it does not hurt to turn on most link types - there may
1118 be a small gain when turning off unused link types. The types are:
1120 bracket The recommended [[link][description]] or [[link]] links with hiding.
1121 angular Links in angular brackets that may contain whitespace like
1122 <bbdb:Carsten Dominik>.
1123 plain Plain links in normal text, no whitespace, like http://google.com.
1124 radio Text that is matched by a radio target, see manual for details.
1125 tag Tag settings in a headline (link to tag search).
1126 date Time stamps (link to calendar).
1127 footnote Footnote labels.
1129 Changing this variable requires a restart of Emacs to become effective."
1130 :group 'org-link
1131 :type '(set :greedy t
1132 (const :tag "Double bracket links (new style)" bracket)
1133 (const :tag "Angular bracket links (old style)" angular)
1134 (const :tag "Plain text links" plain)
1135 (const :tag "Radio target matches" radio)
1136 (const :tag "Tags" tag)
1137 (const :tag "Timestamps" date)
1138 (const :tag "Footnotes" footnote)))
1140 (defcustom org-make-link-description-function nil
1141 "Function to use to generate link descriptions from links. If
1142 nil the link location will be used. This function must take two
1143 parameters; the first is the link and the second the description
1144 org-insert-link has generated, and should return the description
1145 to use."
1146 :group 'org-link
1147 :type 'function)
1149 (defgroup org-link-store nil
1150 "Options concerning storing links in Org-mode."
1151 :tag "Org Store Link"
1152 :group 'org-link)
1154 (defcustom org-email-link-description-format "Email %c: %.30s"
1155 "Format of the description part of a link to an email or usenet message.
1156 The following %-escapes will be replaced by corresponding information:
1158 %F full \"From\" field
1159 %f name, taken from \"From\" field, address if no name
1160 %T full \"To\" field
1161 %t first name in \"To\" field, address if no name
1162 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1163 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1164 %s subject
1165 %m message-id.
1167 You may use normal field width specification between the % and the letter.
1168 This is for example useful to limit the length of the subject.
1170 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1171 :group 'org-link-store
1172 :type 'string)
1174 (defcustom org-from-is-user-regexp
1175 (let (r1 r2)
1176 (when (and user-mail-address (not (string= user-mail-address "")))
1177 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1178 (when (and user-full-name (not (string= user-full-name "")))
1179 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1180 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1181 "Regexp matched against the \"From:\" header of an email or usenet message.
1182 It should match if the message is from the user him/herself."
1183 :group 'org-link-store
1184 :type 'regexp)
1186 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1187 "Non-nil means, storing a link to an Org file will use entry IDs.
1189 Note that before this variable is even considered, org-id must be loaded,
1190 so please customize `org-modules' and turn it on.
1192 The variable can have the following values:
1194 t Create an ID if needed to make a link to the current entry.
1196 create-if-interactive
1197 If `org-store-link' is called directly (interactively, as a user
1198 command), do create an ID to support the link. But when doing the
1199 job for remember, only use the ID if it already exists. The
1200 purpose of this setting is to avoid proliferation of unwanted
1201 IDs, just because you happen to be in an Org file when you
1202 call `org-remember' that automatically and preemptively
1203 creates a link. If you do want to get an ID link in a remember
1204 template to an entry not having an ID, create it first by
1205 explicitly creating a link to it, using `C-c C-l' first.
1207 create-if-interactive-and-no-custom-id
1208 Like create-if-interactive, but do not create an ID if there is
1209 a CUSTOM_ID property defined in the entry. This is the default.
1211 use-existing
1212 Use existing ID, do not create one.
1214 nil Never use an ID to make a link, instead link using a text search for
1215 the headline text."
1216 :group 'org-link-store
1217 :type '(choice
1218 (const :tag "Create ID to make link" t)
1219 (const :tag "Create if storing link interactively"
1220 create-if-interactive)
1221 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1222 create-if-interactive-and-no-custom-id)
1223 (const :tag "Only use existing" use-existing)
1224 (const :tag "Do not use ID to create link" nil)))
1226 (defcustom org-context-in-file-links t
1227 "Non-nil means, file links from `org-store-link' contain context.
1228 A search string will be added to the file name with :: as separator and
1229 used to find the context when the link is activated by the command
1230 `org-open-at-point'.
1231 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1232 negates this setting for the duration of the command."
1233 :group 'org-link-store
1234 :type 'boolean)
1236 (defcustom org-keep-stored-link-after-insertion nil
1237 "Non-nil means, keep link in list for entire session.
1239 The command `org-store-link' adds a link pointing to the current
1240 location to an internal list. These links accumulate during a session.
1241 The command `org-insert-link' can be used to insert links into any
1242 Org-mode file (offering completion for all stored links). When this
1243 option is nil, every link which has been inserted once using \\[org-insert-link]
1244 will be removed from the list, to make completing the unused links
1245 more efficient."
1246 :group 'org-link-store
1247 :type 'boolean)
1249 (defgroup org-link-follow nil
1250 "Options concerning following links in Org-mode."
1251 :tag "Org Follow Link"
1252 :group 'org-link)
1254 (defcustom org-link-translation-function nil
1255 "Function to translate links with different syntax to Org syntax.
1256 This can be used to translate links created for example by the Planner
1257 or emacs-wiki packages to Org syntax.
1258 The function must accept two parameters, a TYPE containing the link
1259 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1260 which is everything after the link protocol. It should return a cons
1261 with possibly modified values of type and path.
1262 Org contains a function for this, so if you set this variable to
1263 `org-translate-link-from-planner', you should be able follow many
1264 links created by planner."
1265 :group 'org-link-follow
1266 :type 'function)
1268 (defcustom org-follow-link-hook nil
1269 "Hook that is run after a link has been followed."
1270 :group 'org-link-follow
1271 :type 'hook)
1273 (defcustom org-tab-follows-link nil
1274 "Non-nil means, on links TAB will follow the link.
1275 Needs to be set before org.el is loaded.
1276 This really should not be used, it does not make sense, and the
1277 implementation is bad."
1278 :group 'org-link-follow
1279 :type 'boolean)
1281 (defcustom org-return-follows-link nil
1282 "Non-nil means, on links RET will follow the link.
1283 Needs to be set before org.el is loaded."
1284 :group 'org-link-follow
1285 :type 'boolean)
1287 (defcustom org-mouse-1-follows-link
1288 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1289 "Non-nil means, mouse-1 on a link will follow the link.
1290 A longer mouse click will still set point. Does not work on XEmacs.
1291 Needs to be set before org.el is loaded."
1292 :group 'org-link-follow
1293 :type 'boolean)
1295 (defcustom org-mark-ring-length 4
1296 "Number of different positions to be recorded in the ring
1297 Changing this requires a restart of Emacs to work correctly."
1298 :group 'org-link-follow
1299 :type 'integer)
1301 (defcustom org-link-frame-setup
1302 '((vm . vm-visit-folder-other-frame)
1303 (gnus . gnus-other-frame)
1304 (file . find-file-other-window))
1305 "Setup the frame configuration for following links.
1306 When following a link with Emacs, it may often be useful to display
1307 this link in another window or frame. This variable can be used to
1308 set this up for the different types of links.
1309 For VM, use any of
1310 `vm-visit-folder'
1311 `vm-visit-folder-other-frame'
1312 For Gnus, use any of
1313 `gnus'
1314 `gnus-other-frame'
1315 `org-gnus-no-new-news'
1316 For FILE, use any of
1317 `find-file'
1318 `find-file-other-window'
1319 `find-file-other-frame'
1320 For the calendar, use the variable `calendar-setup'.
1321 For BBDB, it is currently only possible to display the matches in
1322 another window."
1323 :group 'org-link-follow
1324 :type '(list
1325 (cons (const vm)
1326 (choice
1327 (const vm-visit-folder)
1328 (const vm-visit-folder-other-window)
1329 (const vm-visit-folder-other-frame)))
1330 (cons (const gnus)
1331 (choice
1332 (const gnus)
1333 (const gnus-other-frame)
1334 (const org-gnus-no-new-news)))
1335 (cons (const file)
1336 (choice
1337 (const find-file)
1338 (const find-file-other-window)
1339 (const find-file-other-frame)))))
1341 (defcustom org-display-internal-link-with-indirect-buffer nil
1342 "Non-nil means, use indirect buffer to display infile links.
1343 Activating internal links (from one location in a file to another location
1344 in the same file) normally just jumps to the location. When the link is
1345 activated with a C-u prefix (or with mouse-3), the link is displayed in
1346 another window. When this option is set, the other window actually displays
1347 an indirect buffer clone of the current buffer, to avoid any visibility
1348 changes to the current buffer."
1349 :group 'org-link-follow
1350 :type 'boolean)
1352 (defcustom org-open-non-existing-files nil
1353 "Non-nil means, `org-open-file' will open non-existing files.
1354 When nil, an error will be generated.
1355 This variable applies only to external applications because they
1356 might choke on non-existing files. If the link is to a file that
1357 will be opened in Emacs, the variable is ignored."
1358 :group 'org-link-follow
1359 :type 'boolean)
1361 (defcustom org-open-directory-means-index-dot-org nil
1362 "Non-nil means, a link to a directory really means to index.org.
1363 When nil, following a directory link will run dired or open a finder/explorer
1364 window on that directory."
1365 :group 'org-link-follow
1366 :type 'boolean)
1368 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1369 "Function and arguments to call for following mailto links.
1370 This is a list with the first element being a lisp function, and the
1371 remaining elements being arguments to the function. In string arguments,
1372 %a will be replaced by the address, and %s will be replaced by the subject
1373 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1374 :group 'org-link-follow
1375 :type '(choice
1376 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1377 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1378 (const :tag "message-mail" (message-mail "%a" "%s"))
1379 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1381 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1382 "Non-nil means, ask for confirmation before executing shell links.
1383 Shell links can be dangerous: just think about a link
1385 [[shell:rm -rf ~/*][Google Search]]
1387 This link would show up in your Org-mode document as \"Google Search\",
1388 but really it would remove your entire home directory.
1389 Therefore we advise against setting this variable to nil.
1390 Just change it to `y-or-n-p' if you want to confirm with a
1391 single keystroke rather than having to type \"yes\"."
1392 :group 'org-link-follow
1393 :type '(choice
1394 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1395 (const :tag "with y-or-n (faster)" y-or-n-p)
1396 (const :tag "no confirmation (dangerous)" nil)))
1398 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1399 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1400 Elisp links can be dangerous: just think about a link
1402 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1404 This link would show up in your Org-mode document as \"Google Search\",
1405 but really it would remove your entire home directory.
1406 Therefore we advise against setting this variable to nil.
1407 Just change it to `y-or-n-p' if you want to confirm with a
1408 single keystroke rather than having to type \"yes\"."
1409 :group 'org-link-follow
1410 :type '(choice
1411 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1412 (const :tag "with y-or-n (faster)" y-or-n-p)
1413 (const :tag "no confirmation (dangerous)" nil)))
1415 (defconst org-file-apps-defaults-gnu
1416 '((remote . emacs)
1417 (system . mailcap)
1418 (t . mailcap))
1419 "Default file applications on a UNIX or GNU/Linux system.
1420 See `org-file-apps'.")
1422 (defconst org-file-apps-defaults-macosx
1423 '((remote . emacs)
1424 (t . "open %s")
1425 (system . "open %s")
1426 ("ps.gz" . "gv %s")
1427 ("eps.gz" . "gv %s")
1428 ("dvi" . "xdvi %s")
1429 ("fig" . "xfig %s"))
1430 "Default file applications on a MacOS X system.
1431 The system \"open\" is known as a default, but we use X11 applications
1432 for some files for which the OS does not have a good default.
1433 See `org-file-apps'.")
1435 (defconst org-file-apps-defaults-windowsnt
1436 (list
1437 '(remote . emacs)
1438 (cons t
1439 (list (if (featurep 'xemacs)
1440 'mswindows-shell-execute
1441 'w32-shell-execute)
1442 "open" 'file))
1443 (cons 'system
1444 (list (if (featurep 'xemacs)
1445 'mswindows-shell-execute
1446 'w32-shell-execute)
1447 "open" 'file)))
1448 "Default file applications on a Windows NT system.
1449 The system \"open\" is used for most files.
1450 See `org-file-apps'.")
1452 (defcustom org-file-apps
1454 (auto-mode . emacs)
1455 ("\\.mm\\'" . default)
1456 ("\\.x?html?\\'" . default)
1457 ("\\.pdf\\'" . default)
1459 "External applications for opening `file:path' items in a document.
1460 Org-mode uses system defaults for different file types, but
1461 you can use this variable to set the application for a given file
1462 extension. The entries in this list are cons cells where the car identifies
1463 files and the cdr the corresponding command. Possible values for the
1464 file identifier are
1465 \"regex\" Regular expression matched against the file name. For backward
1466 compatibility, this can also be a string with only alphanumeric
1467 characters, which is then interpreted as an extension.
1468 `directory' Matches a directory
1469 `remote' Matches a remote file, accessible through tramp or efs.
1470 Remote files most likely should be visited through Emacs
1471 because external applications cannot handle such paths.
1472 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1473 so all files Emacs knows how to handle. Using this with
1474 command `emacs' will open most files in Emacs. Beware that this
1475 will also open html files inside Emacs, unless you add
1476 (\"html\" . default) to the list as well.
1477 t Default for files not matched by any of the other options.
1478 `system' The system command to open files, like `open' on Windows
1479 and Mac OS X, and mailcap under GNU/Linux. This is the command
1480 that will be selected if you call `C-c C-o' with a double
1481 `C-u C-u' prefix.
1483 Possible values for the command are:
1484 `emacs' The file will be visited by the current Emacs process.
1485 `default' Use the default application for this file type, which is the
1486 association for t in the list, most likely in the system-specific
1487 part.
1488 This can be used to overrule an unwanted setting in the
1489 system-specific variable.
1490 `system' Use the system command for opening files, like \"open\".
1491 This command is specified by the entry whose car is `system'.
1492 Most likely, the system-specific version of this variable
1493 does define this command, but you can overrule/replace it
1494 here.
1495 string A command to be executed by a shell; %s will be replaced
1496 by the path to the file.
1497 sexp A Lisp form which will be evaluated. The file path will
1498 be available in the Lisp variable `file'.
1499 For more examples, see the system specific constants
1500 `org-file-apps-defaults-macosx'
1501 `org-file-apps-defaults-windowsnt'
1502 `org-file-apps-defaults-gnu'."
1503 :group 'org-link-follow
1504 :type '(repeat
1505 (cons (choice :value ""
1506 (string :tag "Extension")
1507 (const :tag "System command to open files" system)
1508 (const :tag "Default for unrecognized files" t)
1509 (const :tag "Remote file" remote)
1510 (const :tag "Links to a directory" directory)
1511 (const :tag "Any files that have Emacs modes"
1512 auto-mode))
1513 (choice :value ""
1514 (const :tag "Visit with Emacs" emacs)
1515 (const :tag "Use default" default)
1516 (const :tag "Use the system command" system)
1517 (string :tag "Command")
1518 (sexp :tag "Lisp form")))))
1520 (defgroup org-refile nil
1521 "Options concerning refiling entries in Org-mode."
1522 :tag "Org Refile"
1523 :group 'org)
1525 (defcustom org-directory "~/org"
1526 "Directory with org files.
1527 This is just a default location to look for Org files. There is no need
1528 at all to put your files into this directory. It is only used in the
1529 following situations:
1531 1. When a remember template specifies a target file that is not an
1532 absolute path. The path will then be interpreted relative to
1533 `org-directory'
1534 2. When a remember note is filed away in an interactive way (when exiting the
1535 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1536 with `org-directory' as the default path."
1537 :group 'org-refile
1538 :group 'org-remember
1539 :type 'directory)
1541 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1542 "Default target for storing notes.
1543 Used by the hooks for remember.el. This can be a string, or nil to mean
1544 the value of `remember-data-file'.
1545 You can set this on a per-template basis with the variable
1546 `org-remember-templates'."
1547 :group 'org-refile
1548 :group 'org-remember
1549 :type '(choice
1550 (const :tag "Default from remember-data-file" nil)
1551 file))
1553 (defcustom org-goto-interface 'outline
1554 "The default interface to be used for `org-goto'.
1555 Allowed values are:
1556 outline The interface shows an outline of the relevant file
1557 and the correct heading is found by moving through
1558 the outline or by searching with incremental search.
1559 outline-path-completion Headlines in the current buffer are offered via
1560 completion. This is the interface also used by
1561 the refile command."
1562 :group 'org-refile
1563 :type '(choice
1564 (const :tag "Outline" outline)
1565 (const :tag "Outline-path-completion" outline-path-completion)))
1567 (defcustom org-goto-max-level 5
1568 "Maximum level to be considered when running org-goto with refile interface."
1569 :group 'org-refile
1570 :type 'integer)
1572 (defcustom org-reverse-note-order nil
1573 "Non-nil means, store new notes at the beginning of a file or entry.
1574 When nil, new notes will be filed to the end of a file or entry.
1575 This can also be a list with cons cells of regular expressions that
1576 are matched against file names, and values."
1577 :group 'org-remember
1578 :group 'org-refile
1579 :type '(choice
1580 (const :tag "Reverse always" t)
1581 (const :tag "Reverse never" nil)
1582 (repeat :tag "By file name regexp"
1583 (cons regexp boolean))))
1585 (defcustom org-refile-targets nil
1586 "Targets for refiling entries with \\[org-refile].
1587 This is list of cons cells. Each cell contains:
1588 - a specification of the files to be considered, either a list of files,
1589 or a symbol whose function or variable value will be used to retrieve
1590 a file name or a list of file names. If you use `org-agenda-files' for
1591 that, all agenda files will be scanned for targets. Nil means, consider
1592 headings in the current buffer.
1593 - A specification of how to find candidate refile targets. This may be
1594 any of:
1595 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1596 This tag has to be present in all target headlines, inheritance will
1597 not be considered.
1598 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1599 todo keyword.
1600 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1601 headlines that are refiling targets.
1602 - a cons cell (:level . N). Any headline of level N is considered a target.
1603 Note that, when `org-odd-levels-only' is set, level corresponds to
1604 order in hierarchy, not to the number of stars.
1605 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1606 Note that, when `org-odd-levels-only' is set, level corresponds to
1607 order in hierarchy, not to the number of stars.
1609 You can set the variable `org-refile-target-verify-function' to a function
1610 to verify each headline found by the simple critery above.
1612 When this variable is nil, all top-level headlines in the current buffer
1613 are used, equivalent to the value `((nil . (:level . 1))'."
1614 :group 'org-refile
1615 :type '(repeat
1616 (cons
1617 (choice :value org-agenda-files
1618 (const :tag "All agenda files" org-agenda-files)
1619 (const :tag "Current buffer" nil)
1620 (function) (variable) (file))
1621 (choice :tag "Identify target headline by"
1622 (cons :tag "Specific tag" (const :value :tag) (string))
1623 (cons :tag "TODO keyword" (const :value :todo) (string))
1624 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1625 (cons :tag "Level number" (const :value :level) (integer))
1626 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1628 (defcustom org-refile-target-verify-function nil
1629 "Function to verify if the headline at point should be a refile target.
1630 The function will be called without arguments, with point at the
1631 beginning of the headline. It should return t and leave point
1632 where it is if the headline is a valid target for refiling.
1634 If the target should not be selected, the function must return nil.
1635 In addition to this, it may move point to a place from where the search
1636 should be continued. For example, the function may decide that the entire
1637 subtree of the current entry should be excluded and move point to the end
1638 of the subtree."
1639 :group 'org-refile
1640 :type 'function)
1642 (defcustom org-refile-use-outline-path nil
1643 "Non-nil means, provide refile targets as paths.
1644 So a level 3 headline will be available as level1/level2/level3.
1646 When the value is `file', also include the file name (without directory)
1647 into the path. In this case, you can also stop the completion after
1648 the file name, to get entries inserted as top level in the file.
1650 When `full-file-path', include the full file path."
1651 :group 'org-refile
1652 :type '(choice
1653 (const :tag "Not" nil)
1654 (const :tag "Yes" t)
1655 (const :tag "Start with file name" file)
1656 (const :tag "Start with full file path" full-file-path)))
1658 (defcustom org-outline-path-complete-in-steps t
1659 "Non-nil means, complete the outline path in hierarchical steps.
1660 When Org-mode uses the refile interface to select an outline path
1661 \(see variable `org-refile-use-outline-path'), the completion of
1662 the path can be done is a single go, or if can be done in steps down
1663 the headline hierarchy. Going in steps is probably the best if you
1664 do not use a special completion package like `ido' or `icicles'.
1665 However, when using these packages, going in one step can be very
1666 fast, while still showing the whole path to the entry."
1667 :group 'org-refile
1668 :type 'boolean)
1670 (defcustom org-refile-allow-creating-parent-nodes nil
1671 "Non-nil means, allow to create new nodes as refile targets.
1672 New nodes are then created by adding \"/new node name\" to the completion
1673 of an existing node. When the value of this variable is `confirm',
1674 new node creation must be confirmed by the user (recommended)
1675 When nil, the completion must match an existing entry.
1677 Note that, if the new heading is not seen by the criteria
1678 listed in `org-refile-targets', multiple instances of the same
1679 heading would be created by trying again to file under the new
1680 heading."
1681 :group 'org-refile
1682 :type '(choice
1683 (const :tag "Never" nil)
1684 (const :tag "Always" t)
1685 (const :tag "Prompt for confirmation" confirm)))
1687 (defgroup org-todo nil
1688 "Options concerning TODO items in Org-mode."
1689 :tag "Org TODO"
1690 :group 'org)
1692 (defgroup org-progress nil
1693 "Options concerning Progress logging in Org-mode."
1694 :tag "Org Progress"
1695 :group 'org-time)
1697 (defvar org-todo-interpretation-widgets
1699 (:tag "Sequence (cycling hits every state)" sequence)
1700 (:tag "Type (cycling directly to DONE)" type))
1701 "The available interpretation symbols for customizing
1702 `org-todo-keywords'.
1703 Interested libraries should add to this list.")
1705 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1706 "List of TODO entry keyword sequences and their interpretation.
1707 \\<org-mode-map>This is a list of sequences.
1709 Each sequence starts with a symbol, either `sequence' or `type',
1710 indicating if the keywords should be interpreted as a sequence of
1711 action steps, or as different types of TODO items. The first
1712 keywords are states requiring action - these states will select a headline
1713 for inclusion into the global TODO list Org-mode produces. If one of
1714 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1715 signify that no further action is necessary. If \"|\" is not found,
1716 the last keyword is treated as the only DONE state of the sequence.
1718 The command \\[org-todo] cycles an entry through these states, and one
1719 additional state where no keyword is present. For details about this
1720 cycling, see the manual.
1722 TODO keywords and interpretation can also be set on a per-file basis with
1723 the special #+SEQ_TODO and #+TYP_TODO lines.
1725 Each keyword can optionally specify a character for fast state selection
1726 \(in combination with the variable `org-use-fast-todo-selection')
1727 and specifiers for state change logging, using the same syntax
1728 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1729 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1730 indicates to record a time stamp each time this state is selected.
1732 Each keyword may also specify if a timestamp or a note should be
1733 recorded when entering or leaving the state, by adding additional
1734 characters in the parenthesis after the keyword. This looks like this:
1735 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1736 record only the time of the state change. With X and Y being either
1737 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1738 Y when leaving the state if and only if the *target* state does not
1739 define X. You may omit any of the fast-selection key or X or /Y,
1740 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1742 For backward compatibility, this variable may also be just a list
1743 of keywords - in this case the interpretation (sequence or type) will be
1744 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1745 :group 'org-todo
1746 :group 'org-keywords
1747 :type '(choice
1748 (repeat :tag "Old syntax, just keywords"
1749 (string :tag "Keyword"))
1750 (repeat :tag "New syntax"
1751 (cons
1752 (choice
1753 :tag "Interpretation"
1754 ;;Quick and dirty way to see
1755 ;;`org-todo-interpretations'. This takes the
1756 ;;place of item arguments
1757 :convert-widget
1758 (lambda (widget)
1759 (widget-put widget
1760 :args (mapcar
1761 #'(lambda (x)
1762 (widget-convert
1763 (cons 'const x)))
1764 org-todo-interpretation-widgets))
1765 widget))
1766 (repeat
1767 (string :tag "Keyword"))))))
1769 (defvar org-todo-keywords-1 nil
1770 "All TODO and DONE keywords active in a buffer.")
1771 (make-variable-buffer-local 'org-todo-keywords-1)
1772 (defvar org-todo-keywords-for-agenda nil)
1773 (defvar org-done-keywords-for-agenda nil)
1774 (defvar org-drawers-for-agenda nil)
1775 (defvar org-todo-keyword-alist-for-agenda nil)
1776 (defvar org-tag-alist-for-agenda nil)
1777 (defvar org-agenda-contributing-files nil)
1778 (defvar org-not-done-keywords nil)
1779 (make-variable-buffer-local 'org-not-done-keywords)
1780 (defvar org-done-keywords nil)
1781 (make-variable-buffer-local 'org-done-keywords)
1782 (defvar org-todo-heads nil)
1783 (make-variable-buffer-local 'org-todo-heads)
1784 (defvar org-todo-sets nil)
1785 (make-variable-buffer-local 'org-todo-sets)
1786 (defvar org-todo-log-states nil)
1787 (make-variable-buffer-local 'org-todo-log-states)
1788 (defvar org-todo-kwd-alist nil)
1789 (make-variable-buffer-local 'org-todo-kwd-alist)
1790 (defvar org-todo-key-alist nil)
1791 (make-variable-buffer-local 'org-todo-key-alist)
1792 (defvar org-todo-key-trigger nil)
1793 (make-variable-buffer-local 'org-todo-key-trigger)
1795 (defcustom org-todo-interpretation 'sequence
1796 "Controls how TODO keywords are interpreted.
1797 This variable is in principle obsolete and is only used for
1798 backward compatibility, if the interpretation of todo keywords is
1799 not given already in `org-todo-keywords'. See that variable for
1800 more information."
1801 :group 'org-todo
1802 :group 'org-keywords
1803 :type '(choice (const sequence)
1804 (const type)))
1806 (defcustom org-use-fast-todo-selection t
1807 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1808 This variable describes if and under what circumstances the cycling
1809 mechanism for TODO keywords will be replaced by a single-key, direct
1810 selection scheme.
1812 When nil, fast selection is never used.
1814 When the symbol `prefix', it will be used when `org-todo' is called with
1815 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1816 in an agenda buffer.
1818 When t, fast selection is used by default. In this case, the prefix
1819 argument forces cycling instead.
1821 In all cases, the special interface is only used if access keys have actually
1822 been assigned by the user, i.e. if keywords in the configuration are followed
1823 by a letter in parenthesis, like TODO(t)."
1824 :group 'org-todo
1825 :type '(choice
1826 (const :tag "Never" nil)
1827 (const :tag "By default" t)
1828 (const :tag "Only with C-u C-c C-t" prefix)))
1830 (defcustom org-provide-todo-statistics t
1831 "Non-nil means, update todo statistics after insert and toggle.
1832 ALL-HEADLINES means update todo statistics by including headlines
1833 with no TODO keyword as well, counting them as not done.
1834 A list of TODO keywords means the same, but skip keywords that are
1835 not in this list.
1837 When this is set, todo statistics is updated in the parent of the
1838 current entry each time a todo state is changed."
1839 :group 'org-todo
1840 :type '(choice
1841 (const :tag "Yes, only for TODO entries" t)
1842 (const :tag "Yes, including all entries" 'all-headlines)
1843 (repeat :tag "Yes, for TODOs in this list"
1844 (string :tag "TODO keyword"))
1845 (other :tag "No TODO statistics" nil)))
1847 (defcustom org-hierarchical-todo-statistics t
1848 "Non-nil means, TODO statistics covers just direct children.
1849 When nil, all entries in the subtree are considered.
1850 This has only an effect if `org-provide-todo-statistics' is set.
1851 To set this to nil for only a single subtree, use a COOKIE_DATA
1852 property and include the word \"recursive\" into the value."
1853 :group 'org-todo
1854 :type 'boolean)
1856 (defcustom org-after-todo-state-change-hook nil
1857 "Hook which is run after the state of a TODO item was changed.
1858 The new state (a string with a TODO keyword, or nil) is available in the
1859 Lisp variable `state'."
1860 :group 'org-todo
1861 :type 'hook)
1863 (defvar org-blocker-hook nil
1864 "Hook for functions that are allowed to block a state change.
1866 Each function gets as its single argument a property list, see
1867 `org-trigger-hook' for more information about this list.
1869 If any of the functions in this hook returns nil, the state change
1870 is blocked.")
1872 (defvar org-trigger-hook nil
1873 "Hook for functions that are triggered by a state change.
1875 Each function gets as its single argument a property list with at least
1876 the following elements:
1878 (:type type-of-change :position pos-at-entry-start
1879 :from old-state :to new-state)
1881 Depending on the type, more properties may be present.
1883 This mechanism is currently implemented for:
1885 TODO state changes
1886 ------------------
1887 :type todo-state-change
1888 :from previous state (keyword as a string), or nil, or a symbol
1889 'todo' or 'done', to indicate the general type of state.
1890 :to new state, like in :from")
1892 (defcustom org-enforce-todo-dependencies nil
1893 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1894 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1895 be blocked if any prior sibling is not yet done.
1896 Finally, if the parent is blocked because of ordered siblings of its own,
1897 the child will also be blocked.
1898 This variable needs to be set before org.el is loaded, and you need to
1899 restart Emacs after a change to make the change effective. The only way
1900 to change is while Emacs is running is through the customize interface."
1901 :set (lambda (var val)
1902 (set var val)
1903 (if val
1904 (add-hook 'org-blocker-hook
1905 'org-block-todo-from-children-or-siblings-or-parent)
1906 (remove-hook 'org-blocker-hook
1907 'org-block-todo-from-children-or-siblings-or-parent)))
1908 :group 'org-todo
1909 :type 'boolean)
1911 (defcustom org-enforce-todo-checkbox-dependencies nil
1912 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1913 When this is nil, checkboxes have no influence on switching TODO states.
1914 When non-nil, you first need to check off all check boxes before the TODO
1915 entry can be switched to DONE.
1916 This variable needs to be set before org.el is loaded, and you need to
1917 restart Emacs after a change to make the change effective. The only way
1918 to change is while Emacs is running is through the customize interface."
1919 :set (lambda (var val)
1920 (set var val)
1921 (if val
1922 (add-hook 'org-blocker-hook
1923 'org-block-todo-from-checkboxes)
1924 (remove-hook 'org-blocker-hook
1925 'org-block-todo-from-checkboxes)))
1926 :group 'org-todo
1927 :type 'boolean)
1929 (defcustom org-treat-insert-todo-heading-as-state-change nil
1930 "Non-nil means, inserting a TODO heading is treated as state change.
1931 So when the command \\[org-insert-todo-heading] is used, state change
1932 logging will apply if appropriate. When nil, the new TODO item will
1933 be inserted directly, and no logging will take place."
1934 :group 'org-todo
1935 :type 'boolean)
1937 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1938 "Non-nil means, switching TODO states with S-cursor counts as state change.
1939 This is the default behavior. However, setting this to nil allows a
1940 convenient way to select a TODO state and bypass any logging associated
1941 with that."
1942 :group 'org-todo
1943 :type 'boolean)
1945 (defcustom org-todo-state-tags-triggers nil
1946 "Tag changes that should be triggered by TODO state changes.
1947 This is a list. Each entry is
1949 (state-change (tag . flag) .......)
1951 State-change can be a string with a state, and empty string to indicate the
1952 state that has no TODO keyword, or it can be one of the symbols `todo'
1953 or `done', meaning any not-done or done state, respectively."
1954 :group 'org-todo
1955 :group 'org-tags
1956 :type '(repeat
1957 (cons (choice :tag "When changing to"
1958 (const :tag "Not-done state" todo)
1959 (const :tag "Done state" done)
1960 (string :tag "State"))
1961 (repeat
1962 (cons :tag "Tag action"
1963 (string :tag "Tag")
1964 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1966 (defcustom org-log-done nil
1967 "Information to record when a task moves to the DONE state.
1969 Possible values are:
1971 nil Don't add anything, just change the keyword
1972 time Add a time stamp to the task
1973 note Prompt for a note and add it with template `org-log-note-headings'
1975 This option can also be set with on a per-file-basis with
1977 #+STARTUP: nologdone
1978 #+STARTUP: logdone
1979 #+STARTUP: lognotedone
1981 You can have local logging settings for a subtree by setting the LOGGING
1982 property to one or more of these keywords."
1983 :group 'org-todo
1984 :group 'org-progress
1985 :type '(choice
1986 (const :tag "No logging" nil)
1987 (const :tag "Record CLOSED timestamp" time)
1988 (const :tag "Record CLOSED timestamp with note." note)))
1990 ;; Normalize old uses of org-log-done.
1991 (cond
1992 ((eq org-log-done t) (setq org-log-done 'time))
1993 ((and (listp org-log-done) (memq 'done org-log-done))
1994 (setq org-log-done 'note)))
1996 (defcustom org-log-reschedule nil
1997 "Information to record when the scheduling date of a tasks is modified.
1999 Possible values are:
2001 nil Don't add anything, just change the date
2002 time Add a time stamp to the task
2003 note Prompt for a note and add it with template `org-log-note-headings'
2005 This option can also be set with on a per-file-basis with
2007 #+STARTUP: nologreschedule
2008 #+STARTUP: logreschedule
2009 #+STARTUP: lognotereschedule"
2010 :group 'org-todo
2011 :group 'org-progress
2012 :type '(choice
2013 (const :tag "No logging" nil)
2014 (const :tag "Record timestamp" time)
2015 (const :tag "Record timestamp with note." note)))
2017 (defcustom org-log-redeadline nil
2018 "Information to record when the deadline date of a tasks is modified.
2020 Possible values are:
2022 nil Don't add anything, just change the date
2023 time Add a time stamp to the task
2024 note Prompt for a note and add it with template `org-log-note-headings'
2026 This option can also be set with on a per-file-basis with
2028 #+STARTUP: nologredeadline
2029 #+STARTUP: logredeadline
2030 #+STARTUP: lognoteredeadline
2032 You can have local logging settings for a subtree by setting the LOGGING
2033 property to one or more of these keywords."
2034 :group 'org-todo
2035 :group 'org-progress
2036 :type '(choice
2037 (const :tag "No logging" nil)
2038 (const :tag "Record timestamp" time)
2039 (const :tag "Record timestamp with note." note)))
2041 (defcustom org-log-note-clock-out nil
2042 "Non-nil means, record a note when clocking out of an item.
2043 This can also be configured on a per-file basis by adding one of
2044 the following lines anywhere in the buffer:
2046 #+STARTUP: lognoteclock-out
2047 #+STARTUP: nolognoteclock-out"
2048 :group 'org-todo
2049 :group 'org-progress
2050 :type 'boolean)
2052 (defcustom org-log-done-with-time t
2053 "Non-nil means, the CLOSED time stamp will contain date and time.
2054 When nil, only the date will be recorded."
2055 :group 'org-progress
2056 :type 'boolean)
2058 (defcustom org-log-note-headings
2059 '((done . "CLOSING NOTE %t")
2060 (state . "State %-12s from %-12S %t")
2061 (note . "Note taken on %t")
2062 (reschedule . "Rescheduled from %S on %t")
2063 (redeadline . "New deadline from %S on %t")
2064 (clock-out . ""))
2065 "Headings for notes added to entries.
2066 The value is an alist, with the car being a symbol indicating the note
2067 context, and the cdr is the heading to be used. The heading may also be the
2068 empty string.
2069 %t in the heading will be replaced by a time stamp.
2070 %s will be replaced by the new TODO state, in double quotes.
2071 %S will be replaced by the old TODO state, in double quotes.
2072 %u will be replaced by the user name.
2073 %U will be replaced by the full user name.
2075 In fact, it is not a good idea to change the `state' entry, because
2076 agenda log mode depends on the format of these entries."
2077 :group 'org-todo
2078 :group 'org-progress
2079 :type '(list :greedy t
2080 (cons (const :tag "Heading when closing an item" done) string)
2081 (cons (const :tag
2082 "Heading when changing todo state (todo sequence only)"
2083 state) string)
2084 (cons (const :tag "Heading when just taking a note" note) string)
2085 (cons (const :tag "Heading when clocking out" clock-out) string)
2086 (cons (const :tag "Heading when rescheduling" reschedule) string)
2087 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2089 (unless (assq 'note org-log-note-headings)
2090 (push '(note . "%t") org-log-note-headings))
2092 (defcustom org-log-into-drawer nil
2093 "Non-nil means, insert state change notes and time stamps into a drawer.
2094 When nil, state changes notes will be inserted after the headline and
2095 any scheduling and clock lines, but not inside a drawer.
2097 The value of this variable should be the name of the drawer to use.
2098 LOGBOOK is proposed at the default drawer for this purpose, you can
2099 also set this to a string to define the drawer of your choice.
2101 A value of t is also allowed, representing \"LOGBOOK\".
2103 If this variable is set, `org-log-state-notes-insert-after-drawers'
2104 will be ignored.
2106 You can set the property LOG_INTO_DRAWER to overrule this setting for
2107 a subtree."
2108 :group 'org-todo
2109 :group 'org-progress
2110 :type '(choice
2111 (const :tag "Not into a drawer" nil)
2112 (const :tag "LOGBOOK" t)
2113 (string :tag "Other")))
2115 (if (fboundp 'defvaralias)
2116 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2118 (defun org-log-into-drawer ()
2119 "Return the value of `org-log-into-drawer', but let properties overrule.
2120 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2121 used instead of the default value."
2122 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2123 (cond
2124 ((or (not p) (equal p "nil")) org-log-into-drawer)
2125 ((equal p "t") "LOGBOOK")
2126 (t p))))
2128 (defcustom org-log-state-notes-insert-after-drawers nil
2129 "Non-nil means, insert state change notes after any drawers in entry.
2130 Only the drawers that *immediately* follow the headline and the
2131 deadline/scheduled line are skipped.
2132 When nil, insert notes right after the heading and perhaps the line
2133 with deadline/scheduling if present.
2135 This variable will have no effect if `org-log-into-drawer' is
2136 set."
2137 :group 'org-todo
2138 :group 'org-progress
2139 :type 'boolean)
2141 (defcustom org-log-states-order-reversed t
2142 "Non-nil means, the latest state change note will be directly after heading.
2143 When nil, the notes will be orderer according to time."
2144 :group 'org-todo
2145 :group 'org-progress
2146 :type 'boolean)
2148 (defcustom org-log-repeat 'time
2149 "Non-nil means, record moving through the DONE state when triggering repeat.
2150 An auto-repeating task is immediately switched back to TODO when
2151 marked DONE. If you are not logging state changes (by adding \"@\"
2152 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2153 record a closing note, there will be no record of the task moving
2154 through DONE. This variable forces taking a note anyway.
2156 nil Don't force a record
2157 time Record a time stamp
2158 note Record a note
2160 This option can also be set with on a per-file-basis with
2162 #+STARTUP: logrepeat
2163 #+STARTUP: lognoterepeat
2164 #+STARTUP: nologrepeat
2166 You can have local logging settings for a subtree by setting the LOGGING
2167 property to one or more of these keywords."
2168 :group 'org-todo
2169 :group 'org-progress
2170 :type '(choice
2171 (const :tag "Don't force a record" nil)
2172 (const :tag "Force recording the DONE state" time)
2173 (const :tag "Force recording a note with the DONE state" note)))
2176 (defgroup org-priorities nil
2177 "Priorities in Org-mode."
2178 :tag "Org Priorities"
2179 :group 'org-todo)
2181 (defcustom org-enable-priority-commands t
2182 "Non-nil means, priority commands are active.
2183 When nil, these commands will be disabled, so that you never accidentally
2184 set a priority."
2185 :group 'org-priorities
2186 :type 'boolean)
2188 (defcustom org-highest-priority ?A
2189 "The highest priority of TODO items. A character like ?A, ?B etc.
2190 Must have a smaller ASCII number than `org-lowest-priority'."
2191 :group 'org-priorities
2192 :type 'character)
2194 (defcustom org-lowest-priority ?C
2195 "The lowest priority of TODO items. A character like ?A, ?B etc.
2196 Must have a larger ASCII number than `org-highest-priority'."
2197 :group 'org-priorities
2198 :type 'character)
2200 (defcustom org-default-priority ?B
2201 "The default priority of TODO items.
2202 This is the priority an item get if no explicit priority is given."
2203 :group 'org-priorities
2204 :type 'character)
2206 (defcustom org-priority-start-cycle-with-default t
2207 "Non-nil means, start with default priority when starting to cycle.
2208 When this is nil, the first step in the cycle will be (depending on the
2209 command used) one higher or lower that the default priority."
2210 :group 'org-priorities
2211 :type 'boolean)
2213 (defgroup org-time nil
2214 "Options concerning time stamps and deadlines in Org-mode."
2215 :tag "Org Time"
2216 :group 'org)
2218 (defcustom org-insert-labeled-timestamps-at-point nil
2219 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2220 When nil, these labeled time stamps are forces into the second line of an
2221 entry, just after the headline. When scheduling from the global TODO list,
2222 the time stamp will always be forced into the second line."
2223 :group 'org-time
2224 :type 'boolean)
2226 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2227 "Formats for `format-time-string' which are used for time stamps.
2228 It is not recommended to change this constant.")
2230 (defcustom org-time-stamp-rounding-minutes '(0 5)
2231 "Number of minutes to round time stamps to.
2232 These are two values, the first applies when first creating a time stamp.
2233 The second applies when changing it with the commands `S-up' and `S-down'.
2234 When changing the time stamp, this means that it will change in steps
2235 of N minutes, as given by the second value.
2237 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2238 numbers should be factors of 60, so for example 5, 10, 15.
2240 When this is larger than 1, you can still force an exact time-stamp by using
2241 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2242 and by using a prefix arg to `S-up/down' to specify the exact number
2243 of minutes to shift."
2244 :group 'org-time
2245 :get '(lambda (var) ; Make sure all entries have 5 elements
2246 (if (integerp (default-value var))
2247 (list (default-value var) 5)
2248 (default-value var)))
2249 :type '(list
2250 (integer :tag "when inserting times")
2251 (integer :tag "when modifying times")))
2253 ;; Normalize old customizations of this variable.
2254 (when (integerp org-time-stamp-rounding-minutes)
2255 (setq org-time-stamp-rounding-minutes
2256 (list org-time-stamp-rounding-minutes
2257 org-time-stamp-rounding-minutes)))
2259 (defcustom org-display-custom-times nil
2260 "Non-nil means, overlay custom formats over all time stamps.
2261 The formats are defined through the variable `org-time-stamp-custom-formats'.
2262 To turn this on on a per-file basis, insert anywhere in the file:
2263 #+STARTUP: customtime"
2264 :group 'org-time
2265 :set 'set-default
2266 :type 'sexp)
2267 (make-variable-buffer-local 'org-display-custom-times)
2269 (defcustom org-time-stamp-custom-formats
2270 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2271 "Custom formats for time stamps. See `format-time-string' for the syntax.
2272 These are overlayed over the default ISO format if the variable
2273 `org-display-custom-times' is set. Time like %H:%M should be at the
2274 end of the second format. The custom formats are also honored by export
2275 commands, if custom time display is turned on at the time of export."
2276 :group 'org-time
2277 :type 'sexp)
2279 (defun org-time-stamp-format (&optional long inactive)
2280 "Get the right format for a time string."
2281 (let ((f (if long (cdr org-time-stamp-formats)
2282 (car org-time-stamp-formats))))
2283 (if inactive
2284 (concat "[" (substring f 1 -1) "]")
2285 f)))
2287 (defcustom org-time-clocksum-format "%d:%02d"
2288 "The format string used when creating CLOCKSUM lines, or when
2289 org-mode generates a time duration."
2290 :group 'org-time
2291 :type 'string)
2293 (defcustom org-time-clocksum-use-fractional nil
2294 "If non-nil, \\[org-clock-display] uses fractional times.
2295 org-mode generates a time duration."
2296 :group 'org-time
2297 :type 'boolean)
2299 (defcustom org-time-clocksum-fractional-format "%.2f"
2300 "The format string used when creating CLOCKSUM lines, or when
2301 org-mode generates a time duration."
2302 :group 'org-time
2303 :type 'string)
2305 (defcustom org-deadline-warning-days 14
2306 "No. of days before expiration during which a deadline becomes active.
2307 This variable governs the display in sparse trees and in the agenda.
2308 When 0 or negative, it means use this number (the absolute value of it)
2309 even if a deadline has a different individual lead time specified.
2311 Custom commands can set this variable in the options section."
2312 :group 'org-time
2313 :group 'org-agenda-daily/weekly
2314 :type 'integer)
2316 (defcustom org-read-date-prefer-future t
2317 "Non-nil means, assume future for incomplete date input from user.
2318 This affects the following situations:
2319 1. The user gives a month but not a year.
2320 For example, if it is april and you enter \"feb 2\", this will be read
2321 as feb 2, *next* year. \"May 5\", however, will be this year.
2322 2. The user gives a day, but no month.
2323 For example, if today is the 15th, and you enter \"3\", Org-mode will
2324 read this as the third of *next* month. However, if you enter \"17\",
2325 it will be considered as *this* month.
2327 If you set this variable to the symbol `time', then also the following
2328 will work:
2330 3. If the user gives a time, but no day. If the time is before now,
2331 to will be interpreted as tomorrow.
2333 Currently none of this works for ISO week specifications.
2335 When this option is nil, the current day, month and year will always be
2336 used as defaults."
2337 :group 'org-time
2338 :type '(choice
2339 (const :tag "Never" nil)
2340 (const :tag "Check month and day" t)
2341 (const :tag "Check month, day, and time" time)))
2343 (defcustom org-read-date-display-live t
2344 "Non-nil means, display current interpretation of date prompt live.
2345 This display will be in an overlay, in the minibuffer."
2346 :group 'org-time
2347 :type 'boolean)
2349 (defcustom org-read-date-popup-calendar t
2350 "Non-nil means, pop up a calendar when prompting for a date.
2351 In the calendar, the date can be selected with mouse-1. However, the
2352 minibuffer will also be active, and you can simply enter the date as well.
2353 When nil, only the minibuffer will be available."
2354 :group 'org-time
2355 :type 'boolean)
2356 (if (fboundp 'defvaralias)
2357 (defvaralias 'org-popup-calendar-for-date-prompt
2358 'org-read-date-popup-calendar))
2360 (defcustom org-read-date-minibuffer-setup-hook nil
2361 "Hook to be used to set up keys for the date/time interface.
2362 Add key definitions to `minibuffer-local-map', which will be a temporary
2363 copy."
2364 :group 'org-time
2365 :type 'hook)
2367 (defcustom org-extend-today-until 0
2368 "The hour when your day really ends. Must be an integer.
2369 This has influence for the following applications:
2370 - When switching the agenda to \"today\". It it is still earlier than
2371 the time given here, the day recognized as TODAY is actually yesterday.
2372 - When a date is read from the user and it is still before the time given
2373 here, the current date and time will be assumed to be yesterday, 23:59.
2374 Also, timestamps inserted in remember templates follow this rule.
2376 IMPORTANT: This is a feature whose implementation is and likely will
2377 remain incomplete. Really, it is only here because past midnight seems to
2378 be the favorite working time of John Wiegley :-)"
2379 :group 'org-time
2380 :type 'integer)
2382 (defcustom org-edit-timestamp-down-means-later nil
2383 "Non-nil means, S-down will increase the time in a time stamp.
2384 When nil, S-up will increase."
2385 :group 'org-time
2386 :type 'boolean)
2388 (defcustom org-calendar-follow-timestamp-change t
2389 "Non-nil means, make the calendar window follow timestamp changes.
2390 When a timestamp is modified and the calendar window is visible, it will be
2391 moved to the new date."
2392 :group 'org-time
2393 :type 'boolean)
2395 (defgroup org-tags nil
2396 "Options concerning tags in Org-mode."
2397 :tag "Org Tags"
2398 :group 'org)
2400 (defcustom org-tag-alist nil
2401 "List of tags allowed in Org-mode files.
2402 When this list is nil, Org-mode will base TAG input on what is already in the
2403 buffer.
2404 The value of this variable is an alist, the car of each entry must be a
2405 keyword as a string, the cdr may be a character that is used to select
2406 that tag through the fast-tag-selection interface.
2407 See the manual for details."
2408 :group 'org-tags
2409 :type '(repeat
2410 (choice
2411 (cons (string :tag "Tag name")
2412 (character :tag "Access char"))
2413 (list :tag "Start radio group"
2414 (const :startgroup)
2415 (option (string :tag "Group description")))
2416 (list :tag "End radio group"
2417 (const :endgroup)
2418 (option (string :tag "Group description")))
2419 (const :tag "New line" (:newline)))))
2421 (defcustom org-tag-persistent-alist nil
2422 "List of tags that will always appear in all Org-mode files.
2423 This is in addition to any in buffer settings or customizations
2424 of `org-tag-alist'.
2425 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2426 The value of this variable is an alist, the car of each entry must be a
2427 keyword as a string, the cdr may be a character that is used to select
2428 that tag through the fast-tag-selection interface.
2429 See the manual for details.
2430 To disable these tags on a per-file basis, insert anywhere in the file:
2431 #+STARTUP: noptag"
2432 :group 'org-tags
2433 :type '(repeat
2434 (choice
2435 (cons (string :tag "Tag name")
2436 (character :tag "Access char"))
2437 (const :tag "Start radio group" (:startgroup))
2438 (const :tag "End radio group" (:endgroup))
2439 (const :tag "New line" (:newline)))))
2441 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2442 "If non-nil, always offer completion for all tags of all agenda files.
2443 Instead of customizing this variable directly, you might want to
2444 set it locally for remember buffers, because there no list of
2445 tags in that file can be created dynamically (there are none).
2447 (add-hook 'org-remember-mode-hook
2448 (lambda ()
2449 (set (make-local-variable
2450 'org-complete-tags-always-offer-all-agenda-tags)
2451 t)))"
2452 :group 'org-tags
2453 :type 'boolean)
2455 (defvar org-file-tags nil
2456 "List of tags that can be inherited by all entries in the file.
2457 The tags will be inherited if the variable `org-use-tag-inheritance'
2458 says they should be.
2459 This variable is populated from #+FILETAGS lines.")
2461 (defcustom org-use-fast-tag-selection 'auto
2462 "Non-nil means, use fast tag selection scheme.
2463 This is a special interface to select and deselect tags with single keys.
2464 When nil, fast selection is never used.
2465 When the symbol `auto', fast selection is used if and only if selection
2466 characters for tags have been configured, either through the variable
2467 `org-tag-alist' or through a #+TAGS line in the buffer.
2468 When t, fast selection is always used and selection keys are assigned
2469 automatically if necessary."
2470 :group 'org-tags
2471 :type '(choice
2472 (const :tag "Always" t)
2473 (const :tag "Never" nil)
2474 (const :tag "When selection characters are configured" 'auto)))
2476 (defcustom org-fast-tag-selection-single-key nil
2477 "Non-nil means, fast tag selection exits after first change.
2478 When nil, you have to press RET to exit it.
2479 During fast tag selection, you can toggle this flag with `C-c'.
2480 This variable can also have the value `expert'. In this case, the window
2481 displaying the tags menu is not even shown, until you press C-c again."
2482 :group 'org-tags
2483 :type '(choice
2484 (const :tag "No" nil)
2485 (const :tag "Yes" t)
2486 (const :tag "Expert" expert)))
2488 (defvar org-fast-tag-selection-include-todo nil
2489 "Non-nil means, fast tags selection interface will also offer TODO states.
2490 This is an undocumented feature, you should not rely on it.")
2492 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2493 "The column to which tags should be indented in a headline.
2494 If this number is positive, it specifies the column. If it is negative,
2495 it means that the tags should be flushright to that column. For example,
2496 -80 works well for a normal 80 character screen."
2497 :group 'org-tags
2498 :type 'integer)
2500 (defcustom org-auto-align-tags t
2501 "Non-nil means, realign tags after pro/demotion of TODO state change.
2502 These operations change the length of a headline and therefore shift
2503 the tags around. With this options turned on, after each such operation
2504 the tags are again aligned to `org-tags-column'."
2505 :group 'org-tags
2506 :type 'boolean)
2508 (defcustom org-use-tag-inheritance t
2509 "Non-nil means, tags in levels apply also for sublevels.
2510 When nil, only the tags directly given in a specific line apply there.
2511 This may also be a list of tags that should be inherited, or a regexp that
2512 matches tags that should be inherited. Additional control is possible
2513 with the variable `org-tags-exclude-from-inheritance' which gives an
2514 explicit list of tags to be excluded from inheritance., even if the value of
2515 `org-use-tag-inheritance' would select it for inheritance.
2517 If this option is t, a match early-on in a tree can lead to a large
2518 number of matches in the subtree when constructing the agenda or creating
2519 a sparse tree. If you only want to see the first match in a tree during
2520 a search, check out the variable `org-tags-match-list-sublevels'."
2521 :group 'org-tags
2522 :type '(choice
2523 (const :tag "Not" nil)
2524 (const :tag "Always" t)
2525 (repeat :tag "Specific tags" (string :tag "Tag"))
2526 (regexp :tag "Tags matched by regexp")))
2528 (defcustom org-tags-exclude-from-inheritance nil
2529 "List of tags that should never be inherited.
2530 This is a way to exclude a few tags from inheritance. For way to do
2531 the opposite, to actively allow inheritance for selected tags,
2532 see the variable `org-use-tag-inheritance'."
2533 :group 'org-tags
2534 :type '(repeat (string :tag "Tag")))
2536 (defun org-tag-inherit-p (tag)
2537 "Check if TAG is one that should be inherited."
2538 (cond
2539 ((member tag org-tags-exclude-from-inheritance) nil)
2540 ((eq org-use-tag-inheritance t) t)
2541 ((not org-use-tag-inheritance) nil)
2542 ((stringp org-use-tag-inheritance)
2543 (string-match org-use-tag-inheritance tag))
2544 ((listp org-use-tag-inheritance)
2545 (member tag org-use-tag-inheritance))
2546 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2548 (defcustom org-tags-match-list-sublevels t
2549 "Non-nil means list also sublevels of headlines matching a search.
2550 This variable applies to tags/property searches, and also to stuck
2551 projects because this search is based on a tags match as well.
2553 When set to the symbol `indented', sublevels are indented with
2554 leading dots.
2556 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2557 the sublevels of a headline matching a tag search often also match
2558 the same search. Listing all of them can create very long lists.
2559 Setting this variable to nil causes subtrees of a match to be skipped.
2561 This variable is semi-obsolete and probably should always be true. It
2562 is better to limit inheritance to certain tags using the variables
2563 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2564 :group 'org-tags
2565 :type '(choice
2566 (const :tag "No, don't list them" nil)
2567 (const :tag "Yes, do list them" t)
2568 (const :tag "List them, indented with leading dots" indented)))
2570 (defcustom org-tags-sort-function nil
2571 "When set, tags are sorted using this function as a comparator"
2572 :group 'org-tags
2573 :type '(choice
2574 (const :tag "No sorting" nil)
2575 (const :tag "Alphabetical" string<)
2576 (const :tag "Reverse alphabetical" string>)
2577 (function :tag "Custom function" nil)))
2579 (defvar org-tags-history nil
2580 "History of minibuffer reads for tags.")
2581 (defvar org-last-tags-completion-table nil
2582 "The last used completion table for tags.")
2583 (defvar org-after-tags-change-hook nil
2584 "Hook that is run after the tags in a line have changed.")
2586 (defgroup org-properties nil
2587 "Options concerning properties in Org-mode."
2588 :tag "Org Properties"
2589 :group 'org)
2591 (defcustom org-property-format "%-10s %s"
2592 "How property key/value pairs should be formatted by `indent-line'.
2593 When `indent-line' hits a property definition, it will format the line
2594 according to this format, mainly to make sure that the values are
2595 lined-up with respect to each other."
2596 :group 'org-properties
2597 :type 'string)
2599 (defcustom org-use-property-inheritance nil
2600 "Non-nil means, properties apply also for sublevels.
2602 This setting is chiefly used during property searches. Turning it on can
2603 cause significant overhead when doing a search, which is why it is not
2604 on by default.
2606 When nil, only the properties directly given in the current entry count.
2607 When t, every property is inherited. The value may also be a list of
2608 properties that should have inheritance, or a regular expression matching
2609 properties that should be inherited.
2611 However, note that some special properties use inheritance under special
2612 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2613 and the properties ending in \"_ALL\" when they are used as descriptor
2614 for valid values of a property.
2616 Note for programmers:
2617 When querying an entry with `org-entry-get', you can control if inheritance
2618 should be used. By default, `org-entry-get' looks only at the local
2619 properties. You can request inheritance by setting the inherit argument
2620 to t (to force inheritance) or to `selective' (to respect the setting
2621 in this variable)."
2622 :group 'org-properties
2623 :type '(choice
2624 (const :tag "Not" nil)
2625 (const :tag "Always" t)
2626 (repeat :tag "Specific properties" (string :tag "Property"))
2627 (regexp :tag "Properties matched by regexp")))
2629 (defun org-property-inherit-p (property)
2630 "Check if PROPERTY is one that should be inherited."
2631 (cond
2632 ((eq org-use-property-inheritance t) t)
2633 ((not org-use-property-inheritance) nil)
2634 ((stringp org-use-property-inheritance)
2635 (string-match org-use-property-inheritance property))
2636 ((listp org-use-property-inheritance)
2637 (member property org-use-property-inheritance))
2638 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2640 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2641 "The default column format, if no other format has been defined.
2642 This variable can be set on the per-file basis by inserting a line
2644 #+COLUMNS: %25ITEM ....."
2645 :group 'org-properties
2646 :type 'string)
2648 (defcustom org-columns-ellipses ".."
2649 "The ellipses to be used when a field in column view is truncated.
2650 When this is the empty string, as many characters as possible are shown,
2651 but then there will be no visual indication that the field has been truncated.
2652 When this is a string of length N, the last N characters of a truncated
2653 field are replaced by this string. If the column is narrower than the
2654 ellipses string, only part of the ellipses string will be shown."
2655 :group 'org-properties
2656 :type 'string)
2658 (defcustom org-columns-modify-value-for-display-function nil
2659 "Function that modifies values for display in column view.
2660 For example, it can be used to cut out a certain part from a time stamp.
2661 The function must take 2 arguments:
2663 column-title The title of the column (*not* the property name)
2664 value The value that should be modified.
2666 The function should return the value that should be displayed,
2667 or nil if the normal value should be used."
2668 :group 'org-properties
2669 :type 'function)
2671 (defcustom org-effort-property "Effort"
2672 "The property that is being used to keep track of effort estimates.
2673 Effort estimates given in this property need to have the format H:MM."
2674 :group 'org-properties
2675 :group 'org-progress
2676 :type '(string :tag "Property"))
2678 (defconst org-global-properties-fixed
2679 '(("VISIBILITY_ALL" . "folded children content all")
2680 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2681 "List of property/value pairs that can be inherited by any entry.
2683 These are fixed values, for the preset properties. The user variable
2684 that can be used to add to this list is `org-global-properties'.
2686 The entries in this list are cons cells where the car is a property
2687 name and cdr is a string with the value. If the value represents
2688 multiple items like an \"_ALL\" property, separate the items by
2689 spaces.")
2691 (defcustom org-global-properties nil
2692 "List of property/value pairs that can be inherited by any entry.
2694 This list will be combined with the constant `org-global-properties-fixed'.
2696 The entries in this list are cons cells where the car is a property
2697 name and cdr is a string with the value.
2699 You can set buffer-local values for the same purpose in the variable
2700 `org-file-properties' this by adding lines like
2702 #+PROPERTY: NAME VALUE"
2703 :group 'org-properties
2704 :type '(repeat
2705 (cons (string :tag "Property")
2706 (string :tag "Value"))))
2708 (defvar org-file-properties nil
2709 "List of property/value pairs that can be inherited by any entry.
2710 Valid for the current buffer.
2711 This variable is populated from #+PROPERTY lines.")
2712 (make-variable-buffer-local 'org-file-properties)
2714 (defgroup org-agenda nil
2715 "Options concerning agenda views in Org-mode."
2716 :tag "Org Agenda"
2717 :group 'org)
2719 (defvar org-category nil
2720 "Variable used by org files to set a category for agenda display.
2721 Such files should use a file variable to set it, for example
2723 # -*- mode: org; org-category: \"ELisp\"
2725 or contain a special line
2727 #+CATEGORY: ELisp
2729 If the file does not specify a category, then file's base name
2730 is used instead.")
2731 (make-variable-buffer-local 'org-category)
2732 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2734 (defcustom org-agenda-files nil
2735 "The files to be used for agenda display.
2736 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2737 \\[org-remove-file]. You can also use customize to edit the list.
2739 If an entry is a directory, all files in that directory that are matched by
2740 `org-agenda-file-regexp' will be part of the file list.
2742 If the value of the variable is not a list but a single file name, then
2743 the list of agenda files is actually stored and maintained in that file, one
2744 agenda file per line."
2745 :group 'org-agenda
2746 :type '(choice
2747 (repeat :tag "List of files and directories" file)
2748 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2750 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2751 "Regular expression to match files for `org-agenda-files'.
2752 If any element in the list in that variable contains a directory instead
2753 of a normal file, all files in that directory that are matched by this
2754 regular expression will be included."
2755 :group 'org-agenda
2756 :type 'regexp)
2758 (defcustom org-agenda-text-search-extra-files nil
2759 "List of extra files to be searched by text search commands.
2760 These files will be search in addition to the agenda files by the
2761 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2762 Note that these files will only be searched for text search commands,
2763 not for the other agenda views like todo lists, tag searches or the weekly
2764 agenda. This variable is intended to list notes and possibly archive files
2765 that should also be searched by these two commands.
2766 In fact, if the first element in the list is the symbol `agenda-archives',
2767 than all archive files of all agenda files will be added to the search
2768 scope."
2769 :group 'org-agenda
2770 :type '(set :greedy t
2771 (const :tag "Agenda Archives" agenda-archives)
2772 (repeat :inline t (file))))
2774 (if (fboundp 'defvaralias)
2775 (defvaralias 'org-agenda-multi-occur-extra-files
2776 'org-agenda-text-search-extra-files))
2778 (defcustom org-agenda-skip-unavailable-files nil
2779 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2780 A nil value means to remove them, after a query, from the list."
2781 :group 'org-agenda
2782 :type 'boolean)
2784 (defcustom org-calendar-to-agenda-key [?c]
2785 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2786 The command `org-calendar-goto-agenda' will be bound to this key. The
2787 default is the character `c' because then `c' can be used to switch back and
2788 forth between agenda and calendar."
2789 :group 'org-agenda
2790 :type 'sexp)
2792 (defcustom org-calendar-agenda-action-key [?k]
2793 "The key to be installed in `calendar-mode-map' for agenda-action.
2794 The command `org-agenda-action' will be bound to this key. The
2795 default is the character `k' because we use the same key in the agenda."
2796 :group 'org-agenda
2797 :type 'sexp)
2799 (defcustom org-calendar-insert-diary-entry-key [?i]
2800 "The key to be installed in `calendar-mode-map' for adding diary entries.
2801 This option is irrelevant until `org-agenda-diary-file' has been configured
2802 to point to an Org-mode file. When that is the case, the command
2803 `org-agenda-diary-entry' will be bound to the key given here, by default
2804 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2805 if you want to continue doing this, you need to change this to a different
2806 key."
2807 :group 'org-agenda
2808 :type 'sexp)
2810 (defcustom org-agenda-diary-file 'diary-file
2811 "File to which to add new entries with the `i' key in agenda and calendar.
2812 When this is the symbol `diary-file', the functionality in the Emacs
2813 calendar will be used to add entries to the `diary-file'. But when this
2814 points to a file, `org-agenda-diary-entry' will be used instead."
2815 :group 'org-agenda
2816 :type '(choice
2817 (const :tag "The standard Emacs diary file" diary-file)
2818 (file :tag "Special Org file diary entries")))
2820 (eval-after-load "calendar"
2821 '(progn
2822 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2823 'org-calendar-goto-agenda)
2824 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2825 'org-agenda-action)
2826 (add-hook 'calendar-mode-hook
2827 (lambda ()
2828 (unless (eq org-agenda-diary-file 'diary-file)
2829 (define-key calendar-mode-map
2830 org-calendar-insert-diary-entry-key
2831 'org-agenda-diary-entry))))))
2833 (defgroup org-latex nil
2834 "Options for embedding LaTeX code into Org-mode."
2835 :tag "Org LaTeX"
2836 :group 'org)
2838 (defcustom org-format-latex-options
2839 '(:foreground default :background default :scale 1.0
2840 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2841 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2842 "Options for creating images from LaTeX fragments.
2843 This is a property list with the following properties:
2844 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2845 `default' means use the foreground of the default face.
2846 :background the background color, or \"Transparent\".
2847 `default' means use the background of the default face.
2848 :scale a scaling factor for the size of the images.
2849 :html-foreground, :html-background, :html-scale
2850 the same numbers for HTML export.
2851 :matchers a list indicating which matchers should be used to
2852 find LaTeX fragments. Valid members of this list are:
2853 \"begin\" find environments
2854 \"$1\" find single characters surrounded by $.$
2855 \"$\" find math expressions surrounded by $...$
2856 \"$$\" find math expressions surrounded by $$....$$
2857 \"\\(\" find math expressions surrounded by \\(...\\)
2858 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2859 :group 'org-latex
2860 :type 'plist)
2862 (defcustom org-format-latex-header "\\documentclass{article}
2863 \\usepackage{amssymb}
2864 \\usepackage[usenames]{color}
2865 \\usepackage{amsmath}
2866 \\usepackage{latexsym}
2867 \\usepackage[mathscr]{eucal}
2868 \\pagestyle{empty} % do not remove
2869 % The settings below are copied from fullpage.sty
2870 \\setlength{\\textwidth}{\\paperwidth}
2871 \\addtolength{\\textwidth}{-3cm}
2872 \\setlength{\\oddsidemargin}{1.5cm}
2873 \\addtolength{\\oddsidemargin}{-2.54cm}
2874 \\setlength{\\evensidemargin}{\\oddsidemargin}
2875 \\setlength{\\textheight}{\\paperheight}
2876 \\addtolength{\\textheight}{-\\headheight}
2877 \\addtolength{\\textheight}{-\\headsep}
2878 \\addtolength{\\textheight}{-\\footskip}
2879 \\addtolength{\\textheight}{-3cm}
2880 \\setlength{\\topmargin}{1.5cm}
2881 \\addtolength{\\topmargin}{-2.54cm}"
2882 "The document header used for processing LaTeX fragments.
2883 It is imperative that this header make sure that no page number
2884 appears on the page."
2885 :group 'org-latex
2886 :type 'string)
2888 ;; The following variable is defined here because is it also used
2889 ;; when formatting latex fragments. Originally it was part of the
2890 ;; LaTeX exporter, which is why the name includes "export".
2891 (defcustom org-export-latex-packages-alist nil
2892 "Alist of packages to be inserted in the header.
2893 Each cell is of the format \( \"option\" . \"package\" \)."
2894 :group 'org-export-latex
2895 :type '(repeat
2896 (list
2897 (string :tag "option")
2898 (string :tag "package"))))
2900 (defgroup org-font-lock nil
2901 "Font-lock settings for highlighting in Org-mode."
2902 :tag "Org Font Lock"
2903 :group 'org)
2905 (defcustom org-level-color-stars-only nil
2906 "Non-nil means fontify only the stars in each headline.
2907 When nil, the entire headline is fontified.
2908 Changing it requires restart of `font-lock-mode' to become effective
2909 also in regions already fontified."
2910 :group 'org-font-lock
2911 :type 'boolean)
2913 (defcustom org-hide-leading-stars nil
2914 "Non-nil means, hide the first N-1 stars in a headline.
2915 This works by using the face `org-hide' for these stars. This
2916 face is white for a light background, and black for a dark
2917 background. You may have to customize the face `org-hide' to
2918 make this work.
2919 Changing it requires restart of `font-lock-mode' to become effective
2920 also in regions already fontified.
2921 You may also set this on a per-file basis by adding one of the following
2922 lines to the buffer:
2924 #+STARTUP: hidestars
2925 #+STARTUP: showstars"
2926 :group 'org-font-lock
2927 :type 'boolean)
2929 (defcustom org-fontify-done-headline nil
2930 "Non-nil means, change the face of a headline if it is marked DONE.
2931 Normally, only the TODO/DONE keyword indicates the state of a headline.
2932 When this is non-nil, the headline after the keyword is set to the
2933 `org-headline-done' as an additional indication."
2934 :group 'org-font-lock
2935 :type 'boolean)
2937 (defcustom org-fontify-emphasized-text t
2938 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2939 Changing this variable requires a restart of Emacs to take effect."
2940 :group 'org-font-lock
2941 :type 'boolean)
2943 (defcustom org-fontify-whole-heading-line nil
2944 "Non-nil means fontify the whole line for headings.
2945 This is useful when setting a background color for the
2946 org-level-* faces."
2947 :group 'org-font-lock
2948 :type 'boolean)
2950 (defcustom org-highlight-latex-fragments-and-specials nil
2951 "Non-nil means, fontify what is treated specially by the exporters."
2952 :group 'org-font-lock
2953 :type 'boolean)
2955 (defcustom org-hide-emphasis-markers nil
2956 "Non-nil mean font-lock should hide the emphasis marker characters."
2957 :group 'org-font-lock
2958 :type 'boolean)
2960 (defvar org-emph-re nil
2961 "Regular expression for matching emphasis.")
2962 (defvar org-verbatim-re nil
2963 "Regular expression for matching verbatim text.")
2964 (defvar org-emphasis-regexp-components) ; defined just below
2965 (defvar org-emphasis-alist) ; defined just below
2966 (defun org-set-emph-re (var val)
2967 "Set variable and compute the emphasis regular expression."
2968 (set var val)
2969 (when (and (boundp 'org-emphasis-alist)
2970 (boundp 'org-emphasis-regexp-components)
2971 org-emphasis-alist org-emphasis-regexp-components)
2972 (let* ((e org-emphasis-regexp-components)
2973 (pre (car e))
2974 (post (nth 1 e))
2975 (border (nth 2 e))
2976 (body (nth 3 e))
2977 (nl (nth 4 e))
2978 (body1 (concat body "*?"))
2979 (markers (mapconcat 'car org-emphasis-alist ""))
2980 (vmarkers (mapconcat
2981 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2982 org-emphasis-alist "")))
2983 ;; make sure special characters appear at the right position in the class
2984 (if (string-match "\\^" markers)
2985 (setq markers (concat (replace-match "" t t markers) "^")))
2986 (if (string-match "-" markers)
2987 (setq markers (concat (replace-match "" t t markers) "-")))
2988 (if (string-match "\\^" vmarkers)
2989 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2990 (if (string-match "-" vmarkers)
2991 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2992 (if (> nl 0)
2993 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2994 (int-to-string nl) "\\}")))
2995 ;; Make the regexp
2996 (setq org-emph-re
2997 (concat "\\([" pre "]\\|^\\)"
2998 "\\("
2999 "\\([" markers "]\\)"
3000 "\\("
3001 "[^" border "]\\|"
3002 "[^" border "]"
3003 body1
3004 "[^" border "]"
3005 "\\)"
3006 "\\3\\)"
3007 "\\([" post "]\\|$\\)"))
3008 (setq org-verbatim-re
3009 (concat "\\([" pre "]\\|^\\)"
3010 "\\("
3011 "\\([" vmarkers "]\\)"
3012 "\\("
3013 "[^" border "]\\|"
3014 "[^" border "]"
3015 body1
3016 "[^" border "]"
3017 "\\)"
3018 "\\3\\)"
3019 "\\([" post "]\\|$\\)")))))
3021 (defcustom org-emphasis-regexp-components
3022 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3023 "Components used to build the regular expression for emphasis.
3024 This is a list with 6 entries. Terminology: In an emphasis string
3025 like \" *strong word* \", we call the initial space PREMATCH, the final
3026 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3027 and \"trong wor\" is the body. The different components in this variable
3028 specify what is allowed/forbidden in each part:
3030 pre Chars allowed as prematch. Beginning of line will be allowed too.
3031 post Chars allowed as postmatch. End of line will be allowed too.
3032 border The chars *forbidden* as border characters.
3033 body-regexp A regexp like \".\" to match a body character. Don't use
3034 non-shy groups here, and don't allow newline here.
3035 newline The maximum number of newlines allowed in an emphasis exp.
3037 Use customize to modify this, or restart Emacs after changing it."
3038 :group 'org-font-lock
3039 :set 'org-set-emph-re
3040 :type '(list
3041 (sexp :tag "Allowed chars in pre ")
3042 (sexp :tag "Allowed chars in post ")
3043 (sexp :tag "Forbidden chars in border ")
3044 (sexp :tag "Regexp for body ")
3045 (integer :tag "number of newlines allowed")
3046 (option (boolean :tag "Please ignore this button"))))
3048 (defcustom org-emphasis-alist
3049 `(("*" bold "<b>" "</b>")
3050 ("/" italic "<i>" "</i>")
3051 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3052 ("=" org-code "<code>" "</code>" verbatim)
3053 ("~" org-verbatim "<code>" "</code>" verbatim)
3054 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3055 "<del>" "</del>")
3057 "Special syntax for emphasized text.
3058 Text starting and ending with a special character will be emphasized, for
3059 example *bold*, _underlined_ and /italic/. This variable sets the marker
3060 characters, the face to be used by font-lock for highlighting in Org-mode
3061 Emacs buffers, and the HTML tags to be used for this.
3062 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3063 Use customize to modify this, or restart Emacs after changing it."
3064 :group 'org-font-lock
3065 :set 'org-set-emph-re
3066 :type '(repeat
3067 (list
3068 (string :tag "Marker character")
3069 (choice
3070 (face :tag "Font-lock-face")
3071 (plist :tag "Face property list"))
3072 (string :tag "HTML start tag")
3073 (string :tag "HTML end tag")
3074 (option (const verbatim)))))
3076 (defvar org-protecting-blocks
3077 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3078 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3079 This is needed for font-lock setup.")
3081 ;;; Miscellaneous options
3083 (defgroup org-completion nil
3084 "Completion in Org-mode."
3085 :tag "Org Completion"
3086 :group 'org)
3088 (defcustom org-completion-use-ido nil
3089 "Non-nil means, use ido completion wherever possible.
3090 Note that `ido-mode' must be active for this variable to be relevant.
3091 If you decide to turn this variable on, you might well want to turn off
3092 `org-outline-path-complete-in-steps'.
3093 See also `org-completion-use-iswitchb'."
3094 :group 'org-completion
3095 :type 'boolean)
3097 (defcustom org-completion-use-iswitchb nil
3098 "Non-nil means, use iswitchb completion wherever possible.
3099 Note that `iswitchb-mode' must be active for this variable to be relevant.
3100 If you decide to turn this variable on, you might well want to turn off
3101 `org-outline-path-complete-in-steps'.
3102 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3103 :group 'org-completion
3104 :type 'boolean)
3106 (defcustom org-completion-fallback-command 'hippie-expand
3107 "The expansion command called by \\[org-complete] in normal context.
3108 Normal means, no org-mode-specific context."
3109 :group 'org-completion
3110 :type 'function)
3112 ;;; Functions and variables from their packages
3113 ;; Declared here to avoid compiler warnings
3115 ;; XEmacs only
3116 (defvar outline-mode-menu-heading)
3117 (defvar outline-mode-menu-show)
3118 (defvar outline-mode-menu-hide)
3119 (defvar zmacs-regions) ; XEmacs regions
3121 ;; Emacs only
3122 (defvar mark-active)
3124 ;; Various packages
3125 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3126 (declare-function calendar-forward-day "cal-move" (arg))
3127 (declare-function calendar-goto-date "cal-move" (date))
3128 (declare-function calendar-goto-today "cal-move" ())
3129 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3130 (defvar calc-embedded-close-formula)
3131 (defvar calc-embedded-open-formula)
3132 (declare-function cdlatex-tab "ext:cdlatex" ())
3133 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3134 (defvar font-lock-unfontify-region-function)
3135 (declare-function iswitchb-read-buffer "iswitchb"
3136 (prompt &optional default require-match start matches-set))
3137 (defvar iswitchb-temp-buflist)
3138 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3139 (defvar org-agenda-tags-todo-honor-ignore-options)
3140 (declare-function org-agenda-skip "org-agenda" ())
3141 (declare-function
3142 org-format-agenda-item "org-agenda"
3143 (extra txt &optional category tags dotime noprefix remove-re habitp))
3144 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3145 (declare-function org-agenda-change-all-lines "org-agenda"
3146 (newhead hdmarker &optional fixface just-this))
3147 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3148 (declare-function org-agenda-maybe-redo "org-agenda" ())
3149 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3150 (beg end))
3151 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3152 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3153 "org-agenda" (&optional end))
3154 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3155 (declare-function org-indent-mode "org-indent" (&optional arg))
3156 (declare-function parse-time-string "parse-time" (string))
3157 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3158 (defvar remember-data-file)
3159 (defvar texmathp-why)
3160 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3161 (declare-function table--at-cell-p "table" (position &optional object at-column))
3163 (defvar w3m-current-url)
3164 (defvar w3m-current-title)
3166 (defvar org-latex-regexps)
3168 ;;; Autoload and prepare some org modules
3170 ;; Some table stuff that needs to be defined here, because it is used
3171 ;; by the functions setting up org-mode or checking for table context.
3173 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3174 "Detects an org-type or table-type table.")
3175 (defconst org-table-line-regexp "^[ \t]*|"
3176 "Detects an org-type table line.")
3177 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3178 "Detects an org-type table line.")
3179 (defconst org-table-hline-regexp "^[ \t]*|-"
3180 "Detects an org-type table hline.")
3181 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3182 "Detects a table-type table hline.")
3183 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3184 "Searching from within a table (any type) this finds the first line
3185 outside the table.")
3187 ;; Autoload the functions in org-table.el that are needed by functions here.
3189 (eval-and-compile
3190 (org-autoload "org-table"
3191 '(org-table-align org-table-begin org-table-blank-field
3192 org-table-convert org-table-convert-region org-table-copy-down
3193 org-table-copy-region org-table-create
3194 org-table-create-or-convert-from-region
3195 org-table-create-with-table.el org-table-current-dline
3196 org-table-cut-region org-table-delete-column org-table-edit-field
3197 org-table-edit-formulas org-table-end org-table-eval-formula
3198 org-table-export org-table-field-info
3199 org-table-get-stored-formulas org-table-goto-column
3200 org-table-hline-and-move org-table-import org-table-insert-column
3201 org-table-insert-hline org-table-insert-row org-table-iterate
3202 org-table-justify-field-maybe org-table-kill-row
3203 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3204 org-table-move-column org-table-move-column-left
3205 org-table-move-column-right org-table-move-row
3206 org-table-move-row-down org-table-move-row-up
3207 org-table-next-field org-table-next-row org-table-paste-rectangle
3208 org-table-previous-field org-table-recalculate
3209 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3210 org-table-toggle-coordinate-overlays
3211 org-table-toggle-formula-debugger org-table-wrap-region
3212 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3214 (defun org-at-table-p (&optional table-type)
3215 "Return t if the cursor is inside an org-type table.
3216 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3217 (if org-enable-table-editor
3218 (save-excursion
3219 (beginning-of-line 1)
3220 (looking-at (if table-type org-table-any-line-regexp
3221 org-table-line-regexp)))
3222 nil))
3223 (defsubst org-table-p () (org-at-table-p))
3225 (defun org-at-table.el-p ()
3226 "Return t if and only if we are at a table.el table."
3227 (and (org-at-table-p 'any)
3228 (save-excursion
3229 (goto-char (org-table-begin 'any))
3230 (looking-at org-table1-hline-regexp))))
3231 (defun org-table-recognize-table.el ()
3232 "If there is a table.el table nearby, recognize it and move into it."
3233 (if org-table-tab-recognizes-table.el
3234 (if (org-at-table.el-p)
3235 (progn
3236 (beginning-of-line 1)
3237 (if (looking-at org-table-dataline-regexp)
3239 (if (looking-at org-table1-hline-regexp)
3240 (progn
3241 (beginning-of-line 2)
3242 (if (looking-at org-table-any-border-regexp)
3243 (beginning-of-line -1)))))
3244 (if (re-search-forward "|" (org-table-end t) t)
3245 (progn
3246 (require 'table)
3247 (if (table--at-cell-p (point))
3249 (message "recognizing table.el table...")
3250 (table-recognize-table)
3251 (message "recognizing table.el table...done")))
3252 (error "This should not happen..."))
3254 nil)
3255 nil))
3257 (defun org-at-table-hline-p ()
3258 "Return t if the cursor is inside a hline in a table."
3259 (if org-enable-table-editor
3260 (save-excursion
3261 (beginning-of-line 1)
3262 (looking-at org-table-hline-regexp))
3263 nil))
3265 (defvar org-table-clean-did-remove-column nil)
3267 (defun org-table-map-tables (function)
3268 "Apply FUNCTION to the start of all tables in the buffer."
3269 (save-excursion
3270 (save-restriction
3271 (widen)
3272 (goto-char (point-min))
3273 (while (re-search-forward org-table-any-line-regexp nil t)
3274 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3275 (beginning-of-line 1)
3276 (when (looking-at org-table-line-regexp)
3277 (save-excursion (funcall function))
3278 (or (looking-at org-table-line-regexp)
3279 (forward-char 1)))
3280 (re-search-forward org-table-any-border-regexp nil 1))))
3281 (message "Mapping tables: done"))
3283 ;; Declare and autoload functions from org-exp.el & Co
3285 (declare-function org-default-export-plist "org-exp")
3286 (declare-function org-infile-export-plist "org-exp")
3287 (declare-function org-get-current-options "org-exp")
3288 (eval-and-compile
3289 (org-autoload "org-exp"
3290 '(org-export org-export-visible
3291 org-insert-export-options-template
3292 org-table-clean-before-export))
3293 (org-autoload "org-ascii"
3294 '(org-export-as-ascii org-export-ascii-preprocess
3295 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3296 org-export-region-as-ascii))
3297 (org-autoload "org-latex"
3298 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3299 org-replace-region-by-latex org-export-region-as-latex
3300 org-export-as-latex org-export-as-pdf
3301 org-export-as-pdf-and-open))
3302 (org-autoload "org-html"
3303 '(org-export-as-html-and-open
3304 org-export-as-html-batch org-export-as-html-to-buffer
3305 org-replace-region-by-html org-export-region-as-html
3306 org-export-as-html))
3307 (org-autoload "org-docbook"
3308 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3309 org-replace-region-by-docbook org-export-region-as-docbook
3310 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3311 org-export-as-docbook))
3312 (org-autoload "org-icalendar"
3313 '(org-export-icalendar-this-file
3314 org-export-icalendar-all-agenda-files
3315 org-export-icalendar-combine-agenda-files))
3316 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3317 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3319 ;; Declare and autoload functions from org-agenda.el
3321 (eval-and-compile
3322 (org-autoload "org-agenda"
3323 '(org-agenda org-agenda-list org-search-view
3324 org-todo-list org-tags-view org-agenda-list-stuck-projects
3325 org-diary org-agenda-to-appt
3326 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3328 ;; Autoload org-remember
3330 (eval-and-compile
3331 (org-autoload "org-remember"
3332 '(org-remember-insinuate org-remember-annotation
3333 org-remember-apply-template org-remember org-remember-handler)))
3335 ;; Autoload org-clock.el
3338 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3339 (beg end))
3340 (declare-function org-clock-update-mode-line "org-clock" ())
3341 (declare-function org-resolve-clocks "org-clock"
3342 (&optional also-non-dangling-p prompt last-valid))
3343 (defvar org-clock-start-time)
3344 (defvar org-clock-marker (make-marker)
3345 "Marker recording the last clock-in.")
3346 (defvar org-clock-hd-marker (make-marker)
3347 "Marker recording the last clock-in, but the headline position.")
3348 (defvar org-clock-heading ""
3349 "The heading of the current clock entry.")
3350 (defun org-clock-is-active ()
3351 "Return non-nil if clock is currently running.
3352 The return value is actually the clock marker."
3353 (marker-buffer org-clock-marker))
3355 (eval-and-compile
3356 (org-autoload
3357 "org-clock"
3358 '(org-clock-in org-clock-out org-clock-cancel
3359 org-clock-goto org-clock-sum org-clock-display
3360 org-clock-remove-overlays org-clock-report
3361 org-clocktable-shift org-dblock-write:clocktable
3362 org-get-clocktable org-resolve-clocks)))
3364 (defun org-clock-update-time-maybe ()
3365 "If this is a CLOCK line, update it and return t.
3366 Otherwise, return nil."
3367 (interactive)
3368 (save-excursion
3369 (beginning-of-line 1)
3370 (skip-chars-forward " \t")
3371 (when (looking-at org-clock-string)
3372 (let ((re (concat "[ \t]*" org-clock-string
3373 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3374 "\\([ \t]*=>.*\\)?\\)?"))
3375 ts te h m s neg)
3376 (cond
3377 ((not (looking-at re))
3378 nil)
3379 ((not (match-end 2))
3380 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3381 (> org-clock-marker (point))
3382 (<= org-clock-marker (point-at-eol)))
3383 ;; The clock is running here
3384 (setq org-clock-start-time
3385 (apply 'encode-time
3386 (org-parse-time-string (match-string 1))))
3387 (org-clock-update-mode-line)))
3389 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3390 (end-of-line 1)
3391 (setq ts (match-string 1)
3392 te (match-string 3))
3393 (setq s (- (org-float-time
3394 (apply 'encode-time (org-parse-time-string te)))
3395 (org-float-time
3396 (apply 'encode-time (org-parse-time-string ts))))
3397 neg (< s 0)
3398 s (abs s)
3399 h (floor (/ s 3600))
3400 s (- s (* 3600 h))
3401 m (floor (/ s 60))
3402 s (- s (* 60 s)))
3403 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3404 t))))))
3406 (defun org-check-running-clock ()
3407 "Check if the current buffer contains the running clock.
3408 If yes, offer to stop it and to save the buffer with the changes."
3409 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3410 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3411 (buffer-name))))
3412 (org-clock-out)
3413 (when (y-or-n-p "Save changed buffer?")
3414 (save-buffer))))
3416 (defun org-clocktable-try-shift (dir n)
3417 "Check if this line starts a clock table, if yes, shift the time block."
3418 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3419 (org-clocktable-shift dir n)))
3421 ;; Autoload org-timer.el
3423 (eval-and-compile
3424 (org-autoload
3425 "org-timer"
3426 '(org-timer-start org-timer org-timer-item
3427 org-timer-change-times-in-region
3428 org-timer-set-timer
3429 org-timer-reset-timers
3430 org-timer-show-remaining-time)))
3432 ;; Autoload org-feed.el
3434 (eval-and-compile
3435 (org-autoload
3436 "org-feed"
3437 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3440 ;; Autoload org-indent.el
3442 ;; Define the variable already here, to make sure we have it.
3443 (defvar org-indent-mode nil
3444 "Non-nil if Org-Indent mode is enabled.
3445 Use the command `org-indent-mode' to change this variable.")
3447 (eval-and-compile
3448 (org-autoload
3449 "org-indent"
3450 '(org-indent-mode)))
3452 ;; Autoload org-mobile.el
3454 (eval-and-compile
3455 (org-autoload
3456 "org-mobile"
3457 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3459 ;; Autoload archiving code
3460 ;; The stuff that is needed for cycling and tags has to be defined here.
3462 (defgroup org-archive nil
3463 "Options concerning archiving in Org-mode."
3464 :tag "Org Archive"
3465 :group 'org-structure)
3467 (defcustom org-archive-location "%s_archive::"
3468 "The location where subtrees should be archived.
3470 The value of this variable is a string, consisting of two parts,
3471 separated by a double-colon. The first part is a filename and
3472 the second part is a headline.
3474 When the filename is omitted, archiving happens in the same file.
3475 %s in the filename will be replaced by the current file
3476 name (without the directory part). Archiving to a different file
3477 is useful to keep archived entries from contributing to the
3478 Org-mode Agenda.
3480 The archived entries will be filed as subtrees of the specified
3481 headline. When the headline is omitted, the subtrees are simply
3482 filed away at the end of the file, as top-level entries. Also in
3483 the heading you can use %s to represent the file name, this can be
3484 useful when using the same archive for a number of different files.
3486 Here are a few examples:
3487 \"%s_archive::\"
3488 If the current file is Projects.org, archive in file
3489 Projects.org_archive, as top-level trees. This is the default.
3491 \"::* Archived Tasks\"
3492 Archive in the current file, under the top-level headline
3493 \"* Archived Tasks\".
3495 \"~/org/archive.org::\"
3496 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3498 \"~/org/archive.org::From %s\"
3499 Archive in file ~/org/archive.org (absolute path), under headlines
3500 \"From FILENAME\" where file name is the current file name.
3502 \"basement::** Finished Tasks\"
3503 Archive in file ./basement (relative path), as level 3 trees
3504 below the level 2 heading \"** Finished Tasks\".
3506 You may set this option on a per-file basis by adding to the buffer a
3507 line like
3509 #+ARCHIVE: basement::** Finished Tasks
3511 You may also define it locally for a subtree by setting an ARCHIVE property
3512 in the entry. If such a property is found in an entry, or anywhere up
3513 the hierarchy, it will be used."
3514 :group 'org-archive
3515 :type 'string)
3517 (defcustom org-archive-tag "ARCHIVE"
3518 "The tag that marks a subtree as archived.
3519 An archived subtree does not open during visibility cycling, and does
3520 not contribute to the agenda listings.
3521 After changing this, font-lock must be restarted in the relevant buffers to
3522 get the proper fontification."
3523 :group 'org-archive
3524 :group 'org-keywords
3525 :type 'string)
3527 (defcustom org-agenda-skip-archived-trees t
3528 "Non-nil means, the agenda will skip any items located in archived trees.
3529 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3530 variable is no longer recommended, you should leave it at the value t.
3531 Instead, use the key `v' to cycle the archives-mode in the agenda."
3532 :group 'org-archive
3533 :group 'org-agenda-skip
3534 :type 'boolean)
3536 (defcustom org-columns-skip-archived-trees t
3537 "Non-nil means, ignore archived trees when creating column view."
3538 :group 'org-archive
3539 :group 'org-properties
3540 :type 'boolean)
3542 (defcustom org-cycle-open-archived-trees nil
3543 "Non-nil means, `org-cycle' will open archived trees.
3544 An archived tree is a tree marked with the tag ARCHIVE.
3545 When nil, archived trees will stay folded. You can still open them with
3546 normal outline commands like `show-all', but not with the cycling commands."
3547 :group 'org-archive
3548 :group 'org-cycle
3549 :type 'boolean)
3551 (defcustom org-sparse-tree-open-archived-trees nil
3552 "Non-nil means sparse tree construction shows matches in archived trees.
3553 When nil, matches in these trees are highlighted, but the trees are kept in
3554 collapsed state."
3555 :group 'org-archive
3556 :group 'org-sparse-trees
3557 :type 'boolean)
3559 (defun org-cycle-hide-archived-subtrees (state)
3560 "Re-hide all archived subtrees after a visibility state change."
3561 (when (and (not org-cycle-open-archived-trees)
3562 (not (memq state '(overview folded))))
3563 (save-excursion
3564 (let* ((globalp (memq state '(contents all)))
3565 (beg (if globalp (point-min) (point)))
3566 (end (if globalp (point-max) (org-end-of-subtree t))))
3567 (org-hide-archived-subtrees beg end)
3568 (goto-char beg)
3569 (if (looking-at (concat ".*:" org-archive-tag ":"))
3570 (message "%s" (substitute-command-keys
3571 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3573 (defun org-force-cycle-archived ()
3574 "Cycle subtree even if it is archived."
3575 (interactive)
3576 (setq this-command 'org-cycle)
3577 (let ((org-cycle-open-archived-trees t))
3578 (call-interactively 'org-cycle)))
3580 (defun org-hide-archived-subtrees (beg end)
3581 "Re-hide all archived subtrees after a visibility state change."
3582 (save-excursion
3583 (let* ((re (concat ":" org-archive-tag ":")))
3584 (goto-char beg)
3585 (while (re-search-forward re end t)
3586 (and (org-on-heading-p) (org-flag-subtree t))
3587 (org-end-of-subtree t)))))
3589 (defun org-flag-subtree (flag)
3590 (save-excursion
3591 (org-back-to-heading t)
3592 (outline-end-of-heading)
3593 (outline-flag-region (point)
3594 (progn (org-end-of-subtree t) (point))
3595 flag)))
3597 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3599 (eval-and-compile
3600 (org-autoload "org-archive"
3601 '(org-add-archive-files org-archive-subtree
3602 org-archive-to-archive-sibling org-toggle-archive-tag
3603 org-archive-subtree-default
3604 org-archive-subtree-default-with-confirmation)))
3606 ;; Autoload Column View Code
3608 (declare-function org-columns-number-to-string "org-colview")
3609 (declare-function org-columns-get-format-and-top-level "org-colview")
3610 (declare-function org-columns-compute "org-colview")
3612 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3613 '(org-columns-number-to-string org-columns-get-format-and-top-level
3614 org-columns-compute org-agenda-columns org-columns-remove-overlays
3615 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3617 ;; Autoload ID code
3619 (declare-function org-id-store-link "org-id")
3620 (declare-function org-id-locations-load "org-id")
3621 (declare-function org-id-locations-save "org-id")
3622 (defvar org-id-track-globally)
3623 (org-autoload "org-id"
3624 '(org-id-get-create org-id-new org-id-copy org-id-get
3625 org-id-get-with-outline-path-completion
3626 org-id-get-with-outline-drilling
3627 org-id-goto org-id-find org-id-store-link))
3629 ;; Autoload Plotting Code
3631 (org-autoload "org-plot"
3632 '(org-plot/gnuplot))
3634 ;;; Variables for pre-computed regular expressions, all buffer local
3636 (defvar org-drawer-regexp nil
3637 "Matches first line of a hidden block.")
3638 (make-variable-buffer-local 'org-drawer-regexp)
3639 (defvar org-todo-regexp nil
3640 "Matches any of the TODO state keywords.")
3641 (make-variable-buffer-local 'org-todo-regexp)
3642 (defvar org-not-done-regexp nil
3643 "Matches any of the TODO state keywords except the last one.")
3644 (make-variable-buffer-local 'org-not-done-regexp)
3645 (defvar org-not-done-heading-regexp nil
3646 "Matches a TODO headline that is not done.")
3647 (make-variable-buffer-local 'org-not-done-regexp)
3648 (defvar org-todo-line-regexp nil
3649 "Matches a headline and puts TODO state into group 2 if present.")
3650 (make-variable-buffer-local 'org-todo-line-regexp)
3651 (defvar org-complex-heading-regexp nil
3652 "Matches a headline and puts everything into groups:
3653 group 1: the stars
3654 group 2: The todo keyword, maybe
3655 group 3: Priority cookie
3656 group 4: True headline
3657 group 5: Tags")
3658 (make-variable-buffer-local 'org-complex-heading-regexp)
3659 (defvar org-complex-heading-regexp-format nil)
3660 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3661 (defvar org-todo-line-tags-regexp nil
3662 "Matches a headline and puts TODO state into group 2 if present.
3663 Also put tags into group 4 if tags are present.")
3664 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3665 (defvar org-nl-done-regexp nil
3666 "Matches newline followed by a headline with the DONE keyword.")
3667 (make-variable-buffer-local 'org-nl-done-regexp)
3668 (defvar org-looking-at-done-regexp nil
3669 "Matches the DONE keyword a point.")
3670 (make-variable-buffer-local 'org-looking-at-done-regexp)
3671 (defvar org-ds-keyword-length 12
3672 "Maximum length of the Deadline and SCHEDULED keywords.")
3673 (make-variable-buffer-local 'org-ds-keyword-length)
3674 (defvar org-deadline-regexp nil
3675 "Matches the DEADLINE keyword.")
3676 (make-variable-buffer-local 'org-deadline-regexp)
3677 (defvar org-deadline-time-regexp nil
3678 "Matches the DEADLINE keyword together with a time stamp.")
3679 (make-variable-buffer-local 'org-deadline-time-regexp)
3680 (defvar org-deadline-line-regexp nil
3681 "Matches the DEADLINE keyword and the rest of the line.")
3682 (make-variable-buffer-local 'org-deadline-line-regexp)
3683 (defvar org-scheduled-regexp nil
3684 "Matches the SCHEDULED keyword.")
3685 (make-variable-buffer-local 'org-scheduled-regexp)
3686 (defvar org-scheduled-time-regexp nil
3687 "Matches the SCHEDULED keyword together with a time stamp.")
3688 (make-variable-buffer-local 'org-scheduled-time-regexp)
3689 (defvar org-closed-time-regexp nil
3690 "Matches the CLOSED keyword together with a time stamp.")
3691 (make-variable-buffer-local 'org-closed-time-regexp)
3693 (defvar org-keyword-time-regexp nil
3694 "Matches any of the 4 keywords, together with the time stamp.")
3695 (make-variable-buffer-local 'org-keyword-time-regexp)
3696 (defvar org-keyword-time-not-clock-regexp nil
3697 "Matches any of the 3 keywords, together with the time stamp.")
3698 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3699 (defvar org-maybe-keyword-time-regexp nil
3700 "Matches a timestamp, possibly preceeded by a keyword.")
3701 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3702 (defvar org-planning-or-clock-line-re nil
3703 "Matches a line with planning or clock info.")
3704 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3705 (defvar org-all-time-keywords nil
3706 "List of time keywords.")
3707 (make-variable-buffer-local 'org-all-time-keywords)
3709 (defconst org-plain-time-of-day-regexp
3710 (concat
3711 "\\(\\<[012]?[0-9]"
3712 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3713 "\\(--?"
3714 "\\(\\<[012]?[0-9]"
3715 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3716 "\\)?")
3717 "Regular expression to match a plain time or time range.
3718 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3719 groups carry important information:
3720 0 the full match
3721 1 the first time, range or not
3722 8 the second time, if it is a range.")
3724 (defconst org-plain-time-extension-regexp
3725 (concat
3726 "\\(\\<[012]?[0-9]"
3727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3728 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3729 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3730 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3731 groups carry important information:
3732 0 the full match
3733 7 hours of duration
3734 9 minutes of duration")
3736 (defconst org-stamp-time-of-day-regexp
3737 (concat
3738 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3739 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3740 "\\(--?"
3741 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3742 "Regular expression to match a timestamp time or time range.
3743 After a match, the following groups carry important information:
3744 0 the full match
3745 1 date plus weekday, for back referencing to make sure both times are on the same day
3746 2 the first time, range or not
3747 4 the second time, if it is a range.")
3749 (defconst org-startup-options
3750 '(("fold" org-startup-folded t)
3751 ("overview" org-startup-folded t)
3752 ("nofold" org-startup-folded nil)
3753 ("showall" org-startup-folded nil)
3754 ("showeverything" org-startup-folded showeverything)
3755 ("content" org-startup-folded content)
3756 ("indent" org-startup-indented t)
3757 ("noindent" org-startup-indented nil)
3758 ("hidestars" org-hide-leading-stars t)
3759 ("showstars" org-hide-leading-stars nil)
3760 ("odd" org-odd-levels-only t)
3761 ("oddeven" org-odd-levels-only nil)
3762 ("align" org-startup-align-all-tables t)
3763 ("noalign" org-startup-align-all-tables nil)
3764 ("customtime" org-display-custom-times t)
3765 ("logdone" org-log-done time)
3766 ("lognotedone" org-log-done note)
3767 ("nologdone" org-log-done nil)
3768 ("lognoteclock-out" org-log-note-clock-out t)
3769 ("nolognoteclock-out" org-log-note-clock-out nil)
3770 ("logrepeat" org-log-repeat state)
3771 ("lognoterepeat" org-log-repeat note)
3772 ("nologrepeat" org-log-repeat nil)
3773 ("logreschedule" org-log-reschedule time)
3774 ("lognotereschedule" org-log-reschedule note)
3775 ("nologreschedule" org-log-reschedule nil)
3776 ("logredeadline" org-log-redeadline time)
3777 ("lognoteredeadline" org-log-redeadline note)
3778 ("nologredeadline" org-log-redeadline nil)
3779 ("fninline" org-footnote-define-inline t)
3780 ("nofninline" org-footnote-define-inline nil)
3781 ("fnlocal" org-footnote-section nil)
3782 ("fnauto" org-footnote-auto-label t)
3783 ("fnprompt" org-footnote-auto-label nil)
3784 ("fnconfirm" org-footnote-auto-label confirm)
3785 ("fnplain" org-footnote-auto-label plain)
3786 ("fnadjust" org-footnote-auto-adjust t)
3787 ("nofnadjust" org-footnote-auto-adjust nil)
3788 ("constcgs" constants-unit-system cgs)
3789 ("constSI" constants-unit-system SI)
3790 ("noptag" org-tag-persistent-alist nil)
3791 ("hideblocks" org-hide-block-startup t)
3792 ("nohideblocks" org-hide-block-startup nil)
3793 ("beamer" org-startup-with-beamer-mode t))
3794 "Variable associated with STARTUP options for org-mode.
3795 Each element is a list of three items: The startup options as written
3796 in the #+STARTUP line, the corresponding variable, and the value to
3797 set this variable to if the option is found. An optional forth element PUSH
3798 means to push this value onto the list in the variable.")
3800 (defun org-set-regexps-and-options ()
3801 "Precompute regular expressions for current buffer."
3802 (when (org-mode-p)
3803 (org-set-local 'org-todo-kwd-alist nil)
3804 (org-set-local 'org-todo-key-alist nil)
3805 (org-set-local 'org-todo-key-trigger nil)
3806 (org-set-local 'org-todo-keywords-1 nil)
3807 (org-set-local 'org-done-keywords nil)
3808 (org-set-local 'org-todo-heads nil)
3809 (org-set-local 'org-todo-sets nil)
3810 (org-set-local 'org-todo-log-states nil)
3811 (org-set-local 'org-file-properties nil)
3812 (org-set-local 'org-file-tags nil)
3813 (let ((re (org-make-options-regexp
3814 '("CATEGORY" "TODO" "COLUMNS"
3815 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3816 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3817 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3818 (splitre "[ \t]+")
3819 kwds kws0 kwsa key log value cat arch tags const links hw dws
3820 tail sep kws1 prio props ftags drawers beamer-p
3821 ext-setup-or-nil setup-contents (start 0))
3822 (save-excursion
3823 (save-restriction
3824 (widen)
3825 (goto-char (point-min))
3826 (while (or (and ext-setup-or-nil
3827 (string-match re ext-setup-or-nil start)
3828 (setq start (match-end 0)))
3829 (and (setq ext-setup-or-nil nil start 0)
3830 (re-search-forward re nil t)))
3831 (setq key (upcase (match-string 1 ext-setup-or-nil))
3832 value (org-match-string-no-properties 2 ext-setup-or-nil))
3833 (cond
3834 ((equal key "CATEGORY")
3835 (if (string-match "[ \t]+$" value)
3836 (setq value (replace-match "" t t value)))
3837 (setq cat value))
3838 ((member key '("SEQ_TODO" "TODO"))
3839 (push (cons 'sequence (org-split-string value splitre)) kwds))
3840 ((equal key "TYP_TODO")
3841 (push (cons 'type (org-split-string value splitre)) kwds))
3842 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3843 ;; general TODO-like setup
3844 (push (cons (intern (downcase (match-string 1 key)))
3845 (org-split-string value splitre)) kwds))
3846 ((equal key "TAGS")
3847 (setq tags (append tags (if tags '("\\n") nil)
3848 (org-split-string value splitre))))
3849 ((equal key "COLUMNS")
3850 (org-set-local 'org-columns-default-format value))
3851 ((equal key "LINK")
3852 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3853 (push (cons (match-string 1 value)
3854 (org-trim (match-string 2 value)))
3855 links)))
3856 ((equal key "PRIORITIES")
3857 (setq prio (org-split-string value " +")))
3858 ((equal key "PROPERTY")
3859 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3860 (push (cons (match-string 1 value) (match-string 2 value))
3861 props)))
3862 ((equal key "FILETAGS")
3863 (when (string-match "\\S-" value)
3864 (setq ftags
3865 (append
3866 ftags
3867 (apply 'append
3868 (mapcar (lambda (x) (org-split-string x ":"))
3869 (org-split-string value)))))))
3870 ((equal key "DRAWERS")
3871 (setq drawers (org-split-string value splitre)))
3872 ((equal key "CONSTANTS")
3873 (setq const (append const (org-split-string value splitre))))
3874 ((equal key "STARTUP")
3875 (let ((opts (org-split-string value splitre))
3876 l var val)
3877 (while (setq l (pop opts))
3878 (when (setq l (assoc l org-startup-options))
3879 (setq var (nth 1 l) val (nth 2 l))
3880 (if (not (nth 3 l))
3881 (set (make-local-variable var) val)
3882 (if (not (listp (symbol-value var)))
3883 (set (make-local-variable var) nil))
3884 (set (make-local-variable var) (symbol-value var))
3885 (add-to-list var val))))))
3886 ((equal key "ARCHIVE")
3887 (string-match " *$" value)
3888 (setq arch (replace-match "" t t value))
3889 (remove-text-properties 0 (length arch)
3890 '(face t fontified t) arch))
3891 ((equal key "LATEX_CLASS")
3892 (setq beamer-p (equal value "beamer")))
3893 ((equal key "SETUPFILE")
3894 (setq setup-contents (org-file-contents
3895 (expand-file-name
3896 (org-remove-double-quotes value))
3897 'noerror))
3898 (if (not ext-setup-or-nil)
3899 (setq ext-setup-or-nil setup-contents start 0)
3900 (setq ext-setup-or-nil
3901 (concat (substring ext-setup-or-nil 0 start)
3902 "\n" setup-contents "\n"
3903 (substring ext-setup-or-nil start)))))
3904 ))))
3905 (when cat
3906 (org-set-local 'org-category (intern cat))
3907 (push (cons "CATEGORY" cat) props))
3908 (when prio
3909 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3910 (setq prio (mapcar 'string-to-char prio))
3911 (org-set-local 'org-highest-priority (nth 0 prio))
3912 (org-set-local 'org-lowest-priority (nth 1 prio))
3913 (org-set-local 'org-default-priority (nth 2 prio)))
3914 (and props (org-set-local 'org-file-properties (nreverse props)))
3915 (and ftags (org-set-local 'org-file-tags
3916 (mapcar 'org-add-prop-inherited ftags)))
3917 (and drawers (org-set-local 'org-drawers drawers))
3918 (and arch (org-set-local 'org-archive-location arch))
3919 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3920 ;; Process the TODO keywords
3921 (unless kwds
3922 ;; Use the global values as if they had been given locally.
3923 (setq kwds (default-value 'org-todo-keywords))
3924 (if (stringp (car kwds))
3925 (setq kwds (list (cons org-todo-interpretation
3926 (default-value 'org-todo-keywords)))))
3927 (setq kwds (reverse kwds)))
3928 (setq kwds (nreverse kwds))
3929 (let (inter kws kw)
3930 (while (setq kws (pop kwds))
3931 (let ((kws (or
3932 (run-hook-with-args-until-success
3933 'org-todo-setup-filter-hook kws)
3934 kws)))
3935 (setq inter (pop kws) sep (member "|" kws)
3936 kws0 (delete "|" (copy-sequence kws))
3937 kwsa nil
3938 kws1 (mapcar
3939 (lambda (x)
3940 ;; 1 2
3941 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3942 (progn
3943 (setq kw (match-string 1 x)
3944 key (and (match-end 2) (match-string 2 x))
3945 log (org-extract-log-state-settings x))
3946 (push (cons kw (and key (string-to-char key))) kwsa)
3947 (and log (push log org-todo-log-states))
3949 (error "Invalid TODO keyword %s" x)))
3950 kws0)
3951 kwsa (if kwsa (append '((:startgroup))
3952 (nreverse kwsa)
3953 '((:endgroup))))
3954 hw (car kws1)
3955 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3956 tail (list inter hw (car dws) (org-last dws))))
3957 (add-to-list 'org-todo-heads hw 'append)
3958 (push kws1 org-todo-sets)
3959 (setq org-done-keywords (append org-done-keywords dws nil))
3960 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3961 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3962 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3963 (setq org-todo-sets (nreverse org-todo-sets)
3964 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3965 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3966 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3967 ;; Process the constants
3968 (when const
3969 (let (e cst)
3970 (while (setq e (pop const))
3971 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3972 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3973 (setq org-table-formula-constants-local cst)))
3975 ;; Process the tags.
3976 (when tags
3977 (let (e tgs)
3978 (while (setq e (pop tags))
3979 (cond
3980 ((equal e "{") (push '(:startgroup) tgs))
3981 ((equal e "}") (push '(:endgroup) tgs))
3982 ((equal e "\\n") (push '(:newline) tgs))
3983 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3984 (push (cons (match-string 1 e)
3985 (string-to-char (match-string 2 e)))
3986 tgs))
3987 (t (push (list e) tgs))))
3988 (org-set-local 'org-tag-alist nil)
3989 (while (setq e (pop tgs))
3990 (or (and (stringp (car e))
3991 (assoc (car e) org-tag-alist))
3992 (push e org-tag-alist)))))
3994 ;; Compute the regular expressions and other local variables
3995 (if (not org-done-keywords)
3996 (setq org-done-keywords (and org-todo-keywords-1
3997 (list (org-last org-todo-keywords-1)))))
3998 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3999 (length org-scheduled-string)
4000 (length org-clock-string)
4001 (length org-closed-string)))
4002 org-drawer-regexp
4003 (concat "^[ \t]*:\\("
4004 (mapconcat 'regexp-quote org-drawers "\\|")
4005 "\\):[ \t]*$")
4006 org-not-done-keywords
4007 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4008 org-todo-regexp
4009 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4010 "\\|") "\\)\\>")
4011 org-not-done-regexp
4012 (concat "\\<\\("
4013 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4014 "\\)\\>")
4015 org-not-done-heading-regexp
4016 (concat "^\\(\\*+\\)[ \t]+\\("
4017 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4018 "\\)\\>")
4019 org-todo-line-regexp
4020 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4021 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4022 "\\)\\>\\)?[ \t]*\\(.*\\)")
4023 org-complex-heading-regexp
4024 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4025 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4026 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4027 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4028 org-complex-heading-regexp-format
4029 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4030 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4031 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4032 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4033 org-nl-done-regexp
4034 (concat "\n\\*+[ \t]+"
4035 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4036 "\\)" "\\>")
4037 org-todo-line-tags-regexp
4038 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4039 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4040 (org-re
4041 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4042 org-looking-at-done-regexp
4043 (concat "^" "\\(?:"
4044 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4045 "\\>")
4046 org-deadline-regexp (concat "\\<" org-deadline-string)
4047 org-deadline-time-regexp
4048 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4049 org-deadline-line-regexp
4050 (concat "\\<\\(" org-deadline-string "\\).*")
4051 org-scheduled-regexp
4052 (concat "\\<" org-scheduled-string)
4053 org-scheduled-time-regexp
4054 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4055 org-closed-time-regexp
4056 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4057 org-keyword-time-regexp
4058 (concat "\\<\\(" org-scheduled-string
4059 "\\|" org-deadline-string
4060 "\\|" org-closed-string
4061 "\\|" org-clock-string "\\)"
4062 " *[[<]\\([^]>]+\\)[]>]")
4063 org-keyword-time-not-clock-regexp
4064 (concat "\\<\\(" org-scheduled-string
4065 "\\|" org-deadline-string
4066 "\\|" org-closed-string
4067 "\\)"
4068 " *[[<]\\([^]>]+\\)[]>]")
4069 org-maybe-keyword-time-regexp
4070 (concat "\\(\\<\\(" org-scheduled-string
4071 "\\|" org-deadline-string
4072 "\\|" org-closed-string
4073 "\\|" org-clock-string "\\)\\)?"
4074 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4075 org-planning-or-clock-line-re
4076 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4077 "\\|" org-deadline-string
4078 "\\|" org-closed-string "\\|" org-clock-string
4079 "\\)\\>\\)")
4080 org-all-time-keywords
4081 (mapcar (lambda (w) (substring w 0 -1))
4082 (list org-scheduled-string org-deadline-string
4083 org-clock-string org-closed-string))
4085 (org-compute-latex-and-specials-regexp)
4086 (org-set-font-lock-defaults))))
4088 (defun org-file-contents (file &optional noerror)
4089 "Return the contents of FILE, as a string."
4090 (if (or (not file)
4091 (not (file-readable-p file)))
4092 (if noerror
4093 (progn
4094 (message "Cannot read file %s" file)
4095 (ding) (sit-for 2)
4097 (error "Cannot read file %s" file))
4098 (with-temp-buffer
4099 (insert-file-contents file)
4100 (buffer-string))))
4102 (defun org-extract-log-state-settings (x)
4103 "Extract the log state setting from a TODO keyword string.
4104 This will extract info from a string like \"WAIT(w@/!)\"."
4105 (let (kw key log1 log2)
4106 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4107 (setq kw (match-string 1 x)
4108 key (and (match-end 2) (match-string 2 x))
4109 log1 (and (match-end 3) (match-string 3 x))
4110 log2 (and (match-end 4) (match-string 4 x)))
4111 (and (or log1 log2)
4112 (list kw
4113 (and log1 (if (equal log1 "!") 'time 'note))
4114 (and log2 (if (equal log2 "!") 'time 'note)))))))
4116 (defun org-remove-keyword-keys (list)
4117 "Remove a pair of parenthesis at the end of each string in LIST."
4118 (mapcar (lambda (x)
4119 (if (string-match "(.*)$" x)
4120 (substring x 0 (match-beginning 0))
4122 list))
4124 ;; FIXME: this could be done much better, using second characters etc.
4125 (defun org-assign-fast-keys (alist)
4126 "Assign fast keys to a keyword-key alist.
4127 Respect keys that are already there."
4128 (let (new e k c c1 c2 (char ?a))
4129 (while (setq e (pop alist))
4130 (cond
4131 ((equal e '(:startgroup)) (push e new))
4132 ((equal e '(:endgroup)) (push e new))
4133 ((equal e '(:newline)) (push e new))
4135 (setq k (car e) c2 nil)
4136 (if (cdr e)
4137 (setq c (cdr e))
4138 ;; automatically assign a character.
4139 (setq c1 (string-to-char
4140 (downcase (substring
4141 k (if (= (string-to-char k) ?@) 1 0)))))
4142 (if (or (rassoc c1 new) (rassoc c1 alist))
4143 (while (or (rassoc char new) (rassoc char alist))
4144 (setq char (1+ char)))
4145 (setq c2 c1))
4146 (setq c (or c2 char)))
4147 (push (cons k c) new))))
4148 (nreverse new)))
4150 ;;; Some variables used in various places
4152 (defvar org-window-configuration nil
4153 "Used in various places to store a window configuration.")
4154 (defvar org-selected-window nil
4155 "Used in various places to store a window configuration.")
4156 (defvar org-finish-function nil
4157 "Function to be called when `C-c C-c' is used.
4158 This is for getting out of special buffers like remember.")
4161 ;; FIXME: Occasionally check by commenting these, to make sure
4162 ;; no other functions uses these, forgetting to let-bind them.
4163 (defvar entry)
4164 (defvar last-state)
4165 (defvar date)
4167 ;; Defined somewhere in this file, but used before definition.
4168 (defvar org-html-entities)
4169 (defvar org-struct-menu)
4170 (defvar org-org-menu)
4171 (defvar org-tbl-menu)
4173 ;;;; Define the Org-mode
4175 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4176 (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."))
4179 ;; We use a before-change function to check if a table might need
4180 ;; an update.
4181 (defvar org-table-may-need-update t
4182 "Indicates that a table might need an update.
4183 This variable is set by `org-before-change-function'.
4184 `org-table-align' sets it back to nil.")
4185 (defun org-before-change-function (beg end)
4186 "Every change indicates that a table might need an update."
4187 (setq org-table-may-need-update t))
4188 (defvar org-mode-map)
4189 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4190 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4191 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4192 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4193 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4194 (defvar org-table-buffer-is-an nil)
4195 (defconst org-outline-regexp "\\*+ ")
4197 ;;;###autoload
4198 (define-derived-mode org-mode outline-mode "Org"
4199 "Outline-based notes management and organizer, alias
4200 \"Carsten's outline-mode for keeping track of everything.\"
4202 Org-mode develops organizational tasks around a NOTES file which
4203 contains information about projects as plain text. Org-mode is
4204 implemented on top of outline-mode, which is ideal to keep the content
4205 of large files well structured. It supports ToDo items, deadlines and
4206 time stamps, which magically appear in the diary listing of the Emacs
4207 calendar. Tables are easily created with a built-in table editor.
4208 Plain text URL-like links connect to websites, emails (VM), Usenet
4209 messages (Gnus), BBDB entries, and any files related to the project.
4210 For printing and sharing of notes, an Org-mode file (or a part of it)
4211 can be exported as a structured ASCII or HTML file.
4213 The following commands are available:
4215 \\{org-mode-map}"
4217 ;; Get rid of Outline menus, they are not needed
4218 ;; Need to do this here because define-derived-mode sets up
4219 ;; the keymap so late. Still, it is a waste to call this each time
4220 ;; we switch another buffer into org-mode.
4221 (if (featurep 'xemacs)
4222 (when (boundp 'outline-mode-menu-heading)
4223 ;; Assume this is Greg's port, it used easymenu
4224 (easy-menu-remove outline-mode-menu-heading)
4225 (easy-menu-remove outline-mode-menu-show)
4226 (easy-menu-remove outline-mode-menu-hide))
4227 (define-key org-mode-map [menu-bar headings] 'undefined)
4228 (define-key org-mode-map [menu-bar hide] 'undefined)
4229 (define-key org-mode-map [menu-bar show] 'undefined))
4231 (org-load-modules-maybe)
4232 (easy-menu-add org-org-menu)
4233 (easy-menu-add org-tbl-menu)
4234 (org-install-agenda-files-menu)
4235 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4236 (org-add-to-invisibility-spec '(org-cwidth))
4237 (org-add-to-invisibility-spec '(org-hide-block . t))
4238 (when (featurep 'xemacs)
4239 (org-set-local 'line-move-ignore-invisible t))
4240 (org-set-local 'outline-regexp org-outline-regexp)
4241 (org-set-local 'outline-level 'org-outline-level)
4242 (when (and org-ellipsis
4243 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4244 (fboundp 'make-glyph-code))
4245 (unless org-display-table
4246 (setq org-display-table (make-display-table)))
4247 (set-display-table-slot
4248 org-display-table 4
4249 (vconcat (mapcar
4250 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4251 org-ellipsis)))
4252 (if (stringp org-ellipsis) org-ellipsis "..."))))
4253 (setq buffer-display-table org-display-table))
4254 (org-set-regexps-and-options)
4255 (when (and org-tag-faces (not org-tags-special-faces-re))
4256 ;; tag faces set outside customize.... force initialization.
4257 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4258 ;; Calc embedded
4259 (org-set-local 'calc-embedded-open-mode "# ")
4260 (modify-syntax-entry ?# "<")
4261 (modify-syntax-entry ?@ "w")
4262 (if org-startup-truncated (setq truncate-lines t))
4263 (org-set-local 'font-lock-unfontify-region-function
4264 'org-unfontify-region)
4265 ;; Activate before-change-function
4266 (org-set-local 'org-table-may-need-update t)
4267 (org-add-hook 'before-change-functions 'org-before-change-function nil
4268 'local)
4269 ;; Check for running clock before killing a buffer
4270 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4271 ;; Paragraphs and auto-filling
4272 (org-set-autofill-regexps)
4273 (setq indent-line-function 'org-indent-line-function)
4274 (org-update-radio-target-regexp)
4275 ;; Make sure dependence stuff works reliably, even for users who set it
4276 ;; too late :-(
4277 (if org-enforce-todo-dependencies
4278 (add-hook 'org-blocker-hook
4279 'org-block-todo-from-children-or-siblings-or-parent)
4280 (remove-hook 'org-blocker-hook
4281 'org-block-todo-from-children-or-siblings-or-parent))
4282 (if org-enforce-todo-checkbox-dependencies
4283 (add-hook 'org-blocker-hook
4284 'org-block-todo-from-checkboxes)
4285 (remove-hook 'org-blocker-hook
4286 'org-block-todo-from-checkboxes))
4288 ;; Comment characters
4289 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4290 (org-set-local 'comment-padding " ")
4292 ;; Align options lines
4293 (org-set-local
4294 'align-mode-rules-list
4295 '((org-in-buffer-settings
4296 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4297 (modes . '(org-mode)))))
4299 ;; Imenu
4300 (org-set-local 'imenu-create-index-function
4301 'org-imenu-get-tree)
4303 ;; Make isearch reveal context
4304 (if (or (featurep 'xemacs)
4305 (not (boundp 'outline-isearch-open-invisible-function)))
4306 ;; Emacs 21 and XEmacs make use of the hook
4307 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4308 ;; Emacs 22 deals with this through a special variable
4309 (org-set-local 'outline-isearch-open-invisible-function
4310 (lambda (&rest ignore) (org-show-context 'isearch))))
4312 ;; Turn on org-beamer-mode?
4313 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4315 ;; If empty file that did not turn on org-mode automatically, make it to.
4316 (if (and org-insert-mode-line-in-empty-file
4317 (interactive-p)
4318 (= (point-min) (point-max)))
4319 (insert "# -*- mode: org -*-\n\n"))
4320 (unless org-inhibit-startup
4321 (when org-startup-align-all-tables
4322 (let ((bmp (buffer-modified-p)))
4323 (org-table-map-tables 'org-table-align)
4324 (set-buffer-modified-p bmp)))
4325 (when org-startup-indented
4326 (require 'org-indent)
4327 (org-indent-mode 1))
4328 (unless org-inhibit-startup-visibility-stuff
4329 (org-set-startup-visibility))))
4331 (when (fboundp 'abbrev-table-put)
4332 (abbrev-table-put org-mode-abbrev-table
4333 :parents (list text-mode-abbrev-table)))
4335 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4337 (defun org-current-time ()
4338 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4339 (if (> (car org-time-stamp-rounding-minutes) 1)
4340 (let ((r (car org-time-stamp-rounding-minutes))
4341 (time (decode-time)))
4342 (apply 'encode-time
4343 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4344 (nthcdr 2 time))))
4345 (current-time)))
4347 ;;;; Font-Lock stuff, including the activators
4349 (defvar org-mouse-map (make-sparse-keymap))
4350 (org-defkey org-mouse-map
4351 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4352 (org-defkey org-mouse-map
4353 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4354 (when org-mouse-1-follows-link
4355 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4356 (when org-tab-follows-link
4357 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4358 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4360 (require 'font-lock)
4362 (defconst org-non-link-chars "]\t\n\r<>")
4363 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4364 "shell" "elisp"))
4365 (defvar org-link-types-re nil
4366 "Matches a link that has a url-like prefix like \"http:\"")
4367 (defvar org-link-re-with-space nil
4368 "Matches a link with spaces, optional angular brackets around it.")
4369 (defvar org-link-re-with-space2 nil
4370 "Matches a link with spaces, optional angular brackets around it.")
4371 (defvar org-link-re-with-space3 nil
4372 "Matches a link with spaces, only for internal part in bracket links.")
4373 (defvar org-angle-link-re nil
4374 "Matches link with angular brackets, spaces are allowed.")
4375 (defvar org-plain-link-re nil
4376 "Matches plain link, without spaces.")
4377 (defvar org-bracket-link-regexp nil
4378 "Matches a link in double brackets.")
4379 (defvar org-bracket-link-analytic-regexp nil
4380 "Regular expression used to analyze links.
4381 Here is what the match groups contain after a match:
4382 1: http:
4383 2: http
4384 3: path
4385 4: [desc]
4386 5: desc")
4387 (defvar org-bracket-link-analytic-regexp++ nil
4388 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4389 (defvar org-any-link-re nil
4390 "Regular expression matching any link.")
4392 (defun org-make-link-regexps ()
4393 "Update the link regular expressions.
4394 This should be called after the variable `org-link-types' has changed."
4395 (setq org-link-types-re
4396 (concat
4397 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4398 org-link-re-with-space
4399 (concat
4400 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4401 "\\([^" org-non-link-chars " ]"
4402 "[^" org-non-link-chars "]*"
4403 "[^" org-non-link-chars " ]\\)>?")
4404 org-link-re-with-space2
4405 (concat
4406 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4407 "\\([^" org-non-link-chars " ]"
4408 "[^\t\n\r]*"
4409 "[^" org-non-link-chars " ]\\)>?")
4410 org-link-re-with-space3
4411 (concat
4412 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4413 "\\([^" org-non-link-chars " ]"
4414 "[^\t\n\r]*\\)")
4415 org-angle-link-re
4416 (concat
4417 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4418 "\\([^" org-non-link-chars " ]"
4419 "[^" org-non-link-chars "]*"
4420 "\\)>")
4421 org-plain-link-re
4422 (concat
4423 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4424 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4425 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4426 org-bracket-link-regexp
4427 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4428 org-bracket-link-analytic-regexp
4429 (concat
4430 "\\[\\["
4431 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4432 "\\([^]]+\\)"
4433 "\\]"
4434 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4435 "\\]")
4436 org-bracket-link-analytic-regexp++
4437 (concat
4438 "\\[\\["
4439 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4440 "\\([^]]+\\)"
4441 "\\]"
4442 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4443 "\\]")
4444 org-any-link-re
4445 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4446 org-angle-link-re "\\)\\|\\("
4447 org-plain-link-re "\\)")))
4449 (org-make-link-regexps)
4451 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4452 "Regular expression for fast time stamp matching.")
4453 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4454 "Regular expression for fast time stamp matching.")
4455 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4456 "Regular expression matching time strings for analysis.
4457 This one does not require the space after the date, so it can be used
4458 on a string that terminates immediately after the date.")
4459 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4460 "Regular expression matching time strings for analysis.")
4461 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4462 "Regular expression matching time stamps, with groups.")
4463 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4464 "Regular expression matching time stamps (also [..]), with groups.")
4465 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4466 "Regular expression matching a time stamp range.")
4467 (defconst org-tr-regexp-both
4468 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4469 "Regular expression matching a time stamp range.")
4470 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4471 org-ts-regexp "\\)?")
4472 "Regular expression matching a time stamp or time stamp range.")
4473 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4474 org-ts-regexp-both "\\)?")
4475 "Regular expression matching a time stamp or time stamp range.
4476 The time stamps may be either active or inactive.")
4478 (defvar org-emph-face nil)
4480 (defun org-do-emphasis-faces (limit)
4481 "Run through the buffer and add overlays to links."
4482 (let (rtn a)
4483 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4484 (if (not (= (char-after (match-beginning 3))
4485 (char-after (match-beginning 4))))
4486 (progn
4487 (setq rtn t)
4488 (setq a (assoc (match-string 3) org-emphasis-alist))
4489 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4490 'face
4491 (nth 1 a))
4492 (and (nth 4 a)
4493 (org-remove-flyspell-overlays-in
4494 (match-beginning 0) (match-end 0)))
4495 (add-text-properties (match-beginning 2) (match-end 2)
4496 '(font-lock-multiline t))
4497 (when org-hide-emphasis-markers
4498 (add-text-properties (match-end 4) (match-beginning 5)
4499 '(invisible org-link))
4500 (add-text-properties (match-beginning 3) (match-end 3)
4501 '(invisible org-link)))))
4502 (backward-char 1))
4503 rtn))
4505 (defun org-emphasize (&optional char)
4506 "Insert or change an emphasis, i.e. a font like bold or italic.
4507 If there is an active region, change that region to a new emphasis.
4508 If there is no region, just insert the marker characters and position
4509 the cursor between them.
4510 CHAR should be either the marker character, or the first character of the
4511 HTML tag associated with that emphasis. If CHAR is a space, the means
4512 to remove the emphasis of the selected region.
4513 If char is not given (for example in an interactive call) it
4514 will be prompted for."
4515 (interactive)
4516 (let ((eal org-emphasis-alist) e det
4517 (erc org-emphasis-regexp-components)
4518 (prompt "")
4519 (string "") beg end move tag c s)
4520 (if (org-region-active-p)
4521 (setq beg (region-beginning) end (region-end)
4522 string (buffer-substring beg end))
4523 (setq move t))
4525 (while (setq e (pop eal))
4526 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4527 c (aref tag 0))
4528 (push (cons c (string-to-char (car e))) det)
4529 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4530 (substring tag 1)))))
4531 (setq det (nreverse det))
4532 (unless char
4533 (message "%s" (concat "Emphasis marker or tag:" prompt))
4534 (setq char (read-char-exclusive)))
4535 (setq char (or (cdr (assoc char det)) char))
4536 (if (equal char ?\ )
4537 (setq s "" move nil)
4538 (unless (assoc (char-to-string char) org-emphasis-alist)
4539 (error "No such emphasis marker: \"%c\"" char))
4540 (setq s (char-to-string char)))
4541 (while (and (> (length string) 1)
4542 (equal (substring string 0 1) (substring string -1))
4543 (assoc (substring string 0 1) org-emphasis-alist))
4544 (setq string (substring string 1 -1)))
4545 (setq string (concat s string s))
4546 (if beg (delete-region beg end))
4547 (unless (or (bolp)
4548 (string-match (concat "[" (nth 0 erc) "\n]")
4549 (char-to-string (char-before (point)))))
4550 (insert " "))
4551 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4552 (char-to-string (char-after (point))))
4553 (insert " ") (backward-char 1))
4554 (insert string)
4555 (and move (backward-char 1))))
4557 (defconst org-nonsticky-props
4558 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4560 (defsubst org-rear-nonsticky-at (pos)
4561 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4563 (defun org-activate-plain-links (limit)
4564 "Run through the buffer and add overlays to links."
4565 (catch 'exit
4566 (let (f)
4567 (if (re-search-forward org-plain-link-re limit t)
4568 (progn
4569 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4570 (setq f (get-text-property (match-beginning 0) 'face))
4571 (if (or (eq f 'org-tag)
4572 (and (listp f) (memq 'org-tag f)))
4574 (add-text-properties (match-beginning 0) (match-end 0)
4575 (list 'mouse-face 'highlight
4576 'face 'org-link
4577 'keymap org-mouse-map))
4578 (org-rear-nonsticky-at (match-end 0)))
4579 t)))))
4581 (defun org-activate-code (limit)
4582 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4583 (progn
4584 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4585 (remove-text-properties (match-beginning 0) (match-end 0)
4586 '(display t invisible t intangible t))
4587 t)))
4589 (defun org-fontify-meta-lines-and-blocks (limit)
4590 "Fontify #+ lines and blocks, in the correct ways."
4591 (let ((case-fold-search t))
4592 (if (re-search-forward
4593 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4594 limit t)
4595 (let ((beg (match-beginning 0))
4596 (beg1 (line-beginning-position 2))
4597 (dc1 (downcase (match-string 2)))
4598 (dc3 (downcase (match-string 3)))
4599 end end1 quoting block-type)
4600 (cond
4601 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4602 ;; a single line of backend-specific content
4603 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4604 (remove-text-properties (match-beginning 0) (match-end 0)
4605 '(display t invisible t intangible t))
4606 (add-text-properties (match-beginning 1) (match-end 3)
4607 '(font-lock-fontified t face org-meta-line))
4608 (add-text-properties (match-beginning 6) (match-end 6)
4609 '(font-lock-fontified t face org-block))
4611 ((and (match-end 4) (equal dc3 "begin"))
4612 ;; Truely a block
4613 (setq block-type (downcase (match-string 5))
4614 quoting (member block-type org-protecting-blocks))
4615 (when (re-search-forward
4616 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4617 nil t) ;; on purpose, we look further than LIMIT
4618 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4619 (when quoting
4620 (remove-text-properties beg end
4621 '(display t invisible t intangible t)))
4622 (add-text-properties
4623 beg end
4624 '(font-lock-fontified t font-lock-multiline t))
4625 (add-text-properties beg beg1 '(face org-meta-line))
4626 (add-text-properties end1 end '(face org-meta-line))
4627 (cond
4628 (quoting
4629 (add-text-properties beg1 end1 '(face org-block)))
4630 ((string= block-type "quote")
4631 (add-text-properties beg1 end1 '(face org-quote)))
4632 ((string= block-type "verse")
4633 (add-text-properties beg1 end1 '(face org-verse))))
4635 ((not (member (char-after beg) '(?\ ?\t)))
4636 ;; just any other in-buffer setting, but not indented
4637 (add-text-properties
4638 beg (match-end 0)
4639 '(font-lock-fontified t face org-meta-line))
4641 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4642 "orgtbl:" "tblfm:" "tblname:"))
4643 (and (match-end 4) (equal dc3 "attr")))
4644 (add-text-properties
4645 beg (match-end 0)
4646 '(font-lock-fontified t face org-meta-line))
4648 ((member dc3 '(" " ""))
4649 (add-text-properties
4650 beg (match-end 0)
4651 '(font-lock-fontified t face font-lock-comment-face)))
4652 (t nil))))))
4654 (defun org-activate-angle-links (limit)
4655 "Run through the buffer and add overlays to links."
4656 (if (re-search-forward org-angle-link-re limit t)
4657 (progn
4658 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4659 (add-text-properties (match-beginning 0) (match-end 0)
4660 (list 'mouse-face 'highlight
4661 'keymap org-mouse-map))
4662 (org-rear-nonsticky-at (match-end 0))
4663 t)))
4665 (defun org-activate-footnote-links (limit)
4666 "Run through the buffer and add overlays to links."
4667 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4668 limit t)
4669 (progn
4670 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4671 (add-text-properties (match-beginning 2) (match-end 2)
4672 (list 'mouse-face 'highlight
4673 'keymap org-mouse-map
4674 'help-echo
4675 (if (= (point-at-bol) (match-beginning 2))
4676 "Footnote definition"
4677 "Footnote reference")
4679 (org-rear-nonsticky-at (match-end 2))
4680 t)))
4682 (defun org-activate-bracket-links (limit)
4683 "Run through the buffer and add overlays to bracketed links."
4684 (if (re-search-forward org-bracket-link-regexp limit t)
4685 (let* ((help (concat "LINK: "
4686 (org-match-string-no-properties 1)))
4687 ;; FIXME: above we should remove the escapes.
4688 ;; but that requires another match, protecting match data,
4689 ;; a lot of overhead for font-lock.
4690 (ip (org-maybe-intangible
4691 (list 'invisible 'org-link
4692 'keymap org-mouse-map 'mouse-face 'highlight
4693 'font-lock-multiline t 'help-echo help)))
4694 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4695 'font-lock-multiline t 'help-echo help)))
4696 ;; We need to remove the invisible property here. Table narrowing
4697 ;; may have made some of this invisible.
4698 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4699 (remove-text-properties (match-beginning 0) (match-end 0)
4700 '(invisible nil))
4701 (if (match-end 3)
4702 (progn
4703 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4704 (org-rear-nonsticky-at (match-beginning 3))
4705 (add-text-properties (match-beginning 3) (match-end 3) vp)
4706 (org-rear-nonsticky-at (match-end 3))
4707 (add-text-properties (match-end 3) (match-end 0) ip)
4708 (org-rear-nonsticky-at (match-end 0)))
4709 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4710 (org-rear-nonsticky-at (match-beginning 1))
4711 (add-text-properties (match-beginning 1) (match-end 1) vp)
4712 (org-rear-nonsticky-at (match-end 1))
4713 (add-text-properties (match-end 1) (match-end 0) ip)
4714 (org-rear-nonsticky-at (match-end 0)))
4715 t)))
4717 (defun org-activate-dates (limit)
4718 "Run through the buffer and add overlays to dates."
4719 (if (re-search-forward org-tsr-regexp-both limit t)
4720 (progn
4721 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4722 (add-text-properties (match-beginning 0) (match-end 0)
4723 (list 'mouse-face 'highlight
4724 'keymap org-mouse-map))
4725 (org-rear-nonsticky-at (match-end 0))
4726 (when org-display-custom-times
4727 (if (match-end 3)
4728 (org-display-custom-time (match-beginning 3) (match-end 3)))
4729 (org-display-custom-time (match-beginning 1) (match-end 1)))
4730 t)))
4732 (defvar org-target-link-regexp nil
4733 "Regular expression matching radio targets in plain text.")
4734 (make-variable-buffer-local 'org-target-link-regexp)
4735 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4736 "Regular expression matching a link target.")
4737 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4738 "Regular expression matching a radio target.")
4739 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4740 "Regular expression matching any target.")
4742 (defun org-activate-target-links (limit)
4743 "Run through the buffer and add overlays to target matches."
4744 (when org-target-link-regexp
4745 (let ((case-fold-search t))
4746 (if (re-search-forward org-target-link-regexp limit t)
4747 (progn
4748 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4749 (add-text-properties (match-beginning 0) (match-end 0)
4750 (list 'mouse-face 'highlight
4751 'keymap org-mouse-map
4752 'help-echo "Radio target link"
4753 'org-linked-text t))
4754 (org-rear-nonsticky-at (match-end 0))
4755 t)))))
4757 (defun org-update-radio-target-regexp ()
4758 "Find all radio targets in this file and update the regular expression."
4759 (interactive)
4760 (when (memq 'radio org-activate-links)
4761 (setq org-target-link-regexp
4762 (org-make-target-link-regexp (org-all-targets 'radio)))
4763 (org-restart-font-lock)))
4765 (defun org-hide-wide-columns (limit)
4766 (let (s e)
4767 (setq s (text-property-any (point) (or limit (point-max))
4768 'org-cwidth t))
4769 (when s
4770 (setq e (next-single-property-change s 'org-cwidth))
4771 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4772 (goto-char e)
4773 t)))
4775 (defvar org-latex-and-specials-regexp nil
4776 "Regular expression for highlighting export special stuff.")
4777 (defvar org-match-substring-regexp)
4778 (defvar org-match-substring-with-braces-regexp)
4780 ;; This should be with the exporter code, but we also use if for font-locking
4781 (defconst org-export-html-special-string-regexps
4782 '(("\\\\-" . "&shy;")
4783 ("---\\([^-]\\)" . "&mdash;\\1")
4784 ("--\\([^-]\\)" . "&ndash;\\1")
4785 ("\\.\\.\\." . "&hellip;"))
4786 "Regular expressions for special string conversion.")
4789 (defun org-compute-latex-and-specials-regexp ()
4790 "Compute regular expression for stuff treated specially by exporters."
4791 (if (not org-highlight-latex-fragments-and-specials)
4792 (org-set-local 'org-latex-and-specials-regexp nil)
4793 (require 'org-exp)
4794 (let*
4795 ((matchers (plist-get org-format-latex-options :matchers))
4796 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4797 org-latex-regexps)))
4798 (options (org-combine-plists (org-default-export-plist)
4799 (org-infile-export-plist)))
4800 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4801 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4802 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4803 (org-export-html-expand (plist-get options :expand-quoted-html))
4804 (org-export-with-special-strings (plist-get options :special-strings))
4805 (re-sub
4806 (cond
4807 ((equal org-export-with-sub-superscripts '{})
4808 (list org-match-substring-with-braces-regexp))
4809 (org-export-with-sub-superscripts
4810 (list org-match-substring-regexp))
4811 (t nil)))
4812 (re-latex
4813 (if org-export-with-LaTeX-fragments
4814 (mapcar (lambda (x) (nth 1 x)) latexs)))
4815 (re-macros
4816 (if org-export-with-TeX-macros
4817 (list (concat "\\\\"
4818 (regexp-opt
4819 (append (mapcar 'car org-html-entities)
4820 (if (boundp 'org-latex-entities)
4821 (mapcar (lambda (x)
4822 (or (car-safe x) x))
4823 org-latex-entities)
4824 nil))
4825 'words))) ; FIXME
4827 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4828 (re-special (if org-export-with-special-strings
4829 (mapcar (lambda (x) (car x))
4830 org-export-html-special-string-regexps)))
4831 (re-rest
4832 (delq nil
4833 (list
4834 (if org-export-html-expand "@<[^>\n]+>")
4835 ))))
4836 (org-set-local
4837 'org-latex-and-specials-regexp
4838 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4839 re-rest) "\\|")))))
4841 (defun org-do-latex-and-special-faces (limit)
4842 "Run through the buffer and add overlays to links."
4843 (when org-latex-and-specials-regexp
4844 (let (rtn d)
4845 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4846 limit t))
4847 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4848 'face))
4849 '(org-code org-verbatim underline)))
4850 (progn
4851 (setq rtn t
4852 d (cond ((member (char-after (1+ (match-beginning 0)))
4853 '(?_ ?^)) 1)
4854 (t 0)))
4855 (font-lock-prepend-text-property
4856 (+ d (match-beginning 0)) (match-end 0)
4857 'face 'org-latex-and-export-specials)
4858 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4859 '(font-lock-multiline t)))))
4860 rtn)))
4862 (defun org-restart-font-lock ()
4863 "Restart font-lock-mode, to force refontification."
4864 (when (and (boundp 'font-lock-mode) font-lock-mode)
4865 (font-lock-mode -1)
4866 (font-lock-mode 1)))
4868 (defun org-all-targets (&optional radio)
4869 "Return a list of all targets in this file.
4870 With optional argument RADIO, only find radio targets."
4871 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4872 rtn)
4873 (save-excursion
4874 (goto-char (point-min))
4875 (while (re-search-forward re nil t)
4876 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4877 rtn)))
4879 (defun org-make-target-link-regexp (targets)
4880 "Make regular expression matching all strings in TARGETS.
4881 The regular expression finds the targets also if there is a line break
4882 between words."
4883 (and targets
4884 (concat
4885 "\\<\\("
4886 (mapconcat
4887 (lambda (x)
4888 (while (string-match " +" x)
4889 (setq x (replace-match "\\s-+" t t x)))
4891 targets
4892 "\\|")
4893 "\\)\\>")))
4895 (defun org-activate-tags (limit)
4896 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4897 (progn
4898 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4899 (add-text-properties (match-beginning 1) (match-end 1)
4900 (list 'mouse-face 'highlight
4901 'keymap org-mouse-map))
4902 (org-rear-nonsticky-at (match-end 1))
4903 t)))
4905 (defun org-outline-level ()
4906 "Compute the outline level of the heading at point.
4907 This function assumes that the cursor is at the beginning of a line matched
4908 by outline-regexp. Otherwise it returns garbage.
4909 If this is called at a normal headline, the level is the number of stars.
4910 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4911 For plain list items, if they are matched by `outline-regexp', this returns
4912 1000 plus the line indentation."
4913 (save-excursion
4914 (looking-at outline-regexp)
4915 (if (match-beginning 1)
4916 (+ (org-get-string-indentation (match-string 1)) 1000)
4917 (1- (- (match-end 0) (match-beginning 0))))))
4919 (defvar org-font-lock-keywords nil)
4921 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4922 "Regular expression matching a property line.")
4924 (defvar org-font-lock-hook nil
4925 "Functions to be called for special font lock stuff.")
4927 (defun org-font-lock-hook (limit)
4928 (run-hook-with-args 'org-font-lock-hook limit))
4930 (defun org-set-font-lock-defaults ()
4931 (let* ((em org-fontify-emphasized-text)
4932 (lk org-activate-links)
4933 (org-font-lock-extra-keywords
4934 (list
4935 ;; Call the hook
4936 '(org-font-lock-hook)
4937 ;; Headlines
4938 `(,(if org-fontify-whole-heading-line
4939 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4940 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4941 (1 (org-get-level-face 1))
4942 (2 (org-get-level-face 2))
4943 (3 (org-get-level-face 3)))
4944 ;; Table lines
4945 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4946 (1 'org-table t))
4947 ;; Table internals
4948 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4949 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4950 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4951 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4952 ;; Drawers
4953 (list org-drawer-regexp '(0 'org-special-keyword t))
4954 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4955 ;; Properties
4956 (list org-property-re
4957 '(1 'org-special-keyword t)
4958 '(3 'org-property-value t))
4959 ;; Links
4960 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4961 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4962 (if (memq 'plain lk) '(org-activate-plain-links))
4963 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4964 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4965 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4966 (if (memq 'footnote lk) '(org-activate-footnote-links
4967 (2 'org-footnote t)))
4968 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4969 '(org-hide-wide-columns (0 nil append))
4970 ;; TODO lines
4971 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4972 '(1 (org-get-todo-face 1) t))
4973 ;; DONE
4974 (if org-fontify-done-headline
4975 (list (concat "^[*]+ +\\<\\("
4976 (mapconcat 'regexp-quote org-done-keywords "\\|")
4977 "\\)\\(.*\\)")
4978 '(2 'org-headline-done t))
4979 nil)
4980 ;; Priorities
4981 '(org-font-lock-add-priority-faces)
4982 ;; Tags
4983 '(org-font-lock-add-tag-faces)
4984 ;; Special keywords
4985 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4986 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4987 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4988 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4989 ;; Emphasis
4990 (if em
4991 (if (featurep 'xemacs)
4992 '(org-do-emphasis-faces (0 nil append))
4993 '(org-do-emphasis-faces)))
4994 ;; Checkboxes
4995 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4996 2 'org-checkbox prepend)
4997 (if org-provide-checkbox-statistics
4998 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4999 (0 (org-get-checkbox-statistics-face) t)))
5000 ;; Description list items
5001 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5002 2 'bold prepend)
5003 ;; ARCHIVEd headings
5004 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5005 '(1 'org-archived prepend))
5006 ;; Specials
5007 '(org-do-latex-and-special-faces)
5008 ;; Code
5009 '(org-activate-code (1 'org-code t))
5010 ;; COMMENT
5011 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5012 "\\|" org-quote-string "\\)\\>")
5013 '(1 'org-special-keyword t))
5014 '("^#.*" (0 'font-lock-comment-face t))
5015 ;; Blocks and meta lines
5016 '(org-fontify-meta-lines-and-blocks)
5018 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5019 ;; Now set the full font-lock-keywords
5020 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5021 (org-set-local 'font-lock-defaults
5022 '(org-font-lock-keywords t nil nil backward-paragraph))
5023 (kill-local-variable 'font-lock-keywords) nil))
5025 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5026 "Fontify string S like in Org-mode"
5027 (with-temp-buffer
5028 (insert s)
5029 (let ((org-odd-levels-only odd-levels))
5030 (org-mode)
5031 (font-lock-fontify-buffer)
5032 (buffer-string))))
5034 (defvar org-m nil)
5035 (defvar org-l nil)
5036 (defvar org-f nil)
5037 (defun org-get-level-face (n)
5038 "Get the right face for match N in font-lock matching of headlines."
5039 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5040 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5041 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5042 (cond
5043 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5044 ((eq n 2) org-f)
5045 (t (if org-level-color-stars-only nil org-f))))
5047 (defun org-get-todo-face (kwd)
5048 "Get the right face for a TODO keyword KWD.
5049 If KWD is a number, get the corresponding match group."
5050 (if (numberp kwd) (setq kwd (match-string kwd)))
5051 (or (cdr (assoc kwd org-todo-keyword-faces))
5052 (and (member kwd org-done-keywords) 'org-done)
5053 'org-todo))
5055 (defun org-font-lock-add-tag-faces (limit)
5056 "Add the special tag faces."
5057 (when (and org-tag-faces org-tags-special-faces-re)
5058 (while (re-search-forward org-tags-special-faces-re limit t)
5059 (add-text-properties (match-beginning 1) (match-end 1)
5060 (list 'face (org-get-tag-face 1)
5061 'font-lock-fontified t))
5062 (backward-char 1))))
5064 (defun org-font-lock-add-priority-faces (limit)
5065 "Add the special priority faces."
5066 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5067 (add-text-properties
5068 (match-beginning 0) (match-end 0)
5069 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5070 org-priority-faces))
5071 'org-special-keyword)
5072 'font-lock-fontified t))))
5074 (defun org-get-tag-face (kwd)
5075 "Get the right face for a TODO keyword KWD.
5076 If KWD is a number, get the corresponding match group."
5077 (if (numberp kwd) (setq kwd (match-string kwd)))
5078 (or (cdr (assoc kwd org-tag-faces))
5079 'org-tag))
5081 (defun org-unfontify-region (beg end &optional maybe_loudly)
5082 "Remove fontification and activation overlays from links."
5083 (font-lock-default-unfontify-region beg end)
5084 (let* ((buffer-undo-list t)
5085 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5086 (inhibit-modification-hooks t)
5087 deactivate-mark buffer-file-name buffer-file-truename)
5088 (remove-text-properties
5089 beg end
5090 (if org-indent-mode
5091 ;; also remove line-prefix and wrap-prefix properties
5092 '(mouse-face t keymap t org-linked-text t
5093 invisible t intangible t
5094 line-prefix t wrap-prefix t
5095 org-no-flyspell t)
5096 '(mouse-face t keymap t org-linked-text t
5097 invisible t intangible t
5098 org-no-flyspell t)))))
5100 ;;;; Visibility cycling, including org-goto and indirect buffer
5102 ;;; Cycling
5104 (defvar org-cycle-global-status nil)
5105 (make-variable-buffer-local 'org-cycle-global-status)
5106 (defvar org-cycle-subtree-status nil)
5107 (make-variable-buffer-local 'org-cycle-subtree-status)
5109 ;;;###autoload
5111 (defvar org-inlinetask-min-level)
5113 (defun org-cycle (&optional arg)
5114 "TAB-action and visibility cycling for Org-mode.
5116 This is the command invoked in Org-mode by the TAB key. Its main purpose
5117 is outline visibility cycling, but it also invokes other actions
5118 in special contexts.
5120 - When this function is called with a prefix argument, rotate the entire
5121 buffer through 3 states (global cycling)
5122 1. OVERVIEW: Show only top-level headlines.
5123 2. CONTENTS: Show all headlines of all levels, but no body text.
5124 3. SHOW ALL: Show everything.
5125 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5126 determined by the variable `org-startup-folded', and by any VISIBILITY
5127 properties in the buffer.
5128 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5129 including any drawers.
5131 - When inside a table, re-align the table and move to the next field.
5133 - When point is at the beginning of a headline, rotate the subtree started
5134 by this line through 3 different states (local cycling)
5135 1. FOLDED: Only the main headline is shown.
5136 2. CHILDREN: The main headline and the direct children are shown.
5137 From this state, you can move to one of the children
5138 and zoom in further.
5139 3. SUBTREE: Show the entire subtree, including body text.
5140 If there is no subtree, switch directly from CHILDREN to FOLDED.
5142 - When there is a numeric prefix, go up to a heading with level ARG, do
5143 a `show-subtree' and return to the previous cursor position. If ARG
5144 is negative, go up that many levels.
5146 - When point is not at the beginning of a headline, execute the global
5147 binding for TAB, which is re-indenting the line. See the option
5148 `org-cycle-emulate-tab' for details.
5150 - Special case: if point is at the beginning of the buffer and there is
5151 no headline in line 1, this function will act as if called with prefix arg.
5152 But only if also the variable `org-cycle-global-at-bob' is t."
5153 (interactive "P")
5154 (org-load-modules-maybe)
5155 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5156 (and org-cycle-level-after-item/entry-creation
5157 (or (org-cycle-level)
5158 (org-cycle-item-indentation))))
5159 (let* ((limit-level
5160 (or org-cycle-max-level
5161 (and (boundp 'org-inlinetask-min-level)
5162 org-inlinetask-min-level
5163 (1- org-inlinetask-min-level))))
5164 (nstars (and limit-level
5165 (if org-odd-levels-only
5166 (and limit-level (1- (* limit-level 2)))
5167 limit-level)))
5168 (outline-regexp
5169 (cond
5170 ((not (org-mode-p)) outline-regexp)
5171 ((or (eq org-cycle-include-plain-lists 'integrate)
5172 (and org-cycle-include-plain-lists (org-at-item-p)))
5173 (concat "\\(?:\\*"
5174 (if nstars (format "\\{1,%d\\}" nstars) "+")
5175 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5176 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5177 (bob-special (and org-cycle-global-at-bob (bobp)
5178 (not (looking-at outline-regexp))))
5179 (org-cycle-hook
5180 (if bob-special
5181 (delq 'org-optimize-window-after-visibility-change
5182 (copy-sequence org-cycle-hook))
5183 org-cycle-hook))
5184 (pos (point)))
5186 (if (or bob-special (equal arg '(4)))
5187 ;; special case: use global cycling
5188 (setq arg t))
5190 (cond
5192 ((equal arg '(16))
5193 (org-set-startup-visibility)
5194 (message "Startup visibility, plus VISIBILITY properties"))
5196 ((equal arg '(64))
5197 (show-all)
5198 (message "Entire buffer visible, including drawers"))
5200 ((org-at-table-p 'any)
5201 ;; Enter the table or move to the next field in the table
5202 (or (org-table-recognize-table.el)
5203 (progn
5204 (if arg (org-table-edit-field t)
5205 (org-table-justify-field-maybe)
5206 (call-interactively 'org-table-next-field)))))
5208 ((run-hook-with-args-until-success
5209 'org-tab-after-check-for-table-hook))
5211 ((eq arg t) ;; Global cycling
5212 (org-cycle-internal-global))
5214 ((and org-drawers org-drawer-regexp
5215 (save-excursion
5216 (beginning-of-line 1)
5217 (looking-at org-drawer-regexp)))
5218 ;; Toggle block visibility
5219 (org-flag-drawer
5220 (not (get-char-property (match-end 0) 'invisible))))
5222 ((integerp arg)
5223 ;; Show-subtree, ARG levels up from here.
5224 (save-excursion
5225 (org-back-to-heading)
5226 (outline-up-heading (if (< arg 0) (- arg)
5227 (- (funcall outline-level) arg)))
5228 (org-show-subtree)))
5230 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5231 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5233 (org-cycle-internal-local))
5235 ;; TAB emulation and template completion
5236 (buffer-read-only (org-back-to-heading))
5238 ((run-hook-with-args-until-success
5239 'org-tab-after-check-for-cycling-hook))
5241 ((org-try-structure-completion))
5243 ((org-try-cdlatex-tab))
5245 ((run-hook-with-args-until-success
5246 'org-tab-before-tab-emulation-hook))
5248 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5249 (or (not (bolp))
5250 (not (looking-at outline-regexp))))
5251 (call-interactively (global-key-binding "\t")))
5253 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5254 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5255 (or (and (eq org-cycle-emulate-tab 'white)
5256 (= (match-end 0) (point-at-eol)))
5257 (and (eq org-cycle-emulate-tab 'whitestart)
5258 (>= (match-end 0) pos))))
5260 (eq org-cycle-emulate-tab t))
5261 (call-interactively (global-key-binding "\t")))
5263 (t (save-excursion
5264 (org-back-to-heading)
5265 (org-cycle)))))))
5267 (defun org-cycle-internal-global ()
5268 "Do the global cycling action."
5269 (cond
5270 ((and (eq last-command this-command)
5271 (eq org-cycle-global-status 'overview))
5272 ;; We just created the overview - now do table of contents
5273 ;; This can be slow in very large buffers, so indicate action
5274 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5275 (message "CONTENTS...")
5276 (org-content)
5277 (message "CONTENTS...done")
5278 (setq org-cycle-global-status 'contents)
5279 (run-hook-with-args 'org-cycle-hook 'contents))
5281 ((and (eq last-command this-command)
5282 (eq org-cycle-global-status 'contents))
5283 ;; We just showed the table of contents - now show everything
5284 (run-hook-with-args 'org-pre-cycle-hook 'all)
5285 (show-all)
5286 (message "SHOW ALL")
5287 (setq org-cycle-global-status 'all)
5288 (run-hook-with-args 'org-cycle-hook 'all))
5291 ;; Default action: go to overview
5292 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5293 (org-overview)
5294 (message "OVERVIEW")
5295 (setq org-cycle-global-status 'overview)
5296 (run-hook-with-args 'org-cycle-hook 'overview))))
5298 (defun org-cycle-internal-local ()
5299 "Do the local cycling action."
5300 (org-back-to-heading)
5301 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5302 ;; First, some boundaries
5303 (save-excursion
5304 (org-back-to-heading)
5305 (setq level (funcall outline-level))
5306 (save-excursion
5307 (beginning-of-line 2)
5308 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5309 ; XEmacs does not have `next-single-char-property-change'
5310 ; I'm not sure about Emacs 21.
5311 (while (and (not (eobp)) ;; this is like `next-line'
5312 (get-char-property (1- (point)) 'invisible))
5313 (beginning-of-line 2))
5314 (while (and (not (eobp)) ;; this is like `next-line'
5315 (get-char-property (1- (point)) 'invisible))
5316 (goto-char (next-single-char-property-change (point) 'invisible))
5317 ;;;??? (or (bolp) (beginning-of-line 2))))
5318 (and (eolp) (beginning-of-line 2))))
5319 (setq eol (point)))
5320 (outline-end-of-heading) (setq eoh (point))
5321 (save-excursion
5322 (outline-next-heading)
5323 (setq has-children (and (org-at-heading-p t)
5324 (> (funcall outline-level) level))))
5325 (org-end-of-subtree t)
5326 (unless (eobp)
5327 (skip-chars-forward " \t\n")
5328 (beginning-of-line 1) ; in case this is an item
5330 (setq eos (if (eobp) (point) (1- (point)))))
5331 ;; Find out what to do next and set `this-command'
5332 (cond
5333 ((= eos eoh)
5334 ;; Nothing is hidden behind this heading
5335 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5336 (message "EMPTY ENTRY")
5337 (setq org-cycle-subtree-status nil)
5338 (save-excursion
5339 (goto-char eos)
5340 (outline-next-heading)
5341 (if (org-invisible-p) (org-flag-heading nil))))
5342 ((and (or (>= eol eos)
5343 (not (string-match "\\S-" (buffer-substring eol eos))))
5344 (or has-children
5345 (not (setq children-skipped
5346 org-cycle-skip-children-state-if-no-children))))
5347 ;; Entire subtree is hidden in one line: children view
5348 (run-hook-with-args 'org-pre-cycle-hook 'children)
5349 (org-show-entry)
5350 (show-children)
5351 (message "CHILDREN")
5352 (save-excursion
5353 (goto-char eos)
5354 (outline-next-heading)
5355 (if (org-invisible-p) (org-flag-heading nil)))
5356 (setq org-cycle-subtree-status 'children)
5357 (run-hook-with-args 'org-cycle-hook 'children))
5358 ((or children-skipped
5359 (and (eq last-command this-command)
5360 (eq org-cycle-subtree-status 'children)))
5361 ;; We just showed the children, or no children are there,
5362 ;; now show everything.
5363 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5364 (org-show-subtree)
5365 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5366 (setq org-cycle-subtree-status 'subtree)
5367 (run-hook-with-args 'org-cycle-hook 'subtree))
5369 ;; Default action: hide the subtree.
5370 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5371 (hide-subtree)
5372 (message "FOLDED")
5373 (setq org-cycle-subtree-status 'folded)
5374 (run-hook-with-args 'org-cycle-hook 'folded)))))
5376 ;;;###autoload
5377 (defun org-global-cycle (&optional arg)
5378 "Cycle the global visibility. For details see `org-cycle'.
5379 With C-u prefix arg, switch to startup visibility.
5380 With a numeric prefix, show all headlines up to that level."
5381 (interactive "P")
5382 (let ((org-cycle-include-plain-lists
5383 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5384 (cond
5385 ((integerp arg)
5386 (show-all)
5387 (hide-sublevels arg)
5388 (setq org-cycle-global-status 'contents))
5389 ((equal arg '(4))
5390 (org-set-startup-visibility)
5391 (message "Startup visibility, plus VISIBILITY properties."))
5393 (org-cycle '(4))))))
5395 (defun org-set-startup-visibility ()
5396 "Set the visibility required by startup options and properties."
5397 (cond
5398 ((eq org-startup-folded t)
5399 (org-cycle '(4)))
5400 ((eq org-startup-folded 'content)
5401 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5402 (org-cycle '(4)) (org-cycle '(4)))))
5403 (unless (eq org-startup-folded 'showeverything)
5404 (if org-hide-block-startup (org-hide-block-all))
5405 (org-set-visibility-according-to-property 'no-cleanup)
5406 (org-cycle-hide-archived-subtrees 'all)
5407 (org-cycle-hide-drawers 'all)
5408 (org-cycle-show-empty-lines 'all)))
5410 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5411 "Switch subtree visibilities according to :VISIBILITY: property."
5412 (interactive)
5413 (let (org-show-entry-below state)
5414 (save-excursion
5415 (goto-char (point-min))
5416 (while (re-search-forward
5417 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5418 nil t)
5419 (setq state (match-string 1))
5420 (save-excursion
5421 (org-back-to-heading t)
5422 (hide-subtree)
5423 (org-reveal)
5424 (cond
5425 ((equal state '("fold" "folded"))
5426 (hide-subtree))
5427 ((equal state "children")
5428 (org-show-hidden-entry)
5429 (show-children))
5430 ((equal state "content")
5431 (save-excursion
5432 (save-restriction
5433 (org-narrow-to-subtree)
5434 (org-content))))
5435 ((member state '("all" "showall"))
5436 (show-subtree)))))
5437 (unless no-cleanup
5438 (org-cycle-hide-archived-subtrees 'all)
5439 (org-cycle-hide-drawers 'all)
5440 (org-cycle-show-empty-lines 'all)))))
5442 (defun org-overview ()
5443 "Switch to overview mode, showing only top-level headlines.
5444 Really, this shows all headlines with level equal or greater than the level
5445 of the first headline in the buffer. This is important, because if the
5446 first headline is not level one, then (hide-sublevels 1) gives confusing
5447 results."
5448 (interactive)
5449 (let ((level (save-excursion
5450 (goto-char (point-min))
5451 (if (re-search-forward (concat "^" outline-regexp) nil t)
5452 (progn
5453 (goto-char (match-beginning 0))
5454 (funcall outline-level))))))
5455 (and level (hide-sublevels level))))
5457 (defun org-content (&optional arg)
5458 "Show all headlines in the buffer, like a table of contents.
5459 With numerical argument N, show content up to level N."
5460 (interactive "P")
5461 (save-excursion
5462 ;; Visit all headings and show their offspring
5463 (and (integerp arg) (org-overview))
5464 (goto-char (point-max))
5465 (catch 'exit
5466 (while (and (progn (condition-case nil
5467 (outline-previous-visible-heading 1)
5468 (error (goto-char (point-min))))
5470 (looking-at outline-regexp))
5471 (if (integerp arg)
5472 (show-children (1- arg))
5473 (show-branches))
5474 (if (bobp) (throw 'exit nil))))))
5477 (defun org-optimize-window-after-visibility-change (state)
5478 "Adjust the window after a change in outline visibility.
5479 This function is the default value of the hook `org-cycle-hook'."
5480 (when (get-buffer-window (current-buffer))
5481 (cond
5482 ((eq state 'content) nil)
5483 ((eq state 'all) nil)
5484 ((eq state 'folded) nil)
5485 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5486 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5488 (defun org-remove-empty-overlays-at (pos)
5489 "Remove outline overlays that do not contain non-white stuff."
5490 (mapc
5491 (lambda (o)
5492 (and (eq 'outline (org-overlay-get o 'invisible))
5493 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5494 (org-overlay-end o))))
5495 (org-delete-overlay o)))
5496 (org-overlays-at pos)))
5498 (defun org-clean-visibility-after-subtree-move ()
5499 "Fix visibility issues after moving a subtree."
5500 ;; First, find a reasonable region to look at:
5501 ;; Start two siblings above, end three below
5502 (let* ((beg (save-excursion
5503 (and (org-get-last-sibling)
5504 (org-get-last-sibling))
5505 (point)))
5506 (end (save-excursion
5507 (and (org-get-next-sibling)
5508 (org-get-next-sibling)
5509 (org-get-next-sibling))
5510 (if (org-at-heading-p)
5511 (point-at-eol)
5512 (point))))
5513 (level (looking-at "\\*+"))
5514 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5515 (save-excursion
5516 (save-restriction
5517 (narrow-to-region beg end)
5518 (when re
5519 ;; Properly fold already folded siblings
5520 (goto-char (point-min))
5521 (while (re-search-forward re nil t)
5522 (if (and (not (org-invisible-p))
5523 (save-excursion
5524 (goto-char (point-at-eol)) (org-invisible-p)))
5525 (hide-entry))))
5526 (org-cycle-show-empty-lines 'overview)
5527 (org-cycle-hide-drawers 'overview)))))
5529 (defun org-cycle-show-empty-lines (state)
5530 "Show empty lines above all visible headlines.
5531 The region to be covered depends on STATE when called through
5532 `org-cycle-hook'. Lisp program can use t for STATE to get the
5533 entire buffer covered. Note that an empty line is only shown if there
5534 are at least `org-cycle-separator-lines' empty lines before the headline."
5535 (when (not (= org-cycle-separator-lines 0))
5536 (save-excursion
5537 (let* ((n (abs org-cycle-separator-lines))
5538 (re (cond
5539 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5540 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5541 (t (let ((ns (number-to-string (- n 2))))
5542 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5543 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5544 beg end b e)
5545 (cond
5546 ((memq state '(overview contents t))
5547 (setq beg (point-min) end (point-max)))
5548 ((memq state '(children folded))
5549 (setq beg (point) end (progn (org-end-of-subtree t t)
5550 (beginning-of-line 2)
5551 (point)))))
5552 (when beg
5553 (goto-char beg)
5554 (while (re-search-forward re end t)
5555 (unless (get-char-property (match-end 1) 'invisible)
5556 (setq e (match-end 1))
5557 (if (< org-cycle-separator-lines 0)
5558 (setq b (save-excursion
5559 (goto-char (match-beginning 0))
5560 (org-back-over-empty-lines)
5561 (if (save-excursion
5562 (goto-char (max (point-min) (1- (point))))
5563 (org-on-heading-p))
5564 (1- (point))
5565 (point))))
5566 (setq b (match-beginning 1)))
5567 (outline-flag-region b e nil)))))))
5568 ;; Never hide empty lines at the end of the file.
5569 (save-excursion
5570 (goto-char (point-max))
5571 (outline-previous-heading)
5572 (outline-end-of-heading)
5573 (if (and (looking-at "[ \t\n]+")
5574 (= (match-end 0) (point-max)))
5575 (outline-flag-region (point) (match-end 0) nil))))
5577 (defun org-show-empty-lines-in-parent ()
5578 "Move to the parent and re-show empty lines before visible headlines."
5579 (save-excursion
5580 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5581 (org-cycle-show-empty-lines context))))
5583 (defun org-files-list ()
5584 "Return `org-agenda-files' list, plus all open org-mode files.
5585 This is useful for operations that need to scan all of a user's
5586 open and agenda-wise Org files."
5587 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5588 (dolist (buf (buffer-list))
5589 (with-current-buffer buf
5590 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5591 (let ((file (expand-file-name (buffer-file-name))))
5592 (unless (member file files)
5593 (push file files))))))
5594 files))
5596 (defsubst org-entry-beginning-position ()
5597 "Return the beginning position of the current entry."
5598 (save-excursion (outline-back-to-heading t) (point)))
5600 (defsubst org-entry-end-position ()
5601 "Return the end position of the current entry."
5602 (save-excursion (outline-next-heading) (point)))
5604 (defun org-cycle-hide-drawers (state)
5605 "Re-hide all drawers after a visibility state change."
5606 (when (and (org-mode-p)
5607 (not (memq state '(overview folded contents))))
5608 (save-excursion
5609 (let* ((globalp (memq state '(contents all)))
5610 (beg (if globalp (point-min) (point)))
5611 (end (if globalp (point-max)
5612 (if (eq state 'children)
5613 (save-excursion (outline-next-heading) (point))
5614 (org-end-of-subtree t)))))
5615 (goto-char beg)
5616 (while (re-search-forward org-drawer-regexp end t)
5617 (org-flag-drawer t))))))
5619 (defun org-flag-drawer (flag)
5620 (save-excursion
5621 (beginning-of-line 1)
5622 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5623 (let ((b (match-end 0))
5624 (outline-regexp org-outline-regexp))
5625 (if (re-search-forward
5626 "^[ \t]*:END:"
5627 (save-excursion (outline-next-heading) (point)) t)
5628 (outline-flag-region b (point-at-eol) flag)
5629 (error ":END: line missing at position %s" b))))))
5631 (defun org-subtree-end-visible-p ()
5632 "Is the end of the current subtree visible?"
5633 (pos-visible-in-window-p
5634 (save-excursion (org-end-of-subtree t) (point))))
5636 (defun org-first-headline-recenter (&optional N)
5637 "Move cursor to the first headline and recenter the headline.
5638 Optional argument N means, put the headline into the Nth line of the window."
5639 (goto-char (point-min))
5640 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5641 (beginning-of-line)
5642 (recenter (prefix-numeric-value N))))
5644 ;;; Saving and restoring visibility
5646 (defun org-outline-overlay-data (&optional use-markers)
5647 "Return a list of the locations of all outline overlays.
5648 The are overlays with the `invisible' property value `outline'.
5649 The return valus is a list of cons cells, with start and stop
5650 positions for each overlay.
5651 If USE-MARKERS is set, return the positions as markers."
5652 (let (beg end)
5653 (save-excursion
5654 (save-restriction
5655 (widen)
5656 (delq nil
5657 (mapcar (lambda (o)
5658 (when (eq (org-overlay-get o 'invisible) 'outline)
5659 (setq beg (org-overlay-start o)
5660 end (org-overlay-end o))
5661 (and beg end (> end beg)
5662 (if use-markers
5663 (cons (move-marker (make-marker) beg)
5664 (move-marker (make-marker) end))
5665 (cons beg end)))))
5666 (org-overlays-in (point-min) (point-max))))))))
5668 (defun org-set-outline-overlay-data (data)
5669 "Create visibility overlays for all positions in DATA.
5670 DATA should have been made by `org-outline-overlay-data'."
5671 (let (o)
5672 (save-excursion
5673 (save-restriction
5674 (widen)
5675 (show-all)
5676 (mapc (lambda (c)
5677 (setq o (org-make-overlay (car c) (cdr c)))
5678 (org-overlay-put o 'invisible 'outline))
5679 data)))))
5681 (defmacro org-save-outline-visibility (use-markers &rest body)
5682 "Save and restore outline visibility around BODY.
5683 If USE-MARKERS is non-nil, use markers for the positions.
5684 This means that the buffer may change while running BODY,
5685 but it also means that the buffer should stay alive
5686 during the operation, because otherwise all these markers will
5687 point nowhere."
5688 `(let ((data (org-outline-overlay-data ,use-markers)))
5689 (unwind-protect
5690 (progn
5691 ,@body
5692 (org-set-outline-overlay-data data))
5693 (when ,use-markers
5694 (mapc (lambda (c)
5695 (and (markerp (car c)) (move-marker (car c) nil))
5696 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5697 data)))))
5700 ;;; Folding of blocks
5702 (defconst org-block-regexp
5704 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5705 "Regular expression for hiding blocks.")
5707 (defvar org-hide-block-overlays nil
5708 "Overlays hiding blocks.")
5709 (make-variable-buffer-local 'org-hide-block-overlays)
5711 (defun org-block-map (function &optional start end)
5712 "Call func at the head of all source blocks in the current
5713 buffer. Optional arguments START and END can be used to limit
5714 the range."
5715 (let ((start (or start (point-min)))
5716 (end (or end (point-max))))
5717 (save-excursion
5718 (goto-char start)
5719 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5720 (save-excursion
5721 (save-match-data
5722 (goto-char (match-beginning 0))
5723 (funcall function)))))))
5725 (defun org-hide-block-toggle-all ()
5726 "Toggle the visibility of all blocks in the current buffer."
5727 (org-block-map #'org-hide-block-toggle))
5729 (defun org-hide-block-all ()
5730 "Fold all blocks in the current buffer."
5731 (interactive)
5732 (org-show-block-all)
5733 (org-block-map #'org-hide-block-toggle-maybe))
5735 (defun org-show-block-all ()
5736 "Unfold all blocks in the current buffer."
5737 (mapc 'org-delete-overlay org-hide-block-overlays)
5738 (setq org-hide-block-overlays nil))
5740 (defun org-hide-block-toggle-maybe ()
5741 "Toggle visibility of block at point."
5742 (interactive)
5743 (let ((case-fold-search t))
5744 (if (save-excursion
5745 (beginning-of-line 1)
5746 (looking-at org-block-regexp))
5747 (progn (org-hide-block-toggle)
5748 t) ;; to signal that we took action
5749 nil))) ;; to signal that we did not
5751 (defun org-hide-block-toggle (&optional force)
5752 "Toggle the visibility of the current block."
5753 (interactive)
5754 (save-excursion
5755 (beginning-of-line)
5756 (if (re-search-forward org-block-regexp nil t)
5757 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5758 (end (match-end 0)) ;; end of entire body
5760 (if (memq t (mapcar (lambda (overlay)
5761 (eq (org-overlay-get overlay 'invisible)
5762 'org-hide-block))
5763 (org-overlays-at start)))
5764 (if (or (not force) (eq force 'off))
5765 (mapc (lambda (ov)
5766 (when (member ov org-hide-block-overlays)
5767 (setq org-hide-block-overlays
5768 (delq ov org-hide-block-overlays)))
5769 (when (eq (org-overlay-get ov 'invisible)
5770 'org-hide-block)
5771 (org-delete-overlay ov)))
5772 (org-overlays-at start)))
5773 (setq ov (org-make-overlay start end))
5774 (org-overlay-put ov 'invisible 'org-hide-block)
5775 ;; make the block accessible to isearch
5776 (org-overlay-put
5777 ov 'isearch-open-invisible
5778 (lambda (ov)
5779 (when (member ov org-hide-block-overlays)
5780 (setq org-hide-block-overlays
5781 (delq ov org-hide-block-overlays)))
5782 (when (eq (org-overlay-get ov 'invisible)
5783 'org-hide-block)
5784 (org-delete-overlay ov))))
5785 (push ov org-hide-block-overlays)))
5786 (error "Not looking at a source block"))))
5788 ;; org-tab-after-check-for-cycling-hook
5789 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5790 ;; Remove overlays when changing major mode
5791 (add-hook 'org-mode-hook
5792 (lambda () (org-add-hook 'change-major-mode-hook
5793 'org-show-block-all 'append 'local)))
5795 ;;; Org-goto
5797 (defvar org-goto-window-configuration nil)
5798 (defvar org-goto-marker nil)
5799 (defvar org-goto-map
5800 (let ((map (make-sparse-keymap)))
5801 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5802 (while (setq cmd (pop cmds))
5803 (substitute-key-definition cmd cmd map global-map)))
5804 (suppress-keymap map)
5805 (org-defkey map "\C-m" 'org-goto-ret)
5806 (org-defkey map [(return)] 'org-goto-ret)
5807 (org-defkey map [(left)] 'org-goto-left)
5808 (org-defkey map [(right)] 'org-goto-right)
5809 (org-defkey map [(control ?g)] 'org-goto-quit)
5810 (org-defkey map "\C-i" 'org-cycle)
5811 (org-defkey map [(tab)] 'org-cycle)
5812 (org-defkey map [(down)] 'outline-next-visible-heading)
5813 (org-defkey map [(up)] 'outline-previous-visible-heading)
5814 (if org-goto-auto-isearch
5815 (if (fboundp 'define-key-after)
5816 (define-key-after map [t] 'org-goto-local-auto-isearch)
5817 nil)
5818 (org-defkey map "q" 'org-goto-quit)
5819 (org-defkey map "n" 'outline-next-visible-heading)
5820 (org-defkey map "p" 'outline-previous-visible-heading)
5821 (org-defkey map "f" 'outline-forward-same-level)
5822 (org-defkey map "b" 'outline-backward-same-level)
5823 (org-defkey map "u" 'outline-up-heading))
5824 (org-defkey map "/" 'org-occur)
5825 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5826 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5827 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5828 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5829 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5830 map))
5832 (defconst org-goto-help
5833 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5834 RET=jump to location [Q]uit and return to previous location
5835 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5837 (defvar org-goto-start-pos) ; dynamically scoped parameter
5839 ;; FIXME: Docstring does not mention both interfaces
5840 (defun org-goto (&optional alternative-interface)
5841 "Look up a different location in the current file, keeping current visibility.
5843 When you want look-up or go to a different location in a document, the
5844 fastest way is often to fold the entire buffer and then dive into the tree.
5845 This method has the disadvantage, that the previous location will be folded,
5846 which may not be what you want.
5848 This command works around this by showing a copy of the current buffer
5849 in an indirect buffer, in overview mode. You can dive into the tree in
5850 that copy, use org-occur and incremental search to find a location.
5851 When pressing RET or `Q', the command returns to the original buffer in
5852 which the visibility is still unchanged. After RET is will also jump to
5853 the location selected in the indirect buffer and expose the
5854 the headline hierarchy above."
5855 (interactive "P")
5856 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5857 (org-refile-use-outline-path t)
5858 (org-refile-target-verify-function nil)
5859 (interface
5860 (if (not alternative-interface)
5861 org-goto-interface
5862 (if (eq org-goto-interface 'outline)
5863 'outline-path-completion
5864 'outline)))
5865 (org-goto-start-pos (point))
5866 (selected-point
5867 (if (eq interface 'outline)
5868 (car (org-get-location (current-buffer) org-goto-help))
5869 (nth 3 (org-refile-get-location "Goto: ")))))
5870 (if selected-point
5871 (progn
5872 (org-mark-ring-push org-goto-start-pos)
5873 (goto-char selected-point)
5874 (if (or (org-invisible-p) (org-invisible-p2))
5875 (org-show-context 'org-goto)))
5876 (message "Quit"))))
5878 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5879 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5880 (defvar org-goto-local-auto-isearch-map) ; defined below
5882 (defun org-get-location (buf help)
5883 "Let the user select a location in the Org-mode buffer BUF.
5884 This function uses a recursive edit. It returns the selected position
5885 or nil."
5886 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5887 (isearch-hide-immediately nil)
5888 (isearch-search-fun-function
5889 (lambda () 'org-goto-local-search-headings))
5890 (org-goto-selected-point org-goto-exit-command))
5891 (save-excursion
5892 (save-window-excursion
5893 (delete-other-windows)
5894 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5895 (switch-to-buffer
5896 (condition-case nil
5897 (make-indirect-buffer (current-buffer) "*org-goto*")
5898 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5899 (with-output-to-temp-buffer "*Help*"
5900 (princ help))
5901 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5902 (setq buffer-read-only nil)
5903 (let ((org-startup-truncated t)
5904 (org-startup-folded nil)
5905 (org-startup-align-all-tables nil))
5906 (org-mode)
5907 (org-overview))
5908 (setq buffer-read-only t)
5909 (if (and (boundp 'org-goto-start-pos)
5910 (integer-or-marker-p org-goto-start-pos))
5911 (let ((org-show-hierarchy-above t)
5912 (org-show-siblings t)
5913 (org-show-following-heading t))
5914 (goto-char org-goto-start-pos)
5915 (and (org-invisible-p) (org-show-context)))
5916 (goto-char (point-min)))
5917 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5918 (message "Select location and press RET")
5919 (use-local-map org-goto-map)
5920 (recursive-edit)
5922 (kill-buffer "*org-goto*")
5923 (cons org-goto-selected-point org-goto-exit-command)))
5925 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5926 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5927 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5928 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5930 (defun org-goto-local-search-headings (string bound noerror)
5931 "Search and make sure that any matches are in headlines."
5932 (catch 'return
5933 (while (if isearch-forward
5934 (search-forward string bound noerror)
5935 (search-backward string bound noerror))
5936 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5937 (and (member :headline context)
5938 (not (member :tags context))))
5939 (throw 'return (point))))))
5941 (defun org-goto-local-auto-isearch ()
5942 "Start isearch."
5943 (interactive)
5944 (goto-char (point-min))
5945 (let ((keys (this-command-keys)))
5946 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5947 (isearch-mode t)
5948 (isearch-process-search-char (string-to-char keys)))))
5950 (defun org-goto-ret (&optional arg)
5951 "Finish `org-goto' by going to the new location."
5952 (interactive "P")
5953 (setq org-goto-selected-point (point)
5954 org-goto-exit-command 'return)
5955 (throw 'exit nil))
5957 (defun org-goto-left ()
5958 "Finish `org-goto' by going to the new location."
5959 (interactive)
5960 (if (org-on-heading-p)
5961 (progn
5962 (beginning-of-line 1)
5963 (setq org-goto-selected-point (point)
5964 org-goto-exit-command 'left)
5965 (throw 'exit nil))
5966 (error "Not on a heading")))
5968 (defun org-goto-right ()
5969 "Finish `org-goto' by going to the new location."
5970 (interactive)
5971 (if (org-on-heading-p)
5972 (progn
5973 (setq org-goto-selected-point (point)
5974 org-goto-exit-command 'right)
5975 (throw 'exit nil))
5976 (error "Not on a heading")))
5978 (defun org-goto-quit ()
5979 "Finish `org-goto' without cursor motion."
5980 (interactive)
5981 (setq org-goto-selected-point nil)
5982 (setq org-goto-exit-command 'quit)
5983 (throw 'exit nil))
5985 ;;; Indirect buffer display of subtrees
5987 (defvar org-indirect-dedicated-frame nil
5988 "This is the frame being used for indirect tree display.")
5989 (defvar org-last-indirect-buffer nil)
5991 (defun org-tree-to-indirect-buffer (&optional arg)
5992 "Create indirect buffer and narrow it to current subtree.
5993 With numerical prefix ARG, go up to this level and then take that tree.
5994 If ARG is negative, go up that many levels.
5995 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5996 indirect buffer previously made with this command, to avoid proliferation of
5997 indirect buffers. However, when you call the command with a `C-u' prefix, or
5998 when `org-indirect-buffer-display' is `new-frame', the last buffer
5999 is kept so that you can work with several indirect buffers at the same time.
6000 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6001 requests that a new frame be made for the new buffer, so that the dedicated
6002 frame is not changed."
6003 (interactive "P")
6004 (let ((cbuf (current-buffer))
6005 (cwin (selected-window))
6006 (pos (point))
6007 beg end level heading ibuf)
6008 (save-excursion
6009 (org-back-to-heading t)
6010 (when (numberp arg)
6011 (setq level (org-outline-level))
6012 (if (< arg 0) (setq arg (+ level arg)))
6013 (while (> (setq level (org-outline-level)) arg)
6014 (outline-up-heading 1 t)))
6015 (setq beg (point)
6016 heading (org-get-heading))
6017 (org-end-of-subtree t t) (setq end (point)))
6018 (if (and (buffer-live-p org-last-indirect-buffer)
6019 (not (eq org-indirect-buffer-display 'new-frame))
6020 (not arg))
6021 (kill-buffer org-last-indirect-buffer))
6022 (setq ibuf (org-get-indirect-buffer cbuf)
6023 org-last-indirect-buffer ibuf)
6024 (cond
6025 ((or (eq org-indirect-buffer-display 'new-frame)
6026 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6027 (select-frame (make-frame))
6028 (delete-other-windows)
6029 (switch-to-buffer ibuf)
6030 (org-set-frame-title heading))
6031 ((eq org-indirect-buffer-display 'dedicated-frame)
6032 (raise-frame
6033 (select-frame (or (and org-indirect-dedicated-frame
6034 (frame-live-p org-indirect-dedicated-frame)
6035 org-indirect-dedicated-frame)
6036 (setq org-indirect-dedicated-frame (make-frame)))))
6037 (delete-other-windows)
6038 (switch-to-buffer ibuf)
6039 (org-set-frame-title (concat "Indirect: " heading)))
6040 ((eq org-indirect-buffer-display 'current-window)
6041 (switch-to-buffer ibuf))
6042 ((eq org-indirect-buffer-display 'other-window)
6043 (pop-to-buffer ibuf))
6044 (t (error "Invalid value")))
6045 (if (featurep 'xemacs)
6046 (save-excursion (org-mode) (turn-on-font-lock)))
6047 (narrow-to-region beg end)
6048 (show-all)
6049 (goto-char pos)
6050 (and (window-live-p cwin) (select-window cwin))))
6052 (defun org-get-indirect-buffer (&optional buffer)
6053 (setq buffer (or buffer (current-buffer)))
6054 (let ((n 1) (base (buffer-name buffer)) bname)
6055 (while (buffer-live-p
6056 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6057 (setq n (1+ n)))
6058 (condition-case nil
6059 (make-indirect-buffer buffer bname 'clone)
6060 (error (make-indirect-buffer buffer bname)))))
6062 (defun org-set-frame-title (title)
6063 "Set the title of the current frame to the string TITLE."
6064 ;; FIXME: how to name a single frame in XEmacs???
6065 (unless (featurep 'xemacs)
6066 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6068 ;;;; Structure editing
6070 ;;; Inserting headlines
6072 (defun org-previous-line-empty-p ()
6073 (save-excursion
6074 (and (not (bobp))
6075 (or (beginning-of-line 0) t)
6076 (save-match-data
6077 (looking-at "[ \t]*$")))))
6079 (defun org-insert-heading (&optional force-heading)
6080 "Insert a new heading or item with same depth at point.
6081 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6082 If point is at the beginning of a headline, insert a sibling before the
6083 current headline. If point is not at the beginning, do not split the line,
6084 but create the new headline after the current line."
6085 (interactive "P")
6086 (if (or (= (buffer-size) 0)
6087 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
6088 (org-on-heading-p))))
6089 (not (org-in-item-p))))
6090 (insert "\n* ")
6091 (when (or force-heading (not (org-insert-item)))
6092 (let* ((empty-line-p nil)
6093 (head (save-excursion
6094 (condition-case nil
6095 (progn
6096 (org-back-to-heading)
6097 (setq empty-line-p (org-previous-line-empty-p))
6098 (match-string 0))
6099 (error "*"))))
6100 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6101 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6102 pos hide-previous previous-pos)
6103 (cond
6104 ((and (org-on-heading-p) (bolp)
6105 (or (bobp)
6106 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6107 ;; insert before the current line
6108 (open-line (if blank 2 1)))
6109 ((and (bolp)
6110 (not org-insert-heading-respect-content)
6111 (or (bobp)
6112 (save-excursion
6113 (backward-char 1) (not (org-invisible-p)))))
6114 ;; insert right here
6115 nil)
6117 ;; somewhere in the line
6118 (save-excursion
6119 (setq previous-pos (point-at-bol))
6120 (end-of-line)
6121 (setq hide-previous (org-invisible-p)))
6122 (and org-insert-heading-respect-content (org-show-subtree))
6123 (let ((split
6124 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6125 (save-excursion
6126 (let ((p (point)))
6127 (goto-char (point-at-bol))
6128 (and (looking-at org-complex-heading-regexp)
6129 (> p (match-beginning 4)))))))
6130 tags pos)
6131 (cond
6132 (org-insert-heading-respect-content
6133 (org-end-of-subtree nil t)
6134 (or (bolp) (newline))
6135 (or (org-previous-line-empty-p)
6136 (and blank (newline)))
6137 (open-line 1))
6138 ((org-on-heading-p)
6139 (when hide-previous
6140 (show-children)
6141 (org-show-entry))
6142 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6143 (setq tags (and (match-end 2) (match-string 2)))
6144 (and (match-end 1)
6145 (delete-region (match-beginning 1) (match-end 1)))
6146 (setq pos (point-at-bol))
6147 (or split (end-of-line 1))
6148 (delete-horizontal-space)
6149 (newline (if blank 2 1))
6150 (when tags
6151 (save-excursion
6152 (goto-char pos)
6153 (end-of-line 1)
6154 (insert " " tags)
6155 (org-set-tags nil 'align))))
6157 (or split (end-of-line 1))
6158 (newline (if blank 2 1)))))))
6159 (insert head) (just-one-space)
6160 (setq pos (point))
6161 (end-of-line 1)
6162 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6163 (when (and org-insert-heading-respect-content hide-previous)
6164 (save-excursion
6165 (goto-char previous-pos)
6166 (hide-subtree)))
6167 (run-hooks 'org-insert-heading-hook)))))
6169 (defun org-get-heading (&optional no-tags)
6170 "Return the heading of the current entry, without the stars."
6171 (save-excursion
6172 (org-back-to-heading t)
6173 (if (looking-at
6174 (if no-tags
6175 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6176 "\\*+[ \t]+\\([^\r\n]*\\)"))
6177 (match-string 1) "")))
6179 (defun org-heading-components ()
6180 "Return the components of the current heading.
6181 This is a list with the following elements:
6182 - the level as an integer
6183 - the reduced level, different if `org-odd-levels-only' is set.
6184 - the TODO keyword, or nil
6185 - the priority character, like ?A, or nil if no priority is given
6186 - the headline text itself, or the tags string if no headline text
6187 - the tags string, or nil."
6188 (save-excursion
6189 (org-back-to-heading t)
6190 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6191 (list (length (match-string 1))
6192 (org-reduced-level (length (match-string 1)))
6193 (org-match-string-no-properties 2)
6194 (and (match-end 3) (aref (match-string 3) 2))
6195 (org-match-string-no-properties 4)
6196 (org-match-string-no-properties 5)))))
6198 (defun org-get-entry ()
6199 "Get the entry text, after heading, entire subtree."
6200 (save-excursion
6201 (org-back-to-heading t)
6202 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6204 (defun org-insert-heading-after-current ()
6205 "Insert a new heading with same level as current, after current subtree."
6206 (interactive)
6207 (org-back-to-heading)
6208 (org-insert-heading)
6209 (org-move-subtree-down)
6210 (end-of-line 1))
6212 (defun org-insert-heading-respect-content ()
6213 (interactive)
6214 (let ((org-insert-heading-respect-content t))
6215 (org-insert-heading t)))
6217 (defun org-insert-todo-heading-respect-content (&optional force-state)
6218 (interactive "P")
6219 (let ((org-insert-heading-respect-content t))
6220 (org-insert-todo-heading force-state t)))
6222 (defun org-insert-todo-heading (arg &optional force-heading)
6223 "Insert a new heading with the same level and TODO state as current heading.
6224 If the heading has no TODO state, or if the state is DONE, use the first
6225 state (TODO by default). Also with prefix arg, force first state."
6226 (interactive "P")
6227 (when (or force-heading (not (org-insert-item 'checkbox)))
6228 (org-insert-heading force-heading)
6229 (save-excursion
6230 (org-back-to-heading)
6231 (outline-previous-heading)
6232 (looking-at org-todo-line-regexp))
6233 (let*
6234 ((new-mark-x
6235 (if (or arg
6236 (not (match-beginning 2))
6237 (member (match-string 2) org-done-keywords))
6238 (car org-todo-keywords-1)
6239 (match-string 2)))
6240 (new-mark
6242 (run-hook-with-args-until-success
6243 'org-todo-get-default-hook new-mark-x nil)
6244 new-mark-x)))
6245 (beginning-of-line 1)
6246 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6247 (if org-treat-insert-todo-heading-as-state-change
6248 (org-todo new-mark)
6249 (insert new-mark " "))))
6250 (when org-provide-todo-statistics
6251 (org-update-parent-todo-statistics))))
6253 (defun org-insert-subheading (arg)
6254 "Insert a new subheading and demote it.
6255 Works for outline headings and for plain lists alike."
6256 (interactive "P")
6257 (org-insert-heading arg)
6258 (cond
6259 ((org-on-heading-p) (org-do-demote))
6260 ((org-at-item-p) (org-indent-item 1))))
6262 (defun org-insert-todo-subheading (arg)
6263 "Insert a new subheading with TODO keyword or checkbox and demote it.
6264 Works for outline headings and for plain lists alike."
6265 (interactive "P")
6266 (org-insert-todo-heading arg)
6267 (cond
6268 ((org-on-heading-p) (org-do-demote))
6269 ((org-at-item-p) (org-indent-item 1))))
6271 ;;; Promotion and Demotion
6273 (defvar org-after-demote-entry-hook nil
6274 "Hook run after an entry has been demoted.
6275 The cursor will be at the beginning of the entry.
6276 When a subtree is being demoted, the hook will be called for each node.")
6278 (defvar org-after-promote-entry-hook nil
6279 "Hook run after an entry has been promoted.
6280 The cursor will be at the beginning of the entry.
6281 When a subtree is being promoted, the hook will be called for each node.")
6283 (defun org-promote-subtree ()
6284 "Promote the entire subtree.
6285 See also `org-promote'."
6286 (interactive)
6287 (save-excursion
6288 (org-map-tree 'org-promote))
6289 (org-fix-position-after-promote))
6291 (defun org-demote-subtree ()
6292 "Demote the entire subtree. See `org-demote'.
6293 See also `org-promote'."
6294 (interactive)
6295 (save-excursion
6296 (org-map-tree 'org-demote))
6297 (org-fix-position-after-promote))
6300 (defun org-do-promote ()
6301 "Promote the current heading higher up the tree.
6302 If the region is active in `transient-mark-mode', promote all headings
6303 in the region."
6304 (interactive)
6305 (save-excursion
6306 (if (org-region-active-p)
6307 (org-map-region 'org-promote (region-beginning) (region-end))
6308 (org-promote)))
6309 (org-fix-position-after-promote))
6311 (defun org-do-demote ()
6312 "Demote the current heading lower down the tree.
6313 If the region is active in `transient-mark-mode', demote all headings
6314 in the region."
6315 (interactive)
6316 (save-excursion
6317 (if (org-region-active-p)
6318 (org-map-region 'org-demote (region-beginning) (region-end))
6319 (org-demote)))
6320 (org-fix-position-after-promote))
6322 (defun org-fix-position-after-promote ()
6323 "Make sure that after pro/demotion cursor position is right."
6324 (let ((pos (point)))
6325 (when (save-excursion
6326 (beginning-of-line 1)
6327 (looking-at org-todo-line-regexp)
6328 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6329 (cond ((eobp) (insert " "))
6330 ((eolp) (insert " "))
6331 ((equal (char-after) ?\ ) (forward-char 1))))))
6333 (defun org-current-level ()
6334 "Return the level of the current entry, or nil if before the first headline.
6335 The level is the number of stars at the beginning of the headline."
6336 (save-excursion
6337 (condition-case nil
6338 (progn
6339 (org-back-to-heading t)
6340 (funcall outline-level))
6341 (error nil))))
6343 (defun org-reduced-level (l)
6344 "Compute the effective level of a heading.
6345 This takes into account the setting of `org-odd-levels-only'."
6346 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6348 (defun org-get-valid-level (level &optional change)
6349 "Rectify a level change under the influence of `org-odd-levels-only'
6350 LEVEL is a current level, CHANGE is by how much the level should be
6351 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6352 even level numbers will become the next higher odd number."
6353 (if org-odd-levels-only
6354 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6355 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6356 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6357 (max 1 (+ level (or change 0)))))
6359 (if (boundp 'define-obsolete-function-alias)
6360 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6361 (define-obsolete-function-alias 'org-get-legal-level
6362 'org-get-valid-level)
6363 (define-obsolete-function-alias 'org-get-legal-level
6364 'org-get-valid-level "23.1")))
6366 (defun org-promote ()
6367 "Promote the current heading higher up the tree.
6368 If the region is active in `transient-mark-mode', promote all headings
6369 in the region."
6370 (org-back-to-heading t)
6371 (let* ((level (save-match-data (funcall outline-level)))
6372 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6373 (diff (abs (- level (length up-head) -1))))
6374 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6375 (replace-match up-head nil t)
6376 ;; Fixup tag positioning
6377 (and org-auto-align-tags (org-set-tags nil t))
6378 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6379 (run-hooks 'org-after-promote-entry-hook)))
6381 (defun org-demote ()
6382 "Demote the current heading lower down the tree.
6383 If the region is active in `transient-mark-mode', demote all headings
6384 in the region."
6385 (org-back-to-heading t)
6386 (let* ((level (save-match-data (funcall outline-level)))
6387 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6388 (diff (abs (- level (length down-head) -1))))
6389 (replace-match down-head nil t)
6390 ;; Fixup tag positioning
6391 (and org-auto-align-tags (org-set-tags nil t))
6392 (if org-adapt-indentation (org-fixup-indentation diff))
6393 (run-hooks 'org-after-demote-entry-hook)))
6395 (defvar org-tab-ind-state nil)
6397 (defun org-cycle-level ()
6398 (let ((org-adapt-indentation nil))
6399 (when (and (looking-at "[ \t]*$")
6400 (org-looking-back
6401 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6402 (setq this-command 'org-cycle-level)
6403 (if (eq last-command 'org-cycle-level)
6404 (condition-case nil
6405 (progn (org-do-promote)
6406 (if (equal org-tab-ind-state (org-current-level))
6407 (org-do-promote)))
6408 (error
6409 (progn
6410 (save-excursion
6411 (beginning-of-line 1)
6412 (and (looking-at "\\*+")
6413 (replace-match
6414 (make-string org-tab-ind-state ?*))))
6415 (setq this-command 'org-cycle))))
6416 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6417 (org-do-demote))
6418 t)))
6420 (defun org-map-tree (fun)
6421 "Call FUN for every heading underneath the current one."
6422 (org-back-to-heading)
6423 (let ((level (funcall outline-level)))
6424 (save-excursion
6425 (funcall fun)
6426 (while (and (progn
6427 (outline-next-heading)
6428 (> (funcall outline-level) level))
6429 (not (eobp)))
6430 (funcall fun)))))
6432 (defun org-map-region (fun beg end)
6433 "Call FUN for every heading between BEG and END."
6434 (let ((org-ignore-region t))
6435 (save-excursion
6436 (setq end (copy-marker end))
6437 (goto-char beg)
6438 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6439 (< (point) end))
6440 (funcall fun))
6441 (while (and (progn
6442 (outline-next-heading)
6443 (< (point) end))
6444 (not (eobp)))
6445 (funcall fun)))))
6447 (defun org-fixup-indentation (diff)
6448 "Change the indentation in the current entry by DIFF
6449 However, if any line in the current entry has no indentation, or if it
6450 would end up with no indentation after the change, nothing at all is done."
6451 (save-excursion
6452 (let ((end (save-excursion (outline-next-heading)
6453 (point-marker)))
6454 (prohibit (if (> diff 0)
6455 "^\\S-"
6456 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6457 col)
6458 (unless (save-excursion (end-of-line 1)
6459 (re-search-forward prohibit end t))
6460 (while (and (< (point) end)
6461 (re-search-forward "^[ \t]+" end t))
6462 (goto-char (match-end 0))
6463 (setq col (current-column))
6464 (if (< diff 0) (replace-match ""))
6465 (org-indent-to-column (+ diff col))))
6466 (move-marker end nil))))
6468 (defun org-convert-to-odd-levels ()
6469 "Convert an org-mode file with all levels allowed to one with odd levels.
6470 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6471 level 5 etc."
6472 (interactive)
6473 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6474 (let ((outline-regexp org-outline-regexp)
6475 (outline-level 'org-outline-level)
6476 (org-odd-levels-only nil) n)
6477 (save-excursion
6478 (goto-char (point-min))
6479 (while (re-search-forward "^\\*\\*+ " nil t)
6480 (setq n (- (length (match-string 0)) 2))
6481 (while (>= (setq n (1- n)) 0)
6482 (org-demote))
6483 (end-of-line 1))))))
6485 (defun org-convert-to-oddeven-levels ()
6486 "Convert an org-mode file with only odd levels to one with odd and even levels.
6487 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6488 section with an even level, conversion would destroy the structure of the file. An error
6489 is signaled in this case."
6490 (interactive)
6491 (goto-char (point-min))
6492 ;; First check if there are no even levels
6493 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6494 (org-show-context t)
6495 (error "Not all levels are odd in this file. Conversion not possible"))
6496 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6497 (let ((outline-regexp org-outline-regexp)
6498 (outline-level 'org-outline-level)
6499 (org-odd-levels-only nil) n)
6500 (save-excursion
6501 (goto-char (point-min))
6502 (while (re-search-forward "^\\*\\*+ " nil t)
6503 (setq n (/ (1- (length (match-string 0))) 2))
6504 (while (>= (setq n (1- n)) 0)
6505 (org-promote))
6506 (end-of-line 1))))))
6508 (defun org-tr-level (n)
6509 "Make N odd if required."
6510 (if org-odd-levels-only (1+ (/ n 2)) n))
6512 ;;; Vertical tree motion, cutting and pasting of subtrees
6514 (defun org-move-subtree-up (&optional arg)
6515 "Move the current subtree up past ARG headlines of the same level."
6516 (interactive "p")
6517 (org-move-subtree-down (- (prefix-numeric-value arg))))
6519 (defun org-move-subtree-down (&optional arg)
6520 "Move the current subtree down past ARG headlines of the same level."
6521 (interactive "p")
6522 (setq arg (prefix-numeric-value arg))
6523 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6524 'org-get-last-sibling))
6525 (ins-point (make-marker))
6526 (cnt (abs arg))
6527 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6528 ;; Select the tree
6529 (org-back-to-heading)
6530 (setq beg0 (point))
6531 (save-excursion
6532 (setq ne-beg (org-back-over-empty-lines))
6533 (setq beg (point)))
6534 (save-match-data
6535 (save-excursion (outline-end-of-heading)
6536 (setq folded (org-invisible-p)))
6537 (outline-end-of-subtree))
6538 (outline-next-heading)
6539 (setq ne-end (org-back-over-empty-lines))
6540 (setq end (point))
6541 (goto-char beg0)
6542 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6543 ;; include less whitespace
6544 (save-excursion
6545 (goto-char beg)
6546 (forward-line (- ne-beg ne-end))
6547 (setq beg (point))))
6548 ;; Find insertion point, with error handling
6549 (while (> cnt 0)
6550 (or (and (funcall movfunc) (looking-at outline-regexp))
6551 (progn (goto-char beg0)
6552 (error "Cannot move past superior level or buffer limit")))
6553 (setq cnt (1- cnt)))
6554 (if (> arg 0)
6555 ;; Moving forward - still need to move over subtree
6556 (progn (org-end-of-subtree t t)
6557 (save-excursion
6558 (org-back-over-empty-lines)
6559 (or (bolp) (newline)))))
6560 (setq ne-ins (org-back-over-empty-lines))
6561 (move-marker ins-point (point))
6562 (setq txt (buffer-substring beg end))
6563 (org-save-markers-in-region beg end)
6564 (delete-region beg end)
6565 (org-remove-empty-overlays-at beg)
6566 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6567 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6568 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6569 (let ((bbb (point)))
6570 (insert-before-markers txt)
6571 (org-reinstall-markers-in-region bbb)
6572 (move-marker ins-point bbb))
6573 (or (bolp) (insert "\n"))
6574 (setq ins-end (point))
6575 (goto-char ins-point)
6576 (org-skip-whitespace)
6577 (when (and (< arg 0)
6578 (org-first-sibling-p)
6579 (> ne-ins ne-beg))
6580 ;; Move whitespace back to beginning
6581 (save-excursion
6582 (goto-char ins-end)
6583 (let ((kill-whole-line t))
6584 (kill-line (- ne-ins ne-beg)) (point)))
6585 (insert (make-string (- ne-ins ne-beg) ?\n)))
6586 (move-marker ins-point nil)
6587 (if folded
6588 (hide-subtree)
6589 (org-show-entry)
6590 (show-children)
6591 (org-cycle-hide-drawers 'children))
6592 (org-clean-visibility-after-subtree-move)))
6594 (defvar org-subtree-clip ""
6595 "Clipboard for cut and paste of subtrees.
6596 This is actually only a copy of the kill, because we use the normal kill
6597 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6599 (defvar org-subtree-clip-folded nil
6600 "Was the last copied subtree folded?
6601 This is used to fold the tree back after pasting.")
6603 (defun org-cut-subtree (&optional n)
6604 "Cut the current subtree into the clipboard.
6605 With prefix arg N, cut this many sequential subtrees.
6606 This is a short-hand for marking the subtree and then cutting it."
6607 (interactive "p")
6608 (org-copy-subtree n 'cut))
6610 (defun org-copy-subtree (&optional n cut force-store-markers)
6611 "Cut the current subtree into the clipboard.
6612 With prefix arg N, cut this many sequential subtrees.
6613 This is a short-hand for marking the subtree and then copying it.
6614 If CUT is non-nil, actually cut the subtree.
6615 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6616 of some markers in the region, even if CUT is non-nil. This is
6617 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6618 (interactive "p")
6619 (let (beg end folded (beg0 (point)))
6620 (if (interactive-p)
6621 (org-back-to-heading nil) ; take what looks like a subtree
6622 (org-back-to-heading t)) ; take what is really there
6623 (org-back-over-empty-lines)
6624 (setq beg (point))
6625 (skip-chars-forward " \t\r\n")
6626 (save-match-data
6627 (save-excursion (outline-end-of-heading)
6628 (setq folded (org-invisible-p)))
6629 (condition-case nil
6630 (org-forward-same-level (1- n) t)
6631 (error nil))
6632 (org-end-of-subtree t t))
6633 (org-back-over-empty-lines)
6634 (setq end (point))
6635 (goto-char beg0)
6636 (when (> end beg)
6637 (setq org-subtree-clip-folded folded)
6638 (when (or cut force-store-markers)
6639 (org-save-markers-in-region beg end))
6640 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6641 (setq org-subtree-clip (current-kill 0))
6642 (message "%s: Subtree(s) with %d characters"
6643 (if cut "Cut" "Copied")
6644 (length org-subtree-clip)))))
6646 (defun org-paste-subtree (&optional level tree for-yank)
6647 "Paste the clipboard as a subtree, with modification of headline level.
6648 The entire subtree is promoted or demoted in order to match a new headline
6649 level.
6651 If the cursor is at the beginning of a headline, the same level as
6652 that headline is used to paste the tree
6654 If not, the new level is derived from the *visible* headings
6655 before and after the insertion point, and taken to be the inferior headline
6656 level of the two. So if the previous visible heading is level 3 and the
6657 next is level 4 (or vice versa), level 4 will be used for insertion.
6658 This makes sure that the subtree remains an independent subtree and does
6659 not swallow low level entries.
6661 You can also force a different level, either by using a numeric prefix
6662 argument, or by inserting the heading marker by hand. For example, if the
6663 cursor is after \"*****\", then the tree will be shifted to level 5.
6665 If optional TREE is given, use this text instead of the kill ring.
6667 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6668 move back over whitespace before inserting, and move point to the end of
6669 the inserted text when done."
6670 (interactive "P")
6671 (setq tree (or tree (and kill-ring (current-kill 0))))
6672 (unless (org-kill-is-subtree-p tree)
6673 (error "%s"
6674 (substitute-command-keys
6675 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6676 (let* ((visp (not (org-invisible-p)))
6677 (txt tree)
6678 (^re (concat "^\\(" outline-regexp "\\)"))
6679 (re (concat "\\(" outline-regexp "\\)"))
6680 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6682 (old-level (if (string-match ^re txt)
6683 (- (match-end 0) (match-beginning 0) 1)
6684 -1))
6685 (force-level (cond (level (prefix-numeric-value level))
6686 ((and (looking-at "[ \t]*$")
6687 (string-match
6688 ^re_ (buffer-substring
6689 (point-at-bol) (point))))
6690 (- (match-end 1) (match-beginning 1)))
6691 ((and (bolp)
6692 (looking-at org-outline-regexp))
6693 (- (match-end 0) (point) 1))
6694 (t nil)))
6695 (previous-level (save-excursion
6696 (condition-case nil
6697 (progn
6698 (outline-previous-visible-heading 1)
6699 (if (looking-at re)
6700 (- (match-end 0) (match-beginning 0) 1)
6702 (error 1))))
6703 (next-level (save-excursion
6704 (condition-case nil
6705 (progn
6706 (or (looking-at outline-regexp)
6707 (outline-next-visible-heading 1))
6708 (if (looking-at re)
6709 (- (match-end 0) (match-beginning 0) 1)
6711 (error 1))))
6712 (new-level (or force-level (max previous-level next-level)))
6713 (shift (if (or (= old-level -1)
6714 (= new-level -1)
6715 (= old-level new-level))
6717 (- new-level old-level)))
6718 (delta (if (> shift 0) -1 1))
6719 (func (if (> shift 0) 'org-demote 'org-promote))
6720 (org-odd-levels-only nil)
6721 beg end newend)
6722 ;; Remove the forced level indicator
6723 (if force-level
6724 (delete-region (point-at-bol) (point)))
6725 ;; Paste
6726 (beginning-of-line 1)
6727 (unless for-yank (org-back-over-empty-lines))
6728 (setq beg (point))
6729 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6730 (insert-before-markers txt)
6731 (unless (string-match "\n\\'" txt) (insert "\n"))
6732 (setq newend (point))
6733 (org-reinstall-markers-in-region beg)
6734 (setq end (point))
6735 (goto-char beg)
6736 (skip-chars-forward " \t\n\r")
6737 (setq beg (point))
6738 (if (and (org-invisible-p) visp)
6739 (save-excursion (outline-show-heading)))
6740 ;; Shift if necessary
6741 (unless (= shift 0)
6742 (save-restriction
6743 (narrow-to-region beg end)
6744 (while (not (= shift 0))
6745 (org-map-region func (point-min) (point-max))
6746 (setq shift (+ delta shift)))
6747 (goto-char (point-min))
6748 (setq newend (point-max))))
6749 (when (or (interactive-p) for-yank)
6750 (message "Clipboard pasted as level %d subtree" new-level))
6751 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6752 kill-ring
6753 (eq org-subtree-clip (current-kill 0))
6754 org-subtree-clip-folded)
6755 ;; The tree was folded before it was killed/copied
6756 (hide-subtree))
6757 (and for-yank (goto-char newend))))
6759 (defun org-kill-is-subtree-p (&optional txt)
6760 "Check if the current kill is an outline subtree, or a set of trees.
6761 Returns nil if kill does not start with a headline, or if the first
6762 headline level is not the largest headline level in the tree.
6763 So this will actually accept several entries of equal levels as well,
6764 which is OK for `org-paste-subtree'.
6765 If optional TXT is given, check this string instead of the current kill."
6766 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6767 (start-level (and kill
6768 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6769 org-outline-regexp "\\)")
6770 kill)
6771 (- (match-end 2) (match-beginning 2) 1)))
6772 (re (concat "^" org-outline-regexp))
6773 (start (1+ (or (match-beginning 2) -1))))
6774 (if (not start-level)
6775 (progn
6776 nil) ;; does not even start with a heading
6777 (catch 'exit
6778 (while (setq start (string-match re kill (1+ start)))
6779 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6780 (throw 'exit nil)))
6781 t))))
6783 (defvar org-markers-to-move nil
6784 "Markers that should be moved with a cut-and-paste operation.
6785 Those markers are stored together with their positions relative to
6786 the start of the region.")
6788 (defun org-save-markers-in-region (beg end)
6789 "Check markers in region.
6790 If these markers are between BEG and END, record their position relative
6791 to BEG, so that after moving the block of text, we can put the markers back
6792 into place.
6793 This function gets called just before an entry or tree gets cut from the
6794 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6795 called immediately, to move the markers with the entries."
6796 (setq org-markers-to-move nil)
6797 (when (featurep 'org-clock)
6798 (org-clock-save-markers-for-cut-and-paste beg end))
6799 (when (featurep 'org-agenda)
6800 (org-agenda-save-markers-for-cut-and-paste beg end)))
6802 (defun org-check-and-save-marker (marker beg end)
6803 "Check if MARKER is between BEG and END.
6804 If yes, remember the marker and the distance to BEG."
6805 (when (and (marker-buffer marker)
6806 (equal (marker-buffer marker) (current-buffer)))
6807 (if (and (>= marker beg) (< marker end))
6808 (push (cons marker (- marker beg)) org-markers-to-move))))
6810 (defun org-reinstall-markers-in-region (beg)
6811 "Move all remembered markers to their position relative to BEG."
6812 (mapc (lambda (x)
6813 (move-marker (car x) (+ beg (cdr x))))
6814 org-markers-to-move)
6815 (setq org-markers-to-move nil))
6817 (defun org-narrow-to-subtree ()
6818 "Narrow buffer to the current subtree."
6819 (interactive)
6820 (save-excursion
6821 (save-match-data
6822 (narrow-to-region
6823 (progn (org-back-to-heading t) (point))
6824 (progn (org-end-of-subtree t t) (point))))))
6826 (defun org-clone-subtree-with-time-shift (n &optional shift)
6827 "Clone the task (subtree) at point N times.
6828 The clones will be inserted as siblings.
6830 In interactive use, the user will be prompted for the number of clones
6831 to be produced, and for a time SHIFT, which may be a repeater as used
6832 in time stamps, for example `+3d'.
6834 When a valid repeater is given and the entry contains any time stamps,
6835 the clones will become a sequence in time, with time stamps in the
6836 subtree shifted for each clone produced. If SHIFT is nil or the
6837 empty string, time stamps will be left alone.
6839 If the original subtree did contain time stamps with a repeater,
6840 the following will happen:
6841 - the repeater will be removed in each clone
6842 - an additional clone will be produced, with the current, unshifted
6843 date(s) in the entry.
6844 - the original entry will be placed *after* all the clones, with
6845 repeater intact.
6846 - the start days in the repeater in the original entry will be shifted
6847 to past the last clone.
6848 I this way you can spell out a number of instances of a repeating task,
6849 and still retain the repeater to cover future instances of the task."
6850 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6851 (let (beg end template task
6852 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6853 (if (not (and (integerp n) (> n 0)))
6854 (error "Invalid number of replications %s" n))
6855 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6856 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6857 shift)))
6858 (error "Invalid shift specification %s" shift))
6859 (when doshift
6860 (setq shift-n (string-to-number (match-string 1 shift))
6861 shift-what (cdr (assoc (match-string 2 shift)
6862 '(("d" . day) ("w" . week)
6863 ("m" . month) ("y" . year))))))
6864 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6865 (setq nmin 1 nmax n)
6866 (org-back-to-heading t)
6867 (setq beg (point))
6868 (org-end-of-subtree t t)
6869 (or (bolp) (insert "\n"))
6870 (setq end (point))
6871 (setq template (buffer-substring beg end))
6872 (when (and doshift
6873 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6874 (delete-region beg end)
6875 (setq end beg)
6876 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6877 (goto-char end)
6878 (loop for n from nmin to nmax do
6879 (if (not doshift)
6880 (setq task template)
6881 (with-temp-buffer
6882 (insert template)
6883 (org-mode)
6884 (goto-char (point-min))
6885 (while (re-search-forward org-ts-regexp-both nil t)
6886 (org-timestamp-change (* n shift-n) shift-what))
6887 (unless (= n n-no-remove)
6888 (goto-char (point-min))
6889 (while (re-search-forward org-ts-regexp nil t)
6890 (save-excursion
6891 (goto-char (match-beginning 0))
6892 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6893 (delete-region (match-beginning 1) (match-end 1))))))
6894 (setq task (buffer-string))))
6895 (insert task))
6896 (goto-char beg)))
6898 ;;; Outline Sorting
6900 (defun org-sort (with-case)
6901 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6902 Optional argument WITH-CASE means sort case-sensitively.
6903 With a double prefix argument, also remove duplicate entries."
6904 (interactive "P")
6905 (if (org-at-table-p)
6906 (org-call-with-arg 'org-table-sort-lines with-case)
6907 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6909 (defun org-sort-remove-invisible (s)
6910 (remove-text-properties 0 (length s) org-rm-props s)
6911 (while (string-match org-bracket-link-regexp s)
6912 (setq s (replace-match (if (match-end 2)
6913 (match-string 3 s)
6914 (match-string 1 s)) t t s)))
6917 (defvar org-priority-regexp) ; defined later in the file
6919 (defvar org-after-sorting-entries-or-items-hook nil
6920 "Hook that is run after a bunch of entries or items have been sorted.
6921 When children are sorted, the cursor is in the parent line when this
6922 hook gets called. When a region or a plain list is sorted, the cursor
6923 will be in the first entry of the sorted region/list.")
6925 (defun org-sort-entries-or-items
6926 (&optional with-case sorting-type getkey-func compare-func property)
6927 "Sort entries on a certain level of an outline tree, or plain list items.
6928 If there is an active region, the entries in the region are sorted.
6929 Else, if the cursor is before the first entry, sort the top-level items.
6930 Else, the children of the entry at point are sorted.
6931 If the cursor is at the first item in a plain list, the list items will be
6932 sorted.
6934 Sorting can be alphabetically, numerically, by date/time as given by
6935 a time stamp, by a property or by priority.
6937 The command prompts for the sorting type unless it has been given to the
6938 function through the SORTING-TYPE argument, which needs to a character,
6939 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6940 precise meaning of each character:
6942 n Numerically, by converting the beginning of the entry/item to a number.
6943 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6944 t By date/time, either the first active time stamp in the entry, or, if
6945 none exist, by the first inactive one.
6946 In items, only the first line will be checked.
6947 s By the scheduled date/time.
6948 d By deadline date/time.
6949 c By creation time, which is assumed to be the first inactive time stamp
6950 at the beginning of a line.
6951 p By priority according to the cookie.
6952 r By the value of a property.
6954 Capital letters will reverse the sort order.
6956 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6957 called with point at the beginning of the record. It must return either
6958 a string or a number that should serve as the sorting key for that record.
6960 Comparing entries ignores case by default. However, with an optional argument
6961 WITH-CASE, the sorting considers case as well."
6962 (interactive "P")
6963 (let ((case-func (if with-case 'identity 'downcase))
6964 start beg end stars re re2
6965 txt what tmp plain-list-p)
6966 ;; Find beginning and end of region to sort
6967 (cond
6968 ((org-region-active-p)
6969 ;; we will sort the region
6970 (setq end (region-end)
6971 what "region")
6972 (goto-char (region-beginning))
6973 (if (not (org-on-heading-p)) (outline-next-heading))
6974 (setq start (point)))
6975 ((org-at-item-p)
6976 ;; we will sort this plain list
6977 (org-beginning-of-item-list) (setq start (point))
6978 (org-end-of-item-list)
6979 (or (bolp) (insert "\n"))
6980 (setq end (point))
6981 (goto-char start)
6982 (setq plain-list-p t
6983 what "plain list"))
6984 ((or (org-on-heading-p)
6985 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6986 ;; we will sort the children of the current headline
6987 (org-back-to-heading)
6988 (setq start (point)
6989 end (progn (org-end-of-subtree t t)
6990 (or (bolp) (insert "\n"))
6991 (org-back-over-empty-lines)
6992 (point))
6993 what "children")
6994 (goto-char start)
6995 (show-subtree)
6996 (outline-next-heading))
6998 ;; we will sort the top-level entries in this file
6999 (goto-char (point-min))
7000 (or (org-on-heading-p) (outline-next-heading))
7001 (setq start (point))
7002 (goto-char (point-max))
7003 (beginning-of-line 1)
7004 (when (looking-at ".*?\\S-")
7005 ;; File ends in a non-white line
7006 (end-of-line 1)
7007 (insert "\n"))
7008 (setq end (point-max))
7009 (setq what "top-level")
7010 (goto-char start)
7011 (show-all)))
7013 (setq beg (point))
7014 (if (>= beg end) (error "Nothing to sort"))
7016 (unless plain-list-p
7017 (looking-at "\\(\\*+\\)")
7018 (setq stars (match-string 1)
7019 re (concat "^" (regexp-quote stars) " +")
7020 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7021 txt (buffer-substring beg end))
7022 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7023 (if (and (not (equal stars "*")) (string-match re2 txt))
7024 (error "Region to sort contains a level above the first entry")))
7026 (unless sorting-type
7027 (message
7028 (if plain-list-p
7029 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7030 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7031 [t]ime [s]cheduled [d]eadline [c]reated
7032 A/N/T/S/D/C/P/O/F means reversed:")
7033 what)
7034 (setq sorting-type (read-char-exclusive))
7036 (and (= (downcase sorting-type) ?f)
7037 (setq getkey-func
7038 (org-icompleting-read "Sort using function: "
7039 obarray 'fboundp t nil nil))
7040 (setq getkey-func (intern getkey-func)))
7042 (and (= (downcase sorting-type) ?r)
7043 (setq property
7044 (org-icompleting-read "Property: "
7045 (mapcar 'list (org-buffer-property-keys t))
7046 nil t))))
7048 (message "Sorting entries...")
7050 (save-restriction
7051 (narrow-to-region start end)
7053 (let ((dcst (downcase sorting-type))
7054 (case-fold-search nil)
7055 (now (current-time)))
7056 (sort-subr
7057 (/= dcst sorting-type)
7058 ;; This function moves to the beginning character of the "record" to
7059 ;; be sorted.
7060 (if plain-list-p
7061 (lambda nil
7062 (if (org-at-item-p) t (goto-char (point-max))))
7063 (lambda nil
7064 (if (re-search-forward re nil t)
7065 (goto-char (match-beginning 0))
7066 (goto-char (point-max)))))
7067 ;; This function moves to the last character of the "record" being
7068 ;; sorted.
7069 (if plain-list-p
7070 'org-end-of-item
7071 (lambda nil
7072 (save-match-data
7073 (condition-case nil
7074 (outline-forward-same-level 1)
7075 (error
7076 (goto-char (point-max)))))))
7078 ;; This function returns the value that gets sorted against.
7079 (if plain-list-p
7080 (lambda nil
7081 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7082 (cond
7083 ((= dcst ?n)
7084 (string-to-number (buffer-substring (match-end 0)
7085 (point-at-eol))))
7086 ((= dcst ?a)
7087 (buffer-substring (match-end 0) (point-at-eol)))
7088 ((= dcst ?t)
7089 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7090 (re-search-forward org-ts-regexp-both
7091 (point-at-eol) t))
7092 (org-time-string-to-seconds (match-string 0))
7093 (org-float-time now)))
7094 ((= dcst ?f)
7095 (if getkey-func
7096 (progn
7097 (setq tmp (funcall getkey-func))
7098 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7099 tmp)
7100 (error "Invalid key function `%s'" getkey-func)))
7101 (t (error "Invalid sorting type `%c'" sorting-type)))))
7102 (lambda nil
7103 (cond
7104 ((= dcst ?n)
7105 (if (looking-at org-complex-heading-regexp)
7106 (string-to-number (match-string 4))
7107 nil))
7108 ((= dcst ?a)
7109 (if (looking-at org-complex-heading-regexp)
7110 (funcall case-func (match-string 4))
7111 nil))
7112 ((= dcst ?t)
7113 (let ((end (save-excursion (outline-next-heading) (point))))
7114 (if (or (re-search-forward org-ts-regexp end t)
7115 (re-search-forward org-ts-regexp-both end t))
7116 (org-time-string-to-seconds (match-string 0))
7117 (org-float-time now))))
7118 ((= dcst ?c)
7119 (let ((end (save-excursion (outline-next-heading) (point))))
7120 (if (re-search-forward
7121 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7122 end t)
7123 (org-time-string-to-seconds (match-string 0))
7124 (org-float-time now))))
7125 ((= dcst ?s)
7126 (let ((end (save-excursion (outline-next-heading) (point))))
7127 (if (re-search-forward org-scheduled-time-regexp end t)
7128 (org-time-string-to-seconds (match-string 1))
7129 (org-float-time now))))
7130 ((= dcst ?d)
7131 (let ((end (save-excursion (outline-next-heading) (point))))
7132 (if (re-search-forward org-deadline-time-regexp end t)
7133 (org-time-string-to-seconds (match-string 1))
7134 (org-float-time now))))
7135 ((= dcst ?p)
7136 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7137 (string-to-char (match-string 2))
7138 org-default-priority))
7139 ((= dcst ?r)
7140 (or (org-entry-get nil property) ""))
7141 ((= dcst ?o)
7142 (if (looking-at org-complex-heading-regexp)
7143 (- 9999 (length (member (match-string 2)
7144 org-todo-keywords-1)))))
7145 ((= dcst ?f)
7146 (if getkey-func
7147 (progn
7148 (setq tmp (funcall getkey-func))
7149 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7150 tmp)
7151 (error "Invalid key function `%s'" getkey-func)))
7152 (t (error "Invalid sorting type `%c'" sorting-type)))))
7154 (cond
7155 ((= dcst ?a) 'string<)
7156 ((= dcst ?f) compare-func)
7157 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7158 (t nil)))))
7159 (run-hooks 'org-after-sorting-entries-or-items-hook)
7160 (message "Sorting entries...done")))
7162 (defun org-do-sort (table what &optional with-case sorting-type)
7163 "Sort TABLE of WHAT according to SORTING-TYPE.
7164 The user will be prompted for the SORTING-TYPE if the call to this
7165 function does not specify it. WHAT is only for the prompt, to indicate
7166 what is being sorted. The sorting key will be extracted from
7167 the car of the elements of the table.
7168 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7169 (unless sorting-type
7170 (message
7171 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7172 what)
7173 (setq sorting-type (read-char-exclusive)))
7174 (let ((dcst (downcase sorting-type))
7175 extractfun comparefun)
7176 ;; Define the appropriate functions
7177 (cond
7178 ((= dcst ?n)
7179 (setq extractfun 'string-to-number
7180 comparefun (if (= dcst sorting-type) '< '>)))
7181 ((= dcst ?a)
7182 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7183 (lambda(x) (downcase (org-sort-remove-invisible x))))
7184 comparefun (if (= dcst sorting-type)
7185 'string<
7186 (lambda (a b) (and (not (string< a b))
7187 (not (string= a b)))))))
7188 ((= dcst ?t)
7189 (setq extractfun
7190 (lambda (x)
7191 (if (or (string-match org-ts-regexp x)
7192 (string-match org-ts-regexp-both x))
7193 (org-float-time
7194 (org-time-string-to-time (match-string 0 x)))
7196 comparefun (if (= dcst sorting-type) '< '>)))
7197 (t (error "Invalid sorting type `%c'" sorting-type)))
7199 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7200 table)
7201 (lambda (a b) (funcall comparefun (car a) (car b))))))
7204 ;;; The orgstruct minor mode
7206 ;; Define a minor mode which can be used in other modes in order to
7207 ;; integrate the org-mode structure editing commands.
7209 ;; This is really a hack, because the org-mode structure commands use
7210 ;; keys which normally belong to the major mode. Here is how it
7211 ;; works: The minor mode defines all the keys necessary to operate the
7212 ;; structure commands, but wraps the commands into a function which
7213 ;; tests if the cursor is currently at a headline or a plain list
7214 ;; item. If that is the case, the structure command is used,
7215 ;; temporarily setting many Org-mode variables like regular
7216 ;; expressions for filling etc. However, when any of those keys is
7217 ;; used at a different location, function uses `key-binding' to look
7218 ;; up if the key has an associated command in another currently active
7219 ;; keymap (minor modes, major mode, global), and executes that
7220 ;; command. There might be problems if any of the keys is otherwise
7221 ;; used as a prefix key.
7223 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7224 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7225 ;; addresses this by checking explicitly for both bindings.
7227 (defvar orgstruct-mode-map (make-sparse-keymap)
7228 "Keymap for the minor `orgstruct-mode'.")
7230 (defvar org-local-vars nil
7231 "List of local variables, for use by `orgstruct-mode'")
7233 ;;;###autoload
7234 (define-minor-mode orgstruct-mode
7235 "Toggle the minor more `orgstruct-mode'.
7236 This mode is for using Org-mode structure commands in other modes.
7237 The following key behave as if Org-mode was active, if the cursor
7238 is on a headline, or on a plain list item (both in the definition
7239 of Org-mode).
7241 M-up Move entry/item up
7242 M-down Move entry/item down
7243 M-left Promote
7244 M-right Demote
7245 M-S-up Move entry/item up
7246 M-S-down Move entry/item down
7247 M-S-left Promote subtree
7248 M-S-right Demote subtree
7249 M-q Fill paragraph and items like in Org-mode
7250 C-c ^ Sort entries
7251 C-c - Cycle list bullet
7252 TAB Cycle item visibility
7253 M-RET Insert new heading/item
7254 S-M-RET Insert new TODO heading / Checkbox item
7255 C-c C-c Set tags / toggle checkbox"
7256 nil " OrgStruct" nil
7257 (org-load-modules-maybe)
7258 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7260 ;;;###autoload
7261 (defun turn-on-orgstruct ()
7262 "Unconditionally turn on `orgstruct-mode'."
7263 (orgstruct-mode 1))
7265 (defun orgstruct++-mode (&optional arg)
7266 "Toggle `orgstruct-mode', the enhanced version of it.
7267 In addition to setting orgstruct-mode, this also exports all indentation
7268 and autofilling variables from org-mode into the buffer. It will also
7269 recognize item context in multiline items.
7270 Note that turning off orgstruct-mode will *not* remove the
7271 indentation/paragraph settings. This can only be done by refreshing the
7272 major mode, for example with \\[normal-mode]."
7273 (interactive "P")
7274 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7275 (if (< arg 1)
7276 (orgstruct-mode -1)
7277 (orgstruct-mode 1)
7278 (let (var val)
7279 (mapc
7280 (lambda (x)
7281 (when (string-match
7282 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7283 (symbol-name (car x)))
7284 (setq var (car x) val (nth 1 x))
7285 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7286 org-local-vars)
7287 (org-set-local 'orgstruct-is-++ t))))
7289 (defvar orgstruct-is-++ nil
7290 "Is orgstruct-mode in ++ version in the current-buffer?")
7291 (make-variable-buffer-local 'orgstruct-is-++)
7293 ;;;###autoload
7294 (defun turn-on-orgstruct++ ()
7295 "Unconditionally turn on `orgstruct++-mode'."
7296 (orgstruct++-mode 1))
7298 (defun orgstruct-error ()
7299 "Error when there is no default binding for a structure key."
7300 (interactive)
7301 (error "This key has no function outside structure elements"))
7303 (defun orgstruct-setup ()
7304 "Setup orgstruct keymaps."
7305 (let ((nfunc 0)
7306 (bindings
7307 (list
7308 '([(meta up)] org-metaup)
7309 '([(meta down)] org-metadown)
7310 '([(meta left)] org-metaleft)
7311 '([(meta right)] org-metaright)
7312 '([(meta shift up)] org-shiftmetaup)
7313 '([(meta shift down)] org-shiftmetadown)
7314 '([(meta shift left)] org-shiftmetaleft)
7315 '([(meta shift right)] org-shiftmetaright)
7316 '([?\e (up)] org-metaup)
7317 '([?\e (down)] org-metadown)
7318 '([?\e (left)] org-metaleft)
7319 '([?\e (right)] org-metaright)
7320 '([?\e (shift up)] org-shiftmetaup)
7321 '([?\e (shift down)] org-shiftmetadown)
7322 '([?\e (shift left)] org-shiftmetaleft)
7323 '([?\e (shift right)] org-shiftmetaright)
7324 '([(shift up)] org-shiftup)
7325 '([(shift down)] org-shiftdown)
7326 '([(shift left)] org-shiftleft)
7327 '([(shift right)] org-shiftright)
7328 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7329 '("\M-q" fill-paragraph)
7330 '("\C-c^" org-sort)
7331 '("\C-c-" org-cycle-list-bullet)))
7332 elt key fun cmd)
7333 (while (setq elt (pop bindings))
7334 (setq nfunc (1+ nfunc))
7335 (setq key (org-key (car elt))
7336 fun (nth 1 elt)
7337 cmd (orgstruct-make-binding fun nfunc key))
7338 (org-defkey orgstruct-mode-map key cmd))
7340 ;; Special treatment needed for TAB and RET
7341 (org-defkey orgstruct-mode-map [(tab)]
7342 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7343 (org-defkey orgstruct-mode-map "\C-i"
7344 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7346 (org-defkey orgstruct-mode-map "\M-\C-m"
7347 (orgstruct-make-binding 'org-insert-heading 105
7348 "\M-\C-m" [(meta return)]))
7349 (org-defkey orgstruct-mode-map [(meta return)]
7350 (orgstruct-make-binding 'org-insert-heading 106
7351 [(meta return)] "\M-\C-m"))
7353 (org-defkey orgstruct-mode-map [(shift meta return)]
7354 (orgstruct-make-binding 'org-insert-todo-heading 107
7355 [(meta return)] "\M-\C-m"))
7357 (org-defkey orgstruct-mode-map "\e\C-m"
7358 (orgstruct-make-binding 'org-insert-heading 108
7359 "\e\C-m" [?\e (return)]))
7360 (org-defkey orgstruct-mode-map [?\e (return)]
7361 (orgstruct-make-binding 'org-insert-heading 109
7362 [?\e (return)] "\e\C-m"))
7363 (org-defkey orgstruct-mode-map [?\e (shift return)]
7364 (orgstruct-make-binding 'org-insert-todo-heading 110
7365 [?\e (return)] "\e\C-m"))
7367 (unless org-local-vars
7368 (setq org-local-vars (org-get-local-variables)))
7372 (defun orgstruct-make-binding (fun n &rest keys)
7373 "Create a function for binding in the structure minor mode.
7374 FUN is the command to call inside a table. N is used to create a unique
7375 command name. KEYS are keys that should be checked in for a command
7376 to execute outside of tables."
7377 (eval
7378 (list 'defun
7379 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7380 '(arg)
7381 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7382 "Outside of structure, run the binding of `"
7383 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7384 "'.")
7385 '(interactive "p")
7386 (list 'if
7387 `(org-context-p 'headline 'item
7388 (and orgstruct-is-++
7389 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7390 'item-body))
7391 (list 'org-run-like-in-org-mode (list 'quote fun))
7392 (list 'let '(orgstruct-mode)
7393 (list 'call-interactively
7394 (append '(or)
7395 (mapcar (lambda (k)
7396 (list 'key-binding k))
7397 keys)
7398 '('orgstruct-error))))))))
7400 (defun org-context-p (&rest contexts)
7401 "Check if local context is any of CONTEXTS.
7402 Possible values in the list of contexts are `table', `headline', and `item'."
7403 (let ((pos (point)))
7404 (goto-char (point-at-bol))
7405 (prog1 (or (and (memq 'table contexts)
7406 (looking-at "[ \t]*|"))
7407 (and (memq 'headline contexts)
7408 ;;????????? (looking-at "\\*+"))
7409 (looking-at outline-regexp))
7410 (and (memq 'item contexts)
7411 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7412 (and (memq 'item-body contexts)
7413 (org-in-item-p)))
7414 (goto-char pos))))
7416 (defun org-get-local-variables ()
7417 "Return a list of all local variables in an org-mode buffer."
7418 (let (varlist)
7419 (with-current-buffer (get-buffer-create "*Org tmp*")
7420 (erase-buffer)
7421 (org-mode)
7422 (setq varlist (buffer-local-variables)))
7423 (kill-buffer "*Org tmp*")
7424 (delq nil
7425 (mapcar
7426 (lambda (x)
7427 (setq x
7428 (if (symbolp x)
7429 (list x)
7430 (list (car x) (list 'quote (cdr x)))))
7431 (if (string-match
7432 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7433 (symbol-name (car x)))
7434 x nil))
7435 varlist))))
7437 ;;;###autoload
7438 (defun org-run-like-in-org-mode (cmd)
7439 "Run a command, pretending that the current buffer is in Org-mode.
7440 This will temporarily bind local variables that are typically bound in
7441 Org-mode to the values they have in Org-mode, and then interactively
7442 call CMD."
7443 (org-load-modules-maybe)
7444 (unless org-local-vars
7445 (setq org-local-vars (org-get-local-variables)))
7446 (eval (list 'let org-local-vars
7447 (list 'call-interactively (list 'quote cmd)))))
7449 ;;;; Archiving
7451 (defun org-get-category (&optional pos)
7452 "Get the category applying to position POS."
7453 (get-text-property (or pos (point)) 'org-category))
7455 (defun org-refresh-category-properties ()
7456 "Refresh category text properties in the buffer."
7457 (let ((def-cat (cond
7458 ((null org-category)
7459 (if buffer-file-name
7460 (file-name-sans-extension
7461 (file-name-nondirectory buffer-file-name))
7462 "???"))
7463 ((symbolp org-category) (symbol-name org-category))
7464 (t org-category)))
7465 beg end cat pos optionp)
7466 (org-unmodified
7467 (save-excursion
7468 (save-restriction
7469 (widen)
7470 (goto-char (point-min))
7471 (put-text-property (point) (point-max) 'org-category def-cat)
7472 (while (re-search-forward
7473 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7474 (setq pos (match-end 0)
7475 optionp (equal (char-after (match-beginning 0)) ?#)
7476 cat (org-trim (match-string 2)))
7477 (if optionp
7478 (setq beg (point-at-bol) end (point-max))
7479 (org-back-to-heading t)
7480 (setq beg (point) end (org-end-of-subtree t t)))
7481 (put-text-property beg end 'org-category cat)
7482 (goto-char pos)))))))
7485 ;;;; Link Stuff
7487 ;;; Link abbreviations
7489 (defun org-link-expand-abbrev (link)
7490 "Apply replacements as defined in `org-link-abbrev-alist."
7491 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7492 (let* ((key (match-string 1 link))
7493 (as (or (assoc key org-link-abbrev-alist-local)
7494 (assoc key org-link-abbrev-alist)))
7495 (tag (and (match-end 2) (match-string 3 link)))
7496 rpl)
7497 (if (not as)
7498 link
7499 (setq rpl (cdr as))
7500 (cond
7501 ((symbolp rpl) (funcall rpl tag))
7502 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7503 ((string-match "%h" rpl)
7504 (replace-match (url-hexify-string (or tag "")) t t rpl))
7505 (t (concat rpl tag)))))
7506 link))
7508 ;;; Storing and inserting links
7510 (defvar org-insert-link-history nil
7511 "Minibuffer history for links inserted with `org-insert-link'.")
7513 (defvar org-stored-links nil
7514 "Contains the links stored with `org-store-link'.")
7516 (defvar org-store-link-plist nil
7517 "Plist with info about the most recently link created with `org-store-link'.")
7519 (defvar org-link-protocols nil
7520 "Link protocols added to Org-mode using `org-add-link-type'.")
7522 (defvar org-store-link-functions nil
7523 "List of functions that are called to create and store a link.
7524 Each function will be called in turn until one returns a non-nil
7525 value. Each function should check if it is responsible for creating
7526 this link (for example by looking at the major mode).
7527 If not, it must exit and return nil.
7528 If yes, it should return a non-nil value after a calling
7529 `org-store-link-props' with a list of properties and values.
7530 Special properties are:
7532 :type The link prefix. like \"http\". This must be given.
7533 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7534 This is obligatory as well.
7535 :description Optional default description for the second pair
7536 of brackets in an Org-mode link. The user can still change
7537 this when inserting this link into an Org-mode buffer.
7539 In addition to these, any additional properties can be specified
7540 and then used in remember templates.")
7542 (defun org-add-link-type (type &optional follow export)
7543 "Add TYPE to the list of `org-link-types'.
7544 Re-compute all regular expressions depending on `org-link-types'
7546 FOLLOW and EXPORT are two functions.
7548 FOLLOW should take the link path as the single argument and do whatever
7549 is necessary to follow the link, for example find a file or display
7550 a mail message.
7552 EXPORT should format the link path for export to one of the export formats.
7553 It should be a function accepting three arguments:
7555 path the path of the link, the text after the prefix (like \"http:\")
7556 desc the description of the link, if any, nil if there was no description
7557 format the export format, a symbol like `html' or `latex'.
7559 The function may use the FORMAT information to return different values
7560 depending on the format. The return value will be put literally into
7561 the exported file.
7562 Org-mode has a built-in default for exporting links. If you are happy with
7563 this default, there is no need to define an export function for the link
7564 type. For a simple example of an export function, see `org-bbdb.el'."
7565 (add-to-list 'org-link-types type t)
7566 (org-make-link-regexps)
7567 (if (assoc type org-link-protocols)
7568 (setcdr (assoc type org-link-protocols) (list follow export))
7569 (push (list type follow export) org-link-protocols)))
7571 (defvar org-agenda-buffer-name)
7573 ;;;###autoload
7574 (defun org-store-link (arg)
7575 "\\<org-mode-map>Store an org-link to the current location.
7576 This link is added to `org-stored-links' and can later be inserted
7577 into an org-buffer with \\[org-insert-link].
7579 For some link types, a prefix arg is interpreted:
7580 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7581 For file links, arg negates `org-context-in-file-links'."
7582 (interactive "P")
7583 (org-load-modules-maybe)
7584 (setq org-store-link-plist nil) ; reset
7585 (let ((outline-regexp (org-get-limited-outline-regexp))
7586 link cpltxt desc description search txt custom-id)
7587 (cond
7589 ((run-hook-with-args-until-success 'org-store-link-functions)
7590 (setq link (plist-get org-store-link-plist :link)
7591 desc (or (plist-get org-store-link-plist :description) link)))
7593 ((equal (buffer-name) "*Org Edit Src Example*")
7594 (let (label gc)
7595 (while (or (not label)
7596 (save-excursion
7597 (save-restriction
7598 (widen)
7599 (goto-char (point-min))
7600 (re-search-forward
7601 (regexp-quote (format org-coderef-label-format label))
7602 nil t))))
7603 (when label (message "Label exists already") (sit-for 2))
7604 (setq label (read-string "Code line label: " label)))
7605 (end-of-line 1)
7606 (setq link (format org-coderef-label-format label))
7607 (setq gc (- 79 (length link)))
7608 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7609 (insert link)
7610 (setq link (concat "(" label ")") desc nil)))
7612 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7613 ;; We are in the agenda, link to referenced location
7614 (let ((m (or (get-text-property (point) 'org-hd-marker)
7615 (get-text-property (point) 'org-marker))))
7616 (when m
7617 (org-with-point-at m
7618 (call-interactively 'org-store-link)))))
7620 ((eq major-mode 'calendar-mode)
7621 (let ((cd (calendar-cursor-to-date)))
7622 (setq link
7623 (format-time-string
7624 (car org-time-stamp-formats)
7625 (apply 'encode-time
7626 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7627 nil nil nil))))
7628 (org-store-link-props :type "calendar" :date cd)))
7630 ((eq major-mode 'w3-mode)
7631 (setq cpltxt (if (and (buffer-name)
7632 (not (string-match "Untitled" (buffer-name))))
7633 (buffer-name)
7634 (url-view-url t))
7635 link (org-make-link (url-view-url t)))
7636 (org-store-link-props :type "w3" :url (url-view-url t)))
7638 ((eq major-mode 'w3m-mode)
7639 (setq cpltxt (or w3m-current-title w3m-current-url)
7640 link (org-make-link w3m-current-url))
7641 (org-store-link-props :type "w3m" :url (url-view-url t)))
7643 ((setq search (run-hook-with-args-until-success
7644 'org-create-file-search-functions))
7645 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7646 "::" search))
7647 (setq cpltxt (or description link)))
7649 ((eq major-mode 'image-mode)
7650 (setq cpltxt (concat "file:"
7651 (abbreviate-file-name buffer-file-name))
7652 link (org-make-link cpltxt))
7653 (org-store-link-props :type "image" :file buffer-file-name))
7655 ((eq major-mode 'dired-mode)
7656 ;; link to the file in the current line
7657 (setq cpltxt (concat "file:"
7658 (abbreviate-file-name
7659 (expand-file-name
7660 (dired-get-filename nil t))))
7661 link (org-make-link cpltxt)))
7663 ((and buffer-file-name (org-mode-p))
7664 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7665 (cond
7666 ((org-in-regexp "<<\\(.*?\\)>>")
7667 (setq cpltxt
7668 (concat "file:"
7669 (abbreviate-file-name buffer-file-name)
7670 "::" (match-string 1))
7671 link (org-make-link cpltxt)))
7672 ((and (featurep 'org-id)
7673 (or (eq org-link-to-org-use-id t)
7674 (and (eq org-link-to-org-use-id 'create-if-interactive)
7675 (interactive-p))
7676 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7677 (interactive-p)
7678 (not custom-id))
7679 (and org-link-to-org-use-id
7680 (condition-case nil
7681 (org-entry-get nil "ID")
7682 (error nil)))))
7683 ;; We can make a link using the ID.
7684 (setq link (condition-case nil
7685 (prog1 (org-id-store-link)
7686 (setq desc (plist-get org-store-link-plist
7687 :description)))
7688 (error
7689 ;; probably before first headline, link to file only
7690 (concat "file:"
7691 (abbreviate-file-name buffer-file-name))))))
7693 ;; Just link to current headline
7694 (setq cpltxt (concat "file:"
7695 (abbreviate-file-name buffer-file-name)))
7696 ;; Add a context search string
7697 (when (org-xor org-context-in-file-links arg)
7698 (setq txt (cond
7699 ((org-on-heading-p) nil)
7700 ((org-region-active-p)
7701 (buffer-substring (region-beginning) (region-end)))
7702 (t nil)))
7703 (when (or (null txt) (string-match "\\S-" txt))
7704 (setq cpltxt
7705 (concat cpltxt "::"
7706 (condition-case nil
7707 (org-make-org-heading-search-string txt)
7708 (error "")))
7709 desc (or (nth 4 (ignore-errors
7710 (org-heading-components))) "NONE"))))
7711 (if (string-match "::\\'" cpltxt)
7712 (setq cpltxt (substring cpltxt 0 -2)))
7713 (setq link (org-make-link cpltxt)))))
7715 ((buffer-file-name (buffer-base-buffer))
7716 ;; Just link to this file here.
7717 (setq cpltxt (concat "file:"
7718 (abbreviate-file-name
7719 (buffer-file-name (buffer-base-buffer)))))
7720 ;; Add a context string
7721 (when (org-xor org-context-in-file-links arg)
7722 (setq txt (if (org-region-active-p)
7723 (buffer-substring (region-beginning) (region-end))
7724 (buffer-substring (point-at-bol) (point-at-eol))))
7725 ;; Only use search option if there is some text.
7726 (when (string-match "\\S-" txt)
7727 (setq cpltxt
7728 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7729 desc "NONE")))
7730 (setq link (org-make-link cpltxt)))
7732 ((interactive-p)
7733 (error "Cannot link to a buffer which is not visiting a file"))
7735 (t (setq link nil)))
7737 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7738 (setq link (or link cpltxt)
7739 desc (or desc cpltxt))
7740 (if (equal desc "NONE") (setq desc nil))
7742 (if (and (or (interactive-p) executing-kbd-macro) link)
7743 (progn
7744 (setq org-stored-links
7745 (cons (list link desc) org-stored-links))
7746 (message "Stored: %s" (or desc link))
7747 (when custom-id
7748 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7749 "::#" custom-id))
7750 (setq org-stored-links
7751 (cons (list link desc) org-stored-links))))
7752 (and link (org-make-link-string link desc)))))
7754 (defun org-store-link-props (&rest plist)
7755 "Store link properties, extract names and addresses."
7756 (let (x adr)
7757 (when (setq x (plist-get plist :from))
7758 (setq adr (mail-extract-address-components x))
7759 (setq plist (plist-put plist :fromname (car adr)))
7760 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7761 (when (setq x (plist-get plist :to))
7762 (setq adr (mail-extract-address-components x))
7763 (setq plist (plist-put plist :toname (car adr)))
7764 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7765 (let ((from (plist-get plist :from))
7766 (to (plist-get plist :to)))
7767 (when (and from to org-from-is-user-regexp)
7768 (setq plist
7769 (plist-put plist :fromto
7770 (if (string-match org-from-is-user-regexp from)
7771 (concat "to %t")
7772 (concat "from %f"))))))
7773 (setq org-store-link-plist plist))
7775 (defun org-add-link-props (&rest plist)
7776 "Add these properties to the link property list."
7777 (let (key value)
7778 (while plist
7779 (setq key (pop plist) value (pop plist))
7780 (setq org-store-link-plist
7781 (plist-put org-store-link-plist key value)))))
7783 (defun org-email-link-description (&optional fmt)
7784 "Return the description part of an email link.
7785 This takes information from `org-store-link-plist' and formats it
7786 according to FMT (default from `org-email-link-description-format')."
7787 (setq fmt (or fmt org-email-link-description-format))
7788 (let* ((p org-store-link-plist)
7789 (to (plist-get p :toaddress))
7790 (from (plist-get p :fromaddress))
7791 (table
7792 (list
7793 (cons "%c" (plist-get p :fromto))
7794 (cons "%F" (plist-get p :from))
7795 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7796 (cons "%T" (plist-get p :to))
7797 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7798 (cons "%s" (plist-get p :subject))
7799 (cons "%m" (plist-get p :message-id)))))
7800 (when (string-match "%c" fmt)
7801 ;; Check if the user wrote this message
7802 (if (and org-from-is-user-regexp from to
7803 (save-match-data (string-match org-from-is-user-regexp from)))
7804 (setq fmt (replace-match "to %t" t t fmt))
7805 (setq fmt (replace-match "from %f" t t fmt))))
7806 (org-replace-escapes fmt table)))
7808 (defun org-make-org-heading-search-string (&optional string heading)
7809 "Make search string for STRING or current headline."
7810 (interactive)
7811 (let ((s (or string (org-get-heading))))
7812 (unless (and string (not heading))
7813 ;; We are using a headline, clean up garbage in there.
7814 (if (string-match org-todo-regexp s)
7815 (setq s (replace-match "" t t s)))
7816 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7817 (setq s (replace-match "" t t s)))
7818 (setq s (org-trim s))
7819 (if (string-match (concat "^\\(" org-quote-string "\\|"
7820 org-comment-string "\\)") s)
7821 (setq s (replace-match "" t t s)))
7822 (while (string-match org-ts-regexp s)
7823 (setq s (replace-match "" t t s))))
7824 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7825 (setq s (replace-match " " t t s)))
7826 (or string (setq s (concat "*" s))) ; Add * for headlines
7827 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7829 (defun org-make-link (&rest strings)
7830 "Concatenate STRINGS."
7831 (apply 'concat strings))
7833 (defun org-make-link-string (link &optional description)
7834 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7835 (unless (string-match "\\S-" link)
7836 (error "Empty link"))
7837 (when (and description
7838 (stringp description)
7839 (not (string-match "\\S-" description)))
7840 (setq description nil))
7841 (when (stringp description)
7842 ;; Remove brackets from the description, they are fatal.
7843 (while (string-match "\\[" description)
7844 (setq description (replace-match "{" t t description)))
7845 (while (string-match "\\]" description)
7846 (setq description (replace-match "}" t t description))))
7847 (when (equal (org-link-escape link) description)
7848 ;; No description needed, it is identical
7849 (setq description nil))
7850 (when (and (not description)
7851 (not (equal link (org-link-escape link))))
7852 (setq description (org-extract-attributes link)))
7853 (concat "[[" (org-link-escape link) "]"
7854 (if description (concat "[" description "]") "")
7855 "]"))
7857 (defconst org-link-escape-chars
7858 '((?\ . "%20")
7859 (?\[ . "%5B")
7860 (?\] . "%5D")
7861 (?\340 . "%E0") ; `a
7862 (?\342 . "%E2") ; ^a
7863 (?\347 . "%E7") ; ,c
7864 (?\350 . "%E8") ; `e
7865 (?\351 . "%E9") ; 'e
7866 (?\352 . "%EA") ; ^e
7867 (?\356 . "%EE") ; ^i
7868 (?\364 . "%F4") ; ^o
7869 (?\371 . "%F9") ; `u
7870 (?\373 . "%FB") ; ^u
7871 (?\; . "%3B")
7872 (?? . "%3F")
7873 (?= . "%3D")
7874 (?+ . "%2B")
7876 "Association list of escapes for some characters problematic in links.
7877 This is the list that is used for internal purposes.")
7879 (defvar org-url-encoding-use-url-hexify nil)
7881 (defconst org-link-escape-chars-browser
7882 '((?\ . "%20")) ; 32 for the SPC char
7883 "Association list of escapes for some characters problematic in links.
7884 This is the list that is used before handing over to the browser.")
7886 (defun org-link-escape (text &optional table)
7887 "Escape characters in TEXT that are problematic for links."
7888 (if org-url-encoding-use-url-hexify
7889 (url-hexify-string text)
7890 (setq table (or table org-link-escape-chars))
7891 (when text
7892 (let ((re (mapconcat (lambda (x) (regexp-quote
7893 (char-to-string (car x))))
7894 table "\\|")))
7895 (while (string-match re text)
7896 (setq text
7897 (replace-match
7898 (cdr (assoc (string-to-char (match-string 0 text))
7899 table))
7900 t t text)))
7901 text))))
7903 (defun org-link-unescape (text &optional table)
7904 "Reverse the action of `org-link-escape'."
7905 (if org-url-encoding-use-url-hexify
7906 (url-unhex-string text)
7907 (setq table (or table org-link-escape-chars))
7908 (when text
7909 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7910 table "\\|")))
7911 (while (string-match re text)
7912 (setq text
7913 (replace-match
7914 (char-to-string (car (rassoc (match-string 0 text) table)))
7915 t t text)))
7916 text))))
7918 (defun org-xor (a b)
7919 "Exclusive or."
7920 (if a (not b) b))
7922 (defun org-fixup-message-id-for-http (s)
7923 "Replace special characters in a message id, so it can be used in an http query."
7924 (while (string-match "<" s)
7925 (setq s (replace-match "%3C" t t s)))
7926 (while (string-match ">" s)
7927 (setq s (replace-match "%3E" t t s)))
7928 (while (string-match "@" s)
7929 (setq s (replace-match "%40" t t s)))
7932 ;;;###autoload
7933 (defun org-insert-link-global ()
7934 "Insert a link like Org-mode does.
7935 This command can be called in any mode to insert a link in Org-mode syntax."
7936 (interactive)
7937 (org-load-modules-maybe)
7938 (org-run-like-in-org-mode 'org-insert-link))
7940 (defun org-insert-link (&optional complete-file link-location)
7941 "Insert a link. At the prompt, enter the link.
7943 Completion can be used to insert any of the link protocol prefixes like
7944 http or ftp in use.
7946 The history can be used to select a link previously stored with
7947 `org-store-link'. When the empty string is entered (i.e. if you just
7948 press RET at the prompt), the link defaults to the most recently
7949 stored link. As SPC triggers completion in the minibuffer, you need to
7950 use M-SPC or C-q SPC to force the insertion of a space character.
7952 You will also be prompted for a description, and if one is given, it will
7953 be displayed in the buffer instead of the link.
7955 If there is already a link at point, this command will allow you to edit link
7956 and description parts.
7958 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7959 be selected using completion. The path to the file will be relative to the
7960 current directory if the file is in the current directory or a subdirectory.
7961 Otherwise, the link will be the absolute path as completed in the minibuffer
7962 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7963 option `org-link-file-path-type'.
7965 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7966 the current directory or below.
7968 With three \\[universal-argument] prefixes, negate the meaning of
7969 `org-keep-stored-link-after-insertion'.
7971 If `org-make-link-description-function' is non-nil, this function will be
7972 called with the link target, and the result will be the default
7973 link description.
7975 If the LINK-LOCATION parameter is non-nil, this value will be
7976 used as the link location instead of reading one interactively."
7977 (interactive "P")
7978 (let* ((wcf (current-window-configuration))
7979 (region (if (org-region-active-p)
7980 (buffer-substring (region-beginning) (region-end))))
7981 (remove (and region (list (region-beginning) (region-end))))
7982 (desc region)
7983 tmphist ; byte-compile incorrectly complains about this
7984 (link link-location)
7985 entry file all-prefixes)
7986 (cond
7987 (link-location) ; specified by arg, just use it.
7988 ((org-in-regexp org-bracket-link-regexp 1)
7989 ;; We do have a link at point, and we are going to edit it.
7990 (setq remove (list (match-beginning 0) (match-end 0)))
7991 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7992 (setq link (read-string "Link: "
7993 (org-link-unescape
7994 (org-match-string-no-properties 1)))))
7995 ((or (org-in-regexp org-angle-link-re)
7996 (org-in-regexp org-plain-link-re))
7997 ;; Convert to bracket link
7998 (setq remove (list (match-beginning 0) (match-end 0))
7999 link (read-string "Link: "
8000 (org-remove-angle-brackets (match-string 0)))))
8001 ((member complete-file '((4) (16)))
8002 ;; Completing read for file names.
8003 (setq link (org-file-complete-link complete-file)))
8005 ;; Read link, with completion for stored links.
8006 (with-output-to-temp-buffer "*Org Links*"
8007 (princ "Insert a link.
8008 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8009 (when org-stored-links
8010 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8011 (princ (mapconcat
8012 (lambda (x)
8013 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8014 (reverse org-stored-links) "\n"))))
8015 (let ((cw (selected-window)))
8016 (select-window (get-buffer-window "*Org Links*"))
8017 (setq truncate-lines t)
8018 (unless (pos-visible-in-window-p (point-max))
8019 (org-fit-window-to-buffer))
8020 (and (window-live-p cw) (select-window cw)))
8021 ;; Fake a link history, containing the stored links.
8022 (setq tmphist (append (mapcar 'car org-stored-links)
8023 org-insert-link-history))
8024 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8025 (mapcar 'car org-link-abbrev-alist)
8026 org-link-types))
8027 (unwind-protect
8028 (progn
8029 (setq link
8030 (let ((org-completion-use-ido nil)
8031 (org-completion-use-iswitchb nil))
8032 (org-completing-read
8033 "Link: "
8034 (append
8035 (mapcar (lambda (x) (list (concat x ":")))
8036 all-prefixes)
8037 (mapcar 'car org-stored-links))
8038 nil nil nil
8039 'tmphist
8040 (car (car org-stored-links)))))
8041 (if (not (string-match "\\S-" link))
8042 (error "No link selected"))
8043 (if (or (member link all-prefixes)
8044 (and (equal ":" (substring link -1))
8045 (member (substring link 0 -1) all-prefixes)
8046 (setq link (substring link 0 -1))))
8047 (setq link (org-link-try-special-completion link))))
8048 (set-window-configuration wcf)
8049 (kill-buffer "*Org Links*"))
8050 (setq entry (assoc link org-stored-links))
8051 (or entry (push link org-insert-link-history))
8052 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8053 (not org-keep-stored-link-after-insertion))
8054 (setq org-stored-links (delq (assoc link org-stored-links)
8055 org-stored-links)))
8056 (setq desc (or desc (nth 1 entry)))))
8058 (if (string-match org-plain-link-re link)
8059 ;; URL-like link, normalize the use of angular brackets.
8060 (setq link (org-make-link (org-remove-angle-brackets link))))
8062 ;; Check if we are linking to the current file with a search option
8063 ;; If yes, simplify the link by using only the search option.
8064 (when (and buffer-file-name
8065 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8066 (let* ((path (match-string 1 link))
8067 (case-fold-search nil)
8068 (search (match-string 2 link)))
8069 (save-match-data
8070 (if (equal (file-truename buffer-file-name) (file-truename path))
8071 ;; We are linking to this same file, with a search option
8072 (setq link search)))))
8074 ;; Check if we can/should use a relative path. If yes, simplify the link
8075 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8076 (let* ((type (match-string 1 link))
8077 (path (match-string 2 link))
8078 (origpath path)
8079 (case-fold-search nil))
8080 (cond
8081 ((or (eq org-link-file-path-type 'absolute)
8082 (equal complete-file '(16)))
8083 (setq path (abbreviate-file-name (expand-file-name path))))
8084 ((eq org-link-file-path-type 'noabbrev)
8085 (setq path (expand-file-name path)))
8086 ((eq org-link-file-path-type 'relative)
8087 (setq path (file-relative-name path)))
8089 (save-match-data
8090 (if (string-match (concat "^" (regexp-quote
8091 (file-name-as-directory
8092 (expand-file-name "."))))
8093 (expand-file-name path))
8094 ;; We are linking a file with relative path name.
8095 (setq path (substring (expand-file-name path)
8096 (match-end 0)))
8097 (setq path (abbreviate-file-name (expand-file-name path)))))))
8098 (setq link (concat type path))
8099 (if (equal desc origpath)
8100 (setq desc path))))
8102 (if org-make-link-description-function
8103 (setq desc (funcall org-make-link-description-function link desc)))
8105 (setq desc (read-string "Description: " desc))
8106 (unless (string-match "\\S-" desc) (setq desc nil))
8107 (if remove (apply 'delete-region remove))
8108 (insert (org-make-link-string link desc))))
8110 (defun org-link-try-special-completion (type)
8111 "If there is completion support for link type TYPE, offer it."
8112 (let ((fun (intern (concat "org-" type "-complete-link"))))
8113 (if (functionp fun)
8114 (funcall fun)
8115 (read-string "Link (no completion support): " (concat type ":")))))
8117 (defun org-file-complete-link (&optional arg)
8118 "Create a file link using completion."
8119 (let (file link)
8120 (setq file (read-file-name "File: "))
8121 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8122 (pwd1 (file-name-as-directory (abbreviate-file-name
8123 (expand-file-name ".")))))
8124 (cond
8125 ((equal arg '(16))
8126 (setq link (org-make-link
8127 "file:"
8128 (abbreviate-file-name (expand-file-name file)))))
8129 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8130 (setq link (org-make-link "file:" (match-string 1 file))))
8131 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8132 (expand-file-name file))
8133 (setq link (org-make-link
8134 "file:" (match-string 1 (expand-file-name file)))))
8135 (t (setq link (org-make-link "file:" file)))))
8136 link))
8138 (defun org-completing-read (&rest args)
8139 "Completing-read with SPACE being a normal character."
8140 (let ((minibuffer-local-completion-map
8141 (copy-keymap minibuffer-local-completion-map)))
8142 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8143 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8144 (apply 'org-icompleting-read args)))
8146 (defun org-completing-read-no-i (&rest args)
8147 (let (org-completion-use-ido org-completion-use-iswitchb)
8148 (apply 'org-completing-read args)))
8150 (defun org-iswitchb-completing-read (prompt choices &rest args)
8151 "Use iswitch as a completing-read replacement to choose from choices.
8152 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8153 from."
8154 (let* ((iswitchb-use-virtual-buffers nil)
8155 (iswitchb-make-buflist-hook
8156 (lambda ()
8157 (setq iswitchb-temp-buflist choices))))
8158 (iswitchb-read-buffer prompt)))
8160 (defun org-icompleting-read (&rest args)
8161 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8162 (org-without-partial-completion
8163 (if (and org-completion-use-ido
8164 (fboundp 'ido-completing-read)
8165 (boundp 'ido-mode) ido-mode
8166 (listp (second args)))
8167 (let ((ido-enter-matching-directory nil))
8168 (apply 'ido-completing-read (concat (car args))
8169 (if (consp (car (nth 1 args)))
8170 (mapcar (lambda (x) (car x)) (nth 1 args))
8171 (nth 1 args))
8172 (cddr args)))
8173 (if (and org-completion-use-iswitchb
8174 (boundp 'iswitchb-mode) iswitchb-mode
8175 (listp (second args)))
8176 (apply 'org-iswitchb-completing-read (concat (car args))
8177 (if (consp (car (nth 1 args)))
8178 (mapcar (lambda (x) (car x)) (nth 1 args))
8179 (nth 1 args))
8180 (cddr args))
8181 (apply 'completing-read args)))))
8183 (defun org-extract-attributes (s)
8184 "Extract the attributes cookie from a string and set as text property."
8185 (let (a attr (start 0) key value)
8186 (save-match-data
8187 (when (string-match "{{\\([^}]+\\)}}$" s)
8188 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8189 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8190 (setq key (match-string 1 a) value (match-string 2 a)
8191 start (match-end 0)
8192 attr (plist-put attr (intern key) value))))
8193 (org-add-props s nil 'org-attr attr))
8196 (defun org-extract-attributes-from-string (tag)
8197 (let (key value attr)
8198 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8199 (setq key (match-string 1 tag) value (match-string 2 tag)
8200 tag (replace-match "" t t tag)
8201 attr (plist-put attr (intern key) value)))
8202 (cons tag attr)))
8204 (defun org-attributes-to-string (plist)
8205 "Format a property list into an HTML attribute list."
8206 (let ((s "") key value)
8207 (while plist
8208 (setq key (pop plist) value (pop plist))
8209 (and value
8210 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8213 ;;; Opening/following a link
8215 (defvar org-link-search-failed nil)
8217 (defvar org-open-link-functions nil
8218 "Hook for functions finding a plain text link.
8219 These functions must take a single argument, the link content.
8220 They will be called for links that look like [[link text][description]]
8221 when LINK TEXT does not have a protocol like \"http:\" and does not look
8222 like a filename (e.g. \"./blue.png\").
8224 These functions will be called *before* Org attempts to resolve the
8225 link by doing text searches in the current buffer - so if you want a
8226 link \"[[target]]\" to still find \"<<target>>\", your function should
8227 handle this as a special case.
8229 When the function does handle the link, it must return a non-nil value.
8230 If it decides that it is not responsible for this link, it must return
8231 nil to indicate that that Org-mode can continue with other options
8232 like exact and fuzzy text search.")
8234 (defun org-next-link ()
8235 "Move forward to the next link.
8236 If the link is in hidden text, expose it."
8237 (interactive)
8238 (when (and org-link-search-failed (eq this-command last-command))
8239 (goto-char (point-min))
8240 (message "Link search wrapped back to beginning of buffer"))
8241 (setq org-link-search-failed nil)
8242 (let* ((pos (point))
8243 (ct (org-context))
8244 (a (assoc :link ct)))
8245 (if a (goto-char (nth 2 a)))
8246 (if (re-search-forward org-any-link-re nil t)
8247 (progn
8248 (goto-char (match-beginning 0))
8249 (if (org-invisible-p) (org-show-context)))
8250 (goto-char pos)
8251 (setq org-link-search-failed t)
8252 (error "No further link found"))))
8254 (defun org-previous-link ()
8255 "Move backward to the previous link.
8256 If the link is in hidden text, expose it."
8257 (interactive)
8258 (when (and org-link-search-failed (eq this-command last-command))
8259 (goto-char (point-max))
8260 (message "Link search wrapped back to end of buffer"))
8261 (setq org-link-search-failed nil)
8262 (let* ((pos (point))
8263 (ct (org-context))
8264 (a (assoc :link ct)))
8265 (if a (goto-char (nth 1 a)))
8266 (if (re-search-backward org-any-link-re nil t)
8267 (progn
8268 (goto-char (match-beginning 0))
8269 (if (org-invisible-p) (org-show-context)))
8270 (goto-char pos)
8271 (setq org-link-search-failed t)
8272 (error "No further link found"))))
8274 (defun org-translate-link (s)
8275 "Translate a link string if a translation function has been defined."
8276 (if (and org-link-translation-function
8277 (fboundp org-link-translation-function)
8278 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8279 (progn
8280 (setq s (funcall org-link-translation-function
8281 (match-string 1) (match-string 2)))
8282 (concat (car s) ":" (cdr s)))
8285 (defun org-translate-link-from-planner (type path)
8286 "Translate a link from Emacs Planner syntax so that Org can follow it.
8287 This is still an experimental function, your mileage may vary."
8288 (cond
8289 ((member type '("http" "https" "news" "ftp"))
8290 ;; standard Internet links are the same.
8291 nil)
8292 ((and (equal type "irc") (string-match "^//" path))
8293 ;; Planner has two / at the beginning of an irc link, we have 1.
8294 ;; We should have zero, actually....
8295 (setq path (substring path 1)))
8296 ((and (equal type "lisp") (string-match "^/" path))
8297 ;; Planner has a slash, we do not.
8298 (setq type "elisp" path (substring path 1)))
8299 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8300 ;; A typical message link. Planner has the id after the final slash,
8301 ;; we separate it with a hash mark
8302 (setq path (concat (match-string 1 path) "#"
8303 (org-remove-angle-brackets (match-string 2 path)))))
8305 (cons type path))
8307 (defun org-find-file-at-mouse (ev)
8308 "Open file link or URL at mouse."
8309 (interactive "e")
8310 (mouse-set-point ev)
8311 (org-open-at-point 'in-emacs))
8313 (defun org-open-at-mouse (ev)
8314 "Open file link or URL at mouse."
8315 (interactive "e")
8316 (mouse-set-point ev)
8317 (if (eq major-mode 'org-agenda-mode)
8318 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8319 (org-open-at-point))
8321 (defvar org-window-config-before-follow-link nil
8322 "The window configuration before following a link.
8323 This is saved in case the need arises to restore it.")
8325 (defvar org-open-link-marker (make-marker)
8326 "Marker pointing to the location where `org-open-at-point; was called.")
8328 ;;;###autoload
8329 (defun org-open-at-point-global ()
8330 "Follow a link like Org-mode does.
8331 This command can be called in any mode to follow a link that has
8332 Org-mode syntax."
8333 (interactive)
8334 (org-run-like-in-org-mode 'org-open-at-point))
8336 ;;;###autoload
8337 (defun org-open-link-from-string (s &optional arg reference-buffer)
8338 "Open a link in the string S, as if it was in Org-mode."
8339 (interactive "sLink: \nP")
8340 (let ((reference-buffer (or reference-buffer (current-buffer))))
8341 (with-temp-buffer
8342 (let ((org-inhibit-startup t))
8343 (org-mode)
8344 (insert s)
8345 (goto-char (point-min))
8346 (org-open-at-point arg reference-buffer)))))
8348 (defun org-open-at-point (&optional in-emacs reference-buffer)
8349 "Open link at or after point.
8350 If there is no link at point, this function will search forward up to
8351 the end of the current line.
8352 Normally, files will be opened by an appropriate application. If the
8353 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8354 With a double prefix argument, try to open outside of Emacs, in the
8355 application the system uses for this file type."
8356 (interactive "P")
8357 (org-load-modules-maybe)
8358 (move-marker org-open-link-marker (point))
8359 (setq org-window-config-before-follow-link (current-window-configuration))
8360 (org-remove-occur-highlights nil nil t)
8361 (cond
8362 ((and (org-on-heading-p)
8363 (not (org-in-regexp
8364 (concat org-plain-link-re "\\|"
8365 org-bracket-link-regexp "\\|"
8366 org-angle-link-re "\\|"
8367 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8368 (or (org-offer-links-in-entry in-emacs)
8369 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8370 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8371 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8372 (org-footnote-action))
8374 (let (type path link line search (pos (point)))
8375 (catch 'match
8376 (save-excursion
8377 (skip-chars-forward "^]\n\r")
8378 (when (org-in-regexp org-bracket-link-regexp 1)
8379 (setq link (org-extract-attributes
8380 (org-link-unescape (org-match-string-no-properties 1))))
8381 (while (string-match " *\n *" link)
8382 (setq link (replace-match " " t t link)))
8383 (setq link (org-link-expand-abbrev link))
8384 (cond
8385 ((or (file-name-absolute-p link)
8386 (string-match "^\\.\\.?/" link))
8387 (setq type "file" path link))
8388 ((string-match org-link-re-with-space3 link)
8389 (setq type (match-string 1 link) path (match-string 2 link)))
8390 (t (setq type "thisfile" path link)))
8391 (throw 'match t)))
8393 (when (get-text-property (point) 'org-linked-text)
8394 (setq type "thisfile"
8395 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8396 (1+ (point)) (point))
8397 path (buffer-substring
8398 (previous-single-property-change pos 'org-linked-text)
8399 (next-single-property-change pos 'org-linked-text)))
8400 (throw 'match t))
8402 (save-excursion
8403 (when (or (org-in-regexp org-angle-link-re)
8404 (org-in-regexp org-plain-link-re))
8405 (setq type (match-string 1) path (match-string 2))
8406 (throw 'match t)))
8407 (save-excursion
8408 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8409 (setq type "tags"
8410 path (match-string 1))
8411 (while (string-match ":" path)
8412 (setq path (replace-match "+" t t path)))
8413 (throw 'match t)))
8414 (when (org-in-regexp "<\\([^><\n]+\\)>")
8415 (setq type "tree-match"
8416 path (match-string 1))
8417 (throw 'match t)))
8418 (unless path
8419 (error "No link found"))
8421 ;; switch back to reference buffer
8422 ;; needed when if called in a temporary buffer through
8423 ;; org-open-link-from-string
8424 (with-current-buffer (or reference-buffer (current-buffer))
8426 ;; Remove any trailing spaces in path
8427 (if (string-match " +\\'" path)
8428 (setq path (replace-match "" t t path)))
8429 (if (and org-link-translation-function
8430 (fboundp org-link-translation-function))
8431 ;; Check if we need to translate the link
8432 (let ((tmp (funcall org-link-translation-function type path)))
8433 (setq type (car tmp) path (cdr tmp))))
8435 (cond
8437 ((assoc type org-link-protocols)
8438 (funcall (nth 1 (assoc type org-link-protocols)) path))
8440 ((equal type "mailto")
8441 (let ((cmd (car org-link-mailto-program))
8442 (args (cdr org-link-mailto-program)) args1
8443 (address path) (subject "") a)
8444 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8445 (setq address (match-string 1 path)
8446 subject (org-link-escape (match-string 2 path))))
8447 (while args
8448 (cond
8449 ((not (stringp (car args))) (push (pop args) args1))
8450 (t (setq a (pop args))
8451 (if (string-match "%a" a)
8452 (setq a (replace-match address t t a)))
8453 (if (string-match "%s" a)
8454 (setq a (replace-match subject t t a)))
8455 (push a args1))))
8456 (apply cmd (nreverse args1))))
8458 ((member type '("http" "https" "ftp" "news"))
8459 (browse-url (concat type ":" (org-link-escape
8460 path org-link-escape-chars-browser))))
8462 ((member type '("message"))
8463 (browse-url (concat type ":" path)))
8465 ((string= type "tags")
8466 (org-tags-view in-emacs path))
8468 ((string= type "tree-match")
8469 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8471 ((string= type "file")
8472 (if (string-match "::\\([0-9]+\\)\\'" path)
8473 (setq line (string-to-number (match-string 1 path))
8474 path (substring path 0 (match-beginning 0)))
8475 (if (string-match "::\\(.+\\)\\'" path)
8476 (setq search (match-string 1 path)
8477 path (substring path 0 (match-beginning 0)))))
8478 (if (string-match "[*?{]" (file-name-nondirectory path))
8479 (dired path)
8480 (org-open-file path in-emacs line search)))
8482 ((string= type "news")
8483 (require 'org-gnus)
8484 (org-gnus-follow-link path))
8486 ((string= type "shell")
8487 (let ((cmd path))
8488 (if (or (not org-confirm-shell-link-function)
8489 (funcall org-confirm-shell-link-function
8490 (format "Execute \"%s\" in shell? "
8491 (org-add-props cmd nil
8492 'face 'org-warning))))
8493 (progn
8494 (message "Executing %s" cmd)
8495 (shell-command cmd))
8496 (error "Abort"))))
8498 ((string= type "elisp")
8499 (let ((cmd path))
8500 (if (or (not org-confirm-elisp-link-function)
8501 (funcall org-confirm-elisp-link-function
8502 (format "Execute \"%s\" as elisp? "
8503 (org-add-props cmd nil
8504 'face 'org-warning))))
8505 (message "%s => %s" cmd
8506 (if (equal (string-to-char cmd) ?\()
8507 (eval (read cmd))
8508 (call-interactively (read cmd))))
8509 (error "Abort"))))
8511 ((and (string= type "thisfile")
8512 (run-hook-with-args-until-success
8513 'org-open-link-functions path)))
8515 ((string= type "thisfile")
8516 (if in-emacs
8517 (switch-to-buffer-other-window
8518 (org-get-buffer-for-internal-link (current-buffer)))
8519 (org-mark-ring-push))
8520 (let ((cmd `(org-link-search
8521 ,path
8522 ,(cond ((equal in-emacs '(4)) 'occur)
8523 ((equal in-emacs '(16)) 'org-occur)
8524 (t nil))
8525 ,pos)))
8526 (condition-case nil (eval cmd)
8527 (error (progn (widen) (eval cmd))))))
8530 (browse-url-at-point)))))))
8531 (move-marker org-open-link-marker nil)
8532 (run-hook-with-args 'org-follow-link-hook))
8534 (defun org-offer-links-in-entry (&optional nth zero)
8535 "Offer links in the current entry and follow the selected link.
8536 If there is only one link, follow it immediately as well.
8537 If NTH is an integer, immediately pick the NTH link found.
8538 If ZERO is a string, check also this string for a link, and if
8539 there is one, offer it as link number zero."
8540 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8541 "\\(" org-angle-link-re "\\)\\|"
8542 "\\(" org-plain-link-re "\\)"))
8543 (cnt ?0)
8544 (in-emacs (if (integerp nth) nil nth))
8545 have-zero end links link c)
8546 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8547 (push (match-string 0 zero) links)
8548 (setq cnt (1- cnt) have-zero t))
8549 (save-excursion
8550 (org-back-to-heading t)
8551 (setq end (save-excursion (outline-next-heading) (point)))
8552 (while (re-search-forward re end t)
8553 (push (match-string 0) links))
8554 (setq links (org-uniquify (reverse links))))
8556 (cond
8557 ((null links)
8558 (message "No links"))
8559 ((equal (length links) 1)
8560 (setq link (car links)))
8561 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8562 (setq link (nth (if have-zero nth (1- nth)) links)))
8563 (t ; we have to select a link
8564 (save-excursion
8565 (save-window-excursion
8566 (delete-other-windows)
8567 (with-output-to-temp-buffer "*Select Link*"
8568 (mapc (lambda (l)
8569 (if (not (string-match org-bracket-link-regexp l))
8570 (princ (format "[%c] %s\n" (incf cnt)
8571 (org-remove-angle-brackets l)))
8572 (if (match-end 3)
8573 (princ (format "[%c] %s (%s)\n" (incf cnt)
8574 (match-string 3 l) (match-string 1 l)))
8575 (princ (format "[%c] %s\n" (incf cnt)
8576 (match-string 1 l))))))
8577 links))
8578 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8579 (message "Select link to open:")
8580 (setq c (read-char-exclusive))
8581 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8582 (when (equal c ?q) (error "Abort"))
8583 (setq nth (- c ?0))
8584 (if have-zero (setq nth (1+ nth)))
8585 (unless (and (integerp nth) (>= (length links) nth))
8586 (error "Invalid link selection"))
8587 (setq link (nth (1- nth) links))))
8588 (if link
8589 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8590 nil)))
8592 ;;;; Time estimates
8594 (defun org-get-effort (&optional pom)
8595 "Get the effort estimate for the current entry."
8596 (org-entry-get pom org-effort-property))
8598 ;;; File search
8600 (defvar org-create-file-search-functions nil
8601 "List of functions to construct the right search string for a file link.
8602 These functions are called in turn with point at the location to
8603 which the link should point.
8605 A function in the hook should first test if it would like to
8606 handle this file type, for example by checking the major-mode or
8607 the file extension. If it decides not to handle this file, it
8608 should just return nil to give other functions a chance. If it
8609 does handle the file, it must return the search string to be used
8610 when following the link. The search string will be part of the
8611 file link, given after a double colon, and `org-open-at-point'
8612 will automatically search for it. If special measures must be
8613 taken to make the search successful, another function should be
8614 added to the companion hook `org-execute-file-search-functions',
8615 which see.
8617 A function in this hook may also use `setq' to set the variable
8618 `description' to provide a suggestion for the descriptive text to
8619 be used for this link when it gets inserted into an Org-mode
8620 buffer with \\[org-insert-link].")
8622 (defvar org-execute-file-search-functions nil
8623 "List of functions to execute a file search triggered by a link.
8625 Functions added to this hook must accept a single argument, the
8626 search string that was part of the file link, the part after the
8627 double colon. The function must first check if it would like to
8628 handle this search, for example by checking the major-mode or the
8629 file extension. If it decides not to handle this search, it
8630 should just return nil to give other functions a chance. If it
8631 does handle the search, it must return a non-nil value to keep
8632 other functions from trying.
8634 Each function can access the current prefix argument through the
8635 variable `current-prefix-argument'. Note that a single prefix is
8636 used to force opening a link in Emacs, so it may be good to only
8637 use a numeric or double prefix to guide the search function.
8639 In case this is needed, a function in this hook can also restore
8640 the window configuration before `org-open-at-point' was called using:
8642 (set-window-configuration org-window-config-before-follow-link)")
8644 (defun org-link-search (s &optional type avoid-pos)
8645 "Search for a link search option.
8646 If S is surrounded by forward slashes, it is interpreted as a
8647 regular expression. In org-mode files, this will create an `org-occur'
8648 sparse tree. In ordinary files, `occur' will be used to list matches.
8649 If the current buffer is in `dired-mode', grep will be used to search
8650 in all files. If AVOID-POS is given, ignore matches near that position."
8651 (let ((case-fold-search t)
8652 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8653 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8654 (append '(("") (" ") ("\t") ("\n"))
8655 org-emphasis-alist)
8656 "\\|") "\\)"))
8657 (pos (point))
8658 (pre nil) (post nil)
8659 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8660 (cond
8661 ;; First check if there are any special
8662 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8663 ;; Now try the builtin stuff
8664 ((and (equal (string-to-char s0) ?#)
8665 (> (length s0) 1)
8666 (save-excursion
8667 (goto-char (point-min))
8668 (and
8669 (re-search-forward
8670 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8671 (setq type 'dedicated
8672 pos (match-beginning 0))))
8673 ;; There is an exact target for this
8674 (goto-char pos)
8675 (org-back-to-heading t)))
8676 ((save-excursion
8677 (goto-char (point-min))
8678 (and
8679 (re-search-forward
8680 (concat "<<" (regexp-quote s0) ">>") nil t)
8681 (setq type 'dedicated
8682 pos (match-beginning 0))))
8683 ;; There is an exact target for this
8684 (goto-char pos))
8685 ((and (string-match "^(\\(.*\\))$" s0)
8686 (save-excursion
8687 (goto-char (point-min))
8688 (and
8689 (re-search-forward
8690 (concat "[^[]" (regexp-quote
8691 (format org-coderef-label-format
8692 (match-string 1 s0))))
8693 nil t)
8694 (setq type 'dedicated
8695 pos (1+ (match-beginning 0))))))
8696 ;; There is a coderef target for this
8697 (goto-char pos))
8698 ((string-match "^/\\(.*\\)/$" s)
8699 ;; A regular expression
8700 (cond
8701 ((org-mode-p)
8702 (org-occur (match-string 1 s)))
8703 ;;((eq major-mode 'dired-mode)
8704 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8705 (t (org-do-occur (match-string 1 s)))))
8707 ;; A normal search strings
8708 (when (equal (string-to-char s) ?*)
8709 ;; Anchor on headlines, post may include tags.
8710 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8711 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8712 s (substring s 1)))
8713 (remove-text-properties
8714 0 (length s)
8715 '(face nil mouse-face nil keymap nil fontified nil) s)
8716 ;; Make a series of regular expressions to find a match
8717 (setq words (org-split-string s "[ \n\r\t]+")
8719 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8720 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8721 "\\)" markers)
8722 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8723 re2a (concat "[ \t\r\n]" re2a_)
8724 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8725 re4 (concat "[^a-zA-Z_]" re4_)
8727 re1 (concat pre re2 post)
8728 re3 (concat pre (if pre re4_ re4) post)
8729 re5 (concat pre ".*" re4)
8730 re2 (concat pre re2)
8731 re2a (concat pre (if pre re2a_ re2a))
8732 re4 (concat pre (if pre re4_ re4))
8733 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8734 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8735 re5 "\\)"
8737 (cond
8738 ((eq type 'org-occur) (org-occur reall))
8739 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8740 (t (goto-char (point-min))
8741 (setq type 'fuzzy)
8742 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8743 (org-search-not-self 1 re1 nil t)
8744 (org-search-not-self 1 re2 nil t)
8745 (org-search-not-self 1 re2a nil t)
8746 (org-search-not-self 1 re3 nil t)
8747 (org-search-not-self 1 re4 nil t)
8748 (org-search-not-self 1 re5 nil t)
8750 (goto-char (match-beginning 1))
8751 (goto-char pos)
8752 (error "No match")))))
8754 ;; Normal string-search
8755 (goto-char (point-min))
8756 (if (search-forward s nil t)
8757 (goto-char (match-beginning 0))
8758 (error "No match"))))
8759 (and (org-mode-p) (org-show-context 'link-search))
8760 type))
8762 (defun org-search-not-self (group &rest args)
8763 "Execute `re-search-forward', but only accept matches that do not
8764 enclose the position of `org-open-link-marker'."
8765 (let ((m org-open-link-marker))
8766 (catch 'exit
8767 (while (apply 're-search-forward args)
8768 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8769 (goto-char (match-end group))
8770 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8771 (> (match-beginning 0) (marker-position m))
8772 (< (match-end 0) (marker-position m)))
8773 (save-match-data
8774 (or (not (org-in-regexp
8775 org-bracket-link-analytic-regexp 1))
8776 (not (match-end 4)) ; no description
8777 (and (<= (match-beginning 4) (point))
8778 (>= (match-end 4) (point))))))
8779 (throw 'exit (point))))))))
8781 (defun org-get-buffer-for-internal-link (buffer)
8782 "Return a buffer to be used for displaying the link target of internal links."
8783 (cond
8784 ((not org-display-internal-link-with-indirect-buffer)
8785 buffer)
8786 ((string-match "(Clone)$" (buffer-name buffer))
8787 (message "Buffer is already a clone, not making another one")
8788 ;; we also do not modify visibility in this case
8789 buffer)
8790 (t ; make a new indirect buffer for displaying the link
8791 (let* ((bn (buffer-name buffer))
8792 (ibn (concat bn "(Clone)"))
8793 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8794 (with-current-buffer ib (org-overview))
8795 ib))))
8797 (defun org-do-occur (regexp &optional cleanup)
8798 "Call the Emacs command `occur'.
8799 If CLEANUP is non-nil, remove the printout of the regular expression
8800 in the *Occur* buffer. This is useful if the regex is long and not useful
8801 to read."
8802 (occur regexp)
8803 (when cleanup
8804 (let ((cwin (selected-window)) win beg end)
8805 (when (setq win (get-buffer-window "*Occur*"))
8806 (select-window win))
8807 (goto-char (point-min))
8808 (when (re-search-forward "match[a-z]+" nil t)
8809 (setq beg (match-end 0))
8810 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8811 (setq end (1- (match-beginning 0)))))
8812 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8813 (goto-char (point-min))
8814 (select-window cwin))))
8816 ;;; The mark ring for links jumps
8818 (defvar org-mark-ring nil
8819 "Mark ring for positions before jumps in Org-mode.")
8820 (defvar org-mark-ring-last-goto nil
8821 "Last position in the mark ring used to go back.")
8822 ;; Fill and close the ring
8823 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8824 (loop for i from 1 to org-mark-ring-length do
8825 (push (make-marker) org-mark-ring))
8826 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8827 org-mark-ring)
8829 (defun org-mark-ring-push (&optional pos buffer)
8830 "Put the current position or POS into the mark ring and rotate it."
8831 (interactive)
8832 (setq pos (or pos (point)))
8833 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8834 (move-marker (car org-mark-ring)
8835 (or pos (point))
8836 (or buffer (current-buffer)))
8837 (message "%s"
8838 (substitute-command-keys
8839 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8841 (defun org-mark-ring-goto (&optional n)
8842 "Jump to the previous position in the mark ring.
8843 With prefix arg N, jump back that many stored positions. When
8844 called several times in succession, walk through the entire ring.
8845 Org-mode commands jumping to a different position in the current file,
8846 or to another Org-mode file, automatically push the old position
8847 onto the ring."
8848 (interactive "p")
8849 (let (p m)
8850 (if (eq last-command this-command)
8851 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8852 (setq p org-mark-ring))
8853 (setq org-mark-ring-last-goto p)
8854 (setq m (car p))
8855 (switch-to-buffer (marker-buffer m))
8856 (goto-char m)
8857 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8859 (defun org-remove-angle-brackets (s)
8860 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8861 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8863 (defun org-add-angle-brackets (s)
8864 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8865 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8867 (defun org-remove-double-quotes (s)
8868 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8869 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8872 ;;; Following specific links
8874 (defun org-follow-timestamp-link ()
8875 (cond
8876 ((org-at-date-range-p t)
8877 (let ((org-agenda-start-on-weekday)
8878 (t1 (match-string 1))
8879 (t2 (match-string 2)))
8880 (setq t1 (time-to-days (org-time-string-to-time t1))
8881 t2 (time-to-days (org-time-string-to-time t2)))
8882 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8883 ((org-at-timestamp-p t)
8884 (org-agenda-list nil (time-to-days (org-time-string-to-time
8885 (substring (match-string 1) 0 10)))
8887 (t (error "This should not happen"))))
8890 ;;; Following file links
8891 (defvar org-wait nil)
8892 (defun org-open-file (path &optional in-emacs line search)
8893 "Open the file at PATH.
8894 First, this expands any special file name abbreviations. Then the
8895 configuration variable `org-file-apps' is checked if it contains an
8896 entry for this file type, and if yes, the corresponding command is launched.
8898 If no application is found, Emacs simply visits the file.
8900 With optional prefix argument IN-EMACS, Emacs will visit the file.
8901 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8902 and o use an external application to visit the file.
8904 Optional LINE specifies a line to go to, optional SEARCH a string to
8905 search for. If LINE or SEARCH is given, the file will always be
8906 opened in Emacs.
8907 If the file does not exist, an error is thrown."
8908 (setq in-emacs (or in-emacs line search))
8909 (let* ((file (if (equal path "")
8910 buffer-file-name
8911 (substitute-in-file-name (expand-file-name path))))
8912 (apps (append org-file-apps (org-default-apps)))
8913 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8914 (dirp (if remp nil (file-directory-p file)))
8915 (file (if (and dirp org-open-directory-means-index-dot-org)
8916 (concat (file-name-as-directory file) "index.org")
8917 file))
8918 (a-m-a-p (assq 'auto-mode apps))
8919 (dfile (downcase file))
8920 (old-buffer (current-buffer))
8921 (old-pos (point))
8922 (old-mode major-mode)
8923 ext cmd)
8924 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8925 (setq ext (match-string 1 dfile))
8926 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8927 (setq ext (match-string 1 dfile))))
8928 (cond
8929 ((equal in-emacs '(16))
8930 (setq cmd (cdr (assoc 'system apps))))
8931 (in-emacs (setq cmd 'emacs))
8933 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8934 (and dirp (cdr (assoc 'directory apps)))
8935 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8936 'string-match)
8937 (cdr (assoc ext apps))
8938 (cdr (assoc t apps))))))
8939 (when (eq cmd 'system)
8940 (setq cmd (cdr (assoc 'system apps))))
8941 (when (eq cmd 'default)
8942 (setq cmd (cdr (assoc t apps))))
8943 (when (eq cmd 'mailcap)
8944 (require 'mailcap)
8945 (mailcap-parse-mailcaps)
8946 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8947 (command (mailcap-mime-info mime-type)))
8948 (if (stringp command)
8949 (setq cmd command)
8950 (setq cmd 'emacs))))
8951 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8952 (not (file-exists-p file))
8953 (not org-open-non-existing-files))
8954 (error "No such file: %s" file))
8955 (cond
8956 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8957 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8958 (while (string-match "['\"]%s['\"]" cmd)
8959 (setq cmd (replace-match "%s" t t cmd)))
8960 (while (string-match "%s" cmd)
8961 (setq cmd (replace-match
8962 (save-match-data
8963 (shell-quote-argument
8964 (convert-standard-filename file)))
8965 t t cmd)))
8966 (save-window-excursion
8967 (start-process-shell-command cmd nil cmd)
8968 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8970 ((or (stringp cmd)
8971 (eq cmd 'emacs))
8972 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8973 (widen)
8974 (if line (org-goto-line line)
8975 (if search (org-link-search search))))
8976 ((consp cmd)
8977 (let ((file (convert-standard-filename file)))
8978 (eval cmd)))
8979 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8980 (and (org-mode-p) (eq old-mode 'org-mode)
8981 (or (not (equal old-buffer (current-buffer)))
8982 (not (equal old-pos (point))))
8983 (org-mark-ring-push old-pos old-buffer))))
8985 (defun org-default-apps ()
8986 "Return the default applications for this operating system."
8987 (cond
8988 ((eq system-type 'darwin)
8989 org-file-apps-defaults-macosx)
8990 ((eq system-type 'windows-nt)
8991 org-file-apps-defaults-windowsnt)
8992 (t org-file-apps-defaults-gnu)))
8994 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8995 "Convert extensions to regular expressions in the cars of LIST.
8996 Also, weed out any non-string entries, because the return value is used
8997 only for regexp matching.
8998 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8999 point to the symbol `emacs', indicating that the file should
9000 be opened in Emacs."
9001 (append
9002 (delq nil
9003 (mapcar (lambda (x)
9004 (if (not (stringp (car x)))
9006 (if (string-match "\\W" (car x))
9008 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9009 list))
9010 (if add-auto-mode
9011 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9013 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9014 (defun org-file-remote-p (file)
9015 "Test whether FILE specifies a location on a remote system.
9016 Return non-nil if the location is indeed remote.
9018 For example, the filename \"/user@host:/foo\" specifies a location
9019 on the system \"/user@host:\"."
9020 (cond ((fboundp 'file-remote-p)
9021 (file-remote-p file))
9022 ((fboundp 'tramp-handle-file-remote-p)
9023 (tramp-handle-file-remote-p file))
9024 ((and (boundp 'ange-ftp-name-format)
9025 (string-match (car ange-ftp-name-format) file))
9027 (t nil)))
9030 ;;;; Refiling
9032 (defun org-get-org-file ()
9033 "Read a filename, with default directory `org-directory'."
9034 (let ((default (or org-default-notes-file remember-data-file)))
9035 (read-file-name (format "File name [%s]: " default)
9036 (file-name-as-directory org-directory)
9037 default)))
9039 (defun org-notes-order-reversed-p ()
9040 "Check if the current file should receive notes in reversed order."
9041 (cond
9042 ((not org-reverse-note-order) nil)
9043 ((eq t org-reverse-note-order) t)
9044 ((not (listp org-reverse-note-order)) nil)
9045 (t (catch 'exit
9046 (let ((all org-reverse-note-order)
9047 entry)
9048 (while (setq entry (pop all))
9049 (if (string-match (car entry) buffer-file-name)
9050 (throw 'exit (cdr entry))))
9051 nil)))))
9053 (defvar org-refile-target-table nil
9054 "The list of refile targets, created by `org-refile'.")
9056 (defvar org-agenda-new-buffers nil
9057 "Buffers created to visit agenda files.")
9059 (defun org-get-refile-targets (&optional default-buffer)
9060 "Produce a table with refile targets."
9061 (let ((case-fold-search nil)
9062 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9063 (entries (or org-refile-targets '((nil . (:level . 1)))))
9064 targets txt re files f desc descre fast-path-p level pos0)
9065 (message "Getting targets...")
9066 (with-current-buffer (or default-buffer (current-buffer))
9067 (while (setq entry (pop entries))
9068 (setq files (car entry) desc (cdr entry))
9069 (setq fast-path-p nil)
9070 (cond
9071 ((null files) (setq files (list (current-buffer))))
9072 ((eq files 'org-agenda-files)
9073 (setq files (org-agenda-files 'unrestricted)))
9074 ((and (symbolp files) (fboundp files))
9075 (setq files (funcall files)))
9076 ((and (symbolp files) (boundp files))
9077 (setq files (symbol-value files))))
9078 (if (stringp files) (setq files (list files)))
9079 (cond
9080 ((eq (car desc) :tag)
9081 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9082 ((eq (car desc) :todo)
9083 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9084 ((eq (car desc) :regexp)
9085 (setq descre (cdr desc)))
9086 ((eq (car desc) :level)
9087 (setq descre (concat "^\\*\\{" (number-to-string
9088 (if org-odd-levels-only
9089 (1- (* 2 (cdr desc)))
9090 (cdr desc)))
9091 "\\}[ \t]")))
9092 ((eq (car desc) :maxlevel)
9093 (setq fast-path-p t)
9094 (setq descre (concat "^\\*\\{1," (number-to-string
9095 (if org-odd-levels-only
9096 (1- (* 2 (cdr desc)))
9097 (cdr desc)))
9098 "\\}[ \t]")))
9099 (t (error "Bad refiling target description %s" desc)))
9100 (while (setq f (pop files))
9101 (with-current-buffer
9102 (if (bufferp f) f (org-get-agenda-file-buffer f))
9103 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9104 (setq f (and f (expand-file-name f)))
9105 (if (eq org-refile-use-outline-path 'file)
9106 (push (list (file-name-nondirectory f) f nil nil) targets))
9107 (save-excursion
9108 (save-restriction
9109 (widen)
9110 (goto-char (point-min))
9111 (while (re-search-forward descre nil t)
9112 (goto-char (setq pos0 (point-at-bol)))
9113 (catch 'next
9114 (when org-refile-target-verify-function
9115 (save-match-data
9116 (or (funcall org-refile-target-verify-function)
9117 (throw 'next t))))
9118 (when (looking-at org-complex-heading-regexp)
9119 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9120 txt (org-link-display-format (match-string 4))
9121 re (concat "^" (regexp-quote
9122 (buffer-substring (match-beginning 1)
9123 (match-end 4)))))
9124 (if (match-end 5) (setq re (concat re "[ \t]+"
9125 (regexp-quote
9126 (match-string 5)))))
9127 (setq re (concat re "[ \t]*$"))
9128 (when org-refile-use-outline-path
9129 (setq txt (mapconcat 'org-protect-slash
9130 (append
9131 (if (eq org-refile-use-outline-path 'file)
9132 (list (file-name-nondirectory
9133 (buffer-file-name (buffer-base-buffer))))
9134 (if (eq org-refile-use-outline-path 'full-file-path)
9135 (list (buffer-file-name (buffer-base-buffer)))))
9136 (org-get-outline-path fast-path-p level txt)
9137 (list txt))
9138 "/")))
9139 (push (list txt f re (point)) targets)))
9140 (when (= (point) pos0)
9141 ;; verification function has not moved point
9142 (goto-char (point-at-eol))))))))))
9143 (message "Getting targets...done")
9144 (nreverse targets)))
9146 (defun org-protect-slash (s)
9147 (while (string-match "/" s)
9148 (setq s (replace-match "\\" t t s)))
9151 (defvar org-olpa (make-vector 20 nil))
9153 (defun org-get-outline-path (&optional fastp level heading)
9154 "Return the outline path to the current entry, as a list.
9155 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9156 routine which makes outline path derivations for an entire file,
9157 avoiding backtracing."
9158 (if fastp
9159 (progn
9160 (if (> level 19)
9161 (error "Outline path failure, more than 19 levels."))
9162 (loop for i from level upto 19 do
9163 (aset org-olpa i nil))
9164 (prog1
9165 (delq nil (append org-olpa nil))
9166 (aset org-olpa level heading)))
9167 (let (rtn case-fold-search)
9168 (save-excursion
9169 (save-restriction
9170 (widen)
9171 (while (org-up-heading-safe)
9172 (when (looking-at org-complex-heading-regexp)
9173 (push (org-match-string-no-properties 4) rtn)))
9174 rtn)))))
9176 (defun org-format-outline-path (path &optional width prefix)
9177 "Format the outlie path PATH for display.
9178 Width is the maximum number of characters that is available.
9179 Prefix is a prefix to be included in the returned string,
9180 such as the file name."
9181 (setq width (or width 79))
9182 (if prefix (setq width (- width (length prefix))))
9183 (if (not path)
9184 (or prefix "")
9185 (let* ((nsteps (length path))
9186 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9187 (maxwidth (if (<= total-width width)
9188 10000 ;; everything fits
9189 ;; we need to shorten the level headings
9190 (/ (- width nsteps) nsteps)))
9191 (org-odd-levels-only nil)
9192 (n 0)
9193 (total (1+ (length prefix))))
9194 (setq maxwidth (max maxwidth 10))
9195 (concat prefix
9196 (mapconcat
9197 (lambda (h)
9198 (setq n (1+ n))
9199 (if (and (= n nsteps) (< maxwidth 10000))
9200 (setq maxwidth (- total-width total)))
9201 (if (< (length h) maxwidth)
9202 (progn (setq total (+ total (length h) 1)) h)
9203 (setq h (substring h 0 (- maxwidth 2))
9204 total (+ total maxwidth 1))
9205 (if (string-match "[ \t]+\\'" h)
9206 (setq h (substring h 0 (match-beginning 0))))
9207 (setq h (concat h "..")))
9208 (org-add-props h nil 'face
9209 (nth (% (1- n) org-n-level-faces)
9210 org-level-faces))
9212 path "/")))))
9214 (defun org-display-outline-path (&optional file current)
9215 "Display the current outline path in the echo area."
9216 (interactive "P")
9217 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9218 (case-fold-search nil)
9219 (path (and (org-mode-p) (org-get-outline-path))))
9220 (if current (setq path (append path
9221 (save-excursion
9222 (org-back-to-heading t)
9223 (if (looking-at org-complex-heading-regexp)
9224 (list (match-string 4)))))))
9225 (message "%s"
9226 (org-format-outline-path
9227 path
9228 (1- (frame-width))
9229 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9231 (defvar org-refile-history nil
9232 "History for refiling operations.")
9234 (defvar org-after-refile-insert-hook nil
9235 "Hook run after `org-refile' has inserted its stuff at the new location.
9236 Note that this is still *before* the stuff will be removed from
9237 the *old* location.")
9239 (defun org-refile (&optional goto default-buffer rfloc)
9240 "Move the entry at point to another heading.
9241 The list of target headings is compiled using the information in
9242 `org-refile-targets', which see. This list is created before each use
9243 and will therefore always be up-to-date.
9245 At the target location, the entry is filed as a subitem of the target heading.
9246 Depending on `org-reverse-note-order', the new subitem will either be the
9247 first or the last subitem.
9249 If there is an active region, all entries in that region will be moved.
9250 However, the region must fulfil the requirement that the first heading
9251 is the first one sets the top-level of the moved text - at most siblings
9252 below it are allowed.
9254 With prefix arg GOTO, the command will only visit the target location,
9255 not actually move anything.
9256 With a double prefix `C-u C-u', go to the location where the last refiling
9257 operation has put the subtree.
9258 With a prefix argument of `2', refile to the running clock.
9260 RFLOC can be a refile location obtained in a different way.
9262 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9263 (interactive "P")
9264 (let* ((cbuf (current-buffer))
9265 (regionp (org-region-active-p))
9266 (region-start (and regionp (region-beginning)))
9267 (region-end (and regionp (region-end)))
9268 (region-length (and regionp (- region-end region-start)))
9269 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9270 pos it nbuf file re level reversed)
9271 (setq last-command nil)
9272 (when regionp
9273 (goto-char region-start)
9274 (or (bolp) (goto-char (point-at-bol)))
9275 (setq region-start (point))
9276 (unless (org-kill-is-subtree-p
9277 (buffer-substring region-start region-end))
9278 (error "The region is not a (sequence of) subtree(s)")))
9279 (if (equal goto '(16))
9280 (org-refile-goto-last-stored)
9281 (when (or
9282 (and (equal goto 2)
9283 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9284 (prog1
9285 (setq it (list (or org-clock-heading "running clock")
9286 (buffer-file-name
9287 (marker-buffer org-clock-hd-marker))
9289 (marker-position org-clock-hd-marker)))
9290 (setq goto nil)))
9291 (setq it (or rfloc
9292 (save-excursion
9293 (org-refile-get-location
9294 (if goto "Goto: " "Refile to: ") default-buffer
9295 org-refile-allow-creating-parent-nodes)))))
9296 (setq file (nth 1 it)
9297 re (nth 2 it)
9298 pos (nth 3 it))
9299 (if (and (not goto)
9301 (equal (buffer-file-name) file)
9302 (if regionp
9303 (and (>= pos region-start)
9304 (<= pos region-end))
9305 (and (>= pos (point))
9306 (< pos (save-excursion
9307 (org-end-of-subtree t t))))))
9308 (error "Cannot refile to position inside the tree or region"))
9310 (setq nbuf (or (find-buffer-visiting file)
9311 (find-file-noselect file)))
9312 (if goto
9313 (progn
9314 (switch-to-buffer nbuf)
9315 (goto-char pos)
9316 (org-show-context 'org-goto))
9317 (if regionp
9318 (progn
9319 (org-kill-new (buffer-substring region-start region-end))
9320 (org-save-markers-in-region region-start region-end))
9321 (org-copy-subtree 1 nil t))
9322 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9323 (find-file-noselect file)))
9324 (setq reversed (org-notes-order-reversed-p))
9325 (save-excursion
9326 (save-restriction
9327 (widen)
9328 (if pos
9329 (progn
9330 (goto-char pos)
9331 (looking-at outline-regexp)
9332 (setq level (org-get-valid-level (funcall outline-level) 1))
9333 (goto-char
9334 (if reversed
9335 (or (outline-next-heading) (point-max))
9336 (or (save-excursion (org-get-next-sibling))
9337 (org-end-of-subtree t t)
9338 (point-max)))))
9339 (setq level 1)
9340 (if (not reversed)
9341 (goto-char (point-max))
9342 (goto-char (point-min))
9343 (or (outline-next-heading) (goto-char (point-max)))))
9344 (if (not (bolp)) (newline))
9345 (bookmark-set "org-refile-last-stored")
9346 (org-paste-subtree level)
9347 (if (fboundp 'deactivate-mark) (deactivate-mark))
9348 (run-hooks 'org-after-refile-insert-hook))))
9349 (if regionp
9350 (delete-region (point) (+ (point) region-length))
9351 (org-cut-subtree))
9352 (when (featurep 'org-inlinetask)
9353 (org-inlinetask-remove-END-maybe))
9354 (setq org-markers-to-move nil)
9355 (message "Refiled to \"%s\"" (car it))))))
9356 (org-reveal))
9358 (defun org-refile-goto-last-stored ()
9359 "Go to the location where the last refile was stored."
9360 (interactive)
9361 (bookmark-jump "org-refile-last-stored")
9362 (message "This is the location of the last refile"))
9364 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9365 "Prompt the user for a refile location, using PROMPT."
9366 (let ((org-refile-targets org-refile-targets)
9367 (org-refile-use-outline-path org-refile-use-outline-path))
9368 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9369 (unless org-refile-target-table
9370 (error "No refile targets"))
9371 (let* ((cbuf (current-buffer))
9372 (partial-completion-mode nil)
9373 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9374 (cfunc (if (and org-refile-use-outline-path
9375 org-outline-path-complete-in-steps)
9376 'org-olpath-completing-read
9377 'org-icompleting-read))
9378 (extra (if org-refile-use-outline-path "/" ""))
9379 (filename (and cfn (expand-file-name cfn)))
9380 (tbl (mapcar
9381 (lambda (x)
9382 (if (and (not (member org-refile-use-outline-path
9383 '(file full-file-path)))
9384 (not (equal filename (nth 1 x))))
9385 (cons (concat (car x) extra " ("
9386 (file-name-nondirectory (nth 1 x)) ")")
9387 (cdr x))
9388 (cons (concat (car x) extra) (cdr x))))
9389 org-refile-target-table))
9390 (completion-ignore-case t)
9391 pa answ parent-target child parent old-hist)
9392 (setq old-hist org-refile-history)
9393 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9394 nil 'org-refile-history))
9395 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9396 (if pa
9397 (progn
9398 (when (or (not org-refile-history)
9399 (not (eq old-hist org-refile-history))
9400 (not (equal (car pa) (car org-refile-history))))
9401 (setq org-refile-history
9402 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9403 org-refile-history
9404 (cdr org-refile-history))))
9405 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9406 (pop org-refile-history)))
9408 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9409 (setq parent (match-string 1 answ)
9410 child (match-string 2 answ))
9411 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9412 (when (and parent-target
9413 (or (eq new-nodes t)
9414 (and (eq new-nodes 'confirm)
9415 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9416 (org-refile-new-child parent-target child))))))
9418 (defun org-refile-new-child (parent-target child)
9419 "Use refile target PARENT-TARGET to add new CHILD below it."
9420 (unless parent-target
9421 (error "Cannot find parent for new node"))
9422 (let ((file (nth 1 parent-target))
9423 (pos (nth 3 parent-target))
9424 level)
9425 (with-current-buffer (or (find-buffer-visiting file)
9426 (find-file-noselect file))
9427 (save-excursion
9428 (save-restriction
9429 (widen)
9430 (if pos
9431 (goto-char pos)
9432 (goto-char (point-max))
9433 (if (not (bolp)) (newline)))
9434 (when (looking-at outline-regexp)
9435 (setq level (funcall outline-level))
9436 (org-end-of-subtree t t))
9437 (org-back-over-empty-lines)
9438 (insert "\n" (make-string
9439 (if pos (org-get-valid-level level 1) 1) ?*)
9440 " " child "\n")
9441 (beginning-of-line 0)
9442 (list (concat (car parent-target) "/" child) file "" (point)))))))
9444 (defun org-olpath-completing-read (prompt collection &rest args)
9445 "Read an outline path like a file name."
9446 (let ((thetable collection)
9447 (org-completion-use-ido nil) ; does not work with ido.
9448 (org-completion-use-iswitchb nil)) ; or iswitchb
9449 (apply
9450 'org-icompleting-read prompt
9451 (lambda (string predicate &optional flag)
9452 (let (rtn r f (l (length string)))
9453 (cond
9454 ((eq flag nil)
9455 ;; try completion
9456 (try-completion string thetable))
9457 ((eq flag t)
9458 ;; all-completions
9459 (setq rtn (all-completions string thetable predicate))
9460 (mapcar
9461 (lambda (x)
9462 (setq r (substring x l))
9463 (if (string-match " ([^)]*)$" x)
9464 (setq f (match-string 0 x))
9465 (setq f ""))
9466 (if (string-match "/" r)
9467 (concat string (substring r 0 (match-end 0)) f)
9469 rtn))
9470 ((eq flag 'lambda)
9471 ;; exact match?
9472 (assoc string thetable)))
9474 args)))
9476 ;;;; Dynamic blocks
9478 (defun org-find-dblock (name)
9479 "Find the first dynamic block with name NAME in the buffer.
9480 If not found, stay at current position and return nil."
9481 (let (pos)
9482 (save-excursion
9483 (goto-char (point-min))
9484 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9485 nil t)
9486 (match-beginning 0))))
9487 (if pos (goto-char pos))
9488 pos))
9490 (defconst org-dblock-start-re
9491 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9492 "Matches the start line of a dynamic block, with parameters.")
9494 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9495 "Matches the end of a dynamic block.")
9497 (defun org-create-dblock (plist)
9498 "Create a dynamic block section, with parameters taken from PLIST.
9499 PLIST must contain a :name entry which is used as name of the block."
9500 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9501 (end-of-line 1)
9502 (newline))
9503 (let ((col (current-column))
9504 (name (plist-get plist :name)))
9505 (insert "#+BEGIN: " name)
9506 (while plist
9507 (if (eq (car plist) :name)
9508 (setq plist (cddr plist))
9509 (insert " " (prin1-to-string (pop plist)))))
9510 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9511 (beginning-of-line -2)))
9513 (defun org-prepare-dblock ()
9514 "Prepare dynamic block for refresh.
9515 This empties the block, puts the cursor at the insert position and returns
9516 the property list including an extra property :name with the block name."
9517 (unless (looking-at org-dblock-start-re)
9518 (error "Not at a dynamic block"))
9519 (let* ((begdel (1+ (match-end 0)))
9520 (name (org-no-properties (match-string 1)))
9521 (params (append (list :name name)
9522 (read (concat "(" (match-string 3) ")")))))
9523 (save-excursion
9524 (beginning-of-line 1)
9525 (skip-chars-forward " \t")
9526 (setq params (plist-put params :indentation-column (current-column))))
9527 (unless (re-search-forward org-dblock-end-re nil t)
9528 (error "Dynamic block not terminated"))
9529 (setq params
9530 (append params
9531 (list :content (buffer-substring
9532 begdel (match-beginning 0)))))
9533 (delete-region begdel (match-beginning 0))
9534 (goto-char begdel)
9535 (open-line 1)
9536 params))
9538 (defun org-map-dblocks (&optional command)
9539 "Apply COMMAND to all dynamic blocks in the current buffer.
9540 If COMMAND is not given, use `org-update-dblock'."
9541 (let ((cmd (or command 'org-update-dblock))
9542 pos)
9543 (save-excursion
9544 (goto-char (point-min))
9545 (while (re-search-forward org-dblock-start-re nil t)
9546 (goto-char (setq pos (match-beginning 0)))
9547 (condition-case nil
9548 (funcall cmd)
9549 (error (message "Error during update of dynamic block")))
9550 (goto-char pos)
9551 (unless (re-search-forward org-dblock-end-re nil t)
9552 (error "Dynamic block not terminated"))))))
9554 (defun org-dblock-update (&optional arg)
9555 "User command for updating dynamic blocks.
9556 Update the dynamic block at point. With prefix ARG, update all dynamic
9557 blocks in the buffer."
9558 (interactive "P")
9559 (if arg
9560 (org-update-all-dblocks)
9561 (or (looking-at org-dblock-start-re)
9562 (org-beginning-of-dblock))
9563 (org-update-dblock)))
9565 (defun org-update-dblock ()
9566 "Update the dynamic block at point
9567 This means to empty the block, parse for parameters and then call
9568 the correct writing function."
9569 (save-window-excursion
9570 (let* ((pos (point))
9571 (line (org-current-line))
9572 (params (org-prepare-dblock))
9573 (name (plist-get params :name))
9574 (indent (plist-get params :indentation-column))
9575 (cmd (intern (concat "org-dblock-write:" name))))
9576 (message "Updating dynamic block `%s' at line %d..." name line)
9577 (funcall cmd params)
9578 (message "Updating dynamic block `%s' at line %d...done" name line)
9579 (goto-char pos)
9580 (when (and indent (> indent 0))
9581 (setq indent (make-string indent ?\ ))
9582 (save-excursion
9583 (org-beginning-of-dblock)
9584 (forward-line 1)
9585 (while (not (looking-at org-dblock-end-re))
9586 (insert indent)
9587 (beginning-of-line 2))
9588 (when (looking-at org-dblock-end-re)
9589 (and (looking-at "[ \t]+")
9590 (replace-match ""))
9591 (insert indent)))))))
9593 (defun org-beginning-of-dblock ()
9594 "Find the beginning of the dynamic block at point.
9595 Error if there is no such block at point."
9596 (let ((pos (point))
9597 beg)
9598 (end-of-line 1)
9599 (if (and (re-search-backward org-dblock-start-re nil t)
9600 (setq beg (match-beginning 0))
9601 (re-search-forward org-dblock-end-re nil t)
9602 (> (match-end 0) pos))
9603 (goto-char beg)
9604 (goto-char pos)
9605 (error "Not in a dynamic block"))))
9607 (defun org-update-all-dblocks ()
9608 "Update all dynamic blocks in the buffer.
9609 This function can be used in a hook."
9610 (when (org-mode-p)
9611 (org-map-dblocks 'org-update-dblock)))
9614 ;;;; Completion
9616 (defconst org-additional-option-like-keywords
9617 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9618 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9619 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9620 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9621 "BEGIN:" "END:"
9622 "ORGTBL" "TBLFM:" "TBLNAME:"
9623 "BEGIN_EXAMPLE" "END_EXAMPLE"
9624 "BEGIN_QUOTE" "END_QUOTE"
9625 "BEGIN_VERSE" "END_VERSE"
9626 "BEGIN_CENTER" "END_CENTER"
9627 "BEGIN_SRC" "END_SRC"
9628 "CATEGORY" "COLUMNS"
9629 "CAPTION" "LABEL"
9630 "SETUPFILE"
9631 "BIND"
9632 "MACRO"))
9634 (defcustom org-structure-template-alist
9636 ("s" "#+begin_src ?\n\n#+end_src"
9637 "<src lang=\"?\">\n\n</src>")
9638 ("e" "#+begin_example\n?\n#+end_example"
9639 "<example>\n?\n</example>")
9640 ("q" "#+begin_quote\n?\n#+end_quote"
9641 "<quote>\n?\n</quote>")
9642 ("v" "#+begin_verse\n?\n#+end_verse"
9643 "<verse>\n?\n/verse>")
9644 ("c" "#+begin_center\n?\n#+end_center"
9645 "<center>\n?\n/center>")
9646 ("l" "#+begin_latex\n?\n#+end_latex"
9647 "<literal style=\"latex\">\n?\n</literal>")
9648 ("L" "#+latex: "
9649 "<literal style=\"latex\">?</literal>")
9650 ("h" "#+begin_html\n?\n#+end_html"
9651 "<literal style=\"html\">\n?\n</literal>")
9652 ("H" "#+html: "
9653 "<literal style=\"html\">?</literal>")
9654 ("a" "#+begin_ascii\n?\n#+end_ascii")
9655 ("A" "#+ascii: ")
9656 ("i" "#+include %file ?"
9657 "<include file=%file markup=\"?\">")
9659 "Structure completion elements.
9660 This is a list of abbreviation keys and values. The value gets inserted
9661 it you type @samp{.} followed by the key and then the completion key,
9662 usually `M-TAB'. %file will be replaced by a file name after prompting
9663 for the file using completion.
9664 There are two templates for each key, the first uses the original Org syntax,
9665 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9666 the default when the /org-mtags.el/ module has been loaded. See also the
9667 variable `org-mtags-prefer-muse-templates'.
9668 This is an experimental feature, it is undecided if it is going to stay in."
9669 :group 'org-completion
9670 :type '(repeat
9671 (string :tag "Key")
9672 (string :tag "Template")
9673 (string :tag "Muse Template")))
9675 (defun org-try-structure-completion ()
9676 "Try to complete a structure template before point.
9677 This looks for strings like \"<e\" on an otherwise empty line and
9678 expands them."
9679 (let ((l (buffer-substring (point-at-bol) (point)))
9681 (when (and (looking-at "[ \t]*$")
9682 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9683 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9684 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9685 (match-beginning 1)) a)
9686 t)))
9688 (defun org-complete-expand-structure-template (start cell)
9689 "Expand a structure template."
9690 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9691 (rpl (nth (if musep 2 1) cell))
9692 (ind ""))
9693 (delete-region start (point))
9694 (when (string-match "\\`#\\+" rpl)
9695 (cond
9696 ((bolp))
9697 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9698 (setq ind (buffer-substring (point-at-bol) (point))))
9699 (t (newline))))
9700 (setq start (point))
9701 (if (string-match "%file" rpl)
9702 (setq rpl (replace-match
9703 (concat
9704 "\""
9705 (save-match-data
9706 (abbreviate-file-name (read-file-name "Include file: ")))
9707 "\"")
9708 t t rpl)))
9709 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9710 (concat "\n" ind)))
9711 (insert rpl)
9712 (if (re-search-backward "\\?" start t) (delete-char 1))))
9715 (defun org-complete (&optional arg)
9716 "Perform completion on word at point.
9717 At the beginning of a headline, this completes TODO keywords as given in
9718 `org-todo-keywords'.
9719 If the current word is preceded by a backslash, completes the TeX symbols
9720 that are supported for HTML support.
9721 If the current word is preceded by \"#+\", completes special words for
9722 setting file options.
9723 In the line after \"#+STARTUP:, complete valid keywords.\"
9724 At all other locations, this simply calls the value of
9725 `org-completion-fallback-command'."
9726 (interactive "P")
9727 (org-without-partial-completion
9728 (catch 'exit
9729 (let* ((a nil)
9730 (end (point))
9731 (beg1 (save-excursion
9732 (skip-chars-backward (org-re "[:alnum:]_@"))
9733 (point)))
9734 (beg (save-excursion
9735 (skip-chars-backward "a-zA-Z0-9_:$")
9736 (point)))
9737 (confirm (lambda (x) (stringp (car x))))
9738 (searchhead (equal (char-before beg) ?*))
9739 (struct
9740 (when (and (member (char-before beg1) '(?. ?<))
9741 (setq a (assoc (buffer-substring beg1 (point))
9742 org-structure-template-alist)))
9743 (org-complete-expand-structure-template (1- beg1) a)
9744 (throw 'exit t)))
9745 (tag (and (equal (char-before beg1) ?:)
9746 (equal (char-after (point-at-bol)) ?*)))
9747 (prop (and (equal (char-before beg1) ?:)
9748 (not (equal (char-after (point-at-bol)) ?*))))
9749 (texp (equal (char-before beg) ?\\))
9750 (link (equal (char-before beg) ?\[))
9751 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9752 beg)
9753 "#+"))
9754 (startup (string-match "^#\\+STARTUP:.*"
9755 (buffer-substring (point-at-bol) (point))))
9756 (completion-ignore-case opt)
9757 (type nil)
9758 (tbl nil)
9759 (table (cond
9760 (opt
9761 (setq type :opt)
9762 (require 'org-exp)
9763 (append
9764 (delq nil
9765 (mapcar
9766 (lambda (x)
9767 (if (string-match
9768 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9769 (cons (match-string 2 x)
9770 (match-string 1 x))))
9771 (org-split-string (org-get-current-options) "\n")))
9772 (mapcar 'list org-additional-option-like-keywords)))
9773 (startup
9774 (setq type :startup)
9775 org-startup-options)
9776 (link (append org-link-abbrev-alist-local
9777 org-link-abbrev-alist))
9778 (texp
9779 (setq type :tex)
9780 org-html-entities)
9781 ((string-match "\\`\\*+[ \t]+\\'"
9782 (buffer-substring (point-at-bol) beg))
9783 (setq type :todo)
9784 (mapcar 'list org-todo-keywords-1))
9785 (searchhead
9786 (setq type :searchhead)
9787 (save-excursion
9788 (goto-char (point-min))
9789 (while (re-search-forward org-todo-line-regexp nil t)
9790 (push (list
9791 (org-make-org-heading-search-string
9792 (match-string 3) t))
9793 tbl)))
9794 tbl)
9795 (tag (setq type :tag beg beg1)
9796 (or org-tag-alist (org-get-buffer-tags)))
9797 (prop (setq type :prop beg beg1)
9798 (mapcar 'list (org-buffer-property-keys nil t t)))
9799 (t (progn
9800 (call-interactively org-completion-fallback-command)
9801 (throw 'exit nil)))))
9802 (pattern (buffer-substring-no-properties beg end))
9803 (completion (try-completion pattern table confirm)))
9804 (cond ((eq completion t)
9805 (if (not (assoc (upcase pattern) table))
9806 (message "Already complete")
9807 (if (and (equal type :opt)
9808 (not (member (car (assoc (upcase pattern) table))
9809 org-additional-option-like-keywords)))
9810 (insert (substring (cdr (assoc (upcase pattern) table))
9811 (length pattern)))
9812 (if (memq type '(:tag :prop)) (insert ":")))))
9813 ((null completion)
9814 (message "Can't find completion for \"%s\"" pattern)
9815 (ding))
9816 ((not (string= pattern completion))
9817 (delete-region beg end)
9818 (if (string-match " +$" completion)
9819 (setq completion (replace-match "" t t completion)))
9820 (insert completion)
9821 (if (get-buffer-window "*Completions*")
9822 (delete-window (get-buffer-window "*Completions*")))
9823 (if (assoc completion table)
9824 (if (eq type :todo) (insert " ")
9825 (if (memq type '(:tag :prop)) (insert ":"))))
9826 (if (and (equal type :opt) (assoc completion table))
9827 (message "%s" (substitute-command-keys
9828 "Press \\[org-complete] again to insert example settings"))))
9830 (message "Making completion list...")
9831 (let ((list (sort (all-completions pattern table confirm)
9832 'string<)))
9833 (with-output-to-temp-buffer "*Completions*"
9834 (condition-case nil
9835 ;; Protection needed for XEmacs and emacs 21
9836 (display-completion-list list pattern)
9837 (error (display-completion-list list)))))
9838 (message "Making completion list...%s" "done")))))))
9840 ;;;; TODO, DEADLINE, Comments
9842 (defun org-toggle-comment ()
9843 "Change the COMMENT state of an entry."
9844 (interactive)
9845 (save-excursion
9846 (org-back-to-heading)
9847 (let (case-fold-search)
9848 (if (looking-at (concat outline-regexp
9849 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9850 (replace-match "" t t nil 1)
9851 (if (looking-at outline-regexp)
9852 (progn
9853 (goto-char (match-end 0))
9854 (insert org-comment-string " ")))))))
9856 (defvar org-last-todo-state-is-todo nil
9857 "This is non-nil when the last TODO state change led to a TODO state.
9858 If the last change removed the TODO tag or switched to DONE, then
9859 this is nil.")
9861 (defvar org-setting-tags nil) ; dynamically skipped
9863 (defun org-parse-local-options (string var)
9864 "Parse STRING for startup setting relevant for variable VAR."
9865 (let ((rtn (symbol-value var))
9866 e opts)
9867 (save-match-data
9868 (if (or (not string) (not (string-match "\\S-" string)))
9870 (setq opts (delq nil (mapcar (lambda (x)
9871 (setq e (assoc x org-startup-options))
9872 (if (eq (nth 1 e) var) e nil))
9873 (org-split-string string "[ \t]+"))))
9874 (if (not opts)
9876 (setq rtn nil)
9877 (while (setq e (pop opts))
9878 (if (not (nth 3 e))
9879 (setq rtn (nth 2 e))
9880 (if (not (listp rtn)) (setq rtn nil))
9881 (push (nth 2 e) rtn)))
9882 rtn)))))
9884 (defvar org-todo-setup-filter-hook nil
9885 "Hook for functions that pre-filter todo specs.
9887 Each function takes a todo spec and returns either `nil' or the spec
9888 transformed into canonical form." )
9890 (defvar org-todo-get-default-hook nil
9891 "Hook for functions that get a default item for todo.
9893 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9894 `nil' or a string to be used for the todo mark." )
9896 (defvar org-agenda-headline-snapshot-before-repeat)
9898 (defun org-todo (&optional arg)
9899 "Change the TODO state of an item.
9900 The state of an item is given by a keyword at the start of the heading,
9901 like
9902 *** TODO Write paper
9903 *** DONE Call mom
9905 The different keywords are specified in the variable `org-todo-keywords'.
9906 By default the available states are \"TODO\" and \"DONE\".
9907 So for this example: when the item starts with TODO, it is changed to DONE.
9908 When it starts with DONE, the DONE is removed. And when neither TODO nor
9909 DONE are present, add TODO at the beginning of the heading.
9911 With C-u prefix arg, use completion to determine the new state.
9912 With numeric prefix arg, switch to that state.
9913 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9914 With a triple C-u prefix, circumvent any state blocking.
9916 For calling through lisp, arg is also interpreted in the following way:
9917 'none -> empty state
9918 \"\"(empty string) -> switch to empty state
9919 'done -> switch to DONE
9920 'nextset -> switch to the next set of keywords
9921 'previousset -> switch to the previous set of keywords
9922 \"WAITING\" -> switch to the specified keyword, but only if it
9923 really is a member of `org-todo-keywords'."
9924 (interactive "P")
9925 (if (equal arg '(16)) (setq arg 'nextset))
9926 (let ((org-blocker-hook org-blocker-hook)
9927 (case-fold-search nil))
9928 (when (equal arg '(64))
9929 (setq arg nil org-blocker-hook nil))
9930 (when (and org-blocker-hook
9931 (or org-inhibit-blocking
9932 (org-entry-get nil "NOBLOCKING")))
9933 (setq org-blocker-hook nil))
9934 (save-excursion
9935 (catch 'exit
9936 (org-back-to-heading t)
9937 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9938 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9939 (looking-at " *"))
9940 (let* ((match-data (match-data))
9941 (startpos (point-at-bol))
9942 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9943 (org-log-done org-log-done)
9944 (org-log-repeat org-log-repeat)
9945 (org-todo-log-states org-todo-log-states)
9946 (this (match-string 1))
9947 (hl-pos (match-beginning 0))
9948 (head (org-get-todo-sequence-head this))
9949 (ass (assoc head org-todo-kwd-alist))
9950 (interpret (nth 1 ass))
9951 (done-word (nth 3 ass))
9952 (final-done-word (nth 4 ass))
9953 (last-state (or this ""))
9954 (completion-ignore-case t)
9955 (member (member this org-todo-keywords-1))
9956 (tail (cdr member))
9957 (state (cond
9958 ((and org-todo-key-trigger
9959 (or (and (equal arg '(4))
9960 (eq org-use-fast-todo-selection 'prefix))
9961 (and (not arg) org-use-fast-todo-selection
9962 (not (eq org-use-fast-todo-selection
9963 'prefix)))))
9964 ;; Use fast selection
9965 (org-fast-todo-selection))
9966 ((and (equal arg '(4))
9967 (or (not org-use-fast-todo-selection)
9968 (not org-todo-key-trigger)))
9969 ;; Read a state with completion
9970 (org-icompleting-read
9971 "State: " (mapcar (lambda(x) (list x))
9972 org-todo-keywords-1)
9973 nil t))
9974 ((eq arg 'right)
9975 (if this
9976 (if tail (car tail) nil)
9977 (car org-todo-keywords-1)))
9978 ((eq arg 'left)
9979 (if (equal member org-todo-keywords-1)
9981 (if this
9982 (nth (- (length org-todo-keywords-1)
9983 (length tail) 2)
9984 org-todo-keywords-1)
9985 (org-last org-todo-keywords-1))))
9986 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9987 (setq arg nil))) ; hack to fall back to cycling
9988 (arg
9989 ;; user or caller requests a specific state
9990 (cond
9991 ((equal arg "") nil)
9992 ((eq arg 'none) nil)
9993 ((eq arg 'done) (or done-word (car org-done-keywords)))
9994 ((eq arg 'nextset)
9995 (or (car (cdr (member head org-todo-heads)))
9996 (car org-todo-heads)))
9997 ((eq arg 'previousset)
9998 (let ((org-todo-heads (reverse org-todo-heads)))
9999 (or (car (cdr (member head org-todo-heads)))
10000 (car org-todo-heads))))
10001 ((car (member arg org-todo-keywords-1)))
10002 ((stringp arg)
10003 (error "State `%s' not valid in this file" arg))
10004 ((nth (1- (prefix-numeric-value arg))
10005 org-todo-keywords-1))))
10006 ((null member) (or head (car org-todo-keywords-1)))
10007 ((equal this final-done-word) nil) ;; -> make empty
10008 ((null tail) nil) ;; -> first entry
10009 ((memq interpret '(type priority))
10010 (if (eq this-command last-command)
10011 (car tail)
10012 (if (> (length tail) 0)
10013 (or done-word (car org-done-keywords))
10014 nil)))
10016 (car tail))))
10017 (state (or
10018 (run-hook-with-args-until-success
10019 'org-todo-get-default-hook state last-state)
10020 state))
10021 (next (if state (concat " " state " ") " "))
10022 (change-plist (list :type 'todo-state-change :from this :to state
10023 :position startpos))
10024 dolog now-done-p)
10025 (when org-blocker-hook
10026 (setq org-last-todo-state-is-todo
10027 (not (member this org-done-keywords)))
10028 (unless (save-excursion
10029 (save-match-data
10030 (run-hook-with-args-until-failure
10031 'org-blocker-hook change-plist)))
10032 (if (interactive-p)
10033 (error "TODO state change from %s to %s blocked" this state)
10034 ;; fail silently
10035 (message "TODO state change from %s to %s blocked" this state)
10036 (throw 'exit nil))))
10037 (store-match-data match-data)
10038 (replace-match next t t)
10039 (unless (pos-visible-in-window-p hl-pos)
10040 (message "TODO state changed to %s" (org-trim next)))
10041 (unless head
10042 (setq head (org-get-todo-sequence-head state)
10043 ass (assoc head org-todo-kwd-alist)
10044 interpret (nth 1 ass)
10045 done-word (nth 3 ass)
10046 final-done-word (nth 4 ass)))
10047 (when (memq arg '(nextset previousset))
10048 (message "Keyword-Set %d/%d: %s"
10049 (- (length org-todo-sets) -1
10050 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10051 (length org-todo-sets)
10052 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10053 (setq org-last-todo-state-is-todo
10054 (not (member state org-done-keywords)))
10055 (setq now-done-p (and (member state org-done-keywords)
10056 (not (member this org-done-keywords))))
10057 (and logging (org-local-logging logging))
10058 (when (and (or org-todo-log-states org-log-done)
10059 (not (eq org-inhibit-logging t))
10060 (not (memq arg '(nextset previousset))))
10061 ;; we need to look at recording a time and note
10062 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10063 (nth 2 (assoc this org-todo-log-states))))
10064 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10065 (setq dolog 'time))
10066 (when (and state
10067 (member state org-not-done-keywords)
10068 (not (member this org-not-done-keywords)))
10069 ;; This is now a todo state and was not one before
10070 ;; If there was a CLOSED time stamp, get rid of it.
10071 (org-add-planning-info nil nil 'closed))
10072 (when (and now-done-p org-log-done)
10073 ;; It is now done, and it was not done before
10074 (org-add-planning-info 'closed (org-current-time))
10075 (if (and (not dolog) (eq 'note org-log-done))
10076 (org-add-log-setup 'done state this 'findpos 'note)))
10077 (when (and state dolog)
10078 ;; This is a non-nil state, and we need to log it
10079 (org-add-log-setup 'state state this 'findpos dolog)))
10080 ;; Fixup tag positioning
10081 (org-todo-trigger-tag-changes state)
10082 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10083 (when org-provide-todo-statistics
10084 (org-update-parent-todo-statistics))
10085 (run-hooks 'org-after-todo-state-change-hook)
10086 (if (and arg (not (member state org-done-keywords)))
10087 (setq head (org-get-todo-sequence-head state)))
10088 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10089 ;; Do we need to trigger a repeat?
10090 (when now-done-p
10091 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10092 ;; This is for the agenda, take a snapshot of the headline.
10093 (save-match-data
10094 (setq org-agenda-headline-snapshot-before-repeat
10095 (org-get-heading))))
10096 (org-auto-repeat-maybe state))
10097 ;; Fixup cursor location if close to the keyword
10098 (if (and (outline-on-heading-p)
10099 (not (bolp))
10100 (save-excursion (beginning-of-line 1)
10101 (looking-at org-todo-line-regexp))
10102 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10103 (progn
10104 (goto-char (or (match-end 2) (match-end 1)))
10105 (and (looking-at " ") (just-one-space))))
10106 (when org-trigger-hook
10107 (save-excursion
10108 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10110 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10111 "Block turning an entry into a TODO, using the hierarchy.
10112 This checks whether the current task should be blocked from state
10113 changes. Such blocking occurs when:
10115 1. The task has children which are not all in a completed state.
10117 2. A task has a parent with the property :ORDERED:, and there
10118 are siblings prior to the current task with incomplete
10119 status.
10121 3. The parent of the task is blocked because it has siblings that should
10122 be done first, or is child of a block grandparent TODO entry."
10124 (catch 'dont-block
10125 ;; If this is not a todo state change, or if this entry is already DONE,
10126 ;; do not block
10127 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10128 (member (plist-get change-plist :from)
10129 (cons 'done org-done-keywords))
10130 (member (plist-get change-plist :to)
10131 (cons 'todo org-not-done-keywords))
10132 (not (plist-get change-plist :to)))
10133 (throw 'dont-block t))
10134 ;; If this task has children, and any are undone, it's blocked
10135 (save-excursion
10136 (org-back-to-heading t)
10137 (let ((this-level (funcall outline-level)))
10138 (outline-next-heading)
10139 (let ((child-level (funcall outline-level)))
10140 (while (and (not (eobp))
10141 (> child-level this-level))
10142 ;; this todo has children, check whether they are all
10143 ;; completed
10144 (if (and (not (org-entry-is-done-p))
10145 (org-entry-is-todo-p))
10146 (throw 'dont-block nil))
10147 (outline-next-heading)
10148 (setq child-level (funcall outline-level))))))
10149 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10150 ;; any previous siblings are undone, it's blocked
10151 (save-excursion
10152 (org-back-to-heading t)
10153 (let* ((pos (point))
10154 (parent-pos (and (org-up-heading-safe) (point))))
10155 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10156 (when (and (org-entry-get (point) "ORDERED")
10157 (forward-line 1)
10158 (re-search-forward org-not-done-heading-regexp pos t))
10159 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10160 ;; Search further up the hierarchy, to see if an anchestor is blocked
10161 (while t
10162 (goto-char parent-pos)
10163 (if (not (looking-at org-not-done-heading-regexp))
10164 (throw 'dont-block t)) ; do not block, parent is not a TODO
10165 (setq pos (point))
10166 (setq parent-pos (and (org-up-heading-safe) (point)))
10167 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10168 (when (and (org-entry-get (point) "ORDERED")
10169 (forward-line 1)
10170 (re-search-forward org-not-done-heading-regexp pos t))
10171 (throw 'dont-block nil))))))) ; block, older sibling not done.
10173 (defcustom org-track-ordered-property-with-tag nil
10174 "Should the ORDERED property also be shown as a tag?
10175 The ORDERED property decides if an entry should require subtasks to be
10176 completed in sequence. Since a property is not very visible, setting
10177 this option means that toggling the ORDERED property with the command
10178 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10179 not relevant for the behavior, but it makes things more visible.
10181 Note that toggling the tag with tags commands will not change the property
10182 and therefore not influence behavior!
10184 This can be t, meaning the tag ORDERED should be used, It can also be a
10185 string to select a different tag for this task."
10186 :group 'org-todo
10187 :type '(choice
10188 (const :tag "No tracking" nil)
10189 (const :tag "Track with ORDERED tag" t)
10190 (string :tag "Use other tag")))
10192 (defun org-toggle-ordered-property ()
10193 "Toggle the ORDERED property of the current entry.
10194 For better visibility, you can track the value of this property with a tag.
10195 See variable `org-track-ordered-property-with-tag'."
10196 (interactive)
10197 (let* ((t1 org-track-ordered-property-with-tag)
10198 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10199 (save-excursion
10200 (org-back-to-heading)
10201 (if (org-entry-get nil "ORDERED")
10202 (progn
10203 (org-delete-property "ORDERED")
10204 (and tag (org-toggle-tag tag 'off))
10205 (message "Subtasks can be completed in arbitrary order"))
10206 (org-entry-put nil "ORDERED" "t")
10207 (and tag (org-toggle-tag tag 'on))
10208 (message "Subtasks must be completed in sequence")))))
10210 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10211 (defun org-block-todo-from-checkboxes (change-plist)
10212 "Block turning an entry into a TODO, using checkboxes.
10213 This checks whether the current task should be blocked from state
10214 changes because there are unchecked boxes in this entry."
10215 (catch 'dont-block
10216 ;; If this is not a todo state change, or if this entry is already DONE,
10217 ;; do not block
10218 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10219 (member (plist-get change-plist :from)
10220 (cons 'done org-done-keywords))
10221 (member (plist-get change-plist :to)
10222 (cons 'todo org-not-done-keywords))
10223 (not (plist-get change-plist :to)))
10224 (throw 'dont-block t))
10225 ;; If this task has checkboxes that are not checked, it's blocked
10226 (save-excursion
10227 (org-back-to-heading t)
10228 (let ((beg (point)) end)
10229 (outline-next-heading)
10230 (setq end (point))
10231 (goto-char beg)
10232 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10233 end t)
10234 (progn
10235 (if (boundp 'org-blocked-by-checkboxes)
10236 (setq org-blocked-by-checkboxes t))
10237 (throw 'dont-block nil)))))
10238 t)) ; do not block
10240 (defun org-entry-blocked-p ()
10241 "Is the current entry blocked?"
10242 (if (org-entry-get nil "NOBLOCKING")
10243 nil ;; Never block this entry
10244 (not
10245 (run-hook-with-args-until-failure
10246 'org-blocker-hook
10247 (list :type 'todo-state-change
10248 :position (point)
10249 :from 'todo
10250 :to 'done)))))
10252 (defun org-update-statistics-cookies (all)
10253 "Update the statistics cookie, either from TODO or from checkboxes.
10254 This should be called with the cursor in a line with a statistics cookie."
10255 (interactive "P")
10256 (if all
10257 (progn
10258 (org-update-checkbox-count 'all)
10259 (org-map-entries 'org-update-parent-todo-statistics))
10260 (if (not (org-on-heading-p))
10261 (org-update-checkbox-count)
10262 (let ((pos (move-marker (make-marker) (point)))
10263 end l1 l2)
10264 (ignore-errors (org-back-to-heading t))
10265 (if (not (org-on-heading-p))
10266 (org-update-checkbox-count)
10267 (setq l1 (org-outline-level))
10268 (setq end (save-excursion
10269 (outline-next-heading)
10270 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10271 (point)))
10272 (if (and (save-excursion (re-search-forward
10273 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10274 (not (save-excursion (re-search-forward
10275 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10276 (org-update-checkbox-count)
10277 (if (and l2 (> l2 l1))
10278 (progn
10279 (goto-char end)
10280 (org-update-parent-todo-statistics))
10281 (error "No data for statistics cookie"))))
10282 (goto-char pos)
10283 (move-marker pos nil)))))
10285 (defvar org-entry-property-inherited-from) ;; defined below
10286 (defun org-update-parent-todo-statistics ()
10287 "Update any statistics cookie in the parent of the current headline.
10288 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10289 the entire subtree and this will travel up the hierarchy and update
10290 statistics everywhere."
10291 (interactive)
10292 (let* ((lim 0) prop
10293 (recursive (or (not org-hierarchical-todo-statistics)
10294 (string-match
10295 "\\<recursive\\>"
10296 (or (setq prop (org-entry-get
10297 nil "COOKIE_DATA" 'inherit)) ""))))
10298 (lim (or (and prop (marker-position
10299 org-entry-property-inherited-from))
10300 lim))
10301 (first t)
10302 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10303 level ltoggle l1 new ndel
10304 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10305 (catch 'exit
10306 (save-excursion
10307 (beginning-of-line 1)
10308 (if (org-at-heading-p)
10309 (setq ltoggle (funcall outline-level))
10310 (error "This should not happen"))
10311 (while (and (setq level (org-up-heading-safe))
10312 (or recursive first)
10313 (>= (point) lim))
10314 (setq first nil cookie-present nil)
10315 (unless (and level
10316 (not (string-match
10317 "\\<checkbox\\>"
10318 (downcase
10319 (or (org-entry-get
10320 nil "COOKIE_DATA")
10321 "")))))
10322 (throw 'exit nil))
10323 (while (re-search-forward box-re (point-at-eol) t)
10324 (setq cnt-all 0 cnt-done 0 cookie-present t)
10325 (setq is-percent (match-end 2))
10326 (save-match-data
10327 (unless (outline-next-heading) (throw 'exit nil))
10328 (while (and (looking-at org-complex-heading-regexp)
10329 (> (setq l1 (length (match-string 1))) level))
10330 (setq kwd (and (or recursive (= l1 ltoggle))
10331 (match-string 2)))
10332 (if (or (eq org-provide-todo-statistics 'all-headlines)
10333 (and (listp org-provide-todo-statistics)
10334 (or (member kwd org-provide-todo-statistics)
10335 (member kwd org-done-keywords))))
10336 (setq cnt-all (1+ cnt-all))
10337 (if (eq org-provide-todo-statistics t)
10338 (and kwd (setq cnt-all (1+ cnt-all)))))
10339 (and (member kwd org-done-keywords)
10340 (setq cnt-done (1+ cnt-done)))
10341 (outline-next-heading)))
10342 (setq new
10343 (if is-percent
10344 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10345 (format "[%d/%d]" cnt-done cnt-all))
10346 ndel (- (match-end 0) (match-beginning 0)))
10347 (goto-char (match-beginning 0))
10348 (insert new)
10349 (delete-region (point) (+ (point) ndel)))
10350 (when cookie-present
10351 (run-hook-with-args 'org-after-todo-statistics-hook
10352 cnt-done (- cnt-all cnt-done))))))
10353 (run-hooks 'org-todo-statistics-hook)))
10355 (defvar org-after-todo-statistics-hook nil
10356 "Hook that is called after a TODO statistics cookie has been updated.
10357 Each function is called with two arguments: the number of not-done entries
10358 and the number of done entries.
10360 For example, the following function, when added to this hook, will switch
10361 an entry to DONE when all children are done, and back to TODO when new
10362 entries are set to a TODO status. Note that this hook is only called
10363 when there is a statistics cookie in the headline!
10365 (defun org-summary-todo (n-done n-not-done)
10366 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10367 (let (org-log-done org-log-states) ; turn off logging
10368 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10371 (defvar org-todo-statistics-hook nil
10372 "Hook that is run whenever Org thinks TODO statistics should be updated.
10373 This hook runs even if there is no statistics cookie present, in which case
10374 `org-after-todo-statistics-hook' would not run.")
10376 (defun org-todo-trigger-tag-changes (state)
10377 "Apply the changes defined in `org-todo-state-tags-triggers'."
10378 (let ((l org-todo-state-tags-triggers)
10379 changes)
10380 (when (or (not state) (equal state ""))
10381 (setq changes (append changes (cdr (assoc "" l)))))
10382 (when (and (stringp state) (> (length state) 0))
10383 (setq changes (append changes (cdr (assoc state l)))))
10384 (when (member state org-not-done-keywords)
10385 (setq changes (append changes (cdr (assoc 'todo l)))))
10386 (when (member state org-done-keywords)
10387 (setq changes (append changes (cdr (assoc 'done l)))))
10388 (dolist (c changes)
10389 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10391 (defun org-local-logging (value)
10392 "Get logging settings from a property VALUE."
10393 (let* (words w a)
10394 ;; directly set the variables, they are already local.
10395 (setq org-log-done nil
10396 org-log-repeat nil
10397 org-todo-log-states nil)
10398 (setq words (org-split-string value))
10399 (while (setq w (pop words))
10400 (cond
10401 ((setq a (assoc w org-startup-options))
10402 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10403 (set (nth 1 a) (nth 2 a))))
10404 ((setq a (org-extract-log-state-settings w))
10405 (and (member (car a) org-todo-keywords-1)
10406 (push a org-todo-log-states)))))))
10408 (defun org-get-todo-sequence-head (kwd)
10409 "Return the head of the TODO sequence to which KWD belongs.
10410 If KWD is not set, check if there is a text property remembering the
10411 right sequence."
10412 (let (p)
10413 (cond
10414 ((not kwd)
10415 (or (get-text-property (point-at-bol) 'org-todo-head)
10416 (progn
10417 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10418 nil (point-at-eol)))
10419 (get-text-property p 'org-todo-head))))
10420 ((not (member kwd org-todo-keywords-1))
10421 (car org-todo-keywords-1))
10422 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10424 (defun org-fast-todo-selection ()
10425 "Fast TODO keyword selection with single keys.
10426 Returns the new TODO keyword, or nil if no state change should occur."
10427 (let* ((fulltable org-todo-key-alist)
10428 (done-keywords org-done-keywords) ;; needed for the faces.
10429 (maxlen (apply 'max (mapcar
10430 (lambda (x)
10431 (if (stringp (car x)) (string-width (car x)) 0))
10432 fulltable)))
10433 (expert nil)
10434 (fwidth (+ maxlen 3 1 3))
10435 (ncol (/ (- (window-width) 4) fwidth))
10436 tg cnt e c tbl
10437 groups ingroup)
10438 (save-excursion
10439 (save-window-excursion
10440 (if expert
10441 (set-buffer (get-buffer-create " *Org todo*"))
10442 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10443 (erase-buffer)
10444 (org-set-local 'org-done-keywords done-keywords)
10445 (setq tbl fulltable cnt 0)
10446 (while (setq e (pop tbl))
10447 (cond
10448 ((equal e '(:startgroup))
10449 (push '() groups) (setq ingroup t)
10450 (when (not (= cnt 0))
10451 (setq cnt 0)
10452 (insert "\n"))
10453 (insert "{ "))
10454 ((equal e '(:endgroup))
10455 (setq ingroup nil cnt 0)
10456 (insert "}\n"))
10457 ((equal e '(:newline))
10458 (when (not (= cnt 0))
10459 (setq cnt 0)
10460 (insert "\n")
10461 (setq e (car tbl))
10462 (while (equal (car tbl) '(:newline))
10463 (insert "\n")
10464 (setq tbl (cdr tbl)))))
10466 (setq tg (car e) c (cdr e))
10467 (if ingroup (push tg (car groups)))
10468 (setq tg (org-add-props tg nil 'face
10469 (org-get-todo-face tg)))
10470 (if (and (= cnt 0) (not ingroup)) (insert " "))
10471 (insert "[" c "] " tg (make-string
10472 (- fwidth 4 (length tg)) ?\ ))
10473 (when (= (setq cnt (1+ cnt)) ncol)
10474 (insert "\n")
10475 (if ingroup (insert " "))
10476 (setq cnt 0)))))
10477 (insert "\n")
10478 (goto-char (point-min))
10479 (if (not expert) (org-fit-window-to-buffer))
10480 (message "[a-z..]:Set [SPC]:clear")
10481 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10482 (cond
10483 ((or (= c ?\C-g)
10484 (and (= c ?q) (not (rassoc c fulltable))))
10485 (setq quit-flag t))
10486 ((= c ?\ ) nil)
10487 ((setq e (rassoc c fulltable) tg (car e))
10489 (t (setq quit-flag t)))))))
10491 (defun org-entry-is-todo-p ()
10492 (member (org-get-todo-state) org-not-done-keywords))
10494 (defun org-entry-is-done-p ()
10495 (member (org-get-todo-state) org-done-keywords))
10497 (defun org-get-todo-state ()
10498 (save-excursion
10499 (org-back-to-heading t)
10500 (and (looking-at org-todo-line-regexp)
10501 (match-end 2)
10502 (match-string 2))))
10504 (defun org-at-date-range-p (&optional inactive-ok)
10505 "Is the cursor inside a date range?"
10506 (interactive)
10507 (save-excursion
10508 (catch 'exit
10509 (let ((pos (point)))
10510 (skip-chars-backward "^[<\r\n")
10511 (skip-chars-backward "<[")
10512 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10513 (>= (match-end 0) pos)
10514 (throw 'exit t))
10515 (skip-chars-backward "^<[\r\n")
10516 (skip-chars-backward "<[")
10517 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10518 (>= (match-end 0) pos)
10519 (throw 'exit t)))
10520 nil)))
10522 (defun org-get-repeat (&optional tagline)
10523 "Check if there is a deadline/schedule with repeater in this entry."
10524 (save-match-data
10525 (save-excursion
10526 (org-back-to-heading t)
10527 (and (re-search-forward (if tagline
10528 (concat tagline "\\s-*" org-repeat-re)
10529 org-repeat-re)
10530 (org-entry-end-position) t)
10531 (match-string-no-properties 1)))))
10533 (defvar org-last-changed-timestamp)
10534 (defvar org-last-inserted-timestamp)
10535 (defvar org-log-post-message)
10536 (defvar org-log-note-purpose)
10537 (defvar org-log-note-how)
10538 (defvar org-log-note-extra)
10539 (defun org-auto-repeat-maybe (done-word)
10540 "Check if the current headline contains a repeated deadline/schedule.
10541 If yes, set TODO state back to what it was and change the base date
10542 of repeating deadline/scheduled time stamps to new date.
10543 This function is run automatically after each state change to a DONE state."
10544 ;; last-state is dynamically scoped into this function
10545 (let* ((repeat (org-get-repeat))
10546 (aa (assoc last-state org-todo-kwd-alist))
10547 (interpret (nth 1 aa))
10548 (head (nth 2 aa))
10549 (whata '(("d" . day) ("m" . month) ("y" . year)))
10550 (msg "Entry repeats: ")
10551 (org-log-done nil)
10552 (org-todo-log-states nil)
10553 (nshiftmax 10) (nshift 0)
10554 re type n what ts time)
10555 (when repeat
10556 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10557 (org-todo (if (eq interpret 'type) last-state head))
10558 (org-entry-put nil "LAST_REPEAT" (format-time-string
10559 (org-time-stamp-format t t)))
10560 (when org-log-repeat
10561 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10562 (memq 'org-add-log-note post-command-hook))
10563 ;; OK, we are already setup for some record
10564 (if (eq org-log-repeat 'note)
10565 ;; make sure we take a note, not only a time stamp
10566 (setq org-log-note-how 'note))
10567 ;; Set up for taking a record
10568 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10569 last-state
10570 'findpos org-log-repeat)))
10571 (org-back-to-heading t)
10572 (org-add-planning-info nil nil 'closed)
10573 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10574 org-deadline-time-regexp "\\)\\|\\("
10575 org-ts-regexp "\\)"))
10576 (while (re-search-forward
10577 re (save-excursion (outline-next-heading) (point)) t)
10578 (setq type (if (match-end 1) org-scheduled-string
10579 (if (match-end 3) org-deadline-string "Plain:"))
10580 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10581 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10582 (setq n (string-to-number (match-string 2 ts))
10583 what (match-string 3 ts))
10584 (if (equal what "w") (setq n (* n 7) what "d"))
10585 ;; Preparation, see if we need to modify the start date for the change
10586 (when (match-end 1)
10587 (setq time (save-match-data (org-time-string-to-time ts)))
10588 (cond
10589 ((equal (match-string 1 ts) ".")
10590 ;; Shift starting date to today
10591 (org-timestamp-change
10592 (- (time-to-days (current-time)) (time-to-days time))
10593 'day))
10594 ((equal (match-string 1 ts) "+")
10595 (while (or (= nshift 0)
10596 (<= (time-to-days time) (time-to-days (current-time))))
10597 (when (= (incf nshift) nshiftmax)
10598 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10599 (error "Abort")))
10600 (org-timestamp-change n (cdr (assoc what whata)))
10601 (org-at-timestamp-p t)
10602 (setq ts (match-string 1))
10603 (setq time (save-match-data (org-time-string-to-time ts))))
10604 (org-timestamp-change (- n) (cdr (assoc what whata)))
10605 ;; rematch, so that we have everything in place for the real shift
10606 (org-at-timestamp-p t)
10607 (setq ts (match-string 1))
10608 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10609 (org-timestamp-change n (cdr (assoc what whata)))
10610 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10611 (setq org-log-post-message msg)
10612 (message "%s" msg))))
10614 (defun org-show-todo-tree (arg)
10615 "Make a compact tree which shows all headlines marked with TODO.
10616 The tree will show the lines where the regexp matches, and all higher
10617 headlines above the match.
10618 With a \\[universal-argument] prefix, prompt for a regexp to match.
10619 With a numeric prefix N, construct a sparse tree for the Nth element
10620 of `org-todo-keywords-1'."
10621 (interactive "P")
10622 (let ((case-fold-search nil)
10623 (kwd-re
10624 (cond ((null arg) org-not-done-regexp)
10625 ((equal arg '(4))
10626 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10627 (mapcar 'list org-todo-keywords-1))))
10628 (concat "\\("
10629 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10630 "\\)\\>")))
10631 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10632 (regexp-quote (nth (1- (prefix-numeric-value arg))
10633 org-todo-keywords-1)))
10634 (t (error "Invalid prefix argument: %s" arg)))))
10635 (message "%d TODO entries found"
10636 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10638 (defun org-deadline (&optional remove time)
10639 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10640 With argument REMOVE, remove any deadline from the item.
10641 When TIME is set, it should be an internal time specification, and the
10642 scheduling will use the corresponding date."
10643 (interactive "P")
10644 (let ((old-date (org-entry-get nil "DEADLINE")))
10645 (if remove
10646 (progn
10647 (org-remove-timestamp-with-keyword org-deadline-string)
10648 (message "Item no longer has a deadline."))
10649 (if (org-get-repeat)
10650 (error "Cannot change deadline on task with repeater, please do that by hand")
10651 (org-add-planning-info 'deadline time 'closed)
10652 (when (and old-date org-log-redeadline
10653 (not (equal old-date
10654 (substring org-last-inserted-timestamp 1 -1))))
10655 (org-add-log-setup 'redeadline nil old-date 'findpos
10656 org-log-redeadline))
10657 (message "Deadline on %s" org-last-inserted-timestamp)))))
10659 (defun org-schedule (&optional remove time)
10660 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10661 With argument REMOVE, remove any scheduling date from the item.
10662 When TIME is set, it should be an internal time specification, and the
10663 scheduling will use the corresponding date."
10664 (interactive "P")
10665 (let ((old-date (org-entry-get nil "SCHEDULED")))
10666 (if remove
10667 (progn
10668 (org-remove-timestamp-with-keyword org-scheduled-string)
10669 (message "Item is no longer scheduled."))
10670 (if (org-get-repeat)
10671 (error "Cannot reschedule task with repeater, please do that by hand")
10672 (org-add-planning-info 'scheduled time 'closed)
10673 (when (and old-date org-log-reschedule
10674 (not (equal old-date
10675 (substring org-last-inserted-timestamp 1 -1))))
10676 (org-add-log-setup 'reschedule nil old-date 'findpos
10677 org-log-reschedule))
10678 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10680 (defun org-get-scheduled-time (pom &optional inherit)
10681 "Get the scheduled time as a time tuple, of a format suitable
10682 for calling org-schedule with, or if there is no scheduling,
10683 returns nil."
10684 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10685 (when time
10686 (apply 'encode-time (org-parse-time-string time)))))
10688 (defun org-get-deadline-time (pom &optional inherit)
10689 "Get the deadine as a time tuple, of a format suitable for
10690 calling org-deadline with, or if there is no scheduling, returns
10691 nil."
10692 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10693 (when time
10694 (apply 'encode-time (org-parse-time-string time)))))
10696 (defun org-remove-timestamp-with-keyword (keyword)
10697 "Remove all time stamps with KEYWORD in the current entry."
10698 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10699 beg)
10700 (save-excursion
10701 (org-back-to-heading t)
10702 (setq beg (point))
10703 (outline-next-heading)
10704 (while (re-search-backward re beg t)
10705 (replace-match "")
10706 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10707 (equal (char-before) ?\ ))
10708 (backward-delete-char 1)
10709 (if (string-match "^[ \t]*$" (buffer-substring
10710 (point-at-bol) (point-at-eol)))
10711 (delete-region (point-at-bol)
10712 (min (point-max) (1+ (point-at-eol))))))))))
10714 (defun org-add-planning-info (what &optional time &rest remove)
10715 "Insert new timestamp with keyword in the line directly after the headline.
10716 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10717 If non is given, the user is prompted for a date.
10718 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10719 be removed."
10720 (interactive)
10721 (let (org-time-was-given org-end-time-was-given ts
10722 end default-time default-input)
10724 (catch 'exit
10725 (when (and (not time) (memq what '(scheduled deadline)))
10726 ;; Try to get a default date/time from existing timestamp
10727 (save-excursion
10728 (org-back-to-heading t)
10729 (setq end (save-excursion (outline-next-heading) (point)))
10730 (when (re-search-forward (if (eq what 'scheduled)
10731 org-scheduled-time-regexp
10732 org-deadline-time-regexp)
10733 end t)
10734 (setq ts (match-string 1)
10735 default-time
10736 (apply 'encode-time (org-parse-time-string ts))
10737 default-input (and ts (org-get-compact-tod ts))))))
10738 (when what
10739 ;; If necessary, get the time from the user
10740 (setq time (or time (org-read-date nil 'to-time nil nil
10741 default-time default-input))))
10743 (when (and org-insert-labeled-timestamps-at-point
10744 (member what '(scheduled deadline)))
10745 (insert
10746 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10747 (org-insert-time-stamp time org-time-was-given
10748 nil nil nil (list org-end-time-was-given))
10749 (setq what nil))
10750 (save-excursion
10751 (save-restriction
10752 (let (col list elt ts buffer-invisibility-spec)
10753 (org-back-to-heading t)
10754 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10755 (goto-char (match-end 1))
10756 (setq col (current-column))
10757 (goto-char (match-end 0))
10758 (if (eobp) (insert "\n") (forward-char 1))
10759 (when (and (not what)
10760 (not (looking-at
10761 (concat "[ \t]*"
10762 org-keyword-time-not-clock-regexp))))
10763 ;; Nothing to add, nothing to remove...... :-)
10764 (throw 'exit nil))
10765 (if (and (not (looking-at outline-regexp))
10766 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10767 "[^\r\n]*"))
10768 (not (equal (match-string 1) org-clock-string)))
10769 (narrow-to-region (match-beginning 0) (match-end 0))
10770 (insert-before-markers "\n")
10771 (backward-char 1)
10772 (narrow-to-region (point) (point))
10773 (and org-adapt-indentation (org-indent-to-column col)))
10774 ;; Check if we have to remove something.
10775 (setq list (cons what remove))
10776 (while list
10777 (setq elt (pop list))
10778 (goto-char (point-min))
10779 (when (or (and (eq elt 'scheduled)
10780 (re-search-forward org-scheduled-time-regexp nil t))
10781 (and (eq elt 'deadline)
10782 (re-search-forward org-deadline-time-regexp nil t))
10783 (and (eq elt 'closed)
10784 (re-search-forward org-closed-time-regexp nil t)))
10785 (replace-match "")
10786 (if (looking-at "--+<[^>]+>") (replace-match ""))
10787 (skip-chars-backward " ")
10788 (if (looking-at " +") (replace-match ""))))
10789 (goto-char (point-max))
10790 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10791 (when what
10792 (insert
10793 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10794 (cond ((eq what 'scheduled) org-scheduled-string)
10795 ((eq what 'deadline) org-deadline-string)
10796 ((eq what 'closed) org-closed-string))
10797 " ")
10798 (setq ts (org-insert-time-stamp
10799 time
10800 (or org-time-was-given
10801 (and (eq what 'closed) org-log-done-with-time))
10802 (eq what 'closed)
10803 nil nil (list org-end-time-was-given)))
10804 (end-of-line 1))
10805 (goto-char (point-min))
10806 (widen)
10807 (if (and (looking-at "[ \t]+\n")
10808 (equal (char-before) ?\n))
10809 (delete-region (1- (point)) (point-at-eol)))
10810 ts))))))
10812 (defvar org-log-note-marker (make-marker))
10813 (defvar org-log-note-purpose nil)
10814 (defvar org-log-note-state nil)
10815 (defvar org-log-note-previous-state nil)
10816 (defvar org-log-note-how nil)
10817 (defvar org-log-note-extra nil)
10818 (defvar org-log-note-window-configuration nil)
10819 (defvar org-log-note-return-to (make-marker))
10820 (defvar org-log-post-message nil
10821 "Message to be displayed after a log note has been stored.
10822 The auto-repeater uses this.")
10824 (defun org-add-note ()
10825 "Add a note to the current entry.
10826 This is done in the same way as adding a state change note."
10827 (interactive)
10828 (org-add-log-setup 'note nil nil 'findpos nil))
10830 (defvar org-property-end-re)
10831 (defun org-add-log-setup (&optional purpose state prev-state
10832 findpos how &optional extra)
10833 "Set up the post command hook to take a note.
10834 If this is about to TODO state change, the new state is expected in STATE.
10835 When FINDPOS is non-nil, find the correct position for the note in
10836 the current entry. If not, assume that it can be inserted at point.
10837 HOW is an indicator what kind of note should be created.
10838 EXTRA is additional text that will be inserted into the notes buffer."
10839 (let* ((org-log-into-drawer (org-log-into-drawer))
10840 (drawer (cond ((stringp org-log-into-drawer)
10841 org-log-into-drawer)
10842 (org-log-into-drawer "LOGBOOK")
10843 (t nil))))
10844 (save-restriction
10845 (save-excursion
10846 (when findpos
10847 (org-back-to-heading t)
10848 (narrow-to-region (point) (save-excursion
10849 (outline-next-heading) (point)))
10850 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10851 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10852 "[^\r\n]*\\)?"))
10853 (goto-char (match-end 0))
10854 (cond
10855 (drawer
10856 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10857 nil t)
10858 (progn
10859 (goto-char (match-end 0))
10860 (or org-log-states-order-reversed
10861 (and (re-search-forward org-property-end-re nil t)
10862 (goto-char (1- (match-beginning 0))))))
10863 (insert "\n:" drawer ":\n:END:")
10864 (beginning-of-line 0)
10865 (org-indent-line-function)
10866 (beginning-of-line 2)
10867 (org-indent-line-function)
10868 (end-of-line 0)))
10869 ((and org-log-state-notes-insert-after-drawers
10870 (save-excursion
10871 (forward-line) (looking-at org-drawer-regexp)))
10872 (forward-line)
10873 (while (looking-at org-drawer-regexp)
10874 (goto-char (match-end 0))
10875 (re-search-forward org-property-end-re (point-max) t)
10876 (forward-line))
10877 (forward-line -1)))
10878 (unless org-log-states-order-reversed
10879 (and (= (char-after) ?\n) (forward-char 1))
10880 (org-skip-over-state-notes)
10881 (skip-chars-backward " \t\n\r")))
10882 (move-marker org-log-note-marker (point))
10883 (setq org-log-note-purpose purpose
10884 org-log-note-state state
10885 org-log-note-previous-state prev-state
10886 org-log-note-how how
10887 org-log-note-extra extra)
10888 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10890 (defun org-skip-over-state-notes ()
10891 "Skip past the list of State notes in an entry."
10892 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10893 (while (looking-at "[ \t]*- State")
10894 (condition-case nil
10895 (org-next-item)
10896 (error (org-end-of-item)))))
10898 (defun org-add-log-note (&optional purpose)
10899 "Pop up a window for taking a note, and add this note later at point."
10900 (remove-hook 'post-command-hook 'org-add-log-note)
10901 (setq org-log-note-window-configuration (current-window-configuration))
10902 (delete-other-windows)
10903 (move-marker org-log-note-return-to (point))
10904 (switch-to-buffer (marker-buffer org-log-note-marker))
10905 (goto-char org-log-note-marker)
10906 (org-switch-to-buffer-other-window "*Org Note*")
10907 (erase-buffer)
10908 (if (memq org-log-note-how '(time state))
10909 (let (current-prefix-arg) (org-store-log-note))
10910 (let ((org-inhibit-startup t)) (org-mode))
10911 (insert (format "# Insert note for %s.
10912 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10913 (cond
10914 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10915 ((eq org-log-note-purpose 'done) "closed todo item")
10916 ((eq org-log-note-purpose 'state)
10917 (format "state change from \"%s\" to \"%s\""
10918 (or org-log-note-previous-state "")
10919 (or org-log-note-state "")))
10920 ((eq org-log-note-purpose 'reschedule)
10921 "rescheduling")
10922 ((eq org-log-note-purpose 'redeadline)
10923 "changing deadline")
10924 ((eq org-log-note-purpose 'note)
10925 "this entry")
10926 (t (error "This should not happen")))))
10927 (if org-log-note-extra (insert org-log-note-extra))
10928 (org-set-local 'org-finish-function 'org-store-log-note)))
10930 (defvar org-note-abort nil) ; dynamically scoped
10931 (defun org-store-log-note ()
10932 "Finish taking a log note, and insert it to where it belongs."
10933 (let ((txt (buffer-string))
10934 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10935 lines ind)
10936 (kill-buffer (current-buffer))
10937 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10938 (setq txt (replace-match "" t t txt)))
10939 (if (string-match "\\s-+\\'" txt)
10940 (setq txt (replace-match "" t t txt)))
10941 (setq lines (org-split-string txt "\n"))
10942 (when (and note (string-match "\\S-" note))
10943 (setq note
10944 (org-replace-escapes
10945 note
10946 (list (cons "%u" (user-login-name))
10947 (cons "%U" user-full-name)
10948 (cons "%t" (format-time-string
10949 (org-time-stamp-format 'long 'inactive)
10950 (current-time)))
10951 (cons "%s" (if org-log-note-state
10952 (concat "\"" org-log-note-state "\"")
10953 ""))
10954 (cons "%S" (if org-log-note-previous-state
10955 (concat "\"" org-log-note-previous-state "\"")
10956 "\"\"")))))
10957 (if lines (setq note (concat note " \\\\")))
10958 (push note lines))
10959 (when (or current-prefix-arg org-note-abort)
10960 (when org-log-into-drawer
10961 (org-remove-empty-drawer-at
10962 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10963 org-log-note-marker))
10964 (setq lines nil))
10965 (when lines
10966 (with-current-buffer (marker-buffer org-log-note-marker)
10967 (save-excursion
10968 (goto-char org-log-note-marker)
10969 (move-marker org-log-note-marker nil)
10970 (end-of-line 1)
10971 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10972 (insert "- " (pop lines))
10973 (org-indent-line-function)
10974 (beginning-of-line 1)
10975 (looking-at "[ \t]*")
10976 (setq ind (concat (match-string 0) " "))
10977 (end-of-line 1)
10978 (while lines (insert "\n" ind (pop lines)))
10979 (message "Note stored")
10980 (org-back-to-heading t)
10981 (org-cycle-hide-drawers 'children)))))
10982 (set-window-configuration org-log-note-window-configuration)
10983 (with-current-buffer (marker-buffer org-log-note-return-to)
10984 (goto-char org-log-note-return-to))
10985 (move-marker org-log-note-return-to nil)
10986 (and org-log-post-message (message "%s" org-log-post-message)))
10988 (defun org-remove-empty-drawer-at (drawer pos)
10989 "Remove an empty drawer DRAWER at position POS.
10990 POS may also be a marker."
10991 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10992 (save-excursion
10993 (save-restriction
10994 (widen)
10995 (goto-char pos)
10996 (if (org-in-regexp
10997 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10998 (replace-match ""))))))
11000 (defun org-sparse-tree (&optional arg)
11001 "Create a sparse tree, prompt for the details.
11002 This command can create sparse trees. You first need to select the type
11003 of match used to create the tree:
11005 t Show entries with a specific TODO keyword.
11006 m Show entries selected by a tags/property match.
11007 p Enter a property name and its value (both with completion on existing
11008 names/values) and show entries with that property.
11009 / Show entries matching a regular expression (`r' can be used as well)
11010 d Show deadlines due within `org-deadline-warning-days'.
11011 b Show deadlines and scheduled items before a date.
11012 a Show deadlines and scheduled items after a date."
11013 (interactive "P")
11014 (let (ans kwd value)
11015 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11016 (setq ans (read-char-exclusive))
11017 (cond
11018 ((equal ans ?d)
11019 (call-interactively 'org-check-deadlines))
11020 ((equal ans ?b)
11021 (call-interactively 'org-check-before-date))
11022 ((equal ans ?a)
11023 (call-interactively 'org-check-after-date))
11024 ((equal ans ?t)
11025 (org-show-todo-tree '(4)))
11026 ((member ans '(?T ?m))
11027 (call-interactively 'org-match-sparse-tree))
11028 ((member ans '(?p ?P))
11029 (setq kwd (org-icompleting-read "Property: "
11030 (mapcar 'list (org-buffer-property-keys))))
11031 (setq value (org-icompleting-read "Value: "
11032 (mapcar 'list (org-property-values kwd))))
11033 (unless (string-match "\\`{.*}\\'" value)
11034 (setq value (concat "\"" value "\"")))
11035 (org-match-sparse-tree arg (concat kwd "=" value)))
11036 ((member ans '(?r ?R ?/))
11037 (call-interactively 'org-occur))
11038 (t (error "No such sparse tree command \"%c\"" ans)))))
11040 (defvar org-occur-highlights nil
11041 "List of overlays used for occur matches.")
11042 (make-variable-buffer-local 'org-occur-highlights)
11043 (defvar org-occur-parameters nil
11044 "Parameters of the active org-occur calls.
11045 This is a list, each call to org-occur pushes as cons cell,
11046 containing the regular expression and the callback, onto the list.
11047 The list can contain several entries if `org-occur' has been called
11048 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11049 will only contain one set of parameters. When the highlights are
11050 removed (for example with `C-c C-c', or with the next edit (depending
11051 on `org-remove-highlights-with-change'), this variable is emptied
11052 as well.")
11053 (make-variable-buffer-local 'org-occur-parameters)
11055 (defun org-occur (regexp &optional keep-previous callback)
11056 "Make a compact tree which shows all matches of REGEXP.
11057 The tree will show the lines where the regexp matches, and all higher
11058 headlines above the match. It will also show the heading after the match,
11059 to make sure editing the matching entry is easy.
11060 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11061 call to `org-occur' will be kept, to allow stacking of calls to this
11062 command.
11063 If CALLBACK is non-nil, it is a function which is called to confirm
11064 that the match should indeed be shown."
11065 (interactive "sRegexp: \nP")
11066 (when (equal regexp "")
11067 (error "Regexp cannot be empty"))
11068 (unless keep-previous
11069 (org-remove-occur-highlights nil nil t))
11070 (push (cons regexp callback) org-occur-parameters)
11071 (let ((cnt 0))
11072 (save-excursion
11073 (goto-char (point-min))
11074 (if (or (not keep-previous) ; do not want to keep
11075 (not org-occur-highlights)) ; no previous matches
11076 ;; hide everything
11077 (org-overview))
11078 (while (re-search-forward regexp nil t)
11079 (when (or (not callback)
11080 (save-match-data (funcall callback)))
11081 (setq cnt (1+ cnt))
11082 (when org-highlight-sparse-tree-matches
11083 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11084 (org-show-context 'occur-tree))))
11085 (when org-remove-highlights-with-change
11086 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11087 nil 'local))
11088 (unless org-sparse-tree-open-archived-trees
11089 (org-hide-archived-subtrees (point-min) (point-max)))
11090 (run-hooks 'org-occur-hook)
11091 (if (interactive-p)
11092 (message "%d match(es) for regexp %s" cnt regexp))
11093 cnt))
11095 (defun org-show-context (&optional key)
11096 "Make sure point and context and visible.
11097 How much context is shown depends upon the variables
11098 `org-show-hierarchy-above', `org-show-following-heading'. and
11099 `org-show-siblings'."
11100 (let ((heading-p (org-on-heading-p t))
11101 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11102 (following-p (org-get-alist-option org-show-following-heading key))
11103 (entry-p (org-get-alist-option org-show-entry-below key))
11104 (siblings-p (org-get-alist-option org-show-siblings key)))
11105 (catch 'exit
11106 ;; Show heading or entry text
11107 (if (and heading-p (not entry-p))
11108 (org-flag-heading nil) ; only show the heading
11109 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11110 (org-show-hidden-entry))) ; show entire entry
11111 (when following-p
11112 ;; Show next sibling, or heading below text
11113 (save-excursion
11114 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11115 (org-flag-heading nil))))
11116 (when siblings-p (org-show-siblings))
11117 (when hierarchy-p
11118 ;; show all higher headings, possibly with siblings
11119 (save-excursion
11120 (while (and (condition-case nil
11121 (progn (org-up-heading-all 1) t)
11122 (error nil))
11123 (not (bobp)))
11124 (org-flag-heading nil)
11125 (when siblings-p (org-show-siblings))))))))
11127 (defun org-reveal (&optional siblings)
11128 "Show current entry, hierarchy above it, and the following headline.
11129 This can be used to show a consistent set of context around locations
11130 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11131 not t for the search context.
11133 With optional argument SIBLINGS, on each level of the hierarchy all
11134 siblings are shown. This repairs the tree structure to what it would
11135 look like when opened with hierarchical calls to `org-cycle'."
11136 (interactive "P")
11137 (let ((org-show-hierarchy-above t)
11138 (org-show-following-heading t)
11139 (org-show-siblings (if siblings t org-show-siblings)))
11140 (org-show-context nil)))
11142 (defun org-highlight-new-match (beg end)
11143 "Highlight from BEG to END and mark the highlight is an occur headline."
11144 (let ((ov (org-make-overlay beg end)))
11145 (org-overlay-put ov 'face 'secondary-selection)
11146 (push ov org-occur-highlights)))
11148 (defun org-remove-occur-highlights (&optional beg end noremove)
11149 "Remove the occur highlights from the buffer.
11150 BEG and END are ignored. If NOREMOVE is nil, remove this function
11151 from the `before-change-functions' in the current buffer."
11152 (interactive)
11153 (unless org-inhibit-highlight-removal
11154 (mapc 'org-delete-overlay org-occur-highlights)
11155 (setq org-occur-highlights nil)
11156 (setq org-occur-parameters nil)
11157 (unless noremove
11158 (remove-hook 'before-change-functions
11159 'org-remove-occur-highlights 'local))))
11161 ;;;; Priorities
11163 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11164 "Regular expression matching the priority indicator.")
11166 (defvar org-remove-priority-next-time nil)
11168 (defun org-priority-up ()
11169 "Increase the priority of the current item."
11170 (interactive)
11171 (org-priority 'up))
11173 (defun org-priority-down ()
11174 "Decrease the priority of the current item."
11175 (interactive)
11176 (org-priority 'down))
11178 (defun org-priority (&optional action)
11179 "Change the priority of an item by ARG.
11180 ACTION can be `set', `up', `down', or a character."
11181 (interactive)
11182 (unless org-enable-priority-commands
11183 (error "Priority commands are disabled"))
11184 (setq action (or action 'set))
11185 (let (current new news have remove)
11186 (save-excursion
11187 (org-back-to-heading t)
11188 (if (looking-at org-priority-regexp)
11189 (setq current (string-to-char (match-string 2))
11190 have t)
11191 (setq current org-default-priority))
11192 (cond
11193 ((eq action 'remove)
11194 (setq remove t new ?\ ))
11195 ((or (eq action 'set)
11196 (if (featurep 'xemacs) (characterp action) (integerp action)))
11197 (if (not (eq action 'set))
11198 (setq new action)
11199 (message "Priority %c-%c, SPC to remove: "
11200 org-highest-priority org-lowest-priority)
11201 (setq new (read-char-exclusive)))
11202 (if (and (= (upcase org-highest-priority) org-highest-priority)
11203 (= (upcase org-lowest-priority) org-lowest-priority))
11204 (setq new (upcase new)))
11205 (cond ((equal new ?\ ) (setq remove t))
11206 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11207 (error "Priority must be between `%c' and `%c'"
11208 org-highest-priority org-lowest-priority))))
11209 ((eq action 'up)
11210 (if (and (not have) (eq last-command this-command))
11211 (setq new org-lowest-priority)
11212 (setq new (if (and org-priority-start-cycle-with-default (not have))
11213 org-default-priority (1- current)))))
11214 ((eq action 'down)
11215 (if (and (not have) (eq last-command this-command))
11216 (setq new org-highest-priority)
11217 (setq new (if (and org-priority-start-cycle-with-default (not have))
11218 org-default-priority (1+ current)))))
11219 (t (error "Invalid action")))
11220 (if (or (< (upcase new) org-highest-priority)
11221 (> (upcase new) org-lowest-priority))
11222 (setq remove t))
11223 (setq news (format "%c" new))
11224 (if have
11225 (if remove
11226 (replace-match "" t t nil 1)
11227 (replace-match news t t nil 2))
11228 (if remove
11229 (error "No priority cookie found in line")
11230 (let ((case-fold-search nil))
11231 (looking-at org-todo-line-regexp))
11232 (if (match-end 2)
11233 (progn
11234 (goto-char (match-end 2))
11235 (insert " [#" news "]"))
11236 (goto-char (match-beginning 3))
11237 (insert "[#" news "] "))))
11238 (org-preserve-lc (org-set-tags nil 'align)))
11239 (if remove
11240 (message "Priority removed")
11241 (message "Priority of current item set to %s" news))))
11243 (defun org-get-priority (s)
11244 "Find priority cookie and return priority."
11245 (save-match-data
11246 (if (not (string-match org-priority-regexp s))
11247 (* 1000 (- org-lowest-priority org-default-priority))
11248 (* 1000 (- org-lowest-priority
11249 (string-to-char (match-string 2 s)))))))
11251 ;;;; Tags
11253 (defvar org-agenda-archives-mode)
11254 (defvar org-map-continue-from nil
11255 "Position from where mapping should continue.
11256 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11258 (defvar org-scanner-tags nil
11259 "The current tag list while the tags scanner is running.")
11260 (defvar org-trust-scanner-tags nil
11261 "Should `org-get-tags-at' use the tags fro the scanner.
11262 This is for internal dynamical scoping only.
11263 When this is non-nil, the function `org-get-tags-at' will return the value
11264 of `org-scanner-tags' instead of building the list by itself. This
11265 can lead to large speed-ups when the tags scanner is used in a file with
11266 many entries, and when the list of tags is retrieved, for example to
11267 obtain a list of properties. Building the tags list for each entry in such
11268 a file becomes an N^2 operation - but with this variable set, it scales
11269 as N.")
11271 (defun org-scan-tags (action matcher &optional todo-only)
11272 "Scan headline tags with inheritance and produce output ACTION.
11274 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11275 or `agenda' to produce an entry list for an agenda view. It can also be
11276 a Lisp form or a function that should be called at each matched headline, in
11277 this case the return value is a list of all return values from these calls.
11279 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11280 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11281 only lines with a TODO keyword are included in the output."
11282 (require 'org-agenda)
11283 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11284 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11285 (org-re
11286 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11287 (props (list 'face 'default
11288 'done-face 'org-agenda-done
11289 'undone-face 'default
11290 'mouse-face 'highlight
11291 'org-not-done-regexp org-not-done-regexp
11292 'org-todo-regexp org-todo-regexp
11293 'help-echo
11294 (format "mouse-2 or RET jump to org file %s"
11295 (abbreviate-file-name
11296 (or (buffer-file-name (buffer-base-buffer))
11297 (buffer-name (buffer-base-buffer)))))))
11298 (case-fold-search nil)
11299 (org-map-continue-from nil)
11300 lspos tags tags-list
11301 (tags-alist (list (cons 0 org-file-tags)))
11302 (llast 0) rtn rtn1 level category i txt
11303 todo marker entry priority)
11304 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11305 (setq action (list 'lambda nil action)))
11306 (save-excursion
11307 (goto-char (point-min))
11308 (when (eq action 'sparse-tree)
11309 (org-overview)
11310 (org-remove-occur-highlights))
11311 (while (re-search-forward re nil t)
11312 (catch :skip
11313 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11314 tags (if (match-end 4) (org-match-string-no-properties 4)))
11315 (goto-char (setq lspos (match-beginning 0)))
11316 (setq level (org-reduced-level (funcall outline-level))
11317 category (org-get-category))
11318 (setq i llast llast level)
11319 ;; remove tag lists from same and sublevels
11320 (while (>= i level)
11321 (when (setq entry (assoc i tags-alist))
11322 (setq tags-alist (delete entry tags-alist)))
11323 (setq i (1- i)))
11324 ;; add the next tags
11325 (when tags
11326 (setq tags (org-split-string tags ":")
11327 tags-alist
11328 (cons (cons level tags) tags-alist)))
11329 ;; compile tags for current headline
11330 (setq tags-list
11331 (if org-use-tag-inheritance
11332 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11333 tags)
11334 org-scanner-tags tags-list)
11335 (when org-use-tag-inheritance
11336 (setcdr (car tags-alist)
11337 (mapcar (lambda (x)
11338 (setq x (copy-sequence x))
11339 (org-add-prop-inherited x))
11340 (cdar tags-alist))))
11341 (when (and tags org-use-tag-inheritance
11342 (or (not (eq t org-use-tag-inheritance))
11343 org-tags-exclude-from-inheritance))
11344 ;; selective inheritance, remove uninherited ones
11345 (setcdr (car tags-alist)
11346 (org-remove-uniherited-tags (cdar tags-alist))))
11347 (when (and (or (not todo-only)
11348 (and (member todo org-not-done-keywords)
11349 (or (not org-agenda-tags-todo-honor-ignore-options)
11350 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11351 (let ((case-fold-search t)) (eval matcher))
11353 (not (member org-archive-tag tags-list))
11354 ;; we have an archive tag, should we use this anyway?
11355 (or (not org-agenda-skip-archived-trees)
11356 (and (eq action 'agenda) org-agenda-archives-mode))))
11357 (unless (eq action 'sparse-tree) (org-agenda-skip))
11359 ;; select this headline
11361 (cond
11362 ((eq action 'sparse-tree)
11363 (and org-highlight-sparse-tree-matches
11364 (org-get-heading) (match-end 0)
11365 (org-highlight-new-match
11366 (match-beginning 0) (match-beginning 1)))
11367 (org-show-context 'tags-tree))
11368 ((eq action 'agenda)
11369 (setq txt (org-format-agenda-item
11371 (concat
11372 (if (eq org-tags-match-list-sublevels 'indented)
11373 (make-string (1- level) ?.) "")
11374 (org-get-heading))
11375 category
11376 tags-list
11378 priority (org-get-priority txt))
11379 (goto-char lspos)
11380 (setq marker (org-agenda-new-marker))
11381 (org-add-props txt props
11382 'org-marker marker 'org-hd-marker marker 'org-category category
11383 'todo-state todo
11384 'priority priority 'type "tagsmatch")
11385 (push txt rtn))
11386 ((functionp action)
11387 (setq org-map-continue-from nil)
11388 (save-excursion
11389 (setq rtn1 (funcall action))
11390 (push rtn1 rtn)))
11391 (t (error "Invalid action")))
11393 ;; if we are to skip sublevels, jump to end of subtree
11394 (unless org-tags-match-list-sublevels
11395 (org-end-of-subtree t)
11396 (backward-char 1))))
11397 ;; Get the correct position from where to continue
11398 (if org-map-continue-from
11399 (goto-char org-map-continue-from)
11400 (and (= (point) lspos) (end-of-line 1)))))
11401 (when (and (eq action 'sparse-tree)
11402 (not org-sparse-tree-open-archived-trees))
11403 (org-hide-archived-subtrees (point-min) (point-max)))
11404 (nreverse rtn)))
11406 (defun org-remove-uniherited-tags (tags)
11407 "Remove all tags that are not inherited from the list TAGS."
11408 (cond
11409 ((eq org-use-tag-inheritance t)
11410 (if org-tags-exclude-from-inheritance
11411 (org-delete-all org-tags-exclude-from-inheritance tags)
11412 tags))
11413 ((not org-use-tag-inheritance) nil)
11414 ((stringp org-use-tag-inheritance)
11415 (delq nil (mapcar
11416 (lambda (x)
11417 (if (and (string-match org-use-tag-inheritance x)
11418 (not (member x org-tags-exclude-from-inheritance)))
11419 x nil))
11420 tags)))
11421 ((listp org-use-tag-inheritance)
11422 (delq nil (mapcar
11423 (lambda (x)
11424 (if (member x org-use-tag-inheritance) x nil))
11425 tags)))))
11427 (defvar todo-only) ;; dynamically scoped
11429 (defun org-match-sparse-tree (&optional todo-only match)
11430 "Create a sparse tree according to tags string MATCH.
11431 MATCH can contain positive and negative selection of tags, like
11432 \"+WORK+URGENT-WITHBOSS\".
11433 If optional argument TODO-ONLY is non-nil, only select lines that are
11434 also TODO lines."
11435 (interactive "P")
11436 (org-prepare-agenda-buffers (list (current-buffer)))
11437 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11439 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11441 (defvar org-cached-props nil)
11442 (defun org-cached-entry-get (pom property)
11443 (if (or (eq t org-use-property-inheritance)
11444 (and (stringp org-use-property-inheritance)
11445 (string-match org-use-property-inheritance property))
11446 (and (listp org-use-property-inheritance)
11447 (member property org-use-property-inheritance)))
11448 ;; Caching is not possible, check it directly
11449 (org-entry-get pom property 'inherit)
11450 ;; Get all properties, so that we can do complicated checks easily
11451 (cdr (assoc property (or org-cached-props
11452 (setq org-cached-props
11453 (org-entry-properties pom)))))))
11455 (defun org-global-tags-completion-table (&optional files)
11456 "Return the list of all tags in all agenda buffer/files."
11457 (save-excursion
11458 (org-uniquify
11459 (delq nil
11460 (apply 'append
11461 (mapcar
11462 (lambda (file)
11463 (set-buffer (find-file-noselect file))
11464 (append (org-get-buffer-tags)
11465 (mapcar (lambda (x) (if (stringp (car-safe x))
11466 (list (car-safe x)) nil))
11467 org-tag-alist)))
11468 (if (and files (car files))
11469 files
11470 (org-agenda-files))))))))
11472 (defun org-make-tags-matcher (match)
11473 "Create the TAGS//TODO matcher form for the selection string MATCH."
11474 ;; todo-only is scoped dynamically into this function, and the function
11475 ;; may change it if the matcher asks for it.
11476 (unless match
11477 ;; Get a new match request, with completion
11478 (let ((org-last-tags-completion-table
11479 (org-global-tags-completion-table)))
11480 (setq match (org-completing-read-no-i
11481 "Match: " 'org-tags-completion-function nil nil nil
11482 'org-tags-history))))
11484 ;; Parse the string and create a lisp form
11485 (let ((match0 match)
11486 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11487 minus tag mm
11488 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11489 orterms term orlist re-p str-p level-p level-op time-p
11490 prop-p pn pv po cat-p gv rest)
11491 (if (string-match "/+" match)
11492 ;; match contains also a todo-matching request
11493 (progn
11494 (setq tagsmatch (substring match 0 (match-beginning 0))
11495 todomatch (substring match (match-end 0)))
11496 (if (string-match "^!" todomatch)
11497 (setq todo-only t todomatch (substring todomatch 1)))
11498 (if (string-match "^\\s-*$" todomatch)
11499 (setq todomatch nil)))
11500 ;; only matching tags
11501 (setq tagsmatch match todomatch nil))
11503 ;; Make the tags matcher
11504 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11505 (setq tagsmatcher t)
11506 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11507 (while (setq term (pop orterms))
11508 (while (and (equal (substring term -1) "\\") orterms)
11509 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11510 (while (string-match re term)
11511 (setq rest (substring term (match-end 0))
11512 minus (and (match-end 1)
11513 (equal (match-string 1 term) "-"))
11514 tag (match-string 2 term)
11515 re-p (equal (string-to-char tag) ?{)
11516 level-p (match-end 4)
11517 prop-p (match-end 5)
11518 mm (cond
11519 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11520 (level-p
11521 (setq level-op (org-op-to-function (match-string 3 term)))
11522 `(,level-op level ,(string-to-number
11523 (match-string 4 term))))
11524 (prop-p
11525 (setq pn (match-string 5 term)
11526 po (match-string 6 term)
11527 pv (match-string 7 term)
11528 cat-p (equal pn "CATEGORY")
11529 re-p (equal (string-to-char pv) ?{)
11530 str-p (equal (string-to-char pv) ?\")
11531 time-p (save-match-data
11532 (string-match "^\"[[<].*[]>]\"$" pv))
11533 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11534 (if time-p (setq pv (org-matcher-time pv)))
11535 (setq po (org-op-to-function po (if time-p 'time str-p)))
11536 (cond
11537 ((equal pn "CATEGORY")
11538 (setq gv '(get-text-property (point) 'org-category)))
11539 ((equal pn "TODO")
11540 (setq gv 'todo))
11542 (setq gv `(org-cached-entry-get nil ,pn))))
11543 (if re-p
11544 (if (eq po 'org<>)
11545 `(not (string-match ,pv (or ,gv "")))
11546 `(string-match ,pv (or ,gv "")))
11547 (if str-p
11548 `(,po (or ,gv "") ,pv)
11549 `(,po (string-to-number (or ,gv ""))
11550 ,(string-to-number pv) ))))
11551 (t `(member ,tag tags-list)))
11552 mm (if minus (list 'not mm) mm)
11553 term rest)
11554 (push mm tagsmatcher))
11555 (push (if (> (length tagsmatcher) 1)
11556 (cons 'and tagsmatcher)
11557 (car tagsmatcher))
11558 orlist)
11559 (setq tagsmatcher nil))
11560 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11561 (setq tagsmatcher
11562 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11563 ;; Make the todo matcher
11564 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11565 (setq todomatcher t)
11566 (setq orterms (org-split-string todomatch "|") orlist nil)
11567 (while (setq term (pop orterms))
11568 (while (string-match re term)
11569 (setq minus (and (match-end 1)
11570 (equal (match-string 1 term) "-"))
11571 kwd (match-string 2 term)
11572 re-p (equal (string-to-char kwd) ?{)
11573 term (substring term (match-end 0))
11574 mm (if re-p
11575 `(string-match ,(substring kwd 1 -1) todo)
11576 (list 'equal 'todo kwd))
11577 mm (if minus (list 'not mm) mm))
11578 (push mm todomatcher))
11579 (push (if (> (length todomatcher) 1)
11580 (cons 'and todomatcher)
11581 (car todomatcher))
11582 orlist)
11583 (setq todomatcher nil))
11584 (setq todomatcher (if (> (length orlist) 1)
11585 (cons 'or orlist) (car orlist))))
11587 ;; Return the string and lisp forms of the matcher
11588 (setq matcher (if todomatcher
11589 (list 'and tagsmatcher todomatcher)
11590 tagsmatcher))
11591 (cons match0 matcher)))
11593 (defun org-op-to-function (op &optional stringp)
11594 "Turn an operator into the appropriate function."
11595 (setq op
11596 (cond
11597 ((equal op "<" ) '(< string< org-time<))
11598 ((equal op ">" ) '(> org-string> org-time>))
11599 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11600 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11601 ((member op '("=" "==")) '(= string= org-time=))
11602 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11603 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11605 (defun org<> (a b) (not (= a b)))
11606 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11607 (defun org-string>= (a b) (not (string< a b)))
11608 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11609 (defun org-string<> (a b) (not (string= a b)))
11610 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11611 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11612 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11613 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11614 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11615 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11616 (defun org-2ft (s)
11617 "Convert S to a floating point time.
11618 If S is already a number, just return it. If it is a string, parse
11619 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11620 (cond
11621 ((numberp s) s)
11622 ((stringp s)
11623 (condition-case nil
11624 (float-time (apply 'encode-time (org-parse-time-string s)))
11625 (error 0.)))
11626 (t 0.)))
11628 (defun org-time-today ()
11629 "Time in seconds today at 0:00.
11630 Returns the float number of seconds since the beginning of the
11631 epoch to the beginning of today (00:00)."
11632 (float-time (apply 'encode-time
11633 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11635 (defun org-matcher-time (s)
11636 "Interpret a time comparison value."
11637 (save-match-data
11638 (cond
11639 ((string= s "<now>") (float-time))
11640 ((string= s "<today>") (org-time-today))
11641 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11642 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11643 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11644 (+ (org-time-today)
11645 (* (string-to-number (match-string 1 s))
11646 (cdr (assoc (match-string 2 s)
11647 '(("d" . 86400.0) ("w" . 604800.0)
11648 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11649 (t (org-2ft s)))))
11651 (defun org-match-any-p (re list)
11652 "Does re match any element of list?"
11653 (setq list (mapcar (lambda (x) (string-match re x)) list))
11654 (delq nil list))
11656 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11657 (defvar org-tags-overlay (org-make-overlay 1 1))
11658 (org-detach-overlay org-tags-overlay)
11660 (defun org-get-local-tags-at (&optional pos)
11661 "Get a list of tags defined in the current headline."
11662 (org-get-tags-at pos 'local))
11664 (defun org-get-local-tags ()
11665 "Get a list of tags defined in the current headline."
11666 (org-get-tags-at nil 'local))
11668 (defun org-get-tags-at (&optional pos local)
11669 "Get a list of all headline tags applicable at POS.
11670 POS defaults to point. If tags are inherited, the list contains
11671 the targets in the same sequence as the headlines appear, i.e.
11672 the tags of the current headline come last.
11673 When LOCAL is non-nil, only return tags from the current headline,
11674 ignore inherited ones."
11675 (interactive)
11676 (if (and org-trust-scanner-tags
11677 (or (not pos) (equal pos (point)))
11678 (not local))
11679 org-scanner-tags
11680 (let (tags ltags lastpos parent)
11681 (save-excursion
11682 (save-restriction
11683 (widen)
11684 (goto-char (or pos (point)))
11685 (save-match-data
11686 (catch 'done
11687 (condition-case nil
11688 (progn
11689 (org-back-to-heading t)
11690 (while (not (equal lastpos (point)))
11691 (setq lastpos (point))
11692 (when (looking-at
11693 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11694 (setq ltags (org-split-string
11695 (org-match-string-no-properties 1) ":"))
11696 (when parent
11697 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11698 (setq tags (append
11699 (if parent
11700 (org-remove-uniherited-tags ltags)
11701 ltags)
11702 tags)))
11703 (or org-use-tag-inheritance (throw 'done t))
11704 (if local (throw 'done t))
11705 (or (org-up-heading-safe) (error nil))
11706 (setq parent t)))
11707 (error nil)))))
11708 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11710 (defun org-add-prop-inherited (s)
11711 (add-text-properties 0 (length s) '(inherited t) s)
11714 (defun org-toggle-tag (tag &optional onoff)
11715 "Toggle the tag TAG for the current line.
11716 If ONOFF is `on' or `off', don't toggle but set to this state."
11717 (let (res current)
11718 (save-excursion
11719 (org-back-to-heading t)
11720 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11721 (point-at-eol) t)
11722 (progn
11723 (setq current (match-string 1))
11724 (replace-match ""))
11725 (setq current ""))
11726 (setq current (nreverse (org-split-string current ":")))
11727 (cond
11728 ((eq onoff 'on)
11729 (setq res t)
11730 (or (member tag current) (push tag current)))
11731 ((eq onoff 'off)
11732 (or (not (member tag current)) (setq current (delete tag current))))
11733 (t (if (member tag current)
11734 (setq current (delete tag current))
11735 (setq res t)
11736 (push tag current))))
11737 (end-of-line 1)
11738 (if current
11739 (progn
11740 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11741 (org-set-tags nil t))
11742 (delete-horizontal-space))
11743 (run-hooks 'org-after-tags-change-hook))
11744 res))
11746 (defun org-align-tags-here (to-col)
11747 ;; Assumes that this is a headline
11748 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11749 (beginning-of-line 1)
11750 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11751 (< pos (match-beginning 2)))
11752 (progn
11753 (setq tags-l (- (match-end 2) (match-beginning 2)))
11754 (goto-char (match-beginning 1))
11755 (insert " ")
11756 (delete-region (point) (1+ (match-beginning 2)))
11757 (setq ncol (max (1+ (current-column))
11758 (1+ col)
11759 (if (> to-col 0)
11760 to-col
11761 (- (abs to-col) tags-l))))
11762 (setq p (point))
11763 (insert (make-string (- ncol (current-column)) ?\ ))
11764 (setq ncol (current-column))
11765 (when indent-tabs-mode (tabify p (point-at-eol)))
11766 (org-move-to-column (min ncol col) t))
11767 (goto-char pos))))
11769 (defun org-set-tags-command (&optional arg just-align)
11770 "Call the set-tags command for the current entry."
11771 (interactive "P")
11772 (if (org-on-heading-p)
11773 (org-set-tags arg just-align)
11774 (save-excursion
11775 (org-back-to-heading t)
11776 (org-set-tags arg just-align))))
11778 (defun org-set-tags-to (data)
11779 "Set the tags of the current entry to DATA, replacing the current tags.
11780 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11781 If DATA is nil or the empty string, any tags will be removed."
11782 (interactive "sTags: ")
11783 (setq data
11784 (cond
11785 ((eq data nil) "")
11786 ((equal data "") "")
11787 ((stringp data)
11788 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11789 ":"))
11790 ((listp data)
11791 (concat ":" (mapconcat 'identity data ":") ":"))
11792 (t nil)))
11793 (when data
11794 (save-excursion
11795 (org-back-to-heading t)
11796 (when (looking-at org-complex-heading-regexp)
11797 (if (match-end 5)
11798 (progn
11799 (goto-char (match-beginning 5))
11800 (insert data)
11801 (delete-region (point) (point-at-eol))
11802 (org-set-tags nil 'align))
11803 (goto-char (point-at-eol))
11804 (insert " " data)
11805 (org-set-tags nil 'align)))
11806 (beginning-of-line 1)
11807 (if (looking-at ".*?\\([ \t]+\\)$")
11808 (delete-region (match-beginning 1) (match-end 1))))))
11810 (defun org-set-tags (&optional arg just-align)
11811 "Set the tags for the current headline.
11812 With prefix ARG, realign all tags in headings in the current buffer."
11813 (interactive "P")
11814 (let* ((re (concat "^" outline-regexp))
11815 (current (org-get-tags-string))
11816 (col (current-column))
11817 (org-setting-tags t)
11818 table current-tags inherited-tags ; computed below when needed
11819 tags p0 c0 c1 rpl)
11820 (if arg
11821 (save-excursion
11822 (goto-char (point-min))
11823 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11824 (while (re-search-forward re nil t)
11825 (org-set-tags nil t)
11826 (end-of-line 1)))
11827 (message "All tags realigned to column %d" org-tags-column))
11828 (if just-align
11829 (setq tags current)
11830 ;; Get a new set of tags from the user
11831 (save-excursion
11832 (setq table (append org-tag-persistent-alist
11833 (or org-tag-alist (org-get-buffer-tags))
11834 (and org-complete-tags-always-offer-all-agenda-tags
11835 (org-global-tags-completion-table (org-agenda-files))))
11836 org-last-tags-completion-table table
11837 current-tags (org-split-string current ":")
11838 inherited-tags (nreverse
11839 (nthcdr (length current-tags)
11840 (nreverse (org-get-tags-at))))
11841 tags
11842 (if (or (eq t org-use-fast-tag-selection)
11843 (and org-use-fast-tag-selection
11844 (delq nil (mapcar 'cdr table))))
11845 (org-fast-tag-selection
11846 current-tags inherited-tags table
11847 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11848 (let ((org-add-colon-after-tag-completion t))
11849 (org-trim
11850 (org-without-partial-completion
11851 (org-icompleting-read "Tags: " 'org-tags-completion-function
11852 nil nil current 'org-tags-history)))))))
11853 (while (string-match "[-+&]+" tags)
11854 ;; No boolean logic, just a list
11855 (setq tags (replace-match ":" t t tags))))
11857 (if org-tags-sort-function
11858 (setq tags (mapconcat 'identity
11859 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11860 org-tags-sort-function) ":")))
11862 (if (string-match "\\`[\t ]*\\'" tags)
11863 (setq tags "")
11864 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11865 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11867 ;; Insert new tags at the correct column
11868 (beginning-of-line 1)
11869 (cond
11870 ((and (equal current "") (equal tags "")))
11871 ((re-search-forward
11872 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11873 (point-at-eol) t)
11874 (if (equal tags "")
11875 (setq rpl "")
11876 (goto-char (match-beginning 0))
11877 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11878 (1+ (point)) (point))
11879 c1 (max (1+ c0) (if (> org-tags-column 0)
11880 org-tags-column
11881 (- (- org-tags-column) (length tags))))
11882 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11883 (replace-match rpl t t)
11884 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11885 tags)
11886 (t (error "Tags alignment failed")))
11887 (org-move-to-column col)
11888 (unless just-align
11889 (run-hooks 'org-after-tags-change-hook)))))
11891 (defun org-change-tag-in-region (beg end tag off)
11892 "Add or remove TAG for each entry in the region.
11893 This works in the agenda, and also in an org-mode buffer."
11894 (interactive
11895 (list (region-beginning) (region-end)
11896 (let ((org-last-tags-completion-table
11897 (if (org-mode-p)
11898 (org-get-buffer-tags)
11899 (org-global-tags-completion-table))))
11900 (org-icompleting-read
11901 "Tag: " 'org-tags-completion-function nil nil nil
11902 'org-tags-history))
11903 (progn
11904 (message "[s]et or [r]emove? ")
11905 (equal (read-char-exclusive) ?r))))
11906 (if (fboundp 'deactivate-mark) (deactivate-mark))
11907 (let ((agendap (equal major-mode 'org-agenda-mode))
11908 l1 l2 m buf pos newhead (cnt 0))
11909 (goto-char end)
11910 (setq l2 (1- (org-current-line)))
11911 (goto-char beg)
11912 (setq l1 (org-current-line))
11913 (loop for l from l1 to l2 do
11914 (org-goto-line l)
11915 (setq m (get-text-property (point) 'org-hd-marker))
11916 (when (or (and (org-mode-p) (org-on-heading-p))
11917 (and agendap m))
11918 (setq buf (if agendap (marker-buffer m) (current-buffer))
11919 pos (if agendap m (point)))
11920 (with-current-buffer buf
11921 (save-excursion
11922 (save-restriction
11923 (goto-char pos)
11924 (setq cnt (1+ cnt))
11925 (org-toggle-tag tag (if off 'off 'on))
11926 (setq newhead (org-get-heading)))))
11927 (and agendap (org-agenda-change-all-lines newhead m))))
11928 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11930 (defun org-tags-completion-function (string predicate &optional flag)
11931 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11932 (confirm (lambda (x) (stringp (car x)))))
11933 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11934 (setq s1 (match-string 1 string)
11935 s2 (match-string 2 string))
11936 (setq s1 "" s2 string))
11937 (cond
11938 ((eq flag nil)
11939 ;; try completion
11940 (setq rtn (try-completion s2 ctable confirm))
11941 (if (stringp rtn)
11942 (setq rtn
11943 (concat s1 s2 (substring rtn (length s2))
11944 (if (and org-add-colon-after-tag-completion
11945 (assoc rtn ctable))
11946 ":" ""))))
11947 rtn)
11948 ((eq flag t)
11949 ;; all-completions
11950 (all-completions s2 ctable confirm)
11952 ((eq flag 'lambda)
11953 ;; exact match?
11954 (assoc s2 ctable)))
11957 (defun org-fast-tag-insert (kwd tags face &optional end)
11958 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11959 (insert (format "%-12s" (concat kwd ":"))
11960 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11961 (or end "")))
11963 (defun org-fast-tag-show-exit (flag)
11964 (save-excursion
11965 (org-goto-line 3)
11966 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11967 (replace-match ""))
11968 (when flag
11969 (end-of-line 1)
11970 (org-move-to-column (- (window-width) 19) t)
11971 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11973 (defun org-set-current-tags-overlay (current prefix)
11974 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11975 (if (featurep 'xemacs)
11976 (org-overlay-display org-tags-overlay (concat prefix s)
11977 'secondary-selection)
11978 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11979 (org-overlay-display org-tags-overlay (concat prefix s)))))
11981 (defvar org-last-tag-selection-key nil)
11982 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11983 "Fast tag selection with single keys.
11984 CURRENT is the current list of tags in the headline, INHERITED is the
11985 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11986 possibly with grouping information. TODO-TABLE is a similar table with
11987 TODO keywords, should these have keys assigned to them.
11988 If the keys are nil, a-z are automatically assigned.
11989 Returns the new tags string, or nil to not change the current settings."
11990 (let* ((fulltable (append table todo-table))
11991 (maxlen (apply 'max (mapcar
11992 (lambda (x)
11993 (if (stringp (car x)) (string-width (car x)) 0))
11994 fulltable)))
11995 (buf (current-buffer))
11996 (expert (eq org-fast-tag-selection-single-key 'expert))
11997 (buffer-tags nil)
11998 (fwidth (+ maxlen 3 1 3))
11999 (ncol (/ (- (window-width) 4) fwidth))
12000 (i-face 'org-done)
12001 (c-face 'org-todo)
12002 tg cnt e c char c1 c2 ntable tbl rtn
12003 ov-start ov-end ov-prefix
12004 (exit-after-next org-fast-tag-selection-single-key)
12005 (done-keywords org-done-keywords)
12006 groups ingroup)
12007 (save-excursion
12008 (beginning-of-line 1)
12009 (if (looking-at
12010 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12011 (setq ov-start (match-beginning 1)
12012 ov-end (match-end 1)
12013 ov-prefix "")
12014 (setq ov-start (1- (point-at-eol))
12015 ov-end (1+ ov-start))
12016 (skip-chars-forward "^\n\r")
12017 (setq ov-prefix
12018 (concat
12019 (buffer-substring (1- (point)) (point))
12020 (if (> (current-column) org-tags-column)
12022 (make-string (- org-tags-column (current-column)) ?\ ))))))
12023 (org-move-overlay org-tags-overlay ov-start ov-end)
12024 (save-window-excursion
12025 (if expert
12026 (set-buffer (get-buffer-create " *Org tags*"))
12027 (delete-other-windows)
12028 (split-window-vertically)
12029 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12030 (erase-buffer)
12031 (org-set-local 'org-done-keywords done-keywords)
12032 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12033 (org-fast-tag-insert "Current" current c-face "\n\n")
12034 (org-fast-tag-show-exit exit-after-next)
12035 (org-set-current-tags-overlay current ov-prefix)
12036 (setq tbl fulltable char ?a cnt 0)
12037 (while (setq e (pop tbl))
12038 (cond
12039 ((equal (car e) :startgroup)
12040 (push '() groups) (setq ingroup t)
12041 (when (not (= cnt 0))
12042 (setq cnt 0)
12043 (insert "\n"))
12044 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12045 ((equal (car e) :endgroup)
12046 (setq ingroup nil cnt 0)
12047 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12048 ((equal e '(:newline))
12049 (when (not (= cnt 0))
12050 (setq cnt 0)
12051 (insert "\n")
12052 (setq e (car tbl))
12053 (while (equal (car tbl) '(:newline))
12054 (insert "\n")
12055 (setq tbl (cdr tbl)))))
12057 (setq tg (copy-sequence (car e)) c2 nil)
12058 (if (cdr e)
12059 (setq c (cdr e))
12060 ;; automatically assign a character.
12061 (setq c1 (string-to-char
12062 (downcase (substring
12063 tg (if (= (string-to-char tg) ?@) 1 0)))))
12064 (if (or (rassoc c1 ntable) (rassoc c1 table))
12065 (while (or (rassoc char ntable) (rassoc char table))
12066 (setq char (1+ char)))
12067 (setq c2 c1))
12068 (setq c (or c2 char)))
12069 (if ingroup (push tg (car groups)))
12070 (setq tg (org-add-props tg nil 'face
12071 (cond
12072 ((not (assoc tg table))
12073 (org-get-todo-face tg))
12074 ((member tg current) c-face)
12075 ((member tg inherited) i-face)
12076 (t nil))))
12077 (if (and (= cnt 0) (not ingroup)) (insert " "))
12078 (insert "[" c "] " tg (make-string
12079 (- fwidth 4 (length tg)) ?\ ))
12080 (push (cons tg c) ntable)
12081 (when (= (setq cnt (1+ cnt)) ncol)
12082 (insert "\n")
12083 (if ingroup (insert " "))
12084 (setq cnt 0)))))
12085 (setq ntable (nreverse ntable))
12086 (insert "\n")
12087 (goto-char (point-min))
12088 (if (not expert) (org-fit-window-to-buffer))
12089 (setq rtn
12090 (catch 'exit
12091 (while t
12092 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12093 (if (not groups) "no " "")
12094 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12095 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12096 (setq org-last-tag-selection-key c)
12097 (cond
12098 ((= c ?\r) (throw 'exit t))
12099 ((= c ?!)
12100 (setq groups (not groups))
12101 (goto-char (point-min))
12102 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12103 ((= c ?\C-c)
12104 (if (not expert)
12105 (org-fast-tag-show-exit
12106 (setq exit-after-next (not exit-after-next)))
12107 (setq expert nil)
12108 (delete-other-windows)
12109 (split-window-vertically)
12110 (org-switch-to-buffer-other-window " *Org tags*")
12111 (org-fit-window-to-buffer)))
12112 ((or (= c ?\C-g)
12113 (and (= c ?q) (not (rassoc c ntable))))
12114 (org-detach-overlay org-tags-overlay)
12115 (setq quit-flag t))
12116 ((= c ?\ )
12117 (setq current nil)
12118 (if exit-after-next (setq exit-after-next 'now)))
12119 ((= c ?\t)
12120 (condition-case nil
12121 (setq tg (org-icompleting-read
12122 "Tag: "
12123 (or buffer-tags
12124 (with-current-buffer buf
12125 (org-get-buffer-tags)))))
12126 (quit (setq tg "")))
12127 (when (string-match "\\S-" tg)
12128 (add-to-list 'buffer-tags (list tg))
12129 (if (member tg current)
12130 (setq current (delete tg current))
12131 (push tg current)))
12132 (if exit-after-next (setq exit-after-next 'now)))
12133 ((setq e (rassoc c todo-table) tg (car e))
12134 (with-current-buffer buf
12135 (save-excursion (org-todo tg)))
12136 (if exit-after-next (setq exit-after-next 'now)))
12137 ((setq e (rassoc c ntable) tg (car e))
12138 (if (member tg current)
12139 (setq current (delete tg current))
12140 (loop for g in groups do
12141 (if (member tg g)
12142 (mapc (lambda (x)
12143 (setq current (delete x current)))
12144 g)))
12145 (push tg current))
12146 (if exit-after-next (setq exit-after-next 'now))))
12148 ;; Create a sorted list
12149 (setq current
12150 (sort current
12151 (lambda (a b)
12152 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12153 (if (eq exit-after-next 'now) (throw 'exit t))
12154 (goto-char (point-min))
12155 (beginning-of-line 2)
12156 (delete-region (point) (point-at-eol))
12157 (org-fast-tag-insert "Current" current c-face)
12158 (org-set-current-tags-overlay current ov-prefix)
12159 (while (re-search-forward
12160 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12161 (setq tg (match-string 1))
12162 (add-text-properties
12163 (match-beginning 1) (match-end 1)
12164 (list 'face
12165 (cond
12166 ((member tg current) c-face)
12167 ((member tg inherited) i-face)
12168 (t (get-text-property (match-beginning 1) 'face))))))
12169 (goto-char (point-min)))))
12170 (org-detach-overlay org-tags-overlay)
12171 (if rtn
12172 (mapconcat 'identity current ":")
12173 nil))))
12175 (defun org-get-tags-string ()
12176 "Get the TAGS string in the current headline."
12177 (unless (org-on-heading-p t)
12178 (error "Not on a heading"))
12179 (save-excursion
12180 (beginning-of-line 1)
12181 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12182 (org-match-string-no-properties 1)
12183 "")))
12185 (defun org-get-tags ()
12186 "Get the list of tags specified in the current headline."
12187 (org-split-string (org-get-tags-string) ":"))
12189 (defun org-get-buffer-tags ()
12190 "Get a table of all tags used in the buffer, for completion."
12191 (let (tags)
12192 (save-excursion
12193 (goto-char (point-min))
12194 (while (re-search-forward
12195 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12196 (when (equal (char-after (point-at-bol 0)) ?*)
12197 (mapc (lambda (x) (add-to-list 'tags x))
12198 (org-split-string (org-match-string-no-properties 1) ":")))))
12199 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12200 (mapcar 'list tags)))
12202 ;;;; The mapping API
12204 ;;;###autoload
12205 (defun org-map-entries (func &optional match scope &rest skip)
12206 "Call FUNC at each headline selected by MATCH in SCOPE.
12208 FUNC is a function or a lisp form. The function will be called without
12209 arguments, with the cursor positioned at the beginning of the headline.
12210 The return values of all calls to the function will be collected and
12211 returned as a list.
12213 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12214 does not need to preserve point. After evaluation, the cursor will be
12215 moved to the end of the line (presumably of the headline of the
12216 processed entry) and search continues from there. Under some
12217 circumstances, this may not produce the wanted results. For example,
12218 if you have removed (e.g. archived) the current (sub)tree it could
12219 mean that the next entry will be skipped entirely. In such cases, you
12220 can specify the position from where search should continue by making
12221 FUNC set the variable `org-map-continue-from' to the desired buffer
12222 position.
12224 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12225 Only headlines that are matched by this query will be considered during
12226 the iteration. When MATCH is nil or t, all headlines will be
12227 visited by the iteration.
12229 SCOPE determines the scope of this command. It can be any of:
12231 nil The current buffer, respecting the restriction if any
12232 tree The subtree started with the entry at point
12233 file The current buffer, without restriction
12234 file-with-archives
12235 The current buffer, and any archives associated with it
12236 agenda All agenda files
12237 agenda-with-archives
12238 All agenda files with any archive files associated with them
12239 \(file1 file2 ...)
12240 If this is a list, all files in the list will be scanned
12242 The remaining args are treated as settings for the skipping facilities of
12243 the scanner. The following items can be given here:
12245 archive skip trees with the archive tag.
12246 comment skip trees with the COMMENT keyword
12247 function or Emacs Lisp form:
12248 will be used as value for `org-agenda-skip-function', so whenever
12249 the function returns t, FUNC will not be called for that
12250 entry and search will continue from the point where the
12251 function leaves it.
12253 If your function needs to retrieve the tags including inherited tags
12254 at the *current* entry, you can use the value of the variable
12255 `org-scanner-tags' which will be much faster than getting the value
12256 with `org-get-tags-at'. If your function gets properties with
12257 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12258 to t around the call to `org-entry-properties' to get the same speedup.
12259 Note that if your function moves around to retrieve tags and properties at
12260 a *different* entry, you cannot use these techniques."
12261 (let* ((org-agenda-archives-mode nil) ; just to make sure
12262 (org-agenda-skip-archived-trees (memq 'archive skip))
12263 (org-agenda-skip-comment-trees (memq 'comment skip))
12264 (org-agenda-skip-function
12265 (car (org-delete-all '(comment archive) skip)))
12266 (org-tags-match-list-sublevels t)
12267 matcher file res
12268 org-todo-keywords-for-agenda
12269 org-done-keywords-for-agenda
12270 org-todo-keyword-alist-for-agenda
12271 org-drawers-for-agenda
12272 org-tag-alist-for-agenda)
12274 (cond
12275 ((eq match t) (setq matcher t))
12276 ((eq match nil) (setq matcher t))
12277 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12279 (save-excursion
12280 (save-restriction
12281 (when (eq scope 'tree)
12282 (org-back-to-heading t)
12283 (org-narrow-to-subtree)
12284 (setq scope nil))
12286 (if (not scope)
12287 (progn
12288 (org-prepare-agenda-buffers
12289 (list (buffer-file-name (current-buffer))))
12290 (setq res (org-scan-tags func matcher)))
12291 ;; Get the right scope
12292 (cond
12293 ((and scope (listp scope) (symbolp (car scope)))
12294 (setq scope (eval scope)))
12295 ((eq scope 'agenda)
12296 (setq scope (org-agenda-files t)))
12297 ((eq scope 'agenda-with-archives)
12298 (setq scope (org-agenda-files t))
12299 (setq scope (org-add-archive-files scope)))
12300 ((eq scope 'file)
12301 (setq scope (list (buffer-file-name))))
12302 ((eq scope 'file-with-archives)
12303 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12304 (org-prepare-agenda-buffers scope)
12305 (while (setq file (pop scope))
12306 (with-current-buffer (org-find-base-buffer-visiting file)
12307 (save-excursion
12308 (save-restriction
12309 (widen)
12310 (goto-char (point-min))
12311 (setq res (append res (org-scan-tags func matcher))))))))))
12312 res))
12314 ;;;; Properties
12316 ;;; Setting and retrieving properties
12318 (defconst org-special-properties
12319 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12320 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12321 "The special properties valid in Org-mode.
12323 These are properties that are not defined in the property drawer,
12324 but in some other way.")
12326 (defconst org-default-properties
12327 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12328 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12329 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12330 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12331 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12332 "CLOCK_MODELINE_TOTAL" "STYLE")
12333 "Some properties that are used by Org-mode for various purposes.
12334 Being in this list makes sure that they are offered for completion.")
12336 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12337 "Regular expression matching the first line of a property drawer.")
12339 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12340 "Regular expression matching the first line of a property drawer.")
12342 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12343 "Regular expression matching the first line of a property drawer.")
12345 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12346 "Regular expression matching the first line of a property drawer.")
12348 (defconst org-property-drawer-re
12349 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12350 org-property-end-re "\\)\n?")
12351 "Matches an entire property drawer.")
12353 (defconst org-clock-drawer-re
12354 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12355 org-property-end-re "\\)\n?")
12356 "Matches an entire clock drawer.")
12358 (defun org-property-action ()
12359 "Do an action on properties."
12360 (interactive)
12361 (let (c)
12362 (org-at-property-p)
12363 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12364 (setq c (read-char-exclusive))
12365 (cond
12366 ((equal c ?s)
12367 (call-interactively 'org-set-property))
12368 ((equal c ?d)
12369 (call-interactively 'org-delete-property))
12370 ((equal c ?D)
12371 (call-interactively 'org-delete-property-globally))
12372 ((equal c ?c)
12373 (call-interactively 'org-compute-property-at-point))
12374 (t (error "No such property action %c" c)))))
12376 (defun org-set-effort (&optional value)
12377 "Set the effort property of the current entry.
12378 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12379 allowed value."
12380 (interactive "P")
12381 (if (equal value 0) (setq value 10))
12382 (let* ((completion-ignore-case t)
12383 (prop org-effort-property)
12384 (cur (org-entry-get nil prop))
12385 (allowed (org-property-get-allowed-values nil prop 'table))
12386 (existing (mapcar 'list (org-property-values prop)))
12388 (val (cond
12389 ((stringp value) value)
12390 ((and allowed (integerp value))
12391 (or (car (nth (1- value) allowed))
12392 (car (org-last allowed))))
12393 (allowed
12394 (message "Select 1-9,0, [RET%s]: %s"
12395 (if cur (concat "=" cur) "")
12396 (mapconcat 'car allowed " "))
12397 (setq rpl (read-char-exclusive))
12398 (if (equal rpl ?\r)
12400 (setq rpl (- rpl ?0))
12401 (if (equal rpl 0) (setq rpl 10))
12402 (if (and (> rpl 0) (<= rpl (length allowed)))
12403 (car (nth (1- rpl) allowed))
12404 (org-completing-read "Effort: " allowed nil))))
12406 (let (org-completion-use-ido org-completion-use-iswitchb)
12407 (org-completing-read
12408 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12409 (concat "[" cur "]") "")
12410 ": ")
12411 existing nil nil "" nil cur))))))
12412 (unless (equal (org-entry-get nil prop) val)
12413 (org-entry-put nil prop val))
12414 (message "%s is now %s" prop val)))
12416 (defun org-at-property-p ()
12417 "Is the cursor in a property line?"
12418 ;; FIXME: Does not check if we are actually in the drawer.
12419 ;; FIXME: also returns true on any drawers.....
12420 ;; This is used by C-c C-c for property action.
12421 (save-excursion
12422 (beginning-of-line 1)
12423 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12425 (defun org-get-property-block (&optional beg end force)
12426 "Return the (beg . end) range of the body of the property drawer.
12427 BEG and END can be beginning and end of subtree, if not given
12428 they will be found.
12429 If the drawer does not exist and FORCE is non-nil, create the drawer."
12430 (catch 'exit
12431 (save-excursion
12432 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12433 (end (or end (progn (outline-next-heading) (point)))))
12434 (goto-char beg)
12435 (if (re-search-forward org-property-start-re end t)
12436 (setq beg (1+ (match-end 0)))
12437 (if force
12438 (save-excursion
12439 (org-insert-property-drawer)
12440 (setq end (progn (outline-next-heading) (point))))
12441 (throw 'exit nil))
12442 (goto-char beg)
12443 (if (re-search-forward org-property-start-re end t)
12444 (setq beg (1+ (match-end 0)))))
12445 (if (re-search-forward org-property-end-re end t)
12446 (setq end (match-beginning 0))
12447 (or force (throw 'exit nil))
12448 (goto-char beg)
12449 (setq end beg)
12450 (org-indent-line-function)
12451 (insert ":END:\n"))
12452 (cons beg end)))))
12454 (defun org-entry-properties (&optional pom which specific)
12455 "Get all properties of the entry at point-or-marker POM.
12456 This includes the TODO keyword, the tags, time strings for deadline,
12457 scheduled, and clocking, and any additional properties defined in the
12458 entry. The return value is an alist, keys may occur multiple times
12459 if the property key was used several times.
12460 POM may also be nil, in which case the current entry is used.
12461 If WHICH is nil or `all', get all properties. If WHICH is
12462 `special' or `standard', only get that subclass. If WHICH
12463 is a string only get exactly this property. Specific can be a sting, the
12464 specific property we are interested in. Specifying it can speed
12465 things up because then unnecessary parsing is avoided."
12466 (setq which (or which 'all))
12467 (org-with-point-at pom
12468 (let ((clockstr (substring org-clock-string 0 -1))
12469 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12470 beg end range props sum-props key value string clocksum)
12471 (save-excursion
12472 (when (condition-case nil
12473 (and (org-mode-p) (org-back-to-heading t))
12474 (error nil))
12475 (setq beg (point))
12476 (setq sum-props (get-text-property (point) 'org-summaries))
12477 (setq clocksum (get-text-property (point) :org-clock-minutes))
12478 (outline-next-heading)
12479 (setq end (point))
12480 (when (memq which '(all special))
12481 ;; Get the special properties, like TODO and tags
12482 (goto-char beg)
12483 (when (and (or (not specific) (string= specific "TODO"))
12484 (looking-at org-todo-line-regexp) (match-end 2))
12485 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12486 (when (and (or (not specific) (string= specific "PRIORITY"))
12487 (looking-at org-priority-regexp))
12488 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12489 (when (and (or (not specific) (string= specific "TAGS"))
12490 (setq value (org-get-tags-string))
12491 (string-match "\\S-" value))
12492 (push (cons "TAGS" value) props))
12493 (when (and (or (not specific) (string= specific "TAGS"))
12494 (setq value (org-get-tags-at)))
12495 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12496 ":"))
12497 props))
12498 (when (or (not specific) (string= specific "TAGS"))
12499 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12500 (when (or (not specific)
12501 (member specific org-all-time-keywords)
12502 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12503 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12504 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12505 string (if (equal key clockstr)
12506 (org-no-properties
12507 (org-trim
12508 (buffer-substring
12509 (match-beginning 3) (goto-char (point-at-eol)))))
12510 (substring (org-match-string-no-properties 3) 1 -1)))
12511 (unless key
12512 (if (= (char-after (match-beginning 3)) ?\[)
12513 (setq key "TIMESTAMP_IA")
12514 (setq key "TIMESTAMP")))
12515 (when (or (equal key clockstr) (not (assoc key props)))
12516 (push (cons key string) props))))
12520 (when (memq which '(all standard))
12521 ;; Get the standard properties, like :PROP: ...
12522 (setq range (org-get-property-block beg end))
12523 (when range
12524 (goto-char (car range))
12525 (while (re-search-forward
12526 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12527 (cdr range) t)
12528 (setq key (org-match-string-no-properties 1)
12529 value (org-trim (or (org-match-string-no-properties 2) "")))
12530 (unless (member key excluded)
12531 (push (cons key (or value "")) props)))))
12532 (if clocksum
12533 (push (cons "CLOCKSUM"
12534 (org-columns-number-to-string (/ (float clocksum) 60.)
12535 'add_times))
12536 props))
12537 (unless (assoc "CATEGORY" props)
12538 (setq value (or (org-get-category)
12539 (progn (org-refresh-category-properties)
12540 (org-get-category))))
12541 (push (cons "CATEGORY" value) props))
12542 (append sum-props (nreverse props)))))))
12544 (defun org-entry-get (pom property &optional inherit)
12545 "Get value of PROPERTY for entry at point-or-marker POM.
12546 If INHERIT is non-nil and the entry does not have the property,
12547 then also check higher levels of the hierarchy.
12548 If INHERIT is the symbol `selective', use inheritance only if the setting
12549 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12550 If the property is present but empty, the return value is the empty string.
12551 If the property is not present at all, nil is returned."
12552 (org-with-point-at pom
12553 (if (and inherit (if (eq inherit 'selective)
12554 (org-property-inherit-p property)
12556 (org-entry-get-with-inheritance property)
12557 (if (member property org-special-properties)
12558 ;; We need a special property. Use `org-entry-properties' to
12559 ;; retrieve it, but specify the wanted property
12560 (cdr (assoc property (org-entry-properties nil 'special property)))
12561 (let ((range (org-get-property-block)))
12562 (if (and range
12563 (goto-char (car range))
12564 (re-search-forward
12565 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12566 (cdr range) t))
12567 ;; Found the property, return it.
12568 (if (match-end 1)
12569 (org-match-string-no-properties 1)
12570 "")))))))
12572 (defun org-property-or-variable-value (var &optional inherit)
12573 "Check if there is a property fixing the value of VAR.
12574 If yes, return this value. If not, return the current value of the variable."
12575 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12576 (if (and prop (stringp prop) (string-match "\\S-" prop))
12577 (read prop)
12578 (symbol-value var))))
12580 (defun org-entry-delete (pom property)
12581 "Delete the property PROPERTY from entry at point-or-marker POM."
12582 (org-with-point-at pom
12583 (if (member property org-special-properties)
12584 nil ; cannot delete these properties.
12585 (let ((range (org-get-property-block)))
12586 (if (and range
12587 (goto-char (car range))
12588 (re-search-forward
12589 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12590 (cdr range) t))
12591 (progn
12592 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12594 nil)))))
12596 ;; Multi-values properties are properties that contain multiple values
12597 ;; These values are assumed to be single words, separated by whitespace.
12598 (defun org-entry-add-to-multivalued-property (pom property value)
12599 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12600 (let* ((old (org-entry-get pom property))
12601 (values (and old (org-split-string old "[ \t]"))))
12602 (setq value (org-entry-protect-space value))
12603 (unless (member value values)
12604 (setq values (cons value values))
12605 (org-entry-put pom property
12606 (mapconcat 'identity values " ")))))
12608 (defun org-entry-remove-from-multivalued-property (pom property value)
12609 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12610 (let* ((old (org-entry-get pom property))
12611 (values (and old (org-split-string old "[ \t]"))))
12612 (setq value (org-entry-protect-space value))
12613 (when (member value values)
12614 (setq values (delete value values))
12615 (org-entry-put pom property
12616 (mapconcat 'identity values " ")))))
12618 (defun org-entry-member-in-multivalued-property (pom property value)
12619 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12620 (let* ((old (org-entry-get pom property))
12621 (values (and old (org-split-string old "[ \t]"))))
12622 (setq value (org-entry-protect-space value))
12623 (member value values)))
12625 (defun org-entry-get-multivalued-property (pom property)
12626 "Return a list of values in a multivalued property."
12627 (let* ((value (org-entry-get pom property))
12628 (values (and value (org-split-string value "[ \t]"))))
12629 (mapcar 'org-entry-restore-space values)))
12631 (defun org-entry-put-multivalued-property (pom property &rest values)
12632 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12633 VALUES should be a list of strings. Spaces will be protected."
12634 (org-entry-put pom property
12635 (mapconcat 'org-entry-protect-space values " "))
12636 (let* ((value (org-entry-get pom property))
12637 (values (and value (org-split-string value "[ \t]"))))
12638 (mapcar 'org-entry-restore-space values)))
12640 (defun org-entry-protect-space (s)
12641 "Protect spaces and newline in string S."
12642 (while (string-match " " s)
12643 (setq s (replace-match "%20" t t s)))
12644 (while (string-match "\n" s)
12645 (setq s (replace-match "%0A" t t s)))
12648 (defun org-entry-restore-space (s)
12649 "Restore spaces and newline in string S."
12650 (while (string-match "%20" s)
12651 (setq s (replace-match " " t t s)))
12652 (while (string-match "%0A" s)
12653 (setq s (replace-match "\n" t t s)))
12656 (defvar org-entry-property-inherited-from (make-marker)
12657 "Marker pointing to the entry from where a property was inherited.
12658 Each call to `org-entry-get-with-inheritance' will set this marker to the
12659 location of the entry where the inheritance search matched. If there was
12660 no match, the marker will point nowhere.
12661 Note that also `org-entry-get' calls this function, if the INHERIT flag
12662 is set.")
12664 (defun org-entry-get-with-inheritance (property)
12665 "Get entry property, and search higher levels if not present."
12666 (move-marker org-entry-property-inherited-from nil)
12667 (let (tmp)
12668 (save-excursion
12669 (save-restriction
12670 (widen)
12671 (catch 'ex
12672 (while t
12673 (when (setq tmp (org-entry-get nil property))
12674 (org-back-to-heading t)
12675 (move-marker org-entry-property-inherited-from (point))
12676 (throw 'ex tmp))
12677 (or (org-up-heading-safe) (throw 'ex nil)))))
12678 (or tmp
12679 (cdr (assoc property org-file-properties))
12680 (cdr (assoc property org-global-properties))
12681 (cdr (assoc property org-global-properties-fixed))))))
12683 (defvar org-property-changed-functions nil
12684 "Hook called when the value of a property has changed.
12685 Each hook function should accept two arguments, the name of the property
12686 and the new value.")
12688 (defun org-entry-put (pom property value)
12689 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12690 (org-with-point-at pom
12691 (org-back-to-heading t)
12692 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12693 range)
12694 (cond
12695 ((equal property "TODO")
12696 (when (and (stringp value) (string-match "\\S-" value)
12697 (not (member value org-todo-keywords-1)))
12698 (error "\"%s\" is not a valid TODO state" value))
12699 (if (or (not value)
12700 (not (string-match "\\S-" value)))
12701 (setq value 'none))
12702 (org-todo value)
12703 (org-set-tags nil 'align))
12704 ((equal property "PRIORITY")
12705 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12706 (string-to-char value) ?\ ))
12707 (org-set-tags nil 'align))
12708 ((equal property "SCHEDULED")
12709 (if (re-search-forward org-scheduled-time-regexp end t)
12710 (cond
12711 ((eq value 'earlier) (org-timestamp-change -1 'day))
12712 ((eq value 'later) (org-timestamp-change 1 'day))
12713 (t (call-interactively 'org-schedule)))
12714 (call-interactively 'org-schedule)))
12715 ((equal property "DEADLINE")
12716 (if (re-search-forward org-deadline-time-regexp end t)
12717 (cond
12718 ((eq value 'earlier) (org-timestamp-change -1 'day))
12719 ((eq value 'later) (org-timestamp-change 1 'day))
12720 (t (call-interactively 'org-deadline)))
12721 (call-interactively 'org-deadline)))
12722 ((member property org-special-properties)
12723 (error "The %s property can not yet be set with `org-entry-put'"
12724 property))
12725 (t ; a non-special property
12726 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12727 (setq range (org-get-property-block beg end 'force))
12728 (goto-char (car range))
12729 (if (re-search-forward
12730 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12731 (progn
12732 (delete-region (match-beginning 1) (match-end 1))
12733 (goto-char (match-beginning 1)))
12734 (goto-char (cdr range))
12735 (insert "\n")
12736 (backward-char 1)
12737 (org-indent-line-function)
12738 (insert ":" property ":"))
12739 (and value (insert " " value))
12740 (org-indent-line-function)))))
12741 (run-hook-with-args 'org-property-changed-functions property value)))
12743 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12744 "Get all property keys in the current buffer.
12745 With INCLUDE-SPECIALS, also list the special properties that reflect things
12746 like tags and TODO state.
12747 With INCLUDE-DEFAULTS, also include properties that has special meaning
12748 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12749 With INCLUDE-COLUMNS, also include property names given in COLUMN
12750 formats in the current buffer."
12751 (let (rtn range cfmt s p)
12752 (save-excursion
12753 (save-restriction
12754 (widen)
12755 (goto-char (point-min))
12756 (while (re-search-forward org-property-start-re nil t)
12757 (setq range (org-get-property-block))
12758 (goto-char (car range))
12759 (while (re-search-forward
12760 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12761 (cdr range) t)
12762 (add-to-list 'rtn (org-match-string-no-properties 1)))
12763 (outline-next-heading))))
12765 (when include-specials
12766 (setq rtn (append org-special-properties rtn)))
12768 (when include-defaults
12769 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12770 (add-to-list 'rtn org-effort-property))
12772 (when include-columns
12773 (save-excursion
12774 (save-restriction
12775 (widen)
12776 (goto-char (point-min))
12777 (while (re-search-forward
12778 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12779 nil t)
12780 (setq cfmt (match-string 2) s 0)
12781 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12782 cfmt s)
12783 (setq s (match-end 0)
12784 p (match-string 1 cfmt))
12785 (unless (or (equal p "ITEM")
12786 (member p org-special-properties))
12787 (add-to-list 'rtn (match-string 1 cfmt))))))))
12789 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12791 (defun org-property-values (key)
12792 "Return a list of all values of property KEY."
12793 (save-excursion
12794 (save-restriction
12795 (widen)
12796 (goto-char (point-min))
12797 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12798 values)
12799 (while (re-search-forward re nil t)
12800 (add-to-list 'values (org-trim (match-string 1))))
12801 (delete "" values)))))
12803 (defun org-insert-property-drawer ()
12804 "Insert a property drawer into the current entry."
12805 (interactive)
12806 (org-back-to-heading t)
12807 (looking-at outline-regexp)
12808 (let ((indent (if org-adapt-indentation
12809 (- (match-end 0)(match-beginning 0))
12811 (beg (point))
12812 (re (concat "^[ \t]*" org-keyword-time-regexp))
12813 end hiddenp)
12814 (outline-next-heading)
12815 (setq end (point))
12816 (goto-char beg)
12817 (while (re-search-forward re end t))
12818 (setq hiddenp (org-invisible-p))
12819 (end-of-line 1)
12820 (and (equal (char-after) ?\n) (forward-char 1))
12821 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12822 (if (member (match-string 1) '("CLOCK:" ":END:"))
12823 ;; just skip this line
12824 (beginning-of-line 2)
12825 ;; Drawer start, find the end
12826 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12827 (beginning-of-line 1)))
12828 (org-skip-over-state-notes)
12829 (skip-chars-backward " \t\n\r")
12830 (if (eq (char-before) ?*) (forward-char 1))
12831 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12832 (beginning-of-line 0)
12833 (org-indent-to-column indent)
12834 (beginning-of-line 2)
12835 (org-indent-to-column indent)
12836 (beginning-of-line 0)
12837 (if hiddenp
12838 (save-excursion
12839 (org-back-to-heading t)
12840 (hide-entry))
12841 (org-flag-drawer t))))
12843 (defun org-set-property (property value)
12844 "In the current entry, set PROPERTY to VALUE.
12845 When called interactively, this will prompt for a property name, offering
12846 completion on existing and default properties. And then it will prompt
12847 for a value, offering completion either on allowed values (via an inherited
12848 xxx_ALL property) or on existing values in other instances of this property
12849 in the current file."
12850 (interactive
12851 (let* ((completion-ignore-case t)
12852 (keys (org-buffer-property-keys nil t t))
12853 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12854 (prop (if (member prop0 keys)
12855 prop0
12856 (or (cdr (assoc (downcase prop0)
12857 (mapcar (lambda (x) (cons (downcase x) x))
12858 keys)))
12859 prop0)))
12860 (cur (org-entry-get nil prop))
12861 (allowed (org-property-get-allowed-values nil prop 'table))
12862 (existing (mapcar 'list (org-property-values prop)))
12863 (val (if allowed
12864 (org-completing-read "Value: " allowed nil
12865 (not (get-text-property 0 'org-unrestricted
12866 (caar allowed))))
12867 (let (org-completion-use-ido org-completion-use-iswitchb)
12868 (org-completing-read
12869 (concat "Value " (if (and cur (string-match "\\S-" cur))
12870 (concat "[" cur "]") "")
12871 ": ")
12872 existing nil nil "" nil cur)))))
12873 (list prop (if (equal val "") cur val))))
12874 (unless (equal (org-entry-get nil property) value)
12875 (org-entry-put nil property value)))
12877 (defun org-delete-property (property)
12878 "In the current entry, delete PROPERTY."
12879 (interactive
12880 (let* ((completion-ignore-case t)
12881 (prop (org-icompleting-read
12882 "Property: " (org-entry-properties nil 'standard))))
12883 (list prop)))
12884 (message "Property %s %s" property
12885 (if (org-entry-delete nil property)
12886 "deleted"
12887 "was not present in the entry")))
12889 (defun org-delete-property-globally (property)
12890 "Remove PROPERTY globally, from all entries."
12891 (interactive
12892 (let* ((completion-ignore-case t)
12893 (prop (org-icompleting-read
12894 "Globally remove property: "
12895 (mapcar 'list (org-buffer-property-keys)))))
12896 (list prop)))
12897 (save-excursion
12898 (save-restriction
12899 (widen)
12900 (goto-char (point-min))
12901 (let ((cnt 0))
12902 (while (re-search-forward
12903 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12904 nil t)
12905 (setq cnt (1+ cnt))
12906 (replace-match ""))
12907 (message "Property \"%s\" removed from %d entries" property cnt)))))
12909 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12911 (defun org-compute-property-at-point ()
12912 "Compute the property at point.
12913 This looks for an enclosing column format, extracts the operator and
12914 then applies it to the property in the column format's scope."
12915 (interactive)
12916 (unless (org-at-property-p)
12917 (error "Not at a property"))
12918 (let ((prop (org-match-string-no-properties 2)))
12919 (org-columns-get-format-and-top-level)
12920 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12921 (error "No operator defined for property %s" prop))
12922 (org-columns-compute prop)))
12924 (defvar org-property-allowed-value-functions nil
12925 "Hook for functions supplying allowed values for specific.
12926 The functions must take a single argument, the name of the property, and
12927 return a flat list of allowed values. If \":ETC\" is one of
12928 the values, this means that these values are intended as defaults for
12929 completion, but that other values should be allowed too.
12930 The functions must return nil if they are now responsible for this
12931 prioerty.")
12933 (defun org-property-get-allowed-values (pom property &optional table)
12934 "Get allowed values for the property PROPERTY.
12935 When TABLE is non-nil, return an alist that can directly be used for
12936 completion."
12937 (let (vals)
12938 (cond
12939 ((equal property "TODO")
12940 (setq vals (org-with-point-at pom
12941 (append org-todo-keywords-1 '("")))))
12942 ((equal property "PRIORITY")
12943 (let ((n org-lowest-priority))
12944 (while (>= n org-highest-priority)
12945 (push (char-to-string n) vals)
12946 (setq n (1- n)))))
12947 ((member property org-special-properties))
12948 ((setq vals (run-hook-with-args-until-success
12949 'org-property-allowed-value-functions property)))
12951 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12952 (when (and vals (string-match "\\S-" vals))
12953 (setq vals (car (read-from-string (concat "(" vals ")"))))
12954 (setq vals (mapcar (lambda (x)
12955 (cond ((stringp x) x)
12956 ((numberp x) (number-to-string x))
12957 ((symbolp x) (symbol-name x))
12958 (t "???")))
12959 vals)))))
12960 (when (member ":ETC" vals)
12961 (setq vals (remove ":ETC" vals))
12962 (org-add-props (car vals) '(org-unrestricted t)))
12963 (if table (mapcar 'list vals) vals)))
12965 (defun org-property-previous-allowed-value (&optional previous)
12966 "Switch to the next allowed value for this property."
12967 (interactive)
12968 (org-property-next-allowed-value t))
12970 (defun org-property-next-allowed-value (&optional previous)
12971 "Switch to the next allowed value for this property."
12972 (interactive)
12973 (unless (org-at-property-p)
12974 (error "Not at a property"))
12975 (let* ((key (match-string 2))
12976 (value (match-string 3))
12977 (allowed (or (org-property-get-allowed-values (point) key)
12978 (and (member value '("[ ]" "[-]" "[X]"))
12979 '("[ ]" "[X]"))))
12980 nval)
12981 (unless allowed
12982 (error "Allowed values for this property have not been defined"))
12983 (if previous (setq allowed (reverse allowed)))
12984 (if (member value allowed)
12985 (setq nval (car (cdr (member value allowed)))))
12986 (setq nval (or nval (car allowed)))
12987 (if (equal nval value)
12988 (error "Only one allowed value for this property"))
12989 (org-at-property-p)
12990 (replace-match (concat " :" key ": " nval) t t)
12991 (org-indent-line-function)
12992 (beginning-of-line 1)
12993 (skip-chars-forward " \t")
12994 (run-hook-with-args 'org-property-changed-functions key nval)))
12996 (defun org-find-entry-with-id (ident)
12997 "Locate the entry that contains the ID property with exact value IDENT.
12998 IDENT can be a string, a symbol or a number, this function will search for
12999 the string representation of it.
13000 Return the position where this entry starts, or nil if there is no such entry."
13001 (interactive "sID: ")
13002 (let ((id (cond
13003 ((stringp ident) ident)
13004 ((symbol-name ident) (symbol-name ident))
13005 ((numberp ident) (number-to-string ident))
13006 (t (error "IDENT %s must be a string, symbol or number" ident))))
13007 (case-fold-search nil))
13008 (save-excursion
13009 (save-restriction
13010 (widen)
13011 (goto-char (point-min))
13012 (when (re-search-forward
13013 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13014 nil t)
13015 (org-back-to-heading t)
13016 (point))))))
13018 ;;;; Timestamps
13020 (defvar org-last-changed-timestamp nil)
13021 (defvar org-last-inserted-timestamp nil
13022 "The last time stamp inserted with `org-insert-time-stamp'.")
13023 (defvar org-time-was-given) ; dynamically scoped parameter
13024 (defvar org-end-time-was-given) ; dynamically scoped parameter
13025 (defvar org-ts-what) ; dynamically scoped parameter
13027 (defun org-time-stamp (arg &optional inactive)
13028 "Prompt for a date/time and insert a time stamp.
13029 If the user specifies a time like HH:MM, or if this command is called
13030 with a prefix argument, the time stamp will contain date and time.
13031 Otherwise, only the date will be included. All parts of a date not
13032 specified by the user will be filled in from the current date/time.
13033 So if you press just return without typing anything, the time stamp
13034 will represent the current date/time. If there is already a timestamp
13035 at the cursor, it will be modified."
13036 (interactive "P")
13037 (let* ((ts nil)
13038 (default-time
13039 ;; Default time is either today, or, when entering a range,
13040 ;; the range start.
13041 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13042 (save-excursion
13043 (re-search-backward
13044 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13045 (- (point) 20) t)))
13046 (apply 'encode-time (org-parse-time-string (match-string 1)))
13047 (current-time)))
13048 (default-input (and ts (org-get-compact-tod ts)))
13049 org-time-was-given org-end-time-was-given time)
13050 (cond
13051 ((and (org-at-timestamp-p t)
13052 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13053 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13054 (insert "--")
13055 (setq time (let ((this-command this-command))
13056 (org-read-date arg 'totime nil nil
13057 default-time default-input)))
13058 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13059 ((org-at-timestamp-p t)
13060 (setq time (let ((this-command this-command))
13061 (org-read-date arg 'totime nil nil default-time default-input)))
13062 (when (org-at-timestamp-p t) ; just to get the match data
13063 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13064 (replace-match "")
13065 (setq org-last-changed-timestamp
13066 (org-insert-time-stamp
13067 time (or org-time-was-given arg)
13068 inactive nil nil (list org-end-time-was-given))))
13069 (message "Timestamp updated"))
13071 (setq time (let ((this-command this-command))
13072 (org-read-date arg 'totime nil nil default-time default-input)))
13073 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13074 nil nil (list org-end-time-was-given))))))
13076 ;; FIXME: can we use this for something else, like computing time differences?
13077 (defun org-get-compact-tod (s)
13078 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13079 (let* ((t1 (match-string 1 s))
13080 (h1 (string-to-number (match-string 2 s)))
13081 (m1 (string-to-number (match-string 3 s)))
13082 (t2 (and (match-end 4) (match-string 5 s)))
13083 (h2 (and t2 (string-to-number (match-string 6 s))))
13084 (m2 (and t2 (string-to-number (match-string 7 s))))
13085 dh dm)
13086 (if (not t2)
13088 (setq dh (- h2 h1) dm (- m2 m1))
13089 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13090 (concat t1 "+" (number-to-string dh)
13091 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13093 (defun org-time-stamp-inactive (&optional arg)
13094 "Insert an inactive time stamp.
13095 An inactive time stamp is enclosed in square brackets instead of angle
13096 brackets. It is inactive in the sense that it does not trigger agenda entries,
13097 does not link to the calendar and cannot be changed with the S-cursor keys.
13098 So these are more for recording a certain time/date."
13099 (interactive "P")
13100 (org-time-stamp arg 'inactive))
13102 (defvar org-date-ovl (org-make-overlay 1 1))
13103 (org-overlay-put org-date-ovl 'face 'org-warning)
13104 (org-detach-overlay org-date-ovl)
13106 (defvar org-ans1) ; dynamically scoped parameter
13107 (defvar org-ans2) ; dynamically scoped parameter
13109 (defvar org-plain-time-of-day-regexp) ; defined below
13111 (defvar org-overriding-default-time nil) ; dynamically scoped
13112 (defvar org-read-date-overlay nil)
13113 (defvar org-dcst nil) ; dynamically scoped
13114 (defvar org-read-date-history nil)
13115 (defvar org-read-date-final-answer nil)
13117 (defun org-read-date (&optional with-time to-time from-string prompt
13118 default-time default-input)
13119 "Read a date, possibly a time, and make things smooth for the user.
13120 The prompt will suggest to enter an ISO date, but you can also enter anything
13121 which will at least partially be understood by `parse-time-string'.
13122 Unrecognized parts of the date will default to the current day, month, year,
13123 hour and minute. If this command is called to replace a timestamp at point,
13124 of to enter the second timestamp of a range, the default time is taken from the
13125 existing stamp. For example,
13126 3-2-5 --> 2003-02-05
13127 feb 15 --> currentyear-02-15
13128 sep 12 9 --> 2009-09-12
13129 12:45 --> today 12:45
13130 22 sept 0:34 --> currentyear-09-22 0:34
13131 12 --> currentyear-currentmonth-12
13132 Fri --> nearest Friday (today or later)
13133 etc.
13135 Furthermore you can specify a relative date by giving, as the *first* thing
13136 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13137 change in days weeks, months, years.
13138 With a single plus or minus, the date is relative to today. With a double
13139 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13140 +4d --> four days from today
13141 +4 --> same as above
13142 +2w --> two weeks from today
13143 ++5 --> five days from default date
13145 The function understands only English month and weekday abbreviations,
13146 but this can be configured with the variables `parse-time-months' and
13147 `parse-time-weekdays'.
13149 While prompting, a calendar is popped up - you can also select the
13150 date with the mouse (button 1). The calendar shows a period of three
13151 months. To scroll it to other months, use the keys `>' and `<'.
13152 If you don't like the calendar, turn it off with
13153 \(setq org-read-date-popup-calendar nil)
13155 With optional argument TO-TIME, the date will immediately be converted
13156 to an internal time.
13157 With an optional argument WITH-TIME, the prompt will suggest to also
13158 insert a time. Note that when WITH-TIME is not set, you can still
13159 enter a time, and this function will inform the calling routine about
13160 this change. The calling routine may then choose to change the format
13161 used to insert the time stamp into the buffer to include the time.
13162 With optional argument FROM-STRING, read from this string instead from
13163 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13164 the time/date that is used for everything that is not specified by the
13165 user."
13166 (require 'parse-time)
13167 (let* ((org-time-stamp-rounding-minutes
13168 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13169 (org-dcst org-display-custom-times)
13170 (ct (org-current-time))
13171 (def (or org-overriding-default-time default-time ct))
13172 (defdecode (decode-time def))
13173 (dummy (progn
13174 (when (< (nth 2 defdecode) org-extend-today-until)
13175 (setcar (nthcdr 2 defdecode) -1)
13176 (setcar (nthcdr 1 defdecode) 59)
13177 (setq def (apply 'encode-time defdecode)
13178 defdecode (decode-time def)))))
13179 (calendar-frame-setup nil)
13180 (calendar-move-hook nil)
13181 (calendar-view-diary-initially-flag nil)
13182 (view-diary-entries-initially nil)
13183 (calendar-view-holidays-initially-flag nil)
13184 (view-calendar-holidays-initially nil)
13185 (timestr (format-time-string
13186 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13187 (prompt (concat (if prompt (concat prompt " ") "")
13188 (format "Date+time [%s]: " timestr)))
13189 ans (org-ans0 "") org-ans1 org-ans2 final)
13191 (cond
13192 (from-string (setq ans from-string))
13193 (org-read-date-popup-calendar
13194 (save-excursion
13195 (save-window-excursion
13196 (calendar)
13197 (calendar-forward-day (- (time-to-days def)
13198 (calendar-absolute-from-gregorian
13199 (calendar-current-date))))
13200 (org-eval-in-calendar nil t)
13201 (let* ((old-map (current-local-map))
13202 (map (copy-keymap calendar-mode-map))
13203 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13204 (org-defkey map (kbd "RET") 'org-calendar-select)
13205 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13206 'org-calendar-select-mouse)
13207 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13208 'org-calendar-select-mouse)
13209 (org-defkey minibuffer-local-map [(meta shift left)]
13210 (lambda () (interactive)
13211 (org-eval-in-calendar '(calendar-backward-month 1))))
13212 (org-defkey minibuffer-local-map [(meta shift right)]
13213 (lambda () (interactive)
13214 (org-eval-in-calendar '(calendar-forward-month 1))))
13215 (org-defkey minibuffer-local-map [(meta shift up)]
13216 (lambda () (interactive)
13217 (org-eval-in-calendar '(calendar-backward-year 1))))
13218 (org-defkey minibuffer-local-map [(meta shift down)]
13219 (lambda () (interactive)
13220 (org-eval-in-calendar '(calendar-forward-year 1))))
13221 (org-defkey minibuffer-local-map [?\e (shift left)]
13222 (lambda () (interactive)
13223 (org-eval-in-calendar '(calendar-backward-month 1))))
13224 (org-defkey minibuffer-local-map [?\e (shift right)]
13225 (lambda () (interactive)
13226 (org-eval-in-calendar '(calendar-forward-month 1))))
13227 (org-defkey minibuffer-local-map [?\e (shift up)]
13228 (lambda () (interactive)
13229 (org-eval-in-calendar '(calendar-backward-year 1))))
13230 (org-defkey minibuffer-local-map [?\e (shift down)]
13231 (lambda () (interactive)
13232 (org-eval-in-calendar '(calendar-forward-year 1))))
13233 (org-defkey minibuffer-local-map [(shift up)]
13234 (lambda () (interactive)
13235 (org-eval-in-calendar '(calendar-backward-week 1))))
13236 (org-defkey minibuffer-local-map [(shift down)]
13237 (lambda () (interactive)
13238 (org-eval-in-calendar '(calendar-forward-week 1))))
13239 (org-defkey minibuffer-local-map [(shift left)]
13240 (lambda () (interactive)
13241 (org-eval-in-calendar '(calendar-backward-day 1))))
13242 (org-defkey minibuffer-local-map [(shift right)]
13243 (lambda () (interactive)
13244 (org-eval-in-calendar '(calendar-forward-day 1))))
13245 (org-defkey minibuffer-local-map ">"
13246 (lambda () (interactive)
13247 (org-eval-in-calendar '(scroll-calendar-left 1))))
13248 (org-defkey minibuffer-local-map "<"
13249 (lambda () (interactive)
13250 (org-eval-in-calendar '(scroll-calendar-right 1))))
13251 (run-hooks 'org-read-date-minibuffer-setup-hook)
13252 (unwind-protect
13253 (progn
13254 (use-local-map map)
13255 (add-hook 'post-command-hook 'org-read-date-display)
13256 (setq org-ans0 (read-string prompt default-input
13257 'org-read-date-history nil))
13258 ;; org-ans0: from prompt
13259 ;; org-ans1: from mouse click
13260 ;; org-ans2: from calendar motion
13261 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13262 (remove-hook 'post-command-hook 'org-read-date-display)
13263 (use-local-map old-map)
13264 (when org-read-date-overlay
13265 (org-delete-overlay org-read-date-overlay)
13266 (setq org-read-date-overlay nil)))))))
13268 (t ; Naked prompt only
13269 (unwind-protect
13270 (setq ans (read-string prompt default-input
13271 'org-read-date-history timestr))
13272 (when org-read-date-overlay
13273 (org-delete-overlay org-read-date-overlay)
13274 (setq org-read-date-overlay nil)))))
13276 (setq final (org-read-date-analyze ans def defdecode))
13277 (setq org-read-date-final-answer ans)
13279 (if to-time
13280 (apply 'encode-time final)
13281 (if (and (boundp 'org-time-was-given) org-time-was-given)
13282 (format "%04d-%02d-%02d %02d:%02d"
13283 (nth 5 final) (nth 4 final) (nth 3 final)
13284 (nth 2 final) (nth 1 final))
13285 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13287 (defvar def)
13288 (defvar defdecode)
13289 (defvar with-time)
13290 (defvar org-read-date-analyze-futurep nil)
13291 (defun org-read-date-display ()
13292 "Display the current date prompt interpretation in the minibuffer."
13293 (when org-read-date-display-live
13294 (when org-read-date-overlay
13295 (org-delete-overlay org-read-date-overlay))
13296 (let ((p (point)))
13297 (end-of-line 1)
13298 (while (not (equal (buffer-substring
13299 (max (point-min) (- (point) 4)) (point))
13300 " "))
13301 (insert " "))
13302 (goto-char p))
13303 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13304 " " (or org-ans1 org-ans2)))
13305 (org-end-time-was-given nil)
13306 (f (org-read-date-analyze ans def defdecode))
13307 (fmts (if org-dcst
13308 org-time-stamp-custom-formats
13309 org-time-stamp-formats))
13310 (fmt (if (or with-time
13311 (and (boundp 'org-time-was-given) org-time-was-given))
13312 (cdr fmts)
13313 (car fmts)))
13314 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13315 (when (and org-end-time-was-given
13316 (string-match org-plain-time-of-day-regexp txt))
13317 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13318 org-end-time-was-given
13319 (substring txt (match-end 0)))))
13320 (when org-read-date-analyze-futurep
13321 (setq txt (concat txt " (=>F)")))
13322 (setq org-read-date-overlay
13323 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13324 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13326 (defun org-read-date-analyze (ans def defdecode)
13327 "Analyse the combined answer of the date prompt."
13328 ;; FIXME: cleanup and comment
13329 (let (delta deltan deltaw deltadef year month day
13330 hour minute second wday pm h2 m2 tl wday1
13331 iso-year iso-weekday iso-week iso-year iso-date futurep)
13332 (setq org-read-date-analyze-futurep nil)
13333 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13334 (setq ans "+0"))
13336 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13337 (setq ans (replace-match "" t t ans)
13338 deltan (car delta)
13339 deltaw (nth 1 delta)
13340 deltadef (nth 2 delta)))
13342 ;; Check if there is an iso week date in there
13343 ;; If yes, store the info and postpone interpreting it until the rest
13344 ;; of the parsing is done
13345 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13346 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13347 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13348 iso-week (string-to-number (match-string 2 ans)))
13349 (setq ans (replace-match "" t t ans)))
13351 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13352 (when (string-match
13353 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13354 (setq year (if (match-end 2)
13355 (string-to-number (match-string 2 ans))
13356 (string-to-number (format-time-string "%Y")))
13357 month (string-to-number (match-string 3 ans))
13358 day (string-to-number (match-string 4 ans)))
13359 (if (< year 100) (setq year (+ 2000 year)))
13360 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13361 t nil ans)))
13362 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13363 ;; If there is a time with am/pm, and *no* time without it, we convert
13364 ;; so that matching will be successful.
13365 (loop for i from 1 to 2 do ; twice, for end time as well
13366 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13367 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13368 (setq hour (string-to-number (match-string 1 ans))
13369 minute (if (match-end 3)
13370 (string-to-number (match-string 3 ans))
13372 pm (equal ?p
13373 (string-to-char (downcase (match-string 4 ans)))))
13374 (if (and (= hour 12) (not pm))
13375 (setq hour 0)
13376 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13377 (setq ans (replace-match (format "%02d:%02d" hour minute)
13378 t t ans))))
13380 ;; Check if a time range is given as a duration
13381 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13382 (setq hour (string-to-number (match-string 1 ans))
13383 h2 (+ hour (string-to-number (match-string 3 ans)))
13384 minute (string-to-number (match-string 2 ans))
13385 m2 (+ minute (if (match-end 5) (string-to-number
13386 (match-string 5 ans))0)))
13387 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13388 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13389 t t ans)))
13391 ;; Check if there is a time range
13392 (when (boundp 'org-end-time-was-given)
13393 (setq org-time-was-given nil)
13394 (when (and (string-match org-plain-time-of-day-regexp ans)
13395 (match-end 8))
13396 (setq org-end-time-was-given (match-string 8 ans))
13397 (setq ans (concat (substring ans 0 (match-beginning 7))
13398 (substring ans (match-end 7))))))
13400 (setq tl (parse-time-string ans)
13401 day (or (nth 3 tl) (nth 3 defdecode))
13402 month (or (nth 4 tl)
13403 (if (and org-read-date-prefer-future
13404 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13405 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13406 (nth 4 defdecode)))
13407 year (or (nth 5 tl)
13408 (if (and org-read-date-prefer-future
13409 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13410 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13411 (nth 5 defdecode)))
13412 hour (or (nth 2 tl) (nth 2 defdecode))
13413 minute (or (nth 1 tl) (nth 1 defdecode))
13414 second (or (nth 0 tl) 0)
13415 wday (nth 6 tl))
13417 (when (and (eq org-read-date-prefer-future 'time)
13418 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13419 (equal day (nth 3 defdecode))
13420 (equal month (nth 4 defdecode))
13421 (equal year (nth 5 defdecode))
13422 (nth 2 tl)
13423 (or (< (nth 2 tl) (nth 2 defdecode))
13424 (and (= (nth 2 tl) (nth 2 defdecode))
13425 (nth 1 tl)
13426 (< (nth 1 tl) (nth 1 defdecode)))))
13427 (setq day (1+ day)
13428 futurep t))
13430 ;; Special date definitions below
13431 (cond
13432 (iso-week
13433 ;; There was an iso week
13434 (setq futurep nil)
13435 (setq year (or iso-year year)
13436 day (or iso-weekday wday 1)
13437 wday nil ; to make sure that the trigger below does not match
13438 iso-date (calendar-gregorian-from-absolute
13439 (calendar-absolute-from-iso
13440 (list iso-week day year))))
13441 ; FIXME: Should we also push ISO weeks into the future?
13442 ; (when (and org-read-date-prefer-future
13443 ; (not iso-year)
13444 ; (< (calendar-absolute-from-gregorian iso-date)
13445 ; (time-to-days (current-time))))
13446 ; (setq year (1+ year)
13447 ; iso-date (calendar-gregorian-from-absolute
13448 ; (calendar-absolute-from-iso
13449 ; (list iso-week day year)))))
13450 (setq month (car iso-date)
13451 year (nth 2 iso-date)
13452 day (nth 1 iso-date)))
13453 (deltan
13454 (setq futurep nil)
13455 (unless deltadef
13456 (let ((now (decode-time (current-time))))
13457 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13458 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13459 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13460 ((equal deltaw "m") (setq month (+ month deltan)))
13461 ((equal deltaw "y") (setq year (+ year deltan)))))
13462 ((and wday (not (nth 3 tl)))
13463 (setq futurep nil)
13464 ;; Weekday was given, but no day, so pick that day in the week
13465 ;; on or after the derived date.
13466 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13467 (unless (equal wday wday1)
13468 (setq day (+ day (% (- wday wday1 -7) 7))))))
13469 (if (and (boundp 'org-time-was-given)
13470 (nth 2 tl))
13471 (setq org-time-was-given t))
13472 (if (< year 100) (setq year (+ 2000 year)))
13473 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13474 (setq org-read-date-analyze-futurep futurep)
13475 (list second minute hour day month year)))
13477 (defvar parse-time-weekdays)
13479 (defun org-read-date-get-relative (s today default)
13480 "Check string S for special relative date string.
13481 TODAY and DEFAULT are internal times, for today and for a default.
13482 Return shift list (N what def-flag)
13483 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13484 N is the number of WHATs to shift.
13485 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13486 the DEFAULT date rather than TODAY."
13487 (when (and
13488 (string-match
13489 (concat
13490 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13491 "\\([0-9]+\\)?"
13492 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13493 "\\([ \t]\\|$\\)") s)
13494 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13495 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13496 (string-to-char (substring (match-string 1 s) -1))
13497 ?+))
13498 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13499 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13500 (what (if (match-end 3) (match-string 3 s) "d"))
13501 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13502 (date (if rel default today))
13503 (wday (nth 6 (decode-time date)))
13504 delta)
13505 (if wday1
13506 (progn
13507 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13508 (if (= dir ?-) (setq delta (- delta 7)))
13509 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13510 (list delta "d" rel))
13511 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13513 (defun org-eval-in-calendar (form &optional keepdate)
13514 "Eval FORM in the calendar window and return to current window.
13515 Also, store the cursor date in variable org-ans2."
13516 (let ((sf (selected-frame))
13517 (sw (selected-window)))
13518 (select-window (get-buffer-window "*Calendar*" t))
13519 (eval form)
13520 (when (and (not keepdate) (calendar-cursor-to-date))
13521 (let* ((date (calendar-cursor-to-date))
13522 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13523 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13524 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13525 (select-window sw)
13526 (org-select-frame-set-input-focus sf)))
13528 (defun org-calendar-select ()
13529 "Return to `org-read-date' with the date currently selected.
13530 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13531 (interactive)
13532 (when (calendar-cursor-to-date)
13533 (let* ((date (calendar-cursor-to-date))
13534 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13535 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13536 (if (active-minibuffer-window) (exit-minibuffer))))
13538 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13539 "Insert a date stamp for the date given by the internal TIME.
13540 WITH-HM means, use the stamp format that includes the time of the day.
13541 INACTIVE means use square brackets instead of angular ones, so that the
13542 stamp will not contribute to the agenda.
13543 PRE and POST are optional strings to be inserted before and after the
13544 stamp.
13545 The command returns the inserted time stamp."
13546 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13547 stamp)
13548 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13549 (insert-before-markers (or pre ""))
13550 (insert-before-markers (setq stamp (format-time-string fmt time)))
13551 (when (listp extra)
13552 (setq extra (car extra))
13553 (if (and (stringp extra)
13554 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13555 (setq extra (format "-%02d:%02d"
13556 (string-to-number (match-string 1 extra))
13557 (string-to-number (match-string 2 extra))))
13558 (setq extra nil)))
13559 (when extra
13560 (backward-char 1)
13561 (insert-before-markers extra)
13562 (forward-char 1))
13563 (insert-before-markers (or post ""))
13564 (setq org-last-inserted-timestamp stamp)))
13566 (defun org-toggle-time-stamp-overlays ()
13567 "Toggle the use of custom time stamp formats."
13568 (interactive)
13569 (setq org-display-custom-times (not org-display-custom-times))
13570 (unless org-display-custom-times
13571 (let ((p (point-min)) (bmp (buffer-modified-p)))
13572 (while (setq p (next-single-property-change p 'display))
13573 (if (and (get-text-property p 'display)
13574 (eq (get-text-property p 'face) 'org-date))
13575 (remove-text-properties
13576 p (setq p (next-single-property-change p 'display))
13577 '(display t))))
13578 (set-buffer-modified-p bmp)))
13579 (if (featurep 'xemacs)
13580 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13581 (org-restart-font-lock)
13582 (setq org-table-may-need-update t)
13583 (if org-display-custom-times
13584 (message "Time stamps are overlayed with custom format")
13585 (message "Time stamp overlays removed")))
13587 (defun org-display-custom-time (beg end)
13588 "Overlay modified time stamp format over timestamp between BEG and END."
13589 (let* ((ts (buffer-substring beg end))
13590 t1 w1 with-hm tf time str w2 (off 0))
13591 (save-match-data
13592 (setq t1 (org-parse-time-string ts t))
13593 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13594 (setq off (- (match-end 0) (match-beginning 0)))))
13595 (setq end (- end off))
13596 (setq w1 (- end beg)
13597 with-hm (and (nth 1 t1) (nth 2 t1))
13598 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13599 time (org-fix-decoded-time t1)
13600 str (org-add-props
13601 (format-time-string
13602 (substring tf 1 -1) (apply 'encode-time time))
13603 nil 'mouse-face 'highlight)
13604 w2 (length str))
13605 (if (not (= w2 w1))
13606 (add-text-properties (1+ beg) (+ 2 beg)
13607 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13608 (if (featurep 'xemacs)
13609 (progn
13610 (put-text-property beg end 'invisible t)
13611 (put-text-property beg end 'end-glyph (make-glyph str)))
13612 (put-text-property beg end 'display str))))
13614 (defun org-translate-time (string)
13615 "Translate all timestamps in STRING to custom format.
13616 But do this only if the variable `org-display-custom-times' is set."
13617 (when org-display-custom-times
13618 (save-match-data
13619 (let* ((start 0)
13620 (re org-ts-regexp-both)
13621 t1 with-hm inactive tf time str beg end)
13622 (while (setq start (string-match re string start))
13623 (setq beg (match-beginning 0)
13624 end (match-end 0)
13625 t1 (save-match-data
13626 (org-parse-time-string (substring string beg end) t))
13627 with-hm (and (nth 1 t1) (nth 2 t1))
13628 inactive (equal (substring string beg (1+ beg)) "[")
13629 tf (funcall (if with-hm 'cdr 'car)
13630 org-time-stamp-custom-formats)
13631 time (org-fix-decoded-time t1)
13632 str (format-time-string
13633 (concat
13634 (if inactive "[" "<") (substring tf 1 -1)
13635 (if inactive "]" ">"))
13636 (apply 'encode-time time))
13637 string (replace-match str t t string)
13638 start (+ start (length str)))))))
13639 string)
13641 (defun org-fix-decoded-time (time)
13642 "Set 0 instead of nil for the first 6 elements of time.
13643 Don't touch the rest."
13644 (let ((n 0))
13645 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13647 (defun org-days-to-time (timestamp-string)
13648 "Difference between TIMESTAMP-STRING and now in days."
13649 (- (time-to-days (org-time-string-to-time timestamp-string))
13650 (time-to-days (current-time))))
13652 (defun org-deadline-close (timestamp-string &optional ndays)
13653 "Is the time in TIMESTAMP-STRING close to the current date?"
13654 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13655 (and (< (org-days-to-time timestamp-string) ndays)
13656 (not (org-entry-is-done-p))))
13658 (defun org-get-wdays (ts)
13659 "Get the deadline lead time appropriate for timestring TS."
13660 (cond
13661 ((<= org-deadline-warning-days 0)
13662 ;; 0 or negative, enforce this value no matter what
13663 (- org-deadline-warning-days))
13664 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13665 ;; lead time is specified.
13666 (floor (* (string-to-number (match-string 1 ts))
13667 (cdr (assoc (match-string 2 ts)
13668 '(("d" . 1) ("w" . 7)
13669 ("m" . 30.4) ("y" . 365.25)))))))
13670 ;; go for the default.
13671 (t org-deadline-warning-days)))
13673 (defun org-calendar-select-mouse (ev)
13674 "Return to `org-read-date' with the date currently selected.
13675 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13676 (interactive "e")
13677 (mouse-set-point ev)
13678 (when (calendar-cursor-to-date)
13679 (let* ((date (calendar-cursor-to-date))
13680 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13681 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13682 (if (active-minibuffer-window) (exit-minibuffer))))
13684 (defun org-check-deadlines (ndays)
13685 "Check if there are any deadlines due or past due.
13686 A deadline is considered due if it happens within `org-deadline-warning-days'
13687 days from today's date. If the deadline appears in an entry marked DONE,
13688 it is not shown. The prefix arg NDAYS can be used to test that many
13689 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13690 (interactive "P")
13691 (let* ((org-warn-days
13692 (cond
13693 ((equal ndays '(4)) 100000)
13694 (ndays (prefix-numeric-value ndays))
13695 (t (abs org-deadline-warning-days))))
13696 (case-fold-search nil)
13697 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13698 (callback
13699 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13701 (message "%d deadlines past-due or due within %d days"
13702 (org-occur regexp nil callback)
13703 org-warn-days)))
13705 (defun org-check-before-date (date)
13706 "Check if there are deadlines or scheduled entries before DATE."
13707 (interactive (list (org-read-date)))
13708 (let ((case-fold-search nil)
13709 (regexp (concat "\\<\\(" org-deadline-string
13710 "\\|" org-scheduled-string
13711 "\\) *<\\([^>]+\\)>"))
13712 (callback
13713 (lambda () (time-less-p
13714 (org-time-string-to-time (match-string 2))
13715 (org-time-string-to-time date)))))
13716 (message "%d entries before %s"
13717 (org-occur regexp nil callback) date)))
13719 (defun org-check-after-date (date)
13720 "Check if there are deadlines or scheduled entries after DATE."
13721 (interactive (list (org-read-date)))
13722 (let ((case-fold-search nil)
13723 (regexp (concat "\\<\\(" org-deadline-string
13724 "\\|" org-scheduled-string
13725 "\\) *<\\([^>]+\\)>"))
13726 (callback
13727 (lambda () (not
13728 (time-less-p
13729 (org-time-string-to-time (match-string 2))
13730 (org-time-string-to-time date))))))
13731 (message "%d entries after %s"
13732 (org-occur regexp nil callback) date)))
13734 (defun org-evaluate-time-range (&optional to-buffer)
13735 "Evaluate a time range by computing the difference between start and end.
13736 Normally the result is just printed in the echo area, but with prefix arg
13737 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13738 If the time range is actually in a table, the result is inserted into the
13739 next column.
13740 For time difference computation, a year is assumed to be exactly 365
13741 days in order to avoid rounding problems."
13742 (interactive "P")
13744 (org-clock-update-time-maybe)
13745 (save-excursion
13746 (unless (org-at-date-range-p t)
13747 (goto-char (point-at-bol))
13748 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13749 (if (not (org-at-date-range-p t))
13750 (error "Not at a time-stamp range, and none found in current line")))
13751 (let* ((ts1 (match-string 1))
13752 (ts2 (match-string 2))
13753 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13754 (match-end (match-end 0))
13755 (time1 (org-time-string-to-time ts1))
13756 (time2 (org-time-string-to-time ts2))
13757 (t1 (org-float-time time1))
13758 (t2 (org-float-time time2))
13759 (diff (abs (- t2 t1)))
13760 (negative (< (- t2 t1) 0))
13761 ;; (ys (floor (* 365 24 60 60)))
13762 (ds (* 24 60 60))
13763 (hs (* 60 60))
13764 (fy "%dy %dd %02d:%02d")
13765 (fy1 "%dy %dd")
13766 (fd "%dd %02d:%02d")
13767 (fd1 "%dd")
13768 (fh "%02d:%02d")
13769 y d h m align)
13770 (if havetime
13771 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13773 d (floor (/ diff ds)) diff (mod diff ds)
13774 h (floor (/ diff hs)) diff (mod diff hs)
13775 m (floor (/ diff 60)))
13776 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13778 d (floor (+ (/ diff ds) 0.5))
13779 h 0 m 0))
13780 (if (not to-buffer)
13781 (message "%s" (org-make-tdiff-string y d h m))
13782 (if (org-at-table-p)
13783 (progn
13784 (goto-char match-end)
13785 (setq align t)
13786 (and (looking-at " *|") (goto-char (match-end 0))))
13787 (goto-char match-end))
13788 (if (looking-at
13789 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13790 (replace-match ""))
13791 (if negative (insert " -"))
13792 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13793 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13794 (insert " " (format fh h m))))
13795 (if align (org-table-align))
13796 (message "Time difference inserted")))))
13798 (defun org-make-tdiff-string (y d h m)
13799 (let ((fmt "")
13800 (l nil))
13801 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13802 l (push y l)))
13803 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13804 l (push d l)))
13805 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13806 l (push h l)))
13807 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13808 l (push m l)))
13809 (apply 'format fmt (nreverse l))))
13811 (defun org-time-string-to-time (s)
13812 (apply 'encode-time (org-parse-time-string s)))
13813 (defun org-time-string-to-seconds (s)
13814 (org-float-time (org-time-string-to-time s)))
13816 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13817 "Convert a time stamp to an absolute day number.
13818 If there is a specifyer for a cyclic time stamp, get the closest date to
13819 DAYNR.
13820 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13821 the variable date is bound by the calendar when this is called."
13822 (cond
13823 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13824 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13825 daynr
13826 (+ daynr 1000)))
13827 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13828 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13829 (time-to-days (current-time))) (match-string 0 s)
13830 prefer show-all))
13831 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13833 (defun org-days-to-iso-week (days)
13834 "Return the iso week number."
13835 (require 'cal-iso)
13836 (car (calendar-iso-from-absolute days)))
13838 (defun org-small-year-to-year (year)
13839 "Convert 2-digit years into 4-digit years.
13840 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13841 The year 2000 cannot be abbreviated. Any year larger than 99
13842 is returned unchanged."
13843 (if (< year 38)
13844 (setq year (+ 2000 year))
13845 (if (< year 100)
13846 (setq year (+ 1900 year))))
13847 year)
13849 (defun org-time-from-absolute (d)
13850 "Return the time corresponding to date D.
13851 D may be an absolute day number, or a calendar-type list (month day year)."
13852 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13853 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13855 (defun org-calendar-holiday ()
13856 "List of holidays, for Diary display in Org-mode."
13857 (require 'holidays)
13858 (let ((hl (funcall
13859 (if (fboundp 'calendar-check-holidays)
13860 'calendar-check-holidays 'check-calendar-holidays) date)))
13861 (if hl (mapconcat 'identity hl "; "))))
13863 (defun org-diary-sexp-entry (sexp entry date)
13864 "Process a SEXP diary ENTRY for DATE."
13865 (require 'diary-lib)
13866 (let ((result (if calendar-debug-sexp
13867 (let ((stack-trace-on-error t))
13868 (eval (car (read-from-string sexp))))
13869 (condition-case nil
13870 (eval (car (read-from-string sexp)))
13871 (error
13872 (beep)
13873 (message "Bad sexp at line %d in %s: %s"
13874 (org-current-line)
13875 (buffer-file-name) sexp)
13876 (sleep-for 2))))))
13877 (cond ((stringp result) result)
13878 ((and (consp result)
13879 (stringp (cdr result))) (cdr result))
13880 (result entry)
13881 (t nil))))
13883 (defun org-diary-to-ical-string (frombuf)
13884 "Get iCalendar entries from diary entries in buffer FROMBUF.
13885 This uses the icalendar.el library."
13886 (let* ((tmpdir (if (featurep 'xemacs)
13887 (temp-directory)
13888 temporary-file-directory))
13889 (tmpfile (make-temp-name
13890 (expand-file-name "orgics" tmpdir)))
13891 buf rtn b e)
13892 (with-current-buffer frombuf
13893 (icalendar-export-region (point-min) (point-max) tmpfile)
13894 (setq buf (find-buffer-visiting tmpfile))
13895 (set-buffer buf)
13896 (goto-char (point-min))
13897 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13898 (setq b (match-beginning 0)))
13899 (goto-char (point-max))
13900 (if (re-search-backward "^END:VEVENT" nil t)
13901 (setq e (match-end 0)))
13902 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13903 (kill-buffer buf)
13904 (delete-file tmpfile)
13905 rtn))
13907 (defun org-closest-date (start current change prefer show-all)
13908 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13909 When PREFER is `past' return a date that is either CURRENT or past.
13910 When PREFER is `future', return a date that is either CURRENT or future.
13911 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13912 ;; Make the proper lists from the dates
13913 (catch 'exit
13914 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13915 dn dw sday cday n1 n2 n0
13916 d m y y1 y2 date1 date2 nmonths nm ny m2)
13918 (setq start (org-date-to-gregorian start)
13919 current (org-date-to-gregorian
13920 (if show-all
13921 current
13922 (time-to-days (current-time))))
13923 sday (calendar-absolute-from-gregorian start)
13924 cday (calendar-absolute-from-gregorian current))
13926 (if (<= cday sday) (throw 'exit sday))
13928 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13929 (setq dn (string-to-number (match-string 1 change))
13930 dw (cdr (assoc (match-string 2 change) a1)))
13931 (error "Invalid change specifyer: %s" change))
13932 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13933 (cond
13934 ((eq dw 'day)
13935 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13936 n2 (+ n1 dn)))
13937 ((eq dw 'year)
13938 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13939 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13940 (setq date1 (list m d y1)
13941 n1 (calendar-absolute-from-gregorian date1)
13942 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13943 n2 (calendar-absolute-from-gregorian date2)))
13944 ((eq dw 'month)
13945 ;; approx number of month between the two dates
13946 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13947 ;; How often does dn fit in there?
13948 (setq d (nth 1 start) m (car start) y (nth 2 start)
13949 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13950 m (+ m nm)
13951 ny (floor (/ m 12))
13952 y (+ y ny)
13953 m (- m (* ny 12)))
13954 (while (> m 12) (setq m (- m 12) y (1+ y)))
13955 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13956 (setq m2 (+ m dn) y2 y)
13957 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13958 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13959 (while (<= n2 cday)
13960 (setq n1 n2 m m2 y y2)
13961 (setq m2 (+ m dn) y2 y)
13962 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13963 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13964 ;; Make sure n1 is the earlier date
13965 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13966 (if show-all
13967 (cond
13968 ((eq prefer 'past) (if (= cday n2) n2 n1))
13969 ((eq prefer 'future) (if (= cday n1) n1 n2))
13970 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13971 (cond
13972 ((eq prefer 'past) (if (= cday n2) n2 n1))
13973 ((eq prefer 'future) (if (= cday n1) n1 n2))
13974 (t (if (= cday n1) n1 n2)))))))
13976 (defun org-date-to-gregorian (date)
13977 "Turn any specification of DATE into a gregorian date for the calendar."
13978 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13979 ((and (listp date) (= (length date) 3)) date)
13980 ((stringp date)
13981 (setq date (org-parse-time-string date))
13982 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13983 ((listp date)
13984 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13986 (defun org-parse-time-string (s &optional nodefault)
13987 "Parse the standard Org-mode time string.
13988 This should be a lot faster than the normal `parse-time-string'.
13989 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13990 hour and minute fields will be nil if not given."
13991 (if (string-match org-ts-regexp0 s)
13992 (list 0
13993 (if (or (match-beginning 8) (not nodefault))
13994 (string-to-number (or (match-string 8 s) "0")))
13995 (if (or (match-beginning 7) (not nodefault))
13996 (string-to-number (or (match-string 7 s) "0")))
13997 (string-to-number (match-string 4 s))
13998 (string-to-number (match-string 3 s))
13999 (string-to-number (match-string 2 s))
14000 nil nil nil)
14001 (error "Not a standard Org-mode time string: %s" s)))
14003 (defun org-timestamp-up (&optional arg)
14004 "Increase the date item at the cursor by one.
14005 If the cursor is on the year, change the year. If it is on the month or
14006 the day, change that.
14007 With prefix ARG, change by that many units."
14008 (interactive "p")
14009 (org-timestamp-change (prefix-numeric-value arg)))
14011 (defun org-timestamp-down (&optional arg)
14012 "Decrease the date item at the cursor by one.
14013 If the cursor is on the year, change the year. If it is on the month or
14014 the day, change that.
14015 With prefix ARG, change by that many units."
14016 (interactive "p")
14017 (org-timestamp-change (- (prefix-numeric-value arg))))
14019 (defun org-timestamp-up-day (&optional arg)
14020 "Increase the date in the time stamp by one day.
14021 With prefix ARG, change that many days."
14022 (interactive "p")
14023 (if (and (not (org-at-timestamp-p t))
14024 (org-on-heading-p))
14025 (org-todo 'up)
14026 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14028 (defun org-timestamp-down-day (&optional arg)
14029 "Decrease the date in the time stamp by one day.
14030 With prefix ARG, change that many days."
14031 (interactive "p")
14032 (if (and (not (org-at-timestamp-p t))
14033 (org-on-heading-p))
14034 (org-todo 'down)
14035 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14037 (defun org-at-timestamp-p (&optional inactive-ok)
14038 "Determine if the cursor is in or at a timestamp."
14039 (interactive)
14040 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14041 (pos (point))
14042 (ans (or (looking-at tsr)
14043 (save-excursion
14044 (skip-chars-backward "^[<\n\r\t")
14045 (if (> (point) (point-min)) (backward-char 1))
14046 (and (looking-at tsr)
14047 (> (- (match-end 0) pos) -1))))))
14048 (and ans
14049 (boundp 'org-ts-what)
14050 (setq org-ts-what
14051 (cond
14052 ((= pos (match-beginning 0)) 'bracket)
14053 ((= pos (1- (match-end 0))) 'bracket)
14054 ((org-pos-in-match-range pos 2) 'year)
14055 ((org-pos-in-match-range pos 3) 'month)
14056 ((org-pos-in-match-range pos 7) 'hour)
14057 ((org-pos-in-match-range pos 8) 'minute)
14058 ((or (org-pos-in-match-range pos 4)
14059 (org-pos-in-match-range pos 5)) 'day)
14060 ((and (> pos (or (match-end 8) (match-end 5)))
14061 (< pos (match-end 0)))
14062 (- pos (or (match-end 8) (match-end 5))))
14063 (t 'day))))
14064 ans))
14066 (defun org-toggle-timestamp-type ()
14067 "Toggle the type (<active> or [inactive]) of a time stamp."
14068 (interactive)
14069 (when (org-at-timestamp-p t)
14070 (let ((beg (match-beginning 0)) (end (match-end 0))
14071 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14072 (save-excursion
14073 (goto-char beg)
14074 (while (re-search-forward "[][<>]" end t)
14075 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14076 t t)))
14077 (message "Timestamp is now %sactive"
14078 (if (equal (char-after beg) ?<) "" "in")))))
14080 (defun org-timestamp-change (n &optional what)
14081 "Change the date in the time stamp at point.
14082 The date will be changed by N times WHAT. WHAT can be `day', `month',
14083 `year', `minute', `second'. If WHAT is not given, the cursor position
14084 in the timestamp determines what will be changed."
14085 (let ((pos (point))
14086 with-hm inactive
14087 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14088 org-ts-what
14089 extra rem
14090 ts time time0)
14091 (if (not (org-at-timestamp-p t))
14092 (error "Not at a timestamp"))
14093 (if (and (not what) (eq org-ts-what 'bracket))
14094 (org-toggle-timestamp-type)
14095 (if (and (not what) (not (eq org-ts-what 'day))
14096 org-display-custom-times
14097 (get-text-property (point) 'display)
14098 (not (get-text-property (1- (point)) 'display)))
14099 (setq org-ts-what 'day))
14100 (setq org-ts-what (or what org-ts-what)
14101 inactive (= (char-after (match-beginning 0)) ?\[)
14102 ts (match-string 0))
14103 (replace-match "")
14104 (if (string-match
14105 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14107 (setq extra (match-string 1 ts)))
14108 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14109 (setq with-hm t))
14110 (setq time0 (org-parse-time-string ts))
14111 (when (and (eq org-ts-what 'minute)
14112 (eq current-prefix-arg nil))
14113 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14114 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14115 (setcar (cdr time0) (+ (nth 1 time0)
14116 (if (> n 0) (- rem) (- dm rem))))))
14117 (setq time
14118 (encode-time (or (car time0) 0)
14119 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14120 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14121 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14122 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14123 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14124 (nthcdr 6 time0)))
14125 (when (and (member org-ts-what '(hour minute))
14126 extra
14127 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14128 (setq extra (org-modify-ts-extra
14129 extra
14130 (if (eq org-ts-what 'hour) 2 5)
14131 n dm)))
14132 (when (integerp org-ts-what)
14133 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14134 (if (eq what 'calendar)
14135 (let ((cal-date (org-get-date-from-calendar)))
14136 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14137 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14138 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14139 (setcar time0 (or (car time0) 0))
14140 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14141 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14142 (setq time (apply 'encode-time time0))))
14143 (setq org-last-changed-timestamp
14144 (org-insert-time-stamp time with-hm inactive nil nil extra))
14145 (org-clock-update-time-maybe)
14146 (goto-char pos)
14147 ;; Try to recenter the calendar window, if any
14148 (if (and org-calendar-follow-timestamp-change
14149 (get-buffer-window "*Calendar*" t)
14150 (memq org-ts-what '(day month year)))
14151 (org-recenter-calendar (time-to-days time))))))
14153 (defun org-modify-ts-extra (s pos n dm)
14154 "Change the different parts of the lead-time and repeat fields in timestamp."
14155 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14156 ng h m new rem)
14157 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14158 (cond
14159 ((or (org-pos-in-match-range pos 2)
14160 (org-pos-in-match-range pos 3))
14161 (setq m (string-to-number (match-string 3 s))
14162 h (string-to-number (match-string 2 s)))
14163 (if (org-pos-in-match-range pos 2)
14164 (setq h (+ h n))
14165 (setq n (* dm (org-no-warnings (signum n))))
14166 (when (not (= 0 (setq rem (% m dm))))
14167 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14168 (setq m (+ m n)))
14169 (if (< m 0) (setq m (+ m 60) h (1- h)))
14170 (if (> m 59) (setq m (- m 60) h (1+ h)))
14171 (setq h (min 24 (max 0 h)))
14172 (setq ng 1 new (format "-%02d:%02d" h m)))
14173 ((org-pos-in-match-range pos 6)
14174 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14175 ((org-pos-in-match-range pos 5)
14176 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14178 ((org-pos-in-match-range pos 9)
14179 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14180 ((org-pos-in-match-range pos 8)
14181 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14183 (when ng
14184 (setq s (concat
14185 (substring s 0 (match-beginning ng))
14187 (substring s (match-end ng))))))
14190 (defun org-recenter-calendar (date)
14191 "If the calendar is visible, recenter it to DATE."
14192 (let* ((win (selected-window))
14193 (cwin (get-buffer-window "*Calendar*" t))
14194 (calendar-move-hook nil))
14195 (when cwin
14196 (select-window cwin)
14197 (calendar-goto-date (if (listp date) date
14198 (calendar-gregorian-from-absolute date)))
14199 (select-window win))))
14201 (defun org-goto-calendar (&optional arg)
14202 "Go to the Emacs calendar at the current date.
14203 If there is a time stamp in the current line, go to that date.
14204 A prefix ARG can be used to force the current date."
14205 (interactive "P")
14206 (let ((tsr org-ts-regexp) diff
14207 (calendar-move-hook nil)
14208 (calendar-view-holidays-initially-flag nil)
14209 (view-calendar-holidays-initially nil)
14210 (calendar-view-diary-initially-flag nil)
14211 (view-diary-entries-initially nil))
14212 (if (or (org-at-timestamp-p)
14213 (save-excursion
14214 (beginning-of-line 1)
14215 (looking-at (concat ".*" tsr))))
14216 (let ((d1 (time-to-days (current-time)))
14217 (d2 (time-to-days
14218 (org-time-string-to-time (match-string 1)))))
14219 (setq diff (- d2 d1))))
14220 (calendar)
14221 (calendar-goto-today)
14222 (if (and diff (not arg)) (calendar-forward-day diff))))
14224 (defun org-get-date-from-calendar ()
14225 "Return a list (month day year) of date at point in calendar."
14226 (with-current-buffer "*Calendar*"
14227 (save-match-data
14228 (calendar-cursor-to-date))))
14230 (defun org-date-from-calendar ()
14231 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14232 If there is already a time stamp at the cursor position, update it."
14233 (interactive)
14234 (if (org-at-timestamp-p t)
14235 (org-timestamp-change 0 'calendar)
14236 (let ((cal-date (org-get-date-from-calendar)))
14237 (org-insert-time-stamp
14238 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14240 (defun org-minutes-to-hh:mm-string (m)
14241 "Compute H:MM from a number of minutes."
14242 (let ((h (/ m 60)))
14243 (setq m (- m (* 60 h)))
14244 (format org-time-clocksum-format h m)))
14246 (defun org-hh:mm-string-to-minutes (s)
14247 "Convert a string H:MM to a number of minutes.
14248 If the string is just a number, interpret it as minutes.
14249 In fact, the first hh:mm or number in the string will be taken,
14250 there can be extra stuff in the string.
14251 If no number is found, the return value is 0."
14252 (cond
14253 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14254 (+ (* (string-to-number (match-string 1 s)) 60)
14255 (string-to-number (match-string 2 s))))
14256 ((string-match "\\([0-9]+\\)" s)
14257 (string-to-number (match-string 1 s)))
14258 (t 0)))
14260 ;;;; Files
14262 (defun org-save-all-org-buffers ()
14263 "Save all Org-mode buffers without user confirmation."
14264 (interactive)
14265 (message "Saving all Org-mode buffers...")
14266 (save-some-buffers t 'org-mode-p)
14267 (when (featurep 'org-id) (org-id-locations-save))
14268 (message "Saving all Org-mode buffers... done"))
14270 (defun org-revert-all-org-buffers ()
14271 "Revert all Org-mode buffers.
14272 Prompt for confirmation when there are unsaved changes.
14273 Be sure you know what you are doing before letting this function
14274 overwrite your changes.
14276 This function is useful in a setup where one tracks org files
14277 with a version control system, to revert on one machine after pulling
14278 changes from another. I believe the procedure must be like this:
14280 1. M-x org-save-all-org-buffers
14281 2. Pull changes from the other machine, resolve conflicts
14282 3. M-x org-revert-all-org-buffers"
14283 (interactive)
14284 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14285 (error "Abort"))
14286 (save-excursion
14287 (save-window-excursion
14288 (mapc
14289 (lambda (b)
14290 (when (and (with-current-buffer b (org-mode-p))
14291 (with-current-buffer b buffer-file-name))
14292 (switch-to-buffer b)
14293 (revert-buffer t 'no-confirm)))
14294 (buffer-list))
14295 (when (and (featurep 'org-id) org-id-track-globally)
14296 (org-id-locations-load)))))
14298 ;;;; Agenda files
14300 ;;;###autoload
14301 (defun org-iswitchb (&optional arg)
14302 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14303 With a prefix argument, restrict available to files.
14304 With two prefix arguments, restrict available buffers to agenda files."
14305 (interactive "P")
14306 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14307 ((equal arg '(16)) (org-buffer-list 'agenda))
14308 (t (org-buffer-list)))))
14309 (switch-to-buffer
14310 (org-icompleting-read "Org buffer: "
14311 (mapcar 'list (mapcar 'buffer-name blist))
14312 nil t))))
14314 ;;;###autoload
14315 (defalias 'org-ido-switchb 'org-iswitchb)
14317 (defun org-buffer-list (&optional predicate exclude-tmp)
14318 "Return a list of Org buffers.
14319 PREDICATE can be `export', `files' or `agenda'.
14321 export restrict the list to Export buffers.
14322 files restrict the list to buffers visiting Org files.
14323 agenda restrict the list to buffers visiting agenda files.
14325 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14326 (let* ((bfn nil)
14327 (agenda-files (and (eq predicate 'agenda)
14328 (mapcar 'file-truename (org-agenda-files t))))
14329 (filter
14330 (cond
14331 ((eq predicate 'files)
14332 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14333 ((eq predicate 'export)
14334 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14335 ((eq predicate 'agenda)
14336 (lambda (b)
14337 (with-current-buffer b
14338 (and (eq major-mode 'org-mode)
14339 (setq bfn (buffer-file-name b))
14340 (member (file-truename bfn) agenda-files)))))
14341 (t (lambda (b) (with-current-buffer b
14342 (or (eq major-mode 'org-mode)
14343 (string-match "\*Org .*Export"
14344 (buffer-name b)))))))))
14345 (delq nil
14346 (mapcar
14347 (lambda(b)
14348 (if (and (funcall filter b)
14349 (or (not exclude-tmp)
14350 (not (string-match "tmp" (buffer-name b)))))
14352 nil))
14353 (buffer-list)))))
14355 (defun org-agenda-files (&optional unrestricted archives)
14356 "Get the list of agenda files.
14357 Optional UNRESTRICTED means return the full list even if a restriction
14358 is currently in place.
14359 When ARCHIVES is t, include all archive files hat are really being
14360 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14361 `org-agenda-archives-mode' is t."
14362 (let ((files
14363 (cond
14364 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14365 ((stringp org-agenda-files) (org-read-agenda-file-list))
14366 ((listp org-agenda-files) org-agenda-files)
14367 (t (error "Invalid value of `org-agenda-files'")))))
14368 (setq files (apply 'append
14369 (mapcar (lambda (f)
14370 (if (file-directory-p f)
14371 (directory-files
14372 f t org-agenda-file-regexp)
14373 (list f)))
14374 files)))
14375 (when org-agenda-skip-unavailable-files
14376 (setq files (delq nil
14377 (mapcar (function
14378 (lambda (file)
14379 (and (file-readable-p file) file)))
14380 files))))
14381 (when (or (eq archives t)
14382 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14383 (setq files (org-add-archive-files files)))
14384 files))
14386 (defun org-edit-agenda-file-list ()
14387 "Edit the list of agenda files.
14388 Depending on setup, this either uses customize to edit the variable
14389 `org-agenda-files', or it visits the file that is holding the list. In the
14390 latter case, the buffer is set up in a way that saving it automatically kills
14391 the buffer and restores the previous window configuration."
14392 (interactive)
14393 (if (stringp org-agenda-files)
14394 (let ((cw (current-window-configuration)))
14395 (find-file org-agenda-files)
14396 (org-set-local 'org-window-configuration cw)
14397 (org-add-hook 'after-save-hook
14398 (lambda ()
14399 (set-window-configuration
14400 (prog1 org-window-configuration
14401 (kill-buffer (current-buffer))))
14402 (org-install-agenda-files-menu)
14403 (message "New agenda file list installed"))
14404 nil 'local)
14405 (message "%s" (substitute-command-keys
14406 "Edit list and finish with \\[save-buffer]")))
14407 (customize-variable 'org-agenda-files)))
14409 (defun org-store-new-agenda-file-list (list)
14410 "Set new value for the agenda file list and save it correctly."
14411 (if (stringp org-agenda-files)
14412 (let ((f org-agenda-files) b)
14413 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14414 (with-temp-file f
14415 (insert (mapconcat 'identity list "\n") "\n")))
14416 (let ((org-mode-hook nil) (org-inhibit-startup t)
14417 (org-insert-mode-line-in-empty-file nil))
14418 (setq org-agenda-files list)
14419 (customize-save-variable 'org-agenda-files org-agenda-files))))
14421 (defun org-read-agenda-file-list ()
14422 "Read the list of agenda files from a file."
14423 (when (file-directory-p org-agenda-files)
14424 (error "`org-agenda-files' cannot be a single directory"))
14425 (when (stringp org-agenda-files)
14426 (with-temp-buffer
14427 (insert-file-contents org-agenda-files)
14428 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14431 ;;;###autoload
14432 (defun org-cycle-agenda-files ()
14433 "Cycle through the files in `org-agenda-files'.
14434 If the current buffer visits an agenda file, find the next one in the list.
14435 If the current buffer does not, find the first agenda file."
14436 (interactive)
14437 (let* ((fs (org-agenda-files t))
14438 (files (append fs (list (car fs))))
14439 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14440 file)
14441 (unless files (error "No agenda files"))
14442 (catch 'exit
14443 (while (setq file (pop files))
14444 (if (equal (file-truename file) tcf)
14445 (when (car files)
14446 (find-file (car files))
14447 (throw 'exit t))))
14448 (find-file (car fs)))
14449 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14451 (defun org-agenda-file-to-front (&optional to-end)
14452 "Move/add the current file to the top of the agenda file list.
14453 If the file is not present in the list, it is added to the front. If it is
14454 present, it is moved there. With optional argument TO-END, add/move to the
14455 end of the list."
14456 (interactive "P")
14457 (let ((org-agenda-skip-unavailable-files nil)
14458 (file-alist (mapcar (lambda (x)
14459 (cons (file-truename x) x))
14460 (org-agenda-files t)))
14461 (ctf (file-truename buffer-file-name))
14462 x had)
14463 (setq x (assoc ctf file-alist) had x)
14465 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14466 (if to-end
14467 (setq file-alist (append (delq x file-alist) (list x)))
14468 (setq file-alist (cons x (delq x file-alist))))
14469 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14470 (org-install-agenda-files-menu)
14471 (message "File %s to %s of agenda file list"
14472 (if had "moved" "added") (if to-end "end" "front"))))
14474 (defun org-remove-file (&optional file)
14475 "Remove current file from the list of files in variable `org-agenda-files'.
14476 These are the files which are being checked for agenda entries.
14477 Optional argument FILE means, use this file instead of the current."
14478 (interactive)
14479 (let* ((org-agenda-skip-unavailable-files nil)
14480 (file (or file buffer-file-name))
14481 (true-file (file-truename file))
14482 (afile (abbreviate-file-name file))
14483 (files (delq nil (mapcar
14484 (lambda (x)
14485 (if (equal true-file
14486 (file-truename x))
14487 nil x))
14488 (org-agenda-files t)))))
14489 (if (not (= (length files) (length (org-agenda-files t))))
14490 (progn
14491 (org-store-new-agenda-file-list files)
14492 (org-install-agenda-files-menu)
14493 (message "Removed file: %s" afile))
14494 (message "File was not in list: %s (not removed)" afile))))
14496 (defun org-file-menu-entry (file)
14497 (vector file (list 'find-file file) t))
14499 (defun org-check-agenda-file (file)
14500 "Make sure FILE exists. If not, ask user what to do."
14501 (when (not (file-exists-p file))
14502 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14503 (abbreviate-file-name file))
14504 (let ((r (downcase (read-char-exclusive))))
14505 (cond
14506 ((equal r ?r)
14507 (org-remove-file file)
14508 (throw 'nextfile t))
14509 (t (error "Abort"))))))
14511 (defun org-get-agenda-file-buffer (file)
14512 "Get a buffer visiting FILE. If the buffer needs to be created, add
14513 it to the list of buffers which might be released later."
14514 (let ((buf (org-find-base-buffer-visiting file)))
14515 (if buf
14516 buf ; just return it
14517 ;; Make a new buffer and remember it
14518 (setq buf (find-file-noselect file))
14519 (if buf (push buf org-agenda-new-buffers))
14520 buf)))
14522 (defun org-release-buffers (blist)
14523 "Release all buffers in list, asking the user for confirmation when needed.
14524 When a buffer is unmodified, it is just killed. When modified, it is saved
14525 \(if the user agrees) and then killed."
14526 (let (buf file)
14527 (while (setq buf (pop blist))
14528 (setq file (buffer-file-name buf))
14529 (when (and (buffer-modified-p buf)
14530 file
14531 (y-or-n-p (format "Save file %s? " file)))
14532 (with-current-buffer buf (save-buffer)))
14533 (kill-buffer buf))))
14535 (defun org-prepare-agenda-buffers (files)
14536 "Create buffers for all agenda files, protect archived trees and comments."
14537 (interactive)
14538 (let ((pa '(:org-archived t))
14539 (pc '(:org-comment t))
14540 (pall '(:org-archived t :org-comment t))
14541 (inhibit-read-only t)
14542 (rea (concat ":" org-archive-tag ":"))
14543 bmp file re)
14544 (save-excursion
14545 (save-restriction
14546 (while (setq file (pop files))
14547 (catch 'nextfile
14548 (if (bufferp file)
14549 (set-buffer file)
14550 (org-check-agenda-file file)
14551 (set-buffer (org-get-agenda-file-buffer file)))
14552 (widen)
14553 (setq bmp (buffer-modified-p))
14554 (org-refresh-category-properties)
14555 (setq org-todo-keywords-for-agenda
14556 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14557 (setq org-done-keywords-for-agenda
14558 (append org-done-keywords-for-agenda org-done-keywords))
14559 (setq org-todo-keyword-alist-for-agenda
14560 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14561 (setq org-drawers-for-agenda
14562 (append org-drawers-for-agenda org-drawers))
14563 (setq org-tag-alist-for-agenda
14564 (append org-tag-alist-for-agenda org-tag-alist))
14566 (save-excursion
14567 (remove-text-properties (point-min) (point-max) pall)
14568 (when org-agenda-skip-archived-trees
14569 (goto-char (point-min))
14570 (while (re-search-forward rea nil t)
14571 (if (org-on-heading-p t)
14572 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14573 (goto-char (point-min))
14574 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14575 (while (re-search-forward re nil t)
14576 (add-text-properties
14577 (match-beginning 0) (org-end-of-subtree t) pc)))
14578 (set-buffer-modified-p bmp)))))
14579 (setq org-todo-keyword-alist-for-agenda
14580 (org-uniquify org-todo-keyword-alist-for-agenda)
14581 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14583 ;;;; Embedded LaTeX
14585 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14586 "Keymap for the minor `org-cdlatex-mode'.")
14588 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14589 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14590 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14591 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14592 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14594 (defvar org-cdlatex-texmathp-advice-is-done nil
14595 "Flag remembering if we have applied the advice to texmathp already.")
14597 (define-minor-mode org-cdlatex-mode
14598 "Toggle the minor `org-cdlatex-mode'.
14599 This mode supports entering LaTeX environment and math in LaTeX fragments
14600 in Org-mode.
14601 \\{org-cdlatex-mode-map}"
14602 nil " OCDL" nil
14603 (when org-cdlatex-mode (require 'cdlatex))
14604 (unless org-cdlatex-texmathp-advice-is-done
14605 (setq org-cdlatex-texmathp-advice-is-done t)
14606 (defadvice texmathp (around org-math-always-on activate)
14607 "Always return t in org-mode buffers.
14608 This is because we want to insert math symbols without dollars even outside
14609 the LaTeX math segments. If Orgmode thinks that point is actually inside
14610 an embedded LaTeX fragment, let texmathp do its job.
14611 \\[org-cdlatex-mode-map]"
14612 (interactive)
14613 (let (p)
14614 (cond
14615 ((not (org-mode-p)) ad-do-it)
14616 ((eq this-command 'cdlatex-math-symbol)
14617 (setq ad-return-value t
14618 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14620 (let ((p (org-inside-LaTeX-fragment-p)))
14621 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14622 (setq ad-return-value t
14623 texmathp-why '("Org-mode embedded math" . 0))
14624 (if p ad-do-it)))))))))
14626 (defun turn-on-org-cdlatex ()
14627 "Unconditionally turn on `org-cdlatex-mode'."
14628 (org-cdlatex-mode 1))
14630 (defun org-inside-LaTeX-fragment-p ()
14631 "Test if point is inside a LaTeX fragment.
14632 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14633 sequence appearing also before point.
14634 Even though the matchers for math are configurable, this function assumes
14635 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14636 delimiters are skipped when they have been removed by customization.
14637 The return value is nil, or a cons cell with the delimiter and
14638 and the position of this delimiter.
14640 This function does a reasonably good job, but can locally be fooled by
14641 for example currency specifications. For example it will assume being in
14642 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14643 fragments that are properly closed, but during editing, we have to live
14644 with the uncertainty caused by missing closing delimiters. This function
14645 looks only before point, not after."
14646 (catch 'exit
14647 (let ((pos (point))
14648 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14649 (lim (progn
14650 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14651 (point)))
14652 dd-on str (start 0) m re)
14653 (goto-char pos)
14654 (when dodollar
14655 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14656 re (nth 1 (assoc "$" org-latex-regexps)))
14657 (while (string-match re str start)
14658 (cond
14659 ((= (match-end 0) (length str))
14660 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14661 ((= (match-end 0) (- (length str) 5))
14662 (throw 'exit nil))
14663 (t (setq start (match-end 0))))))
14664 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14665 (goto-char pos)
14666 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14667 (and (match-beginning 2) (throw 'exit nil))
14668 ;; count $$
14669 (while (re-search-backward "\\$\\$" lim t)
14670 (setq dd-on (not dd-on)))
14671 (goto-char pos)
14672 (if dd-on (cons "$$" m))))))
14674 (defun org-inside-latex-macro-p ()
14675 "Is point inside a LaTeX macro or its arguments?"
14676 (save-match-data
14677 (org-in-regexp
14678 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14680 (defun org-try-cdlatex-tab ()
14681 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14682 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14683 - inside a LaTeX fragment, or
14684 - after the first word in a line, where an abbreviation expansion could
14685 insert a LaTeX environment."
14686 (when org-cdlatex-mode
14687 (cond
14688 ((save-excursion
14689 (skip-chars-backward "a-zA-Z0-9*")
14690 (skip-chars-backward " \t")
14691 (bolp))
14692 (cdlatex-tab) t)
14693 ((org-inside-LaTeX-fragment-p)
14694 (cdlatex-tab) t)
14695 (t nil))))
14697 (defun org-cdlatex-underscore-caret (&optional arg)
14698 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14699 Revert to the normal definition outside of these fragments."
14700 (interactive "P")
14701 (if (org-inside-LaTeX-fragment-p)
14702 (call-interactively 'cdlatex-sub-superscript)
14703 (let (org-cdlatex-mode)
14704 (call-interactively (key-binding (vector last-input-event))))))
14706 (defun org-cdlatex-math-modify (&optional arg)
14707 "Execute `cdlatex-math-modify' in LaTeX fragments.
14708 Revert to the normal definition outside of these fragments."
14709 (interactive "P")
14710 (if (org-inside-LaTeX-fragment-p)
14711 (call-interactively 'cdlatex-math-modify)
14712 (let (org-cdlatex-mode)
14713 (call-interactively (key-binding (vector last-input-event))))))
14715 (defvar org-latex-fragment-image-overlays nil
14716 "List of overlays carrying the images of latex fragments.")
14717 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14719 (defun org-remove-latex-fragment-image-overlays ()
14720 "Remove all overlays with LaTeX fragment images in current buffer."
14721 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14722 (setq org-latex-fragment-image-overlays nil))
14724 (defun org-preview-latex-fragment (&optional subtree)
14725 "Preview the LaTeX fragment at point, or all locally or globally.
14726 If the cursor is in a LaTeX fragment, create the image and overlay
14727 it over the source code. If there is no fragment at point, display
14728 all fragments in the current text, from one headline to the next. With
14729 prefix SUBTREE, display all fragments in the current subtree. With a
14730 double prefix `C-u C-u', or when the cursor is before the first headline,
14731 display all fragments in the buffer.
14732 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14733 (interactive "P")
14734 (org-remove-latex-fragment-image-overlays)
14735 (save-excursion
14736 (save-restriction
14737 (let (beg end at msg)
14738 (cond
14739 ((or (equal subtree '(16))
14740 (not (save-excursion
14741 (re-search-backward (concat "^" outline-regexp) nil t))))
14742 (setq beg (point-min) end (point-max)
14743 msg "Creating images for buffer...%s"))
14744 ((equal subtree '(4))
14745 (org-back-to-heading)
14746 (setq beg (point) end (org-end-of-subtree t)
14747 msg "Creating images for subtree...%s"))
14749 (if (setq at (org-inside-LaTeX-fragment-p))
14750 (goto-char (max (point-min) (- (cdr at) 2)))
14751 (org-back-to-heading))
14752 (setq beg (point) end (progn (outline-next-heading) (point))
14753 msg (if at "Creating image...%s"
14754 "Creating images for entry...%s"))))
14755 (message msg "")
14756 (narrow-to-region beg end)
14757 (goto-char beg)
14758 (org-format-latex
14759 (concat "ltxpng/" (file-name-sans-extension
14760 (file-name-nondirectory
14761 buffer-file-name)))
14762 default-directory 'overlays msg at 'forbuffer)
14763 (message msg "done. Use `C-c C-c' to remove images.")))))
14765 (defvar org-latex-regexps
14766 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14767 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14768 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14769 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14770 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14771 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14772 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14773 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14774 "Regular expressions for matching embedded LaTeX.")
14776 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14777 "Replace LaTeX fragments with links to an image, and produce images.
14778 Some of the options can be changed using the variable
14779 `org-format-latex-options'."
14780 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14781 (let* ((prefixnodir (file-name-nondirectory prefix))
14782 (absprefix (expand-file-name prefix dir))
14783 (todir (file-name-directory absprefix))
14784 (opt org-format-latex-options)
14785 (matchers (plist-get opt :matchers))
14786 (re-list org-latex-regexps)
14787 (cnt 0) txt hash link beg end re e checkdir
14788 executables-checked
14789 m n block linkfile movefile ov)
14790 ;; Check the different regular expressions
14791 (while (setq e (pop re-list))
14792 (setq m (car e) re (nth 1 e) n (nth 2 e)
14793 block (if (nth 3 e) "\n\n" ""))
14794 (when (member m matchers)
14795 (goto-char (point-min))
14796 (while (re-search-forward re nil t)
14797 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14798 (not (get-text-property (match-beginning n)
14799 'org-protected))
14800 (or (not overlays)
14801 (not (eq (get-char-property (match-beginning n)
14802 'org-overlay-type)
14803 'org-latex-overlay))))
14804 (setq txt (match-string n)
14805 beg (match-beginning n) end (match-end n)
14806 cnt (1+ cnt))
14807 (let (print-length print-level) ; make sure full list is printed
14808 (setq hash (sha1 (prin1-to-string
14809 (list org-format-latex-header
14810 org-export-latex-packages-alist
14811 org-format-latex-options
14812 forbuffer txt)))
14813 linkfile (format "%s_%s.png" prefix hash)
14814 movefile (format "%s_%s.png" absprefix hash)))
14815 (setq link (concat block "[[file:" linkfile "]]" block))
14816 (if msg (message msg cnt))
14817 (goto-char beg)
14818 (unless checkdir ; make sure the directory exists
14819 (setq checkdir t)
14820 (or (file-directory-p todir) (make-directory todir)))
14822 (unless executables-checked
14823 (org-check-external-command
14824 "latex" "needed to convert LaTeX fragments to images")
14825 (org-check-external-command
14826 "dvipng" "needed to convert LaTeX fragments to images")
14827 (setq executables-checked t))
14829 (unless (file-exists-p movefile)
14830 (org-create-formula-image
14831 txt movefile opt forbuffer))
14832 (if overlays
14833 (progn
14834 (mapc (lambda (o)
14835 (if (eq (org-overlay-get o 'org-overlay-type)
14836 'org-latex-overlay)
14837 (org-delete-overlay o)))
14838 (org-overlays-in beg end))
14839 (setq ov (org-make-overlay beg end))
14840 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14841 (if (featurep 'xemacs)
14842 (progn
14843 (org-overlay-put ov 'invisible t)
14844 (org-overlay-put
14845 ov 'end-glyph
14846 (make-glyph (vector 'png :file movefile))))
14847 (org-overlay-put
14848 ov 'display
14849 (list 'image :type 'png :file movefile :ascent 'center)))
14850 (push ov org-latex-fragment-image-overlays)
14851 (goto-char end))
14852 (delete-region beg end)
14853 (insert link))))))))
14855 ;; This function borrows from Ganesh Swami's latex2png.el
14856 (defun org-create-formula-image (string tofile options buffer)
14857 "This calls dvipng."
14858 (require 'org-latex)
14859 (let* ((tmpdir (if (featurep 'xemacs)
14860 (temp-directory)
14861 temporary-file-directory))
14862 (texfilebase (make-temp-name
14863 (expand-file-name "orgtex" tmpdir)))
14864 (texfile (concat texfilebase ".tex"))
14865 (dvifile (concat texfilebase ".dvi"))
14866 (pngfile (concat texfilebase ".png"))
14867 (fnh (if (featurep 'xemacs)
14868 (font-height (get-face-font 'default))
14869 (face-attribute 'default :height nil)))
14870 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14871 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14872 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14873 "Black"))
14874 (bg (or (plist-get options (if buffer :background :html-background))
14875 "Transparent")))
14876 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14877 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14878 (with-temp-file texfile
14879 (insert org-format-latex-header
14880 (if org-export-latex-packages-alist
14881 (concat "\n"
14882 (mapconcat (lambda(p)
14883 (if (equal "" (car p))
14884 (format "\\usepackage{%s}" (cadr p))
14885 (format "\\usepackage[%s]{%s}"
14886 (car p) (cadr p))))
14887 org-export-latex-packages-alist "\n"))
14889 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14890 (let ((dir default-directory))
14891 (condition-case nil
14892 (progn
14893 (cd tmpdir)
14894 (call-process "latex" nil nil nil texfile))
14895 (error nil))
14896 (cd dir))
14897 (if (not (file-exists-p dvifile))
14898 (progn (message "Failed to create dvi file from %s" texfile) nil)
14899 (condition-case nil
14900 (call-process "dvipng" nil nil nil
14901 "-fg" fg "-bg" bg
14902 "-D" dpi
14903 ;;"-x" scale "-y" scale
14904 "-T" "tight"
14905 "-o" pngfile
14906 dvifile)
14907 (error nil))
14908 (if (not (file-exists-p pngfile))
14909 (progn (message "Failed to create png file from %s" texfile) nil)
14910 ;; Use the requested file name and clean up
14911 (copy-file pngfile tofile 'replace)
14912 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14913 (delete-file (concat texfilebase e)))
14914 pngfile))))
14916 (defun org-dvipng-color (attr)
14917 "Return an rgb color specification for dvipng."
14918 (apply 'format "rgb %s %s %s"
14919 (mapcar 'org-normalize-color
14920 (color-values (face-attribute 'default attr nil)))))
14922 (defun org-normalize-color (value)
14923 "Return string to be used as color value for an RGB component."
14924 (format "%g" (/ value 65535.0)))
14926 ;;;; Key bindings
14928 ;; Make `C-c C-x' a prefix key
14929 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14931 ;; TAB key with modifiers
14932 (org-defkey org-mode-map "\C-i" 'org-cycle)
14933 (org-defkey org-mode-map [(tab)] 'org-cycle)
14934 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14935 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14936 (org-defkey org-mode-map "\M-\t" 'org-complete)
14937 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14938 ;; The following line is necessary under Suse GNU/Linux
14939 (unless (featurep 'xemacs)
14940 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14941 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14942 (define-key org-mode-map [backtab] 'org-shifttab)
14944 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14945 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14946 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14948 ;; Cursor keys with modifiers
14949 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14950 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14951 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14952 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14954 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14955 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14956 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14957 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14959 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14960 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14961 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14962 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14964 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14965 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14967 ;;; Extra keys for tty access.
14968 ;; We only set them when really needed because otherwise the
14969 ;; menus don't show the simple keys
14971 (when (or org-use-extra-keys
14972 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14973 (not window-system))
14974 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14975 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14976 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14977 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14978 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14979 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14980 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14981 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14982 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14983 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14984 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14985 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14986 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14987 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14988 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14989 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14990 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14991 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14992 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14993 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14994 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14995 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14996 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14997 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14998 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14999 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15000 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15001 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15003 ;; All the other keys
15005 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15006 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15007 (if (boundp 'narrow-map)
15008 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15009 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15010 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15011 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15012 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15013 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15014 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15015 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15016 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15017 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15018 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15019 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15020 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15021 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15022 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15023 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15024 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15025 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15026 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15027 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15028 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15029 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15030 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15031 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15032 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15033 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15034 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15035 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15036 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15037 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15038 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15039 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15040 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15041 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15042 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15043 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15044 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15045 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15046 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15047 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15048 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15049 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15050 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15051 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15052 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15053 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15054 (org-defkey org-mode-map "\C-c^" 'org-sort)
15055 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15056 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15057 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15058 (org-defkey org-mode-map "\C-m" 'org-return)
15059 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15060 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15061 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15062 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15063 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15064 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15065 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15066 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15067 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15068 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15069 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15070 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15071 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15072 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15073 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15074 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15075 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15076 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15077 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15078 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15079 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15081 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15082 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15083 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15084 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15086 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15087 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15088 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15089 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15090 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15091 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15092 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15093 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15094 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15095 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15096 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15097 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15098 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15099 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15100 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15102 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15103 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15104 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15105 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15107 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15109 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15111 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15112 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15114 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15117 (when (featurep 'xemacs)
15118 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15121 (defconst org-speed-commands-default
15123 ("Outline Navigation")
15124 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15125 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15126 ("f" . (org-speed-move-safe 'org-forward-same-level))
15127 ("b" . (org-speed-move-safe 'org-backward-same-level))
15128 ("u" . (org-speed-move-safe 'outline-up-heading))
15129 ("j" . org-goto)
15130 ("g" . (org-refile t))
15131 ("Outline Visibility")
15132 ("c" . org-cycle)
15133 ("C" . org-shifttab)
15134 (" " . org-display-outline-path)
15135 ("Outline Structure Editing")
15136 ("U" . org-shiftmetaup)
15137 ("D" . org-shiftmetadown)
15138 ("r" . org-metaright)
15139 ("l" . org-metaleft)
15140 ("R" . org-shiftmetaright)
15141 ("L" . org-shiftmetaleft)
15142 ("i" . (progn (forward-char 1) (call-interactively
15143 'org-insert-heading-respect-content)))
15144 ("^" . org-sort)
15145 ("w" . org-refile)
15146 ("a" . org-archive-subtree-default-with-confirmation)
15147 ("." . outline-mark-subtree)
15148 ("Clock Commands")
15149 ("I" . org-clock-in)
15150 ("O" . org-clock-out)
15151 ("Meta Data Editing")
15152 ("t" . org-todo)
15153 ("0" . (org-priority ?\ ))
15154 ("1" . (org-priority ?A))
15155 ("2" . (org-priority ?B))
15156 ("3" . (org-priority ?C))
15157 (";" . org-set-tags-command)
15158 ("e" . org-set-effort)
15159 ("Agenda Views etc")
15160 ("v" . org-agenda)
15161 ("/" . org-sparse-tree)
15162 ("Misc")
15163 ("o" . org-open-at-point)
15164 ("?" . org-speed-command-help)
15166 "The default speed commands.")
15168 (defun org-print-speed-command (e)
15169 (if (> (length (car e)) 1)
15170 (progn
15171 (princ "\n")
15172 (princ (car e))
15173 (princ "\n")
15174 (princ (make-string (length (car e)) ?-))
15175 (princ "\n"))
15176 (princ (car e))
15177 (princ " ")
15178 (if (symbolp (cdr e))
15179 (princ (symbol-name (cdr e)))
15180 (prin1 (cdr e)))
15181 (princ "\n")))
15183 (defun org-speed-command-help ()
15184 "Show the available speed commands."
15185 (interactive)
15186 (if (not org-use-speed-commands)
15187 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15188 (with-output-to-temp-buffer "*Help*"
15189 (princ "User-defined Speed commands\n===========================\n")
15190 (mapc 'org-print-speed-command org-speed-commands-user)
15191 (princ "\n")
15192 (princ "Built-in Speed commands\n=======================\n")
15193 (mapc 'org-print-speed-command org-speed-commands-default))
15194 (with-current-buffer "*Help*"
15195 (setq truncate-lines t))))
15197 (defun org-speed-move-safe (cmd)
15198 "Execute CMD, but make sure that the cursor always ends up in a headline.
15199 If not, return to the original position and throw an error."
15200 (interactive)
15201 (let ((pos (point)))
15202 (call-interactively cmd)
15203 (unless (and (bolp) (org-on-heading-p))
15204 (goto-char pos)
15205 (error "Boundary reached while executing %s" cmd))))
15207 (defvar org-self-insert-command-undo-counter 0)
15209 (defvar org-table-auto-blank-field) ; defined in org-table.el
15210 (defvar org-speed-command nil)
15211 (defun org-self-insert-command (N)
15212 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15213 If the cursor is in a table looking at whitespace, the whitespace is
15214 overwritten, and the table is not marked as requiring realignment."
15215 (interactive "p")
15216 (cond
15217 ((and org-use-speed-commands
15218 (or (and (bolp) (looking-at outline-regexp))
15219 (and (functionp org-use-speed-commands)
15220 (funcall org-use-speed-commands)))
15221 (setq
15222 org-speed-command
15223 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15224 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15225 (cond
15226 ((commandp org-speed-command)
15227 (setq this-command org-speed-command)
15228 (call-interactively org-speed-command))
15229 ((functionp org-speed-command)
15230 (funcall org-speed-command))
15231 ((and org-speed-command (listp org-speed-command))
15232 (eval org-speed-command))
15233 (t (let (org-use-speed-commands)
15234 (call-interactively 'org-self-insert-command)))))
15235 ((and
15236 (org-table-p)
15237 (progn
15238 ;; check if we blank the field, and if that triggers align
15239 (and (featurep 'org-table) org-table-auto-blank-field
15240 (member last-command
15241 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15242 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15243 ;; got extra space, this field does not determine column width
15244 (let (org-table-may-need-update) (org-table-blank-field))
15245 ;; no extra space, this field may determine column width
15246 (org-table-blank-field)))
15248 (eq N 1)
15249 (looking-at "[^|\n]* |"))
15250 (let (org-table-may-need-update)
15251 (goto-char (1- (match-end 0)))
15252 (delete-backward-char 1)
15253 (goto-char (match-beginning 0))
15254 (self-insert-command N)))
15256 (setq org-table-may-need-update t)
15257 (self-insert-command N)
15258 (org-fix-tags-on-the-fly)
15259 (if org-self-insert-cluster-for-undo
15260 (if (not (eq last-command 'org-self-insert-command))
15261 (setq org-self-insert-command-undo-counter 1)
15262 (if (>= org-self-insert-command-undo-counter 20)
15263 (setq org-self-insert-command-undo-counter 1)
15264 (and (> org-self-insert-command-undo-counter 0)
15265 buffer-undo-list
15266 (not (cadr buffer-undo-list)) ; remove nil entry
15267 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15268 (setq org-self-insert-command-undo-counter
15269 (1+ org-self-insert-command-undo-counter))))))))
15271 (defun org-fix-tags-on-the-fly ()
15272 (when (and (equal (char-after (point-at-bol)) ?*)
15273 (org-on-heading-p))
15274 (org-align-tags-here org-tags-column)))
15276 (defun org-delete-backward-char (N)
15277 "Like `delete-backward-char', insert whitespace at field end in tables.
15278 When deleting backwards, in tables this function will insert whitespace in
15279 front of the next \"|\" separator, to keep the table aligned. The table will
15280 still be marked for re-alignment if the field did fill the entire column,
15281 because, in this case the deletion might narrow the column."
15282 (interactive "p")
15283 (if (and (org-table-p)
15284 (eq N 1)
15285 (string-match "|" (buffer-substring (point-at-bol) (point)))
15286 (looking-at ".*?|"))
15287 (let ((pos (point))
15288 (noalign (looking-at "[^|\n\r]* |"))
15289 (c org-table-may-need-update))
15290 (backward-delete-char N)
15291 (skip-chars-forward "^|")
15292 (insert " ")
15293 (goto-char (1- pos))
15294 ;; noalign: if there were two spaces at the end, this field
15295 ;; does not determine the width of the column.
15296 (if noalign (setq org-table-may-need-update c)))
15297 (backward-delete-char N)
15298 (org-fix-tags-on-the-fly)))
15300 (defun org-delete-char (N)
15301 "Like `delete-char', but insert whitespace at field end in tables.
15302 When deleting characters, in tables this function will insert whitespace in
15303 front of the next \"|\" separator, to keep the table aligned. The table will
15304 still be marked for re-alignment if the field did fill the entire column,
15305 because, in this case the deletion might narrow the column."
15306 (interactive "p")
15307 (if (and (org-table-p)
15308 (not (bolp))
15309 (not (= (char-after) ?|))
15310 (eq N 1))
15311 (if (looking-at ".*?|")
15312 (let ((pos (point))
15313 (noalign (looking-at "[^|\n\r]* |"))
15314 (c org-table-may-need-update))
15315 (replace-match (concat
15316 (substring (match-string 0) 1 -1)
15317 " |"))
15318 (goto-char pos)
15319 ;; noalign: if there were two spaces at the end, this field
15320 ;; does not determine the width of the column.
15321 (if noalign (setq org-table-may-need-update c)))
15322 (delete-char N))
15323 (delete-char N)
15324 (org-fix-tags-on-the-fly)))
15326 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15327 (put 'org-self-insert-command 'delete-selection t)
15328 (put 'orgtbl-self-insert-command 'delete-selection t)
15329 (put 'org-delete-char 'delete-selection 'supersede)
15330 (put 'org-delete-backward-char 'delete-selection 'supersede)
15331 (put 'org-yank 'delete-selection 'yank)
15333 ;; Make `flyspell-mode' delay after some commands
15334 (put 'org-self-insert-command 'flyspell-delayed t)
15335 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15336 (put 'org-delete-char 'flyspell-delayed t)
15337 (put 'org-delete-backward-char 'flyspell-delayed t)
15339 ;; Make pabbrev-mode expand after org-mode commands
15340 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15341 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15343 ;; How to do this: Measure non-white length of current string
15344 ;; If equal to column width, we should realign.
15346 (defun org-remap (map &rest commands)
15347 "In MAP, remap the functions given in COMMANDS.
15348 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15349 (let (new old)
15350 (while commands
15351 (setq old (pop commands) new (pop commands))
15352 (if (fboundp 'command-remapping)
15353 (org-defkey map (vector 'remap old) new)
15354 (substitute-key-definition old new map global-map)))))
15356 (when (eq org-enable-table-editor 'optimized)
15357 ;; If the user wants maximum table support, we need to hijack
15358 ;; some standard editing functions
15359 (org-remap org-mode-map
15360 'self-insert-command 'org-self-insert-command
15361 'delete-char 'org-delete-char
15362 'delete-backward-char 'org-delete-backward-char)
15363 (org-defkey org-mode-map "|" 'org-force-self-insert))
15365 (defvar org-ctrl-c-ctrl-c-hook nil
15366 "Hook for functions attaching themselves to `C-c C-c'.
15367 This can be used to add additional functionality to the C-c C-c key which
15368 executes context-dependent commands.
15369 Each function will be called with no arguments. The function must check
15370 if the context is appropriate for it to act. If yes, it should do its
15371 thing and then return a non-nil value. If the context is wrong,
15372 just do nothing and return nil.")
15374 (defvar org-tab-first-hook nil
15375 "Hook for functions to attach themselves to TAB.
15376 See `org-ctrl-c-ctrl-c-hook' for more information.
15377 This hook runs as the first action when TAB is pressed, even before
15378 `org-cycle' messes around with the `outline-regexp' to cater for
15379 inline tasks and plain list item folding.
15380 If any function in this hook returns t, not other actions like table
15381 field motion visibility cycling will be done.")
15383 (defvar org-tab-after-check-for-table-hook nil
15384 "Hook for functions to attach themselves to TAB.
15385 See `org-ctrl-c-ctrl-c-hook' for more information.
15386 This hook runs after it has been established that the cursor is not in a
15387 table, but before checking if the cursor is in a headline or if global cycling
15388 should be done.
15389 If any function in this hook returns t, not other actions like visibility
15390 cycling will be done.")
15392 (defvar org-tab-after-check-for-cycling-hook nil
15393 "Hook for functions to attach themselves to TAB.
15394 See `org-ctrl-c-ctrl-c-hook' for more information.
15395 This hook runs after it has been established that not table field motion and
15396 not visibility should be done because of current context. This is probably
15397 the place where a package like yasnippets can hook in.")
15399 (defvar org-tab-before-tab-emulation-hook nil
15400 "Hook for functions to attach themselves to TAB.
15401 See `org-ctrl-c-ctrl-c-hook' for more information.
15402 This hook runs after every other options for TAB have been exhausted, but
15403 before indentation and \t insertion takes place.")
15405 (defvar org-metaleft-hook nil
15406 "Hook for functions attaching themselves to `M-left'.
15407 See `org-ctrl-c-ctrl-c-hook' for more information.")
15408 (defvar org-metaright-hook nil
15409 "Hook for functions attaching themselves to `M-right'.
15410 See `org-ctrl-c-ctrl-c-hook' for more information.")
15411 (defvar org-metaup-hook nil
15412 "Hook for functions attaching themselves to `M-up'.
15413 See `org-ctrl-c-ctrl-c-hook' for more information.")
15414 (defvar org-metadown-hook nil
15415 "Hook for functions attaching themselves to `M-down'.
15416 See `org-ctrl-c-ctrl-c-hook' for more information.")
15417 (defvar org-shiftmetaleft-hook nil
15418 "Hook for functions attaching themselves to `M-S-left'.
15419 See `org-ctrl-c-ctrl-c-hook' for more information.")
15420 (defvar org-shiftmetaright-hook nil
15421 "Hook for functions attaching themselves to `M-S-right'.
15422 See `org-ctrl-c-ctrl-c-hook' for more information.")
15423 (defvar org-shiftmetaup-hook nil
15424 "Hook for functions attaching themselves to `M-S-up'.
15425 See `org-ctrl-c-ctrl-c-hook' for more information.")
15426 (defvar org-shiftmetadown-hook nil
15427 "Hook for functions attaching themselves to `M-S-down'.
15428 See `org-ctrl-c-ctrl-c-hook' for more information.")
15429 (defvar org-metareturn-hook nil
15430 "Hook for functions attaching themselves to `M-RET'.
15431 See `org-ctrl-c-ctrl-c-hook' for more information.")
15433 (defun org-modifier-cursor-error ()
15434 "Throw an error, a modified cursor command was applied in wrong context."
15435 (error "This command is active in special context like tables, headlines or items"))
15437 (defun org-shiftselect-error ()
15438 "Throw an error because Shift-Cursor command was applied in wrong context."
15439 (if (and (boundp 'shift-select-mode) shift-select-mode)
15440 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15441 (error "This command works only in special context like headlines or timestamps")))
15443 (defun org-call-for-shift-select (cmd)
15444 (let ((this-command-keys-shift-translated t))
15445 (call-interactively cmd)))
15447 (defun org-shifttab (&optional arg)
15448 "Global visibility cycling or move to previous table field.
15449 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15450 on context.
15451 See the individual commands for more information."
15452 (interactive "P")
15453 (cond
15454 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15455 ((integerp arg)
15456 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15457 (message "Content view to level: %d" arg)
15458 (org-content (prefix-numeric-value arg2))
15459 (setq org-cycle-global-status 'overview)))
15460 (t (call-interactively 'org-global-cycle))))
15462 (defun org-shiftmetaleft ()
15463 "Promote subtree or delete table column.
15464 Calls `org-promote-subtree', `org-outdent-item',
15465 or `org-table-delete-column', depending on context.
15466 See the individual commands for more information."
15467 (interactive)
15468 (cond
15469 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15470 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15471 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15472 ((org-at-item-p) (call-interactively 'org-outdent-item))
15473 (t (org-modifier-cursor-error))))
15475 (defun org-shiftmetaright ()
15476 "Demote subtree or insert table column.
15477 Calls `org-demote-subtree', `org-indent-item',
15478 or `org-table-insert-column', depending on context.
15479 See the individual commands for more information."
15480 (interactive)
15481 (cond
15482 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15483 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15484 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15485 ((org-at-item-p) (call-interactively 'org-indent-item))
15486 (t (org-modifier-cursor-error))))
15488 (defun org-shiftmetaup (&optional arg)
15489 "Move subtree up or kill table row.
15490 Calls `org-move-subtree-up' or `org-table-kill-row' or
15491 `org-move-item-up' depending on context. See the individual commands
15492 for more information."
15493 (interactive "P")
15494 (cond
15495 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15496 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15497 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15498 ((org-at-item-p) (call-interactively 'org-move-item-up))
15499 (t (org-modifier-cursor-error))))
15501 (defun org-shiftmetadown (&optional arg)
15502 "Move subtree down or insert table row.
15503 Calls `org-move-subtree-down' or `org-table-insert-row' or
15504 `org-move-item-down', depending on context. See the individual
15505 commands for more information."
15506 (interactive "P")
15507 (cond
15508 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15509 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15510 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15511 ((org-at-item-p) (call-interactively 'org-move-item-down))
15512 (t (org-modifier-cursor-error))))
15514 (defun org-metaleft (&optional arg)
15515 "Promote heading or move table column to left.
15516 Calls `org-do-promote' or `org-table-move-column', depending on context.
15517 With no specific context, calls the Emacs default `backward-word'.
15518 See the individual commands for more information."
15519 (interactive "P")
15520 (cond
15521 ((run-hook-with-args-until-success 'org-metaleft-hook))
15522 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15523 ((or (org-on-heading-p)
15524 (and (org-region-active-p)
15525 (save-excursion
15526 (goto-char (region-beginning))
15527 (org-on-heading-p))))
15528 (call-interactively 'org-do-promote))
15529 ((or (org-at-item-p)
15530 (and (org-region-active-p)
15531 (save-excursion
15532 (goto-char (region-beginning))
15533 (org-at-item-p))))
15534 (call-interactively 'org-outdent-item))
15535 (t (call-interactively 'backward-word))))
15537 (defun org-metaright (&optional arg)
15538 "Demote subtree or move table column to right.
15539 Calls `org-do-demote' or `org-table-move-column', depending on context.
15540 With no specific context, calls the Emacs default `forward-word'.
15541 See the individual commands for more information."
15542 (interactive "P")
15543 (cond
15544 ((run-hook-with-args-until-success 'org-metaright-hook))
15545 ((org-at-table-p) (call-interactively 'org-table-move-column))
15546 ((or (org-on-heading-p)
15547 (and (org-region-active-p)
15548 (save-excursion
15549 (goto-char (region-beginning))
15550 (org-on-heading-p))))
15551 (call-interactively 'org-do-demote))
15552 ((or (org-at-item-p)
15553 (and (org-region-active-p)
15554 (save-excursion
15555 (goto-char (region-beginning))
15556 (org-at-item-p))))
15557 (call-interactively 'org-indent-item))
15558 (t (call-interactively 'forward-word))))
15560 (defun org-metaup (&optional arg)
15561 "Move subtree up or move table row up.
15562 Calls `org-move-subtree-up' or `org-table-move-row' or
15563 `org-move-item-up', depending on context. See the individual commands
15564 for more information."
15565 (interactive "P")
15566 (cond
15567 ((run-hook-with-args-until-success 'org-metaup-hook))
15568 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15569 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15570 ((org-at-item-p) (call-interactively 'org-move-item-up))
15571 (t (transpose-lines 1) (beginning-of-line -1))))
15573 (defun org-metadown (&optional arg)
15574 "Move subtree down or move table row down.
15575 Calls `org-move-subtree-down' or `org-table-move-row' or
15576 `org-move-item-down', depending on context. See the individual
15577 commands for more information."
15578 (interactive "P")
15579 (cond
15580 ((run-hook-with-args-until-success 'org-metadown-hook))
15581 ((org-at-table-p) (call-interactively 'org-table-move-row))
15582 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15583 ((org-at-item-p) (call-interactively 'org-move-item-down))
15584 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15586 (defun org-shiftup (&optional arg)
15587 "Increase item in timestamp or increase priority of current headline.
15588 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15589 depending on context. See the individual commands for more information."
15590 (interactive "P")
15591 (cond
15592 ((and org-support-shift-select (org-region-active-p))
15593 (org-call-for-shift-select 'previous-line))
15594 ((org-at-timestamp-p t)
15595 (call-interactively (if org-edit-timestamp-down-means-later
15596 'org-timestamp-down 'org-timestamp-up)))
15597 ((and (not (eq org-support-shift-select 'always))
15598 org-enable-priority-commands
15599 (org-on-heading-p))
15600 (call-interactively 'org-priority-up))
15601 ((and (not org-support-shift-select) (org-at-item-p))
15602 (call-interactively 'org-previous-item))
15603 ((org-clocktable-try-shift 'up arg))
15604 (org-support-shift-select
15605 (org-call-for-shift-select 'previous-line))
15606 (t (org-shiftselect-error))))
15608 (defun org-shiftdown (&optional arg)
15609 "Decrease item in timestamp or decrease priority of current headline.
15610 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15611 depending on context. See the individual commands for more information."
15612 (interactive "P")
15613 (cond
15614 ((and org-support-shift-select (org-region-active-p))
15615 (org-call-for-shift-select 'next-line))
15616 ((org-at-timestamp-p t)
15617 (call-interactively (if org-edit-timestamp-down-means-later
15618 'org-timestamp-up 'org-timestamp-down)))
15619 ((and (not (eq org-support-shift-select 'always))
15620 org-enable-priority-commands
15621 (org-on-heading-p))
15622 (call-interactively 'org-priority-down))
15623 ((and (not org-support-shift-select) (org-at-item-p))
15624 (call-interactively 'org-next-item))
15625 ((org-clocktable-try-shift 'down arg))
15626 (org-support-shift-select
15627 (org-call-for-shift-select 'next-line))
15628 (t (org-shiftselect-error))))
15630 (defun org-shiftright (&optional arg)
15631 "Cycle the thing at point or in the current line, depending on context.
15632 Depending on context, this does one of the following:
15634 - switch a timestamp at point one day into the future
15635 - on a headline, switch to the next TODO keyword.
15636 - on an item, switch entire list to the next bullet type
15637 - on a property line, switch to the next allowed value
15638 - on a clocktable definition line, move time block into the future"
15639 (interactive "P")
15640 (cond
15641 ((and org-support-shift-select (org-region-active-p))
15642 (org-call-for-shift-select 'forward-char))
15643 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15644 ((and (not (eq org-support-shift-select 'always))
15645 (org-on-heading-p))
15646 (let ((org-inhibit-logging
15647 (not org-treat-S-cursor-todo-selection-as-state-change))
15648 (org-inhibit-blocking
15649 (not org-treat-S-cursor-todo-selection-as-state-change)))
15650 (org-call-with-arg 'org-todo 'right)))
15651 ((or (and org-support-shift-select
15652 (not (eq org-support-shift-select 'always))
15653 (org-at-item-bullet-p))
15654 (and (not org-support-shift-select) (org-at-item-p)))
15655 (org-call-with-arg 'org-cycle-list-bullet nil))
15656 ((and (not (eq org-support-shift-select 'always))
15657 (org-at-property-p))
15658 (call-interactively 'org-property-next-allowed-value))
15659 ((org-clocktable-try-shift 'right arg))
15660 (org-support-shift-select
15661 (org-call-for-shift-select 'forward-char))
15662 (t (org-shiftselect-error))))
15664 (defun org-shiftleft (&optional arg)
15665 "Cycle the thing at point or in the current line, depending on context.
15666 Depending on context, this does one of the following:
15668 - switch a timestamp at point one day into the past
15669 - on a headline, switch to the previous TODO keyword.
15670 - on an item, switch entire list to the previous bullet type
15671 - on a property line, switch to the previous allowed value
15672 - on a clocktable definition line, move time block into the past"
15673 (interactive "P")
15674 (cond
15675 ((and org-support-shift-select (org-region-active-p))
15676 (org-call-for-shift-select 'backward-char))
15677 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15678 ((and (not (eq org-support-shift-select 'always))
15679 (org-on-heading-p))
15680 (let ((org-inhibit-logging
15681 (not org-treat-S-cursor-todo-selection-as-state-change))
15682 (org-inhibit-blocking
15683 (not org-treat-S-cursor-todo-selection-as-state-change)))
15684 (org-call-with-arg 'org-todo 'left)))
15685 ((or (and org-support-shift-select
15686 (not (eq org-support-shift-select 'always))
15687 (org-at-item-bullet-p))
15688 (and (not org-support-shift-select) (org-at-item-p)))
15689 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15690 ((and (not (eq org-support-shift-select 'always))
15691 (org-at-property-p))
15692 (call-interactively 'org-property-previous-allowed-value))
15693 ((org-clocktable-try-shift 'left arg))
15694 (org-support-shift-select
15695 (org-call-for-shift-select 'backward-char))
15696 (t (org-shiftselect-error))))
15698 (defun org-shiftcontrolright ()
15699 "Switch to next TODO set."
15700 (interactive)
15701 (cond
15702 ((and org-support-shift-select (org-region-active-p))
15703 (org-call-for-shift-select 'forward-word))
15704 ((and (not (eq org-support-shift-select 'always))
15705 (org-on-heading-p))
15706 (org-call-with-arg 'org-todo 'nextset))
15707 (org-support-shift-select
15708 (org-call-for-shift-select 'forward-word))
15709 (t (org-shiftselect-error))))
15711 (defun org-shiftcontrolleft ()
15712 "Switch to previous TODO set."
15713 (interactive)
15714 (cond
15715 ((and org-support-shift-select (org-region-active-p))
15716 (org-call-for-shift-select 'backward-word))
15717 ((and (not (eq org-support-shift-select 'always))
15718 (org-on-heading-p))
15719 (org-call-with-arg 'org-todo 'previousset))
15720 (org-support-shift-select
15721 (org-call-for-shift-select 'backward-word))
15722 (t (org-shiftselect-error))))
15724 (defun org-ctrl-c-ret ()
15725 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15726 (interactive)
15727 (cond
15728 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15729 (t (call-interactively 'org-insert-heading))))
15731 (defun org-copy-special ()
15732 "Copy region in table or copy current subtree.
15733 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15734 See the individual commands for more information."
15735 (interactive)
15736 (call-interactively
15737 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15739 (defun org-cut-special ()
15740 "Cut region in table or cut current subtree.
15741 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15742 See the individual commands for more information."
15743 (interactive)
15744 (call-interactively
15745 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15747 (defun org-paste-special (arg)
15748 "Paste rectangular region into table, or past subtree relative to level.
15749 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15750 See the individual commands for more information."
15751 (interactive "P")
15752 (if (org-at-table-p)
15753 (org-table-paste-rectangle)
15754 (org-paste-subtree arg)))
15756 (defun org-edit-special ()
15757 "Call a special editor for the stuff at point.
15758 When at a table, call the formula editor with `org-table-edit-formulas'.
15759 When at the first line of an src example, call `org-edit-src-code'.
15760 When in an #+include line, visit the include file. Otherwise call
15761 `ffap' to visit the file at point."
15762 (interactive)
15763 (cond
15764 ((org-at-table-p)
15765 (call-interactively 'org-table-edit-formulas))
15766 ((save-excursion
15767 (beginning-of-line 1)
15768 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15769 (find-file (org-trim (match-string 1))))
15770 ((org-edit-src-code))
15771 ((org-edit-fixed-width-region))
15772 (t (call-interactively 'ffap))))
15775 (defun org-ctrl-c-ctrl-c (&optional arg)
15776 "Set tags in headline, or update according to changed information at point.
15778 This command does many different things, depending on context:
15780 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15781 this is what we do.
15783 - If the cursor is on a statistics cookie, update it.
15785 - If the cursor is in a headline, prompt for tags and insert them
15786 into the current line, aligned to `org-tags-column'. When called
15787 with prefix arg, realign all tags in the current buffer.
15789 - If the cursor is in one of the special #+KEYWORD lines, this
15790 triggers scanning the buffer for these lines and updating the
15791 information.
15793 - If the cursor is inside a table, realign the table. This command
15794 works even if the automatic table editor has been turned off.
15796 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15797 the entire table.
15799 - If the cursor is at a footnote reference or definition, jump to
15800 the corresponding definition or references, respectively.
15802 - If the cursor is a the beginning of a dynamic block, update it.
15804 - If the cursor is inside a table created by the table.el package,
15805 activate that table.
15807 - If the current buffer is a remember buffer, close note and file
15808 it. A prefix argument of 1 files to the default location
15809 without further interaction. A prefix argument of 2 files to
15810 the currently clocking task.
15812 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15813 links in this buffer.
15815 - If the cursor is on a numbered item in a plain list, renumber the
15816 ordered list.
15818 - If the cursor is on a checkbox, toggle it."
15819 (interactive "P")
15820 (let ((org-enable-table-editor t))
15821 (cond
15822 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15823 org-occur-highlights
15824 org-latex-fragment-image-overlays)
15825 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15826 (org-remove-occur-highlights)
15827 (org-remove-latex-fragment-image-overlays)
15828 (message "Temporary highlights/overlays removed from current buffer"))
15829 ((and (local-variable-p 'org-finish-function (current-buffer))
15830 (fboundp org-finish-function))
15831 (funcall org-finish-function))
15832 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15833 ((org-at-property-p)
15834 (call-interactively 'org-property-action))
15835 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15836 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15837 (or (org-on-heading-p) (org-at-item-p)))
15838 (call-interactively 'org-update-statistics-cookies))
15839 ((org-on-heading-p) (call-interactively 'org-set-tags))
15840 ((org-at-table.el-p)
15841 (require 'table)
15842 (beginning-of-line 1)
15843 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15844 (call-interactively 'table-recognize-table))
15845 ((org-at-table-p)
15846 (org-table-maybe-eval-formula)
15847 (if arg
15848 (call-interactively 'org-table-recalculate)
15849 (org-table-maybe-recalculate-line))
15850 (call-interactively 'org-table-align))
15851 ((or (org-footnote-at-reference-p)
15852 (org-footnote-at-definition-p))
15853 (call-interactively 'org-footnote-action))
15854 ((org-at-item-checkbox-p)
15855 (call-interactively 'org-toggle-checkbox))
15856 ((org-at-item-p)
15857 (if arg
15858 (call-interactively 'org-toggle-checkbox)
15859 (call-interactively 'org-maybe-renumber-ordered-list)))
15860 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15861 ;; Dynamic block
15862 (beginning-of-line 1)
15863 (save-excursion (org-update-dblock)))
15864 ((save-excursion
15865 (beginning-of-line 1)
15866 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15867 (cond
15868 ((equal (match-string 1) "TBLFM")
15869 ;; Recalculate the table before this line
15870 (save-excursion
15871 (beginning-of-line 1)
15872 (skip-chars-backward " \r\n\t")
15873 (if (org-at-table-p)
15874 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15876 (let ((org-inhibit-startup-visibility-stuff t)
15877 (org-startup-align-all-tables nil))
15878 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15879 (message "Local setup has been refreshed"))))
15880 ((org-clock-update-time-maybe))
15881 (t (error "C-c C-c can do nothing useful at this location")))))
15883 (defun org-mode-restart ()
15884 "Restart Org-mode, to scan again for special lines.
15885 Also updates the keyword regular expressions."
15886 (interactive)
15887 (org-mode)
15888 (message "Org-mode restarted"))
15890 (defun org-kill-note-or-show-branches ()
15891 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15892 (interactive)
15893 (if (not org-finish-function)
15894 (call-interactively 'show-branches)
15895 (let ((org-note-abort t))
15896 (funcall org-finish-function))))
15898 (defun org-return (&optional indent)
15899 "Goto next table row or insert a newline.
15900 Calls `org-table-next-row' or `newline', depending on context.
15901 See the individual commands for more information."
15902 (interactive)
15903 (cond
15904 ((bobp) (if indent (newline-and-indent) (newline)))
15905 ((org-at-table-p)
15906 (org-table-justify-field-maybe)
15907 (call-interactively 'org-table-next-row))
15908 ((and org-return-follows-link
15909 (eq (get-text-property (point) 'face) 'org-link))
15910 (call-interactively 'org-open-at-point))
15911 ((and (org-at-heading-p)
15912 (looking-at
15913 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15914 (org-show-entry)
15915 (end-of-line 1)
15916 (newline))
15917 (t (if indent (newline-and-indent) (newline)))))
15919 (defun org-return-indent ()
15920 "Goto next table row or insert a newline and indent.
15921 Calls `org-table-next-row' or `newline-and-indent', depending on
15922 context. See the individual commands for more information."
15923 (interactive)
15924 (org-return t))
15926 (defun org-ctrl-c-star ()
15927 "Compute table, or change heading status of lines.
15928 Calls `org-table-recalculate' or `org-toggle-heading',
15929 depending on context."
15930 (interactive)
15931 (cond
15932 ((org-at-table-p)
15933 (call-interactively 'org-table-recalculate))
15935 ;; Convert all lines in region to list items
15936 (call-interactively 'org-toggle-heading))))
15938 (defun org-ctrl-c-minus ()
15939 "Insert separator line in table or modify bullet status of line.
15940 Also turns a plain line or a region of lines into list items.
15941 Calls `org-table-insert-hline', `org-toggle-item', or
15942 `org-cycle-list-bullet', depending on context."
15943 (interactive)
15944 (cond
15945 ((org-at-table-p)
15946 (call-interactively 'org-table-insert-hline))
15947 ((org-region-active-p)
15948 (call-interactively 'org-toggle-item))
15949 ((org-in-item-p)
15950 (call-interactively 'org-cycle-list-bullet))
15952 (call-interactively 'org-toggle-item))))
15954 (defun org-toggle-item ()
15955 "Convert headings or normal lines to items, items to normal lines.
15956 If there is no active region, only the current line is considered.
15958 If the first line in the region is a headline, convert all headlines to items.
15960 If the first line in the region is an item, convert all items to normal lines.
15962 If the first line is normal text, add an item bullet to each line."
15963 (interactive)
15964 (let (l2 l beg end)
15965 (if (org-region-active-p)
15966 (setq beg (region-beginning) end (region-end))
15967 (setq beg (point-at-bol)
15968 end (min (1+ (point-at-eol)) (point-max))))
15969 (save-excursion
15970 (goto-char end)
15971 (setq l2 (org-current-line))
15972 (goto-char beg)
15973 (beginning-of-line 1)
15974 (setq l (1- (org-current-line)))
15975 (if (org-at-item-p)
15976 ;; We already have items, de-itemize
15977 (while (< (setq l (1+ l)) l2)
15978 (when (org-at-item-p)
15979 (goto-char (match-beginning 2))
15980 (delete-region (match-beginning 2) (match-end 2))
15981 (and (looking-at "[ \t]+") (replace-match "")))
15982 (beginning-of-line 2))
15983 (if (org-on-heading-p)
15984 ;; Headings, convert to items
15985 (while (< (setq l (1+ l)) l2)
15986 (if (looking-at org-outline-regexp)
15987 (replace-match "- " t t))
15988 (beginning-of-line 2))
15989 ;; normal lines, turn them into items
15990 (while (< (setq l (1+ l)) l2)
15991 (unless (org-at-item-p)
15992 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15993 (replace-match "\\1- \\2")))
15994 (beginning-of-line 2)))))))
15996 (defun org-toggle-heading (&optional nstars)
15997 "Convert headings to normal text, or items or text to headings.
15998 If there is no active region, only the current line is considered.
16000 If the first line is a heading, remove the stars from all headlines
16001 in the region.
16003 If the first line is a plain list item, turn all plain list items
16004 into headings.
16006 If the first line is a normal line, turn each and every line in the
16007 region into a heading.
16009 When converting a line into a heading, the number of stars is chosen
16010 such that the lines become children of the current entry. However,
16011 when a prefix argument is given, its value determines the number of
16012 stars to add."
16013 (interactive "P")
16014 (let (l2 l itemp beg end)
16015 (if (org-region-active-p)
16016 (setq beg (region-beginning) end (region-end))
16017 (setq beg (point-at-bol)
16018 end (min (1+ (point-at-eol)) (point-max))))
16019 (save-excursion
16020 (goto-char end)
16021 (setq l2 (org-current-line))
16022 (goto-char beg)
16023 (beginning-of-line 1)
16024 (setq l (1- (org-current-line)))
16025 (if (org-on-heading-p)
16026 ;; We already have headlines, de-star them
16027 (while (< (setq l (1+ l)) l2)
16028 (when (org-on-heading-p t)
16029 (and (looking-at outline-regexp) (replace-match "")))
16030 (beginning-of-line 2))
16031 (setq itemp (org-at-item-p))
16032 (let* ((stars
16033 (if nstars
16034 (make-string (prefix-numeric-value current-prefix-arg)
16036 (save-excursion
16037 (if (re-search-backward org-complex-heading-regexp nil t)
16038 (match-string 1) ""))))
16039 (add-stars (cond (nstars "")
16040 ((equal stars "") "*")
16041 (org-odd-levels-only "**")
16042 (t "*")))
16043 (rpl (concat stars add-stars " ")))
16044 (while (< (setq l (1+ l)) l2)
16045 (if itemp
16046 (and (org-at-item-p) (replace-match rpl t t))
16047 (unless (org-on-heading-p)
16048 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16049 (replace-match (concat rpl (match-string 2))))))
16050 (beginning-of-line 2)))))))
16052 (defun org-meta-return (&optional arg)
16053 "Insert a new heading or wrap a region in a table.
16054 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16055 See the individual commands for more information."
16056 (interactive "P")
16057 (cond
16058 ((run-hook-with-args-until-success 'org-metareturn-hook))
16059 ((org-at-table-p)
16060 (call-interactively 'org-table-wrap-region))
16061 (t (call-interactively 'org-insert-heading))))
16063 ;;; Menu entries
16065 ;; Define the Org-mode menus
16066 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16067 '("Tbl"
16068 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16069 ["Next Field" org-cycle (org-at-table-p)]
16070 ["Previous Field" org-shifttab (org-at-table-p)]
16071 ["Next Row" org-return (org-at-table-p)]
16072 "--"
16073 ["Blank Field" org-table-blank-field (org-at-table-p)]
16074 ["Edit Field" org-table-edit-field (org-at-table-p)]
16075 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16076 "--"
16077 ("Column"
16078 ["Move Column Left" org-metaleft (org-at-table-p)]
16079 ["Move Column Right" org-metaright (org-at-table-p)]
16080 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16081 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16082 ("Row"
16083 ["Move Row Up" org-metaup (org-at-table-p)]
16084 ["Move Row Down" org-metadown (org-at-table-p)]
16085 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16086 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16087 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16088 "--"
16089 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16090 ("Rectangle"
16091 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16092 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16093 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16094 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16095 "--"
16096 ("Calculate"
16097 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16098 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16099 ["Edit Formulas" org-edit-special (org-at-table-p)]
16100 "--"
16101 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16102 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16103 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16104 "--"
16105 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16106 "--"
16107 ["Sum Column/Rectangle" org-table-sum
16108 (or (org-at-table-p) (org-region-active-p))]
16109 ["Which Column?" org-table-current-column (org-at-table-p)])
16110 ["Debug Formulas"
16111 org-table-toggle-formula-debugger
16112 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16113 ["Show Col/Row Numbers"
16114 org-table-toggle-coordinate-overlays
16115 :style toggle
16116 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16117 "--"
16118 ["Create" org-table-create (and (not (org-at-table-p))
16119 org-enable-table-editor)]
16120 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16121 ["Import from File" org-table-import (not (org-at-table-p))]
16122 ["Export to File" org-table-export (org-at-table-p)]
16123 "--"
16124 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16126 (easy-menu-define org-org-menu org-mode-map "Org menu"
16127 '("Org"
16128 ("Show/Hide"
16129 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16130 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16131 ["Sparse Tree..." org-sparse-tree t]
16132 ["Reveal Context" org-reveal t]
16133 ["Show All" show-all t]
16134 "--"
16135 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16136 "--"
16137 ["New Heading" org-insert-heading t]
16138 ("Navigate Headings"
16139 ["Up" outline-up-heading t]
16140 ["Next" outline-next-visible-heading t]
16141 ["Previous" outline-previous-visible-heading t]
16142 ["Next Same Level" outline-forward-same-level t]
16143 ["Previous Same Level" outline-backward-same-level t]
16144 "--"
16145 ["Jump" org-goto t])
16146 ("Edit Structure"
16147 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16148 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16149 "--"
16150 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16151 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16152 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16153 "--"
16154 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16155 "--"
16156 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16157 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16158 ["Demote Heading" org-metaright (not (org-at-table-p))]
16159 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16160 "--"
16161 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16162 "--"
16163 ["Convert to odd levels" org-convert-to-odd-levels t]
16164 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16165 ("Editing"
16166 ["Emphasis..." org-emphasize t]
16167 ["Edit Source Example" org-edit-special t]
16168 "--"
16169 ["Footnote new/jump" org-footnote-action t]
16170 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16171 ("Archive"
16172 ["Archive (default method)" org-archive-subtree-default t]
16173 "--"
16174 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16175 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16176 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16178 "--"
16179 ("Hyperlinks"
16180 ["Store Link (Global)" org-store-link t]
16181 ["Find existing link to here" org-occur-link-in-agenda-files t]
16182 ["Insert Link" org-insert-link t]
16183 ["Follow Link" org-open-at-point t]
16184 "--"
16185 ["Next link" org-next-link t]
16186 ["Previous link" org-previous-link t]
16187 "--"
16188 ["Descriptive Links"
16189 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16190 :style radio
16191 :selected (member '(org-link) buffer-invisibility-spec)]
16192 ["Literal Links"
16193 (progn
16194 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16195 :style radio
16196 :selected (not (member '(org-link) buffer-invisibility-spec))])
16197 "--"
16198 ("TODO Lists"
16199 ["TODO/DONE/-" org-todo t]
16200 ("Select keyword"
16201 ["Next keyword" org-shiftright (org-on-heading-p)]
16202 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16203 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16204 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16205 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16206 ["Show TODO Tree" org-show-todo-tree t]
16207 ["Global TODO list" org-todo-list t]
16208 "--"
16209 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16210 :selected org-enforce-todo-dependencies :style toggle :active t]
16211 "Settings for tree at point"
16212 ["Do Children sequentially" org-toggle-ordered-property :style radio
16213 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16214 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16215 ["Do Children parallel" org-toggle-ordered-property :style radio
16216 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16217 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16218 "--"
16219 ["Set Priority" org-priority t]
16220 ["Priority Up" org-shiftup t]
16221 ["Priority Down" org-shiftdown t]
16222 "--"
16223 ["Get news from all feeds" org-feed-update-all t]
16224 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16225 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16226 ("TAGS and Properties"
16227 ["Set Tags" org-set-tags-command t]
16228 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16229 "--"
16230 ["Set property" org-set-property t]
16231 ["Column view of properties" org-columns t]
16232 ["Insert Column View DBlock" org-insert-columns-dblock t])
16233 ("Dates and Scheduling"
16234 ["Timestamp" org-time-stamp t]
16235 ["Timestamp (inactive)" org-time-stamp-inactive t]
16236 ("Change Date"
16237 ["1 Day Later" org-shiftright t]
16238 ["1 Day Earlier" org-shiftleft t]
16239 ["1 ... Later" org-shiftup t]
16240 ["1 ... Earlier" org-shiftdown t])
16241 ["Compute Time Range" org-evaluate-time-range t]
16242 ["Schedule Item" org-schedule t]
16243 ["Deadline" org-deadline t]
16244 "--"
16245 ["Custom time format" org-toggle-time-stamp-overlays
16246 :style radio :selected org-display-custom-times]
16247 "--"
16248 ["Goto Calendar" org-goto-calendar t]
16249 ["Date from Calendar" org-date-from-calendar t]
16250 "--"
16251 ["Start/Restart Timer" org-timer-start t]
16252 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16253 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16254 ["Insert Timer String" org-timer t]
16255 ["Insert Timer Item" org-timer-item t])
16256 ("Logging work"
16257 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16258 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16259 ["Clock out" org-clock-out t]
16260 ["Clock cancel" org-clock-cancel t]
16261 "--"
16262 ["Mark as default task" org-clock-mark-default-task t]
16263 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16264 ["Goto running clock" org-clock-goto t]
16265 "--"
16266 ["Display times" org-clock-display t]
16267 ["Create clock table" org-clock-report t]
16268 "--"
16269 ["Record DONE time"
16270 (progn (setq org-log-done (not org-log-done))
16271 (message "Switching to %s will %s record a timestamp"
16272 (car org-done-keywords)
16273 (if org-log-done "automatically" "not")))
16274 :style toggle :selected org-log-done])
16275 "--"
16276 ["Agenda Command..." org-agenda t]
16277 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16278 ("File List for Agenda")
16279 ("Special views current file"
16280 ["TODO Tree" org-show-todo-tree t]
16281 ["Check Deadlines" org-check-deadlines t]
16282 ["Timeline" org-timeline t]
16283 ["Tags/Property tree" org-match-sparse-tree t])
16284 "--"
16285 ["Export/Publish..." org-export t]
16286 ("LaTeX"
16287 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16288 :selected org-cdlatex-mode]
16289 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16290 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16291 ["Modify math symbol" org-cdlatex-math-modify
16292 (org-inside-LaTeX-fragment-p)]
16293 ["Insert citation" org-reftex-citation t]
16294 "--"
16295 ["Export LaTeX fragments as images"
16296 (if (featurep 'org-exp)
16297 (setq org-export-with-LaTeX-fragments
16298 (not org-export-with-LaTeX-fragments))
16299 (require 'org-exp))
16300 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16301 org-export-with-LaTeX-fragments)]
16302 "--"
16303 ["Template for BEAMER" org-beamer-settings-template t])
16304 "--"
16305 ("MobileOrg"
16306 ["Push Files and Views" org-mobile-push t]
16307 ["Get Captured and Flagged" org-mobile-pull t]
16308 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16309 "--"
16310 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16311 "--"
16312 ("Documentation"
16313 ["Show Version" org-version t]
16314 ["Info Documentation" org-info t])
16315 ("Customize"
16316 ["Browse Org Group" org-customize t]
16317 "--"
16318 ["Expand This Menu" org-create-customize-menu
16319 (fboundp 'customize-menu-create)])
16320 ["Send bug report" org-submit-bug-report t]
16321 "--"
16322 ("Refresh/Reload"
16323 ["Refresh setup current buffer" org-mode-restart t]
16324 ["Reload Org (after update)" org-reload t]
16325 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16328 (defun org-info (&optional node)
16329 "Read documentation for Org-mode in the info system.
16330 With optional NODE, go directly to that node."
16331 (interactive)
16332 (info (format "(org)%s" (or node ""))))
16334 ;;;###autoload
16335 (defun org-submit-bug-report ()
16336 "Submit a bug report on Org-mode via mail.
16338 Don't hesitate to report any problems or inaccurate documentation.
16340 If you don't have setup sending mail from (X)Emacs, please copy the
16341 output buffer into your mail program, as it gives us important
16342 information about your Org-mode version and configuration."
16343 (interactive)
16344 (require 'reporter)
16345 (org-load-modules-maybe)
16346 (org-require-autoloaded-modules)
16347 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16348 (reporter-submit-bug-report
16349 "emacs-orgmode@gnu.org"
16350 (org-version)
16351 (let (list)
16352 (save-window-excursion
16353 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16354 (delete-other-windows)
16355 (erase-buffer)
16356 (insert "You are about to submit a bug report to the Org-mode mailing list.
16358 We would like to add your full Org-mode and Outline configuration to the
16359 bug report. This greatly simplifies the work of the maintainer and
16360 other experts on the mailing list.
16362 HOWEVER, some variables you have customized may contain private
16363 information. The names of customers, colleagues, or friends, might
16364 appear in the form of file names, tags, todo states, or search strings.
16365 If you answer yes to the prompt, you might want to check and remove
16366 such private information before sending the email.")
16367 (add-text-properties (point-min) (point-max) '(face org-warning))
16368 (when (yes-or-no-p "Include your Org-mode configuration ")
16369 (mapatoms
16370 (lambda (v)
16371 (and (boundp v)
16372 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16373 (or (and (symbol-value v)
16374 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16375 (and
16376 (get v 'custom-type) (get v 'standard-value)
16377 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16378 (push v list)))))
16379 (kill-buffer (get-buffer "*Warn about privacy*"))
16380 list))
16381 nil nil
16382 "Remember to cover the basics, that is, what you expected to happen and
16383 what in fact did happen. You don't know how to make a good report? See
16385 http://orgmode.org/manual/Feedback.html#Feedback
16387 Your bug report will be posted to the Org-mode mailing list.
16388 ------------------------------------------------------------------------")
16389 (save-excursion
16390 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16391 (replace-match "\\1Bug: \\3 [\\2]")))))
16394 (defun org-install-agenda-files-menu ()
16395 (let ((bl (buffer-list)))
16396 (save-excursion
16397 (while bl
16398 (set-buffer (pop bl))
16399 (if (org-mode-p) (setq bl nil)))
16400 (when (org-mode-p)
16401 (easy-menu-change
16402 '("Org") "File List for Agenda"
16403 (append
16404 (list
16405 ["Edit File List" (org-edit-agenda-file-list) t]
16406 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16407 ["Remove Current File from List" org-remove-file t]
16408 ["Cycle through agenda files" org-cycle-agenda-files t]
16409 ["Occur in all agenda files" org-occur-in-agenda-files t]
16410 "--")
16411 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16413 ;;;; Documentation
16415 ;;;###autoload
16416 (defun org-require-autoloaded-modules ()
16417 (interactive)
16418 (mapc 'require
16419 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16420 org-docbook org-exp org-html org-icalendar
16421 org-id org-latex
16422 org-publish org-remember org-table
16423 org-timer org-xoxo)))
16425 ;;;###autoload
16426 (defun org-reload (&optional uncompiled)
16427 "Reload all org lisp files.
16428 With prefix arg UNCOMPILED, load the uncompiled versions."
16429 (interactive "P")
16430 (require 'find-func)
16431 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16432 (dir-org (file-name-directory (org-find-library-name "org")))
16433 (dir-org-contrib (ignore-errors
16434 (file-name-directory
16435 (org-find-library-name "org-contribdir"))))
16436 (files
16437 (append (directory-files dir-org t file-re)
16438 (and dir-org-contrib
16439 (directory-files dir-org-contrib t file-re))))
16440 (remove-re (concat (if (featurep 'xemacs)
16441 "org-colview" "org-colview-xemacs")
16442 "\\'")))
16443 (setq files (mapcar 'file-name-sans-extension files))
16444 (setq files (mapcar
16445 (lambda (x) (if (string-match remove-re x) nil x))
16446 files))
16447 (setq files (delq nil files))
16448 (mapc
16449 (lambda (f)
16450 (when (featurep (intern (file-name-nondirectory f)))
16451 (if (and (not uncompiled)
16452 (file-exists-p (concat f ".elc")))
16453 (load (concat f ".elc") nil nil t)
16454 (load (concat f ".el") nil nil t))))
16455 files))
16456 (org-version))
16458 ;;;###autoload
16459 (defun org-customize ()
16460 "Call the customize function with org as argument."
16461 (interactive)
16462 (org-load-modules-maybe)
16463 (org-require-autoloaded-modules)
16464 (customize-browse 'org))
16466 (defun org-create-customize-menu ()
16467 "Create a full customization menu for Org-mode, insert it into the menu."
16468 (interactive)
16469 (org-load-modules-maybe)
16470 (org-require-autoloaded-modules)
16471 (if (fboundp 'customize-menu-create)
16472 (progn
16473 (easy-menu-change
16474 '("Org") "Customize"
16475 `(["Browse Org group" org-customize t]
16476 "--"
16477 ,(customize-menu-create 'org)
16478 ["Set" Custom-set t]
16479 ["Save" Custom-save t]
16480 ["Reset to Current" Custom-reset-current t]
16481 ["Reset to Saved" Custom-reset-saved t]
16482 ["Reset to Standard Settings" Custom-reset-standard t]))
16483 (message "\"Org\"-menu now contains full customization menu"))
16484 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16486 ;;;; Miscellaneous stuff
16488 ;;; Generally useful functions
16490 (defun org-get-at-bol (property)
16491 "Get text property PROPERTY at beginning of line."
16492 (get-text-property (point-at-bol) property))
16494 (defun org-find-text-property-in-string (prop s)
16495 "Return the first non-nil value of property PROP in string S."
16496 (or (get-text-property 0 prop s)
16497 (get-text-property (or (next-single-property-change 0 prop s) 0)
16498 prop s)))
16500 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16501 "Display the given MESSAGE as a warning."
16502 (if (fboundp 'display-warning)
16503 (display-warning 'org message
16504 (if (featurep 'xemacs)
16505 'warning
16506 :warning))
16507 (let ((buf (get-buffer-create "*Org warnings*")))
16508 (with-current-buffer buf
16509 (goto-char (point-max))
16510 (insert "Warning (Org): " message)
16511 (unless (bolp)
16512 (newline)))
16513 (display-buffer buf)
16514 (sit-for 0))))
16516 (defun org-in-commented-line ()
16517 "Is point in a line starting with `#'?"
16518 (equal (char-after (point-at-bol)) ?#))
16520 (defun org-in-verbatim-emphasis ()
16521 (save-match-data
16522 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16524 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16525 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16526 (if (and marker (marker-buffer marker)
16527 (buffer-live-p (marker-buffer marker)))
16528 (progn
16529 (switch-to-buffer (marker-buffer marker))
16530 (if (or (> marker (point-max)) (< marker (point-min)))
16531 (widen))
16532 (goto-char marker)
16533 (org-show-context 'org-goto))
16534 (if bookmark
16535 (bookmark-jump bookmark)
16536 (error "Cannot find location"))))
16538 (defun org-quote-csv-field (s)
16539 "Quote field for inclusion in CSV material."
16540 (if (string-match "[\",]" s)
16541 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16544 (defun org-plist-delete (plist property)
16545 "Delete PROPERTY from PLIST.
16546 This is in contrast to merely setting it to 0."
16547 (let (p)
16548 (while plist
16549 (if (not (eq property (car plist)))
16550 (setq p (plist-put p (car plist) (nth 1 plist))))
16551 (setq plist (cddr plist)))
16554 (defun org-force-self-insert (N)
16555 "Needed to enforce self-insert under remapping."
16556 (interactive "p")
16557 (self-insert-command N))
16559 (defun org-string-width (s)
16560 "Compute width of string, ignoring invisible characters.
16561 This ignores character with invisibility property `org-link', and also
16562 characters with property `org-cwidth', because these will become invisible
16563 upon the next fontification round."
16564 (let (b l)
16565 (when (or (eq t buffer-invisibility-spec)
16566 (assq 'org-link buffer-invisibility-spec))
16567 (while (setq b (text-property-any 0 (length s)
16568 'invisible 'org-link s))
16569 (setq s (concat (substring s 0 b)
16570 (substring s (or (next-single-property-change
16571 b 'invisible s) (length s)))))))
16572 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16573 (setq s (concat (substring s 0 b)
16574 (substring s (or (next-single-property-change
16575 b 'org-cwidth s) (length s))))))
16576 (setq l (string-width s) b -1)
16577 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16578 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16581 (defun org-get-indentation (&optional line)
16582 "Get the indentation of the current line, interpreting tabs.
16583 When LINE is given, assume it represents a line and compute its indentation."
16584 (if line
16585 (if (string-match "^ *" (org-remove-tabs line))
16586 (match-end 0))
16587 (save-excursion
16588 (beginning-of-line 1)
16589 (skip-chars-forward " \t")
16590 (current-column))))
16592 (defun org-remove-tabs (s &optional width)
16593 "Replace tabulators in S with spaces.
16594 Assumes that s is a single line, starting in column 0."
16595 (setq width (or width tab-width))
16596 (while (string-match "\t" s)
16597 (setq s (replace-match
16598 (make-string
16599 (- (* width (/ (+ (match-beginning 0) width) width))
16600 (match-beginning 0)) ?\ )
16601 t t s)))
16604 (defun org-fix-indentation (line ind)
16605 "Fix indentation in LINE.
16606 IND is a cons cell with target and minimum indentation.
16607 If the current indentation in LINE is smaller than the minimum,
16608 leave it alone. If it is larger than ind, set it to the target."
16609 (let* ((l (org-remove-tabs line))
16610 (i (org-get-indentation l))
16611 (i1 (car ind)) (i2 (cdr ind)))
16612 (if (>= i i2) (setq l (substring line i2)))
16613 (if (> i1 0)
16614 (concat (make-string i1 ?\ ) l)
16615 l)))
16617 (defun org-remove-indentation (code &optional n)
16618 "Remove the maximum common indentation from the lines in CODE.
16619 N may optionally be the number of spaces to remove."
16620 (with-temp-buffer
16621 (insert code)
16622 (org-do-remove-indentation n)
16623 (buffer-string)))
16625 (defun org-do-remove-indentation (&optional n)
16626 "Remove the maximum common indentation from the buffer."
16627 (untabify (point-min) (point-max))
16628 (let ((min 10000) re)
16629 (if n
16630 (setq min n)
16631 (goto-char (point-min))
16632 (while (re-search-forward "^ *[^ \n]" nil t)
16633 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16634 (unless (or (= min 0) (= min 10000))
16635 (setq re (format "^ \\{%d\\}" min))
16636 (goto-char (point-min))
16637 (while (re-search-forward re nil t)
16638 (replace-match "")
16639 (end-of-line 1))
16640 min)))
16642 (defun org-fill-template (template alist)
16643 "Find each %key of ALIST in TEMPLATE and replace it."
16644 (let ((case-fold-search nil)
16645 entry key value)
16646 (setq alist (sort (copy-sequence alist)
16647 (lambda (a b) (< (length (car a)) (length (car b))))))
16648 (while (setq entry (pop alist))
16649 (setq template
16650 (replace-regexp-in-string
16651 (concat "%" (regexp-quote (car entry)))
16652 (cdr entry) template t t)))
16653 template))
16655 (defun org-base-buffer (buffer)
16656 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16657 (if (not buffer)
16658 buffer
16659 (or (buffer-base-buffer buffer)
16660 buffer)))
16662 (defun org-trim (s)
16663 "Remove whitespace at beginning and end of string."
16664 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16665 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16668 (defun org-wrap (string &optional width lines)
16669 "Wrap string to either a number of lines, or a width in characters.
16670 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16671 that costs. If there is a word longer than WIDTH, the text is actually
16672 wrapped to the length of that word.
16673 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16674 many lines, whatever width that takes.
16675 The return value is a list of lines, without newlines at the end."
16676 (let* ((words (org-split-string string "[ \t\n]+"))
16677 (maxword (apply 'max (mapcar 'org-string-width words)))
16678 w ll)
16679 (cond (width
16680 (org-do-wrap words (max maxword width)))
16681 (lines
16682 (setq w maxword)
16683 (setq ll (org-do-wrap words maxword))
16684 (if (<= (length ll) lines)
16686 (setq ll words)
16687 (while (> (length ll) lines)
16688 (setq w (1+ w))
16689 (setq ll (org-do-wrap words w)))
16690 ll))
16691 (t (error "Cannot wrap this")))))
16693 (defun org-do-wrap (words width)
16694 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16695 (let (lines line)
16696 (while words
16697 (setq line (pop words))
16698 (while (and words (< (+ (length line) (length (car words))) width))
16699 (setq line (concat line " " (pop words))))
16700 (setq lines (push line lines)))
16701 (nreverse lines)))
16703 (defun org-split-string (string &optional separators)
16704 "Splits STRING into substrings at SEPARATORS.
16705 No empty strings are returned if there are matches at the beginning
16706 and end of string."
16707 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16708 (start 0)
16709 notfirst
16710 (list nil))
16711 (while (and (string-match rexp string
16712 (if (and notfirst
16713 (= start (match-beginning 0))
16714 (< start (length string)))
16715 (1+ start) start))
16716 (< (match-beginning 0) (length string)))
16717 (setq notfirst t)
16718 (or (eq (match-beginning 0) 0)
16719 (and (eq (match-beginning 0) (match-end 0))
16720 (eq (match-beginning 0) start))
16721 (setq list
16722 (cons (substring string start (match-beginning 0))
16723 list)))
16724 (setq start (match-end 0)))
16725 (or (eq start (length string))
16726 (setq list
16727 (cons (substring string start)
16728 list)))
16729 (nreverse list)))
16731 (defun org-quote-vert (s)
16732 "Replace \"|\" with \"\\vert\"."
16733 (while (string-match "|" s)
16734 (setq s (replace-match "\\vert" t t s)))
16737 (defun org-uuidgen-p (s)
16738 "Is S an ID created by UUIDGEN?"
16739 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16741 (defun org-context ()
16742 "Return a list of contexts of the current cursor position.
16743 If several contexts apply, all are returned.
16744 Each context entry is a list with a symbol naming the context, and
16745 two positions indicating start and end of the context. Possible
16746 contexts are:
16748 :headline anywhere in a headline
16749 :headline-stars on the leading stars in a headline
16750 :todo-keyword on a TODO keyword (including DONE) in a headline
16751 :tags on the TAGS in a headline
16752 :priority on the priority cookie in a headline
16753 :item on the first line of a plain list item
16754 :item-bullet on the bullet/number of a plain list item
16755 :checkbox on the checkbox in a plain list item
16756 :table in an org-mode table
16757 :table-special on a special filed in a table
16758 :table-table in a table.el table
16759 :link on a hyperlink
16760 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16761 :target on a <<target>>
16762 :radio-target on a <<<radio-target>>>
16763 :latex-fragment on a LaTeX fragment
16764 :latex-preview on a LaTeX fragment with overlayed preview image
16766 This function expects the position to be visible because it uses font-lock
16767 faces as a help to recognize the following contexts: :table-special, :link,
16768 and :keyword."
16769 (let* ((f (get-text-property (point) 'face))
16770 (faces (if (listp f) f (list f)))
16771 (p (point)) clist o)
16772 ;; First the large context
16773 (cond
16774 ((org-on-heading-p t)
16775 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16776 (when (progn
16777 (beginning-of-line 1)
16778 (looking-at org-todo-line-tags-regexp))
16779 (push (org-point-in-group p 1 :headline-stars) clist)
16780 (push (org-point-in-group p 2 :todo-keyword) clist)
16781 (push (org-point-in-group p 4 :tags) clist))
16782 (goto-char p)
16783 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16784 (if (looking-at "\\[#[A-Z0-9]\\]")
16785 (push (org-point-in-group p 0 :priority) clist)))
16787 ((org-at-item-p)
16788 (push (org-point-in-group p 2 :item-bullet) clist)
16789 (push (list :item (point-at-bol)
16790 (save-excursion (org-end-of-item) (point)))
16791 clist)
16792 (and (org-at-item-checkbox-p)
16793 (push (org-point-in-group p 0 :checkbox) clist)))
16795 ((org-at-table-p)
16796 (push (list :table (org-table-begin) (org-table-end)) clist)
16797 (if (memq 'org-formula faces)
16798 (push (list :table-special
16799 (previous-single-property-change p 'face)
16800 (next-single-property-change p 'face)) clist)))
16801 ((org-at-table-p 'any)
16802 (push (list :table-table) clist)))
16803 (goto-char p)
16805 ;; Now the small context
16806 (cond
16807 ((org-at-timestamp-p)
16808 (push (org-point-in-group p 0 :timestamp) clist))
16809 ((memq 'org-link faces)
16810 (push (list :link
16811 (previous-single-property-change p 'face)
16812 (next-single-property-change p 'face)) clist))
16813 ((memq 'org-special-keyword faces)
16814 (push (list :keyword
16815 (previous-single-property-change p 'face)
16816 (next-single-property-change p 'face)) clist))
16817 ((org-on-target-p)
16818 (push (org-point-in-group p 0 :target) clist)
16819 (goto-char (1- (match-beginning 0)))
16820 (if (looking-at org-radio-target-regexp)
16821 (push (org-point-in-group p 0 :radio-target) clist))
16822 (goto-char p))
16823 ((setq o (car (delq nil
16824 (mapcar
16825 (lambda (x)
16826 (if (memq x org-latex-fragment-image-overlays) x))
16827 (org-overlays-at (point))))))
16828 (push (list :latex-fragment
16829 (org-overlay-start o) (org-overlay-end o)) clist)
16830 (push (list :latex-preview
16831 (org-overlay-start o) (org-overlay-end o)) clist))
16832 ((org-inside-LaTeX-fragment-p)
16833 ;; FIXME: positions wrong.
16834 (push (list :latex-fragment (point) (point)) clist)))
16836 (setq clist (nreverse (delq nil clist)))
16837 clist))
16839 ;; FIXME: Compare with at-regexp-p Do we need both?
16840 (defun org-in-regexp (re &optional nlines visually)
16841 "Check if point is inside a match of regexp.
16842 Normally only the current line is checked, but you can include NLINES extra
16843 lines both before and after point into the search.
16844 If VISUALLY is set, require that the cursor is not after the match but
16845 really on, so that the block visually is on the match."
16846 (catch 'exit
16847 (let ((pos (point))
16848 (eol (point-at-eol (+ 1 (or nlines 0))))
16849 (inc (if visually 1 0)))
16850 (save-excursion
16851 (beginning-of-line (- 1 (or nlines 0)))
16852 (while (re-search-forward re eol t)
16853 (if (and (<= (match-beginning 0) pos)
16854 (>= (+ inc (match-end 0)) pos))
16855 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16857 (defun org-at-regexp-p (regexp)
16858 "Is point inside a match of REGEXP in the current line?"
16859 (catch 'exit
16860 (save-excursion
16861 (let ((pos (point)) (end (point-at-eol)))
16862 (beginning-of-line 1)
16863 (while (re-search-forward regexp end t)
16864 (if (and (<= (match-beginning 0) pos)
16865 (>= (match-end 0) pos))
16866 (throw 'exit t)))
16867 nil))))
16869 (defun org-occur-in-agenda-files (regexp &optional nlines)
16870 "Call `multi-occur' with buffers for all agenda files."
16871 (interactive "sOrg-files matching: \np")
16872 (let* ((files (org-agenda-files))
16873 (tnames (mapcar 'file-truename files))
16874 (extra org-agenda-text-search-extra-files)
16876 (when (eq (car extra) 'agenda-archives)
16877 (setq extra (cdr extra))
16878 (setq files (org-add-archive-files files)))
16879 (while (setq f (pop extra))
16880 (unless (member (file-truename f) tnames)
16881 (add-to-list 'files f 'append)
16882 (add-to-list 'tnames (file-truename f) 'append)))
16883 (multi-occur
16884 (mapcar (lambda (x)
16885 (with-current-buffer
16886 (or (get-file-buffer x) (find-file-noselect x))
16887 (widen)
16888 (current-buffer)))
16889 files)
16890 regexp)))
16892 (if (boundp 'occur-mode-find-occurrence-hook)
16893 ;; Emacs 23
16894 (add-hook 'occur-mode-find-occurrence-hook
16895 (lambda ()
16896 (when (org-mode-p)
16897 (org-reveal))))
16898 ;; Emacs 22
16899 (defadvice occur-mode-goto-occurrence
16900 (after org-occur-reveal activate)
16901 (and (org-mode-p) (org-reveal)))
16902 (defadvice occur-mode-goto-occurrence-other-window
16903 (after org-occur-reveal activate)
16904 (and (org-mode-p) (org-reveal)))
16905 (defadvice occur-mode-display-occurrence
16906 (after org-occur-reveal activate)
16907 (when (org-mode-p)
16908 (let ((pos (occur-mode-find-occurrence)))
16909 (with-current-buffer (marker-buffer pos)
16910 (save-excursion
16911 (goto-char pos)
16912 (org-reveal)))))))
16914 (defun org-occur-link-in-agenda-files ()
16915 "Create a link and search for it in the agendas.
16916 The link is not stored in `org-stored-links', it is just created
16917 for the search purpose."
16918 (interactive)
16919 (let ((link (condition-case nil
16920 (org-store-link nil)
16921 (error "Unable to create a link to here"))))
16922 (org-occur-in-agenda-files (regexp-quote link))))
16924 (defun org-uniquify (list)
16925 "Remove duplicate elements from LIST."
16926 (let (res)
16927 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16928 res))
16930 (defun org-delete-all (elts list)
16931 "Remove all elements in ELTS from LIST."
16932 (while elts
16933 (setq list (delete (pop elts) list)))
16934 list)
16936 (defun org-back-over-empty-lines ()
16937 "Move backwards over whitespace, to the beginning of the first empty line.
16938 Returns the number of empty lines passed."
16939 (let ((pos (point)))
16940 (skip-chars-backward " \t\n\r")
16941 (beginning-of-line 2)
16942 (goto-char (min (point) pos))
16943 (count-lines (point) pos)))
16945 (defun org-skip-whitespace ()
16946 (skip-chars-forward " \t\n\r"))
16948 (defun org-point-in-group (point group &optional context)
16949 "Check if POINT is in match-group GROUP.
16950 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16951 match. If the match group does ot exist or point is not inside it,
16952 return nil."
16953 (and (match-beginning group)
16954 (>= point (match-beginning group))
16955 (<= point (match-end group))
16956 (if context
16957 (list context (match-beginning group) (match-end group))
16958 t)))
16960 (defun org-switch-to-buffer-other-window (&rest args)
16961 "Switch to buffer in a second window on the current frame.
16962 In particular, do not allow pop-up frames."
16963 (let (pop-up-frames special-display-buffer-names special-display-regexps
16964 special-display-function)
16965 (apply 'switch-to-buffer-other-window args)))
16967 (defun org-combine-plists (&rest plists)
16968 "Create a single property list from all plists in PLISTS.
16969 The process starts by copying the first list, and then setting properties
16970 from the other lists. Settings in the last list are the most significant
16971 ones and overrule settings in the other lists."
16972 (let ((rtn (copy-sequence (pop plists)))
16973 p v ls)
16974 (while plists
16975 (setq ls (pop plists))
16976 (while ls
16977 (setq p (pop ls) v (pop ls))
16978 (setq rtn (plist-put rtn p v))))
16979 rtn))
16981 (defun org-move-line-down (arg)
16982 "Move the current line down. With prefix argument, move it past ARG lines."
16983 (interactive "p")
16984 (let ((col (current-column))
16985 beg end pos)
16986 (beginning-of-line 1) (setq beg (point))
16987 (beginning-of-line 2) (setq end (point))
16988 (beginning-of-line (+ 1 arg))
16989 (setq pos (move-marker (make-marker) (point)))
16990 (insert (delete-and-extract-region beg end))
16991 (goto-char pos)
16992 (org-move-to-column col)))
16994 (defun org-move-line-up (arg)
16995 "Move the current line up. With prefix argument, move it past ARG lines."
16996 (interactive "p")
16997 (let ((col (current-column))
16998 beg end pos)
16999 (beginning-of-line 1) (setq beg (point))
17000 (beginning-of-line 2) (setq end (point))
17001 (beginning-of-line (- arg))
17002 (setq pos (move-marker (make-marker) (point)))
17003 (insert (delete-and-extract-region beg end))
17004 (goto-char pos)
17005 (org-move-to-column col)))
17007 (defun org-replace-escapes (string table)
17008 "Replace %-escapes in STRING with values in TABLE.
17009 TABLE is an association list with keys like \"%a\" and string values.
17010 The sequences in STRING may contain normal field width and padding information,
17011 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17012 so values can contain further %-escapes if they are define later in TABLE."
17013 (let ((case-fold-search nil)
17014 e re rpl)
17015 (while (setq e (pop table))
17016 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17017 (while (string-match re string)
17018 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17019 (cdr e)))
17020 (setq string (replace-match rpl t t string))))
17021 string))
17024 (defun org-sublist (list start end)
17025 "Return a section of LIST, from START to END.
17026 Counting starts at 1."
17027 (let (rtn (c start))
17028 (setq list (nthcdr (1- start) list))
17029 (while (and list (<= c end))
17030 (push (pop list) rtn)
17031 (setq c (1+ c)))
17032 (nreverse rtn)))
17034 (defun org-find-base-buffer-visiting (file)
17035 "Like `find-buffer-visiting' but always return the base buffer and
17036 not an indirect buffer."
17037 (let ((buf (or (get-file-buffer file)
17038 (find-buffer-visiting file))))
17039 (if buf
17040 (or (buffer-base-buffer buf) buf)
17041 nil)))
17043 (defun org-image-file-name-regexp (&optional extensions)
17044 "Return regexp matching the file names of images.
17045 If EXTENSIONS is given, only match these."
17046 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17047 (image-file-name-regexp)
17048 (let ((image-file-name-extensions
17049 (or extensions
17050 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17051 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17052 (concat "\\."
17053 (regexp-opt (nconc (mapcar 'upcase
17054 image-file-name-extensions)
17055 image-file-name-extensions)
17057 "\\'"))))
17059 (defun org-file-image-p (file &optional extensions)
17060 "Return non-nil if FILE is an image."
17061 (save-match-data
17062 (string-match (org-image-file-name-regexp extensions) file)))
17064 (defun org-get-cursor-date ()
17065 "Return the date at cursor in as a time.
17066 This works in the calendar and in the agenda, anywhere else it just
17067 returns the current time."
17068 (let (date day defd)
17069 (cond
17070 ((eq major-mode 'calendar-mode)
17071 (setq date (calendar-cursor-to-date)
17072 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17073 ((eq major-mode 'org-agenda-mode)
17074 (setq day (get-text-property (point) 'day))
17075 (if day
17076 (setq date (calendar-gregorian-from-absolute day)
17077 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17078 (nth 2 date))))))
17079 (or defd (current-time))))
17081 (defvar org-agenda-action-marker (make-marker)
17082 "Marker pointing to the entry for the next agenda action.")
17084 (defun org-mark-entry-for-agenda-action ()
17085 "Mark the current entry as target of an agenda action.
17086 Agenda actions are actions executed from the agenda with the key `k',
17087 which make use of the date at the cursor."
17088 (interactive)
17089 (move-marker org-agenda-action-marker
17090 (save-excursion (org-back-to-heading t) (point))
17091 (current-buffer))
17092 (message
17093 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17095 ;;; Paragraph filling stuff.
17096 ;; We want this to be just right, so use the full arsenal.
17098 (defun org-indent-line-function ()
17099 "Indent line like previous, but further if previous was headline or item."
17100 (interactive)
17101 (let* ((pos (point))
17102 (itemp (org-at-item-p))
17103 (case-fold-search t)
17104 (org-drawer-regexp (or org-drawer-regexp "\000"))
17105 column bpos bcol tpos tcol bullet btype bullet-type)
17106 ;; Find the previous relevant line
17107 (beginning-of-line 1)
17108 (cond
17109 ((looking-at "#") (setq column 0))
17110 ((looking-at "\\*+ ") (setq column 0))
17111 ((and (looking-at "[ \t]*:END:")
17112 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17113 (save-excursion
17114 (goto-char (1- (match-beginning 1)))
17115 (setq column (current-column))))
17116 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17117 (save-excursion
17118 (re-search-backward
17119 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17120 (setq column (org-get-indentation (match-string 0))))
17122 (beginning-of-line 0)
17123 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17124 (not (looking-at "[ \t]*:END:"))
17125 (not (looking-at org-drawer-regexp)))
17126 (beginning-of-line 0))
17127 (cond
17128 ((looking-at "\\*+[ \t]+")
17129 (if (not org-adapt-indentation)
17130 (setq column 0)
17131 (goto-char (match-end 0))
17132 (setq column (current-column))))
17133 ((looking-at org-drawer-regexp)
17134 (goto-char (1- (match-beginning 1)))
17135 (setq column (current-column)))
17136 ((looking-at "\\([ \t]*\\):END:")
17137 (goto-char (match-end 1))
17138 (setq column (current-column)))
17139 ((org-in-item-p)
17140 (org-beginning-of-item)
17141 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17142 (setq bpos (match-beginning 1) tpos (match-end 0)
17143 bcol (progn (goto-char bpos) (current-column))
17144 tcol (progn (goto-char tpos) (current-column))
17145 bullet (match-string 1)
17146 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17147 (if (> tcol (+ bcol org-description-max-indent))
17148 (setq tcol (+ bcol 5)))
17149 (if (not itemp)
17150 (setq column tcol)
17151 (goto-char pos)
17152 (beginning-of-line 1)
17153 (if (looking-at "\\S-")
17154 (progn
17155 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17156 (setq bullet (match-string 1)
17157 btype (if (string-match "[0-9]" bullet) "n" bullet))
17158 (setq column (if (equal btype bullet-type) bcol tcol)))
17159 (setq column (org-get-indentation)))))
17160 (t (setq column (org-get-indentation))))))
17161 (goto-char pos)
17162 (if (<= (current-column) (current-indentation))
17163 (org-indent-line-to column)
17164 (save-excursion (org-indent-line-to column)))
17165 (setq column (current-column))
17166 (beginning-of-line 1)
17167 (if (looking-at
17168 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17169 (replace-match (concat (match-string 1)
17170 (format org-property-format
17171 (match-string 2) (match-string 3)))
17172 t t))
17173 (org-move-to-column column)))
17175 (defun org-set-autofill-regexps ()
17176 (interactive)
17177 ;; In the paragraph separator we include headlines, because filling
17178 ;; text in a line directly attached to a headline would otherwise
17179 ;; fill the headline as well.
17180 (org-set-local 'comment-start-skip "^#+[ \t]*")
17181 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17182 ;; The paragraph starter includes hand-formatted lists.
17183 (org-set-local
17184 'paragraph-start
17185 (concat
17186 "\f" "\\|"
17187 "[ ]*$" "\\|"
17188 "\\*+ " "\\|"
17189 "[ \t]*#" "\\|"
17190 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17191 "[ \t]*[:|]" "\\|"
17192 "\\$\\$" "\\|"
17193 "\\\\\\(begin\\|end\\|[][]\\)"))
17194 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17195 ;; But only if the user has not turned off tables or fixed-width regions
17196 (org-set-local
17197 'auto-fill-inhibit-regexp
17198 (concat "\\*+ \\|#\\+"
17199 "\\|[ \t]*" org-keyword-time-regexp
17200 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17201 (concat
17202 "\\|[ \t]*["
17203 (if org-enable-table-editor "|" "")
17204 (if org-enable-fixed-width-editor ":" "")
17205 "]"))))
17206 ;; We use our own fill-paragraph function, to make sure that tables
17207 ;; and fixed-width regions are not wrapped. That function will pass
17208 ;; through to `fill-paragraph' when appropriate.
17209 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17210 ; Adaptive filling: To get full control, first make sure that
17211 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17212 (org-set-local 'adaptive-fill-regexp "\000")
17213 (org-set-local 'adaptive-fill-function
17214 'org-adaptive-fill-function)
17215 (org-set-local
17216 'align-mode-rules-list
17217 '((org-in-buffer-settings
17218 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17219 (modes . '(org-mode))))))
17221 (defun org-fill-paragraph (&optional justify)
17222 "Re-align a table, pass through to fill-paragraph if no table."
17223 (let ((table-p (org-at-table-p))
17224 (table.el-p (org-at-table.el-p)))
17225 (cond ((and (equal (char-after (point-at-bol)) ?*)
17226 (save-excursion (goto-char (point-at-bol))
17227 (looking-at outline-regexp)))
17228 t) ; skip headlines
17229 (table.el-p t) ; skip table.el tables
17230 (table-p (org-table-align) t) ; align org-mode tables
17231 (t nil)))) ; call paragraph-fill
17233 ;; For reference, this is the default value of adaptive-fill-regexp
17234 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17236 (defun org-adaptive-fill-function ()
17237 "Return a fill prefix for org-mode files.
17238 In particular, this makes sure hanging paragraphs for hand-formatted lists
17239 work correctly."
17240 (cond ((looking-at "#[ \t]+")
17241 (match-string 0))
17242 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17243 (save-excursion
17244 (if (> (match-end 1) (+ (match-beginning 1)
17245 org-description-max-indent))
17246 (goto-char (+ (match-beginning 1) 5))
17247 (goto-char (match-end 0)))
17248 (make-string (current-column) ?\ )))
17249 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17250 (save-excursion
17251 (goto-char (match-end 0))
17252 (make-string (current-column) ?\ )))
17253 (t nil)))
17255 ;;; Other stuff.
17257 (defun org-toggle-fixed-width-section (arg)
17258 "Toggle the fixed-width export.
17259 If there is no active region, the QUOTE keyword at the current headline is
17260 inserted or removed. When present, it causes the text between this headline
17261 and the next to be exported as fixed-width text, and unmodified.
17262 If there is an active region, this command adds or removes a colon as the
17263 first character of this line. If the first character of a line is a colon,
17264 this line is also exported in fixed-width font."
17265 (interactive "P")
17266 (let* ((cc 0)
17267 (regionp (org-region-active-p))
17268 (beg (if regionp (region-beginning) (point)))
17269 (end (if regionp (region-end)))
17270 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17271 (case-fold-search nil)
17272 (re "[ \t]*\\(: \\)")
17273 off)
17274 (if regionp
17275 (save-excursion
17276 (goto-char beg)
17277 (setq cc (current-column))
17278 (beginning-of-line 1)
17279 (setq off (looking-at re))
17280 (while (> nlines 0)
17281 (setq nlines (1- nlines))
17282 (beginning-of-line 1)
17283 (cond
17284 (arg
17285 (org-move-to-column cc t)
17286 (insert ": \n")
17287 (forward-line -1))
17288 ((and off (looking-at re))
17289 (replace-match "" t t nil 1))
17290 ((not off) (org-move-to-column cc t) (insert ": ")))
17291 (forward-line 1)))
17292 (save-excursion
17293 (org-back-to-heading)
17294 (if (looking-at (concat outline-regexp
17295 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17296 (replace-match "" t t nil 1)
17297 (if (looking-at outline-regexp)
17298 (progn
17299 (goto-char (match-end 0))
17300 (insert org-quote-string " "))))))))
17302 (defun org-reftex-citation ()
17303 "Use reftex-citation to insert a citation into the buffer.
17304 This looks for a line like
17306 #+BIBLIOGRAPHY: foo plain option:-d
17308 and derives from it that foo.bib is the bibliography file relevant
17309 for this document. It then installs the necessary environment for RefTeX
17310 to work in this buffer and calls `reftex-citation' to insert a citation
17311 into the buffer.
17313 Export of such citations to both LaTeX and HTML is handled by the contributed
17314 package org-exp-bibtex by Taru Karttunen."
17315 (interactive)
17316 (let ((reftex-docstruct-symbol 'rds)
17317 (reftex-cite-format "\\cite{%l}")
17318 rds bib)
17319 (save-excursion
17320 (save-restriction
17321 (widen)
17322 (let ((case-fold-search t)
17323 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17324 (if (not (save-excursion
17325 (or (re-search-forward re nil t)
17326 (re-search-backward re nil t))))
17327 (error "No bibliography defined in file")
17328 (setq bib (concat (match-string 1) ".bib")
17329 rds (list (list 'bib bib)))))))
17330 (call-interactively 'reftex-citation)))
17332 ;;;; Functions extending outline functionality
17334 (defun org-beginning-of-line (&optional arg)
17335 "Go to the beginning of the current line. If that is invisible, continue
17336 to a visible line beginning. This makes the function of C-a more intuitive.
17337 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17338 first attempt, and only move to after the tags when the cursor is already
17339 beyond the end of the headline."
17340 (interactive "P")
17341 (let ((pos (point))
17342 (special (if (consp org-special-ctrl-a/e)
17343 (car org-special-ctrl-a/e)
17344 org-special-ctrl-a/e))
17345 refpos)
17346 (if (org-bound-and-true-p line-move-visual)
17347 (beginning-of-visual-line 1)
17348 (beginning-of-line 1))
17349 (if (and arg (fboundp 'move-beginning-of-line))
17350 (call-interactively 'move-beginning-of-line)
17351 (if (bobp)
17353 (backward-char 1)
17354 (if (org-invisible-p)
17355 (while (and (not (bobp)) (org-invisible-p))
17356 (backward-char 1)
17357 (beginning-of-line 1))
17358 (forward-char 1))))
17359 (when special
17360 (cond
17361 ((and (looking-at org-complex-heading-regexp)
17362 (= (char-after (match-end 1)) ?\ ))
17363 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17364 (point-at-eol)))
17365 (goto-char
17366 (if (eq special t)
17367 (cond ((> pos refpos) refpos)
17368 ((= pos (point)) refpos)
17369 (t (point)))
17370 (cond ((> pos (point)) (point))
17371 ((not (eq last-command this-command)) (point))
17372 (t refpos)))))
17373 ((org-at-item-p)
17374 (goto-char
17375 (if (eq special t)
17376 (cond ((> pos (match-end 4)) (match-end 4))
17377 ((= pos (point)) (match-end 4))
17378 (t (point)))
17379 (cond ((> pos (point)) (point))
17380 ((not (eq last-command this-command)) (point))
17381 (t (match-end 4))))))))
17382 (org-no-warnings
17383 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17385 (defun org-end-of-line (&optional arg)
17386 "Go to the end of the line.
17387 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17388 first attempt, and only move to after the tags when the cursor is already
17389 beyond the end of the headline."
17390 (interactive "P")
17391 (let ((special (if (consp org-special-ctrl-a/e)
17392 (cdr org-special-ctrl-a/e)
17393 org-special-ctrl-a/e)))
17394 (if (or (not special)
17395 (not (org-on-heading-p))
17396 arg)
17397 (call-interactively
17398 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17399 ((fboundp 'move-end-of-line) 'move-end-of-line)
17400 (t 'end-of-line)))
17401 (let ((pos (point)))
17402 (beginning-of-line 1)
17403 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17404 (if (eq special t)
17405 (if (or (< pos (match-beginning 1))
17406 (= pos (match-end 0)))
17407 (goto-char (match-beginning 1))
17408 (goto-char (match-end 0)))
17409 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17410 (goto-char (match-end 0))
17411 (goto-char (match-beginning 1))))
17412 (call-interactively (if (fboundp 'move-end-of-line)
17413 'move-end-of-line
17414 'end-of-line)))))
17415 (org-no-warnings
17416 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17418 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17419 (define-key org-mode-map "\C-e" 'org-end-of-line)
17420 (define-key org-mode-map [home] 'org-beginning-of-line)
17421 (define-key org-mode-map [end] 'org-end-of-line)
17423 (defun org-backward-sentence (&optional arg)
17424 "Go to beginning of sentence, or beginning of table field.
17425 This will call `backward-sentence' or `org-table-beginning-of-field',
17426 depending on context."
17427 (interactive "P")
17428 (cond
17429 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17430 (t (call-interactively 'backward-sentence))))
17432 (defun org-forward-sentence (&optional arg)
17433 "Go to end of sentence, or end of table field.
17434 This will call `forward-sentence' or `org-table-end-of-field',
17435 depending on context."
17436 (interactive "P")
17437 (cond
17438 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17439 (t (call-interactively 'forward-sentence))))
17441 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17442 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17444 (defun org-kill-line (&optional arg)
17445 "Kill line, to tags or end of line."
17446 (interactive "P")
17447 (cond
17448 ((or (not org-special-ctrl-k)
17449 (bolp)
17450 (not (org-on-heading-p)))
17451 (call-interactively 'kill-line))
17452 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17453 (kill-region (point) (match-beginning 1))
17454 (org-set-tags nil t))
17455 (t (kill-region (point) (point-at-eol)))))
17457 (define-key org-mode-map "\C-k" 'org-kill-line)
17459 (defun org-yank (&optional arg)
17460 "Yank. If the kill is a subtree, treat it specially.
17461 This command will look at the current kill and check if is a single
17462 subtree, or a series of subtrees[1]. If it passes the test, and if the
17463 cursor is at the beginning of a line or after the stars of a currently
17464 empty headline, then the yank is handled specially. How exactly depends
17465 on the value of the following variables, both set by default.
17467 org-yank-folded-subtrees
17468 When set, the subtree(s) will be folded after insertion, but only
17469 if doing so would now swallow text after the yanked text.
17471 org-yank-adjusted-subtrees
17472 When set, the subtree will be promoted or demoted in order to
17473 fit into the local outline tree structure, which means that the level
17474 will be adjusted so that it becomes the smaller one of the two
17475 *visible* surrounding headings.
17477 Any prefix to this command will cause `yank' to be called directly with
17478 no special treatment. In particular, a simple `C-u' prefix will just
17479 plainly yank the text as it is.
17481 \[1] The test checks if the first non-white line is a heading
17482 and if there are no other headings with fewer stars."
17483 (interactive "P")
17484 (org-yank-generic 'yank arg))
17486 (defun org-yank-generic (command arg)
17487 "Perform some yank-like command.
17489 This function implements the behavior described in the `org-yank'
17490 documentation. However, it has been generalized to work for any
17491 interactive command with similar behavior."
17493 ;; pretend to be command COMMAND
17494 (setq this-command command)
17496 (if arg
17497 (call-interactively command)
17499 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17500 (and (org-kill-is-subtree-p)
17501 (or (bolp)
17502 (and (looking-at "[ \t]*$")
17503 (string-match
17504 "\\`\\*+\\'"
17505 (buffer-substring (point-at-bol) (point)))))))
17506 swallowp)
17507 (cond
17508 ((and subtreep org-yank-folded-subtrees)
17509 (let ((beg (point))
17510 end)
17511 (if (and subtreep org-yank-adjusted-subtrees)
17512 (org-paste-subtree nil nil 'for-yank)
17513 (call-interactively command))
17515 (setq end (point))
17516 (goto-char beg)
17517 (when (and (bolp) subtreep
17518 (not (setq swallowp
17519 (org-yank-folding-would-swallow-text beg end))))
17520 (or (looking-at outline-regexp)
17521 (re-search-forward (concat "^" outline-regexp) end t))
17522 (while (and (< (point) end) (looking-at outline-regexp))
17523 (hide-subtree)
17524 (org-cycle-show-empty-lines 'folded)
17525 (condition-case nil
17526 (outline-forward-same-level 1)
17527 (error (goto-char end)))))
17528 (when swallowp
17529 (message
17530 "Inserted text not folded because that would swallow text"))
17532 (goto-char end)
17533 (skip-chars-forward " \t\n\r")
17534 (beginning-of-line 1)
17535 (push-mark beg 'nomsg)))
17536 ((and subtreep org-yank-adjusted-subtrees)
17537 (let ((beg (point-at-bol)))
17538 (org-paste-subtree nil nil 'for-yank)
17539 (push-mark beg 'nomsg)))
17541 (call-interactively command))))))
17543 (defun org-yank-folding-would-swallow-text (beg end)
17544 "Would hide-subtree at BEG swallow any text after END?"
17545 (let (level)
17546 (save-excursion
17547 (goto-char beg)
17548 (when (or (looking-at outline-regexp)
17549 (re-search-forward (concat "^" outline-regexp) end t))
17550 (setq level (org-outline-level)))
17551 (goto-char end)
17552 (skip-chars-forward " \t\r\n\v\f")
17553 (if (or (eobp)
17554 (and (bolp) (looking-at org-outline-regexp)
17555 (<= (org-outline-level) level)))
17556 nil ; Nothing would be swallowed
17557 t)))) ; something would swallow
17559 (define-key org-mode-map "\C-y" 'org-yank)
17561 (defun org-invisible-p ()
17562 "Check if point is at a character currently not visible."
17563 ;; Early versions of noutline don't have `outline-invisible-p'.
17564 (if (fboundp 'outline-invisible-p)
17565 (outline-invisible-p)
17566 (get-char-property (point) 'invisible)))
17568 (defun org-invisible-p2 ()
17569 "Check if point is at a character currently not visible."
17570 (save-excursion
17571 (if (and (eolp) (not (bobp))) (backward-char 1))
17572 ;; Early versions of noutline don't have `outline-invisible-p'.
17573 (if (fboundp 'outline-invisible-p)
17574 (outline-invisible-p)
17575 (get-char-property (point) 'invisible))))
17577 (defun org-back-to-heading (&optional invisible-ok)
17578 "Call `outline-back-to-heading', but provide a better error message."
17579 (condition-case nil
17580 (outline-back-to-heading invisible-ok)
17581 (error (error "Before first headline at position %d in buffer %s"
17582 (point) (current-buffer)))))
17584 (defun org-before-first-heading-p ()
17585 "Before first heading?"
17586 (save-excursion
17587 (null (re-search-backward "^\\*+ " nil t))))
17589 (defun org-on-heading-p (&optional ignored)
17590 (outline-on-heading-p t))
17591 (defun org-at-heading-p (&optional ignored)
17592 (outline-on-heading-p t))
17594 (defun org-at-heading-or-item-p ()
17595 (or (org-on-heading-p) (org-at-item-p)))
17597 (defun org-on-target-p ()
17598 (or (org-in-regexp org-radio-target-regexp)
17599 (org-in-regexp org-target-regexp)))
17601 (defun org-up-heading-all (arg)
17602 "Move to the heading line of which the present line is a subheading.
17603 This function considers both visible and invisible heading lines.
17604 With argument, move up ARG levels."
17605 (if (fboundp 'outline-up-heading-all)
17606 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17607 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17609 (defun org-up-heading-safe ()
17610 "Move to the heading line of which the present line is a subheading.
17611 This version will not throw an error. It will return the level of the
17612 headline found, or nil if no higher level is found.
17614 Also, this function will be a lot faster than `outline-up-heading',
17615 because it relies on stars being the outline starters. This can really
17616 make a significant difference in outlines with very many siblings."
17617 (let (start-level re)
17618 (org-back-to-heading t)
17619 (setq start-level (funcall outline-level))
17620 (if (equal start-level 1)
17622 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17623 (if (re-search-backward re nil t)
17624 (funcall outline-level)))))
17626 (defun org-first-sibling-p ()
17627 "Is this heading the first child of its parents?"
17628 (interactive)
17629 (let ((re (concat "^" outline-regexp))
17630 level l)
17631 (unless (org-at-heading-p t)
17632 (error "Not at a heading"))
17633 (setq level (funcall outline-level))
17634 (save-excursion
17635 (if (not (re-search-backward re nil t))
17637 (setq l (funcall outline-level))
17638 (< l level)))))
17640 (defun org-goto-sibling (&optional previous)
17641 "Goto the next sibling, even if it is invisible.
17642 When PREVIOUS is set, go to the previous sibling instead. Returns t
17643 when a sibling was found. When none is found, return nil and don't
17644 move point."
17645 (let ((fun (if previous 're-search-backward 're-search-forward))
17646 (pos (point))
17647 (re (concat "^" outline-regexp))
17648 level l)
17649 (when (condition-case nil (org-back-to-heading t) (error nil))
17650 (setq level (funcall outline-level))
17651 (catch 'exit
17652 (or previous (forward-char 1))
17653 (while (funcall fun re nil t)
17654 (setq l (funcall outline-level))
17655 (when (< l level) (goto-char pos) (throw 'exit nil))
17656 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17657 (goto-char pos)
17658 nil))))
17660 (defun org-show-siblings ()
17661 "Show all siblings of the current headline."
17662 (save-excursion
17663 (while (org-goto-sibling) (org-flag-heading nil)))
17664 (save-excursion
17665 (while (org-goto-sibling 'previous)
17666 (org-flag-heading nil))))
17668 (defun org-show-hidden-entry ()
17669 "Show an entry where even the heading is hidden."
17670 (save-excursion
17671 (org-show-entry)))
17673 (defun org-flag-heading (flag &optional entry)
17674 "Flag the current heading. FLAG non-nil means make invisible.
17675 When ENTRY is non-nil, show the entire entry."
17676 (save-excursion
17677 (org-back-to-heading t)
17678 ;; Check if we should show the entire entry
17679 (if entry
17680 (progn
17681 (org-show-entry)
17682 (save-excursion
17683 (and (outline-next-heading)
17684 (org-flag-heading nil))))
17685 (outline-flag-region (max (point-min) (1- (point)))
17686 (save-excursion (outline-end-of-heading) (point))
17687 flag))))
17689 (defun org-get-next-sibling ()
17690 "Move to next heading of the same level, and return point.
17691 If there is no such heading, return nil.
17692 This is like outline-next-sibling, but invisible headings are ok."
17693 (let ((level (funcall outline-level)))
17694 (outline-next-heading)
17695 (while (and (not (eobp)) (> (funcall outline-level) level))
17696 (outline-next-heading))
17697 (if (or (eobp) (< (funcall outline-level) level))
17699 (point))))
17701 (defun org-get-last-sibling ()
17702 "Move to previous heading of the same level, and return point.
17703 If there is no such heading, return nil."
17704 (let ((opoint (point))
17705 (level (funcall outline-level)))
17706 (outline-previous-heading)
17707 (when (and (/= (point) opoint) (outline-on-heading-p t))
17708 (while (and (> (funcall outline-level) level)
17709 (not (bobp)))
17710 (outline-previous-heading))
17711 (if (< (funcall outline-level) level)
17713 (point)))))
17715 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17716 ;; This contains an exact copy of the original function, but it uses
17717 ;; `org-back-to-heading', to make it work also in invisible
17718 ;; trees. And is uses an invisible-OK argument.
17719 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17720 ;; Furthermore, when used inside Org, finding the end of a large subtree
17721 ;; with many children and grandchildren etc, this can be much faster
17722 ;; than the outline version.
17723 (org-back-to-heading invisible-OK)
17724 (let ((first t)
17725 (level (funcall outline-level)))
17726 (if (and (org-mode-p) (< level 1000))
17727 ;; A true heading (not a plain list item), in Org-mode
17728 ;; This means we can easily find the end by looking
17729 ;; only for the right number of stars. Using a regexp to do
17730 ;; this is so much faster than using a Lisp loop.
17731 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17732 (forward-char 1)
17733 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17734 ;; something else, do it the slow way
17735 (while (and (not (eobp))
17736 (or first (> (funcall outline-level) level)))
17737 (setq first nil)
17738 (outline-next-heading)))
17739 (unless to-heading
17740 (if (memq (preceding-char) '(?\n ?\^M))
17741 (progn
17742 ;; Go to end of line before heading
17743 (forward-char -1)
17744 (if (memq (preceding-char) '(?\n ?\^M))
17745 ;; leave blank line before heading
17746 (forward-char -1))))))
17747 (point))
17749 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17750 "Use Org version in org-mode, for dramatic speed-up."
17751 (if (eq major-mode 'org-mode)
17752 (progn
17753 (org-end-of-subtree nil t)
17754 (unless (eobp) (backward-char 1)))
17755 ad-do-it))
17757 (defun org-forward-same-level (arg &optional invisible-ok)
17758 "Move forward to the arg'th subheading at same level as this one.
17759 Stop at the first and last subheadings of a superior heading."
17760 (interactive "p")
17761 (org-back-to-heading invisible-ok)
17762 (org-on-heading-p)
17763 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17764 (re (format "^\\*\\{1,%d\\} " level))
17766 (forward-char 1)
17767 (while (> arg 0)
17768 (while (and (re-search-forward re nil 'move)
17769 (setq l (- (match-end 0) (match-beginning 0) 1))
17770 (= l level)
17771 (not invisible-ok)
17772 (progn (backward-char 1) (org-invisible-p)))
17773 (if (< l level) (setq arg 1)))
17774 (setq arg (1- arg)))
17775 (beginning-of-line 1)))
17777 (defun org-backward-same-level (arg &optional invisible-ok)
17778 "Move backward to the arg'th subheading at same level as this one.
17779 Stop at the first and last subheadings of a superior heading."
17780 (interactive "p")
17781 (org-back-to-heading)
17782 (org-on-heading-p)
17783 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17784 (re (format "^\\*\\{1,%d\\} " level))
17786 (while (> arg 0)
17787 (while (and (re-search-backward re nil 'move)
17788 (setq l (- (match-end 0) (match-beginning 0) 1))
17789 (= l level)
17790 (not invisible-ok)
17791 (org-invisible-p))
17792 (if (< l level) (setq arg 1)))
17793 (setq arg (1- arg)))))
17795 (defun org-show-subtree ()
17796 "Show everything after this heading at deeper levels."
17797 (outline-flag-region
17798 (point)
17799 (save-excursion
17800 (org-end-of-subtree t t))
17801 nil))
17803 (defun org-show-entry ()
17804 "Show the body directly following this heading.
17805 Show the heading too, if it is currently invisible."
17806 (interactive)
17807 (save-excursion
17808 (condition-case nil
17809 (progn
17810 (org-back-to-heading t)
17811 (outline-flag-region
17812 (max (point-min) (1- (point)))
17813 (save-excursion
17814 (if (re-search-forward
17815 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17816 (match-beginning 1)
17817 (point-max)))
17818 nil)
17819 (org-cycle-hide-drawers 'children))
17820 (error nil))))
17822 (defun org-make-options-regexp (kwds &optional extra)
17823 "Make a regular expression for keyword lines."
17824 (concat
17826 "#?[ \t]*\\+\\("
17827 (mapconcat 'regexp-quote kwds "\\|")
17828 (if extra (concat "\\|" extra))
17829 "\\):[ \t]*"
17830 "\\(.*\\)"))
17832 ;; Make isearch reveal the necessary context
17833 (defun org-isearch-end ()
17834 "Reveal context after isearch exits."
17835 (when isearch-success ; only if search was successful
17836 (if (featurep 'xemacs)
17837 ;; Under XEmacs, the hook is run in the correct place,
17838 ;; we directly show the context.
17839 (org-show-context 'isearch)
17840 ;; In Emacs the hook runs *before* restoring the overlays.
17841 ;; So we have to use a one-time post-command-hook to do this.
17842 ;; (Emacs 22 has a special variable, see function `org-mode')
17843 (unless (and (boundp 'isearch-mode-end-hook-quit)
17844 isearch-mode-end-hook-quit)
17845 ;; Only when the isearch was not quitted.
17846 (org-add-hook 'post-command-hook 'org-isearch-post-command
17847 'append 'local)))))
17849 (defun org-isearch-post-command ()
17850 "Remove self from hook, and show context."
17851 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17852 (org-show-context 'isearch))
17855 ;;;; Integration with and fixes for other packages
17857 ;;; Imenu support
17859 (defvar org-imenu-markers nil
17860 "All markers currently used by Imenu.")
17861 (make-variable-buffer-local 'org-imenu-markers)
17863 (defun org-imenu-new-marker (&optional pos)
17864 "Return a new marker for use by Imenu, and remember the marker."
17865 (let ((m (make-marker)))
17866 (move-marker m (or pos (point)))
17867 (push m org-imenu-markers)
17870 (defun org-imenu-get-tree ()
17871 "Produce the index for Imenu."
17872 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17873 (setq org-imenu-markers nil)
17874 (let* ((n org-imenu-depth)
17875 (re (concat "^" outline-regexp))
17876 (subs (make-vector (1+ n) nil))
17877 (last-level 0)
17878 m level head)
17879 (save-excursion
17880 (save-restriction
17881 (widen)
17882 (goto-char (point-max))
17883 (while (re-search-backward re nil t)
17884 (setq level (org-reduced-level (funcall outline-level)))
17885 (when (<= level n)
17886 (looking-at org-complex-heading-regexp)
17887 (setq head (org-link-display-format
17888 (org-match-string-no-properties 4))
17889 m (org-imenu-new-marker))
17890 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17891 (if (>= level last-level)
17892 (push (cons head m) (aref subs level))
17893 (push (cons head (aref subs (1+ level))) (aref subs level))
17894 (loop for i from (1+ level) to n do (aset subs i nil)))
17895 (setq last-level level)))))
17896 (aref subs 1)))
17898 (eval-after-load "imenu"
17899 '(progn
17900 (add-hook 'imenu-after-jump-hook
17901 (lambda ()
17902 (if (eq major-mode 'org-mode)
17903 (org-show-context 'org-goto))))))
17905 (defun org-link-display-format (link)
17906 "Replace a link with either the description, or the link target
17907 if no description is present"
17908 (save-match-data
17909 (if (string-match org-bracket-link-analytic-regexp link)
17910 (replace-match (if (match-end 5)
17911 (match-string 5 link)
17912 (concat (match-string 1 link)
17913 (match-string 3 link)))
17914 nil t link)
17915 link)))
17917 ;; Speedbar support
17919 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17920 "Overlay marking the agenda restriction line in speedbar.")
17921 (org-overlay-put org-speedbar-restriction-lock-overlay
17922 'face 'org-agenda-restriction-lock)
17923 (org-overlay-put org-speedbar-restriction-lock-overlay
17924 'help-echo "Agendas are currently limited to this item.")
17925 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17927 (defun org-speedbar-set-agenda-restriction ()
17928 "Restrict future agenda commands to the location at point in speedbar.
17929 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17930 (interactive)
17931 (require 'org-agenda)
17932 (let (p m tp np dir txt)
17933 (cond
17934 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17935 'org-imenu t))
17936 (setq m (get-text-property p 'org-imenu-marker))
17937 (with-current-buffer (marker-buffer m)
17938 (goto-char m)
17939 (org-agenda-set-restriction-lock 'subtree)))
17940 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17941 'speedbar-function 'speedbar-find-file))
17942 (setq tp (previous-single-property-change
17943 (1+ p) 'speedbar-function)
17944 np (next-single-property-change
17945 tp 'speedbar-function)
17946 dir (speedbar-line-directory)
17947 txt (buffer-substring-no-properties (or tp (point-min))
17948 (or np (point-max))))
17949 (with-current-buffer (find-file-noselect
17950 (let ((default-directory dir))
17951 (expand-file-name txt)))
17952 (unless (org-mode-p)
17953 (error "Cannot restrict to non-Org-mode file"))
17954 (org-agenda-set-restriction-lock 'file)))
17955 (t (error "Don't know how to restrict Org-mode's agenda")))
17956 (org-move-overlay org-speedbar-restriction-lock-overlay
17957 (point-at-bol) (point-at-eol))
17958 (setq current-prefix-arg nil)
17959 (org-agenda-maybe-redo)))
17961 (eval-after-load "speedbar"
17962 '(progn
17963 (speedbar-add-supported-extension ".org")
17964 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17965 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17966 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17967 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17968 (add-hook 'speedbar-visiting-tag-hook
17969 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17972 ;;; Fixes and Hacks for problems with other packages
17974 ;; Make flyspell not check words in links, to not mess up our keymap
17975 (defun org-mode-flyspell-verify ()
17976 "Don't let flyspell put overlays at active buttons."
17977 (and (not (get-text-property (point) 'keymap))
17978 (not (get-text-property (point) 'org-no-flyspell))))
17980 (defun org-remove-flyspell-overlays-in (beg end)
17981 "Remove flyspell overlays in region."
17982 (and (org-bound-and-true-p flyspell-mode)
17983 (fboundp 'flyspell-delete-region-overlays)
17984 (flyspell-delete-region-overlays beg end))
17985 (add-text-properties beg end '(org-no-flyspell t)))
17987 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17988 (eval-after-load "bookmark"
17989 '(if (boundp 'bookmark-after-jump-hook)
17990 ;; We can use the hook
17991 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17992 ;; Hook not available, use advice
17993 (defadvice bookmark-jump (after org-make-visible activate)
17994 "Make the position visible."
17995 (org-bookmark-jump-unhide))))
17997 ;; Make sure saveplace shows the location if it was hidden
17998 (eval-after-load "saveplace"
17999 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18000 "Make the position visible."
18001 (org-bookmark-jump-unhide)))
18003 ;; Make sure ecb shows the location if it was hidden
18004 (eval-after-load "ecb"
18005 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18006 "Make hierarchy visible when jumping into location from ECB tree buffer."
18007 (if (eq major-mode 'org-mode)
18008 (org-show-context))))
18010 (defun org-bookmark-jump-unhide ()
18011 "Unhide the current position, to show the bookmark location."
18012 (and (org-mode-p)
18013 (or (org-invisible-p)
18014 (save-excursion (goto-char (max (point-min) (1- (point))))
18015 (org-invisible-p)))
18016 (org-show-context 'bookmark-jump)))
18018 ;; Make session.el ignore our circular variable
18019 (eval-after-load "session"
18020 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18022 ;;;; Experimental code
18024 (defun org-closed-in-range ()
18025 "Sparse tree of items closed in a certain time range.
18026 Still experimental, may disappear in the future."
18027 (interactive)
18028 ;; Get the time interval from the user.
18029 (let* ((time1 (org-float-time
18030 (org-read-date nil 'to-time nil "Starting date: ")))
18031 (time2 (org-float-time
18032 (org-read-date nil 'to-time nil "End date:")))
18033 ;; callback function
18034 (callback (lambda ()
18035 (let ((time
18036 (org-float-time
18037 (apply 'encode-time
18038 (org-parse-time-string
18039 (match-string 1))))))
18040 ;; check if time in interval
18041 (and (>= time time1) (<= time time2))))))
18042 ;; make tree, check each match with the callback
18043 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18045 ;;;; Finish up
18047 (provide 'org)
18049 (run-hooks 'org-load-hook)
18051 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18053 ;;; org.el ends here