Don't build org-refile-cache if org-refile-use-cache is nil
[org-mode.git] / lisp / org.el
blob496ecebd57a98a0b00f47bb1694a208ef9bbb860
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, 2010
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.36trans
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))
77 (require 'calendar)
78 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
79 (unless (boundp 'calendar-view-holidays-initially-flag)
80 (defvaralias 'calendar-view-holidays-initially-flag
81 'view-calendar-holidays-initially))
82 (unless (boundp 'calendar-view-diary-initially-flag)
83 (defvaralias 'calendar-view-diary-initially-flag
84 'view-diary-entries-initially))
85 (unless (boundp 'diary-fancy-buffer)
86 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
88 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
89 ;; the file noutline.el being loaded.
90 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
91 ;; We require noutline, which might be provided in outline.el
92 (require 'outline) (require 'noutline)
93 ;; Other stuff we need.
94 (require 'time-date)
95 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
96 (require 'easymenu)
97 (require 'overlay)
99 (require 'org-macs)
100 (require 'org-entities)
101 (require 'org-compat)
102 (require 'org-faces)
103 (require 'org-list)
104 (require 'org-src)
105 (require 'org-footnote)
107 ;;;; Customization variables
108 (defcustom org-clone-delete-id nil
109 "Remove ID property of clones of a subtree.
110 When non-nil, clones of a subtree don't inherit the ID property.
111 Otherwise they inherit the ID property with a new unique
112 identifier."
113 :type 'boolean
114 :group 'org-id)
116 ;;; Version
118 (defconst org-version "6.36trans"
119 "The version number of the file org.el.")
121 (defun org-version (&optional here)
122 "Show the org-mode version in the echo area.
123 With prefix arg HERE, insert it at point."
124 (interactive "P")
125 (let* ((origin default-directory)
126 (version org-version)
127 (git-version)
128 (dir (concat (file-name-directory (locate-library "org")) "../" )))
129 (when (and (file-exists-p (expand-file-name ".git" dir))
130 (executable-find "git"))
131 (unwind-protect
132 (progn
133 (cd dir)
134 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
135 (with-current-buffer "*Shell Command Output*"
136 (goto-char (point-min))
137 (setq git-version (buffer-substring (point) (point-at-eol))))
138 (subst-char-in-string ?- ?. git-version t)
139 (when (string-match "\\S-"
140 (shell-command-to-string
141 "git diff-index --name-only HEAD --"))
142 (setq git-version (concat git-version ".dirty")))
143 (setq version (concat version " (" git-version ")"))))
144 (cd origin)))
145 (setq version (format "Org-mode version %s" version))
146 (if here (insert version))
147 (message version)))
149 ;;; Compatibility constants
151 ;;; The custom variables
153 (defgroup org nil
154 "Outline-based notes management and organizer."
155 :tag "Org"
156 :group 'outlines
157 :group 'calendar)
159 (defcustom org-mode-hook nil
160 "Mode hook for Org-mode, run after the mode was turned on."
161 :group 'org
162 :type 'hook)
164 (defcustom org-load-hook nil
165 "Hook that is run after org.el has been loaded."
166 :group 'org
167 :type 'hook)
169 (defvar org-modules) ; defined below
170 (defvar org-modules-loaded nil
171 "Have the modules been loaded already?")
173 (defun org-load-modules-maybe (&optional force)
174 "Load all extensions listed in `org-modules'."
175 (when (or force (not org-modules-loaded))
176 (mapc (lambda (ext)
177 (condition-case nil (require ext)
178 (error (message "Problems while trying to load feature `%s'" ext))))
179 org-modules)
180 (setq org-modules-loaded t)))
182 (defun org-set-modules (var value)
183 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
184 (set var value)
185 (when (featurep 'org)
186 (org-load-modules-maybe 'force)))
188 (when (org-bound-and-true-p org-modules)
189 (let ((a (member 'org-infojs org-modules)))
190 (and a (setcar a 'org-jsinfo))))
192 (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)
193 "Modules that should always be loaded together with org.el.
194 If a description starts with <C>, the file is not part of Emacs
195 and loading it will require that you have downloaded and properly installed
196 the org-mode distribution.
198 You can also use this system to load external packages (i.e. neither Org
199 core modules, nor modules from the CONTRIB directory). Just add symbols
200 to the end of the list. If the package is called org-xyz.el, then you need
201 to add the symbol `xyz', and the package must have a call to
203 (provide 'org-xyz)"
204 :group 'org
205 :set 'org-set-modules
206 :type
207 '(set :greedy t
208 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
209 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
210 (const :tag " crypt: Encryption of subtrees" org-crypt)
211 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
212 (const :tag " docview: Links to doc-view buffers" org-docview)
213 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
214 (const :tag " id: Global IDs for identifying entries" org-id)
215 (const :tag " info: Links to Info nodes" org-info)
216 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
217 (const :tag " habit: Track your consistency with habits" org-habit)
218 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
219 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
220 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
221 (const :tag " mew Links to Mew folders/messages" org-mew)
222 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
223 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
224 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
225 (const :tag " vm: Links to VM folders/messages" org-vm)
226 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
227 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
228 (const :tag " mouse: Additional mouse support" org-mouse)
230 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
231 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
232 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
233 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
234 (const :tag "C collector: Collect properties into tables" org-collector)
235 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
236 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
237 (const :tag "C eval: Include command output as text" org-eval)
238 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
239 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
240 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
241 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
242 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
244 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
246 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
247 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
248 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
249 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
250 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
251 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
252 (const :tag "C mtags: Support for muse-like tags" org-mtags)
253 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
254 (const :tag "C registry: A registry for Org-mode links" org-registry)
255 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
256 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
257 (const :tag "C secretary: Team management with org-mode" org-secretary)
258 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
259 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
260 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
261 (const :tag "C track: Keep up with Org-mode development" org-track)
262 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
264 (defcustom org-support-shift-select nil
265 "Non-nil means make shift-cursor commands select text when possible.
267 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
268 selecting a region, or enlarge thusly regions started in this way.
269 In Org-mode, in special contexts, these same keys are used for other
270 purposes, important enough to compete with shift selection. Org tries
271 to balance these needs by supporting `shift-select-mode' outside these
272 special contexts, under control of this variable.
274 The default of this variable is nil, to avoid confusing behavior. Shifted
275 cursor keys will then execute Org commands in the following contexts:
276 - on a headline, changing TODO state (left/right) and priority (up/down)
277 - on a time stamp, changing the time
278 - in a plain list item, changing the bullet type
279 - in a property definition line, switching between allowed values
280 - in the BEGIN line of a clock table (changing the time block).
281 Outside these contexts, the commands will throw an error.
283 When this variable is t and the cursor is not in a special context,
284 Org-mode will support shift-selection for making and enlarging regions.
285 To make this more effective, the bullet cycling will no longer happen
286 anywhere in an item line, but only if the cursor is exactly on the bullet.
288 If you set this variable to the symbol `always', then the keys
289 will not be special in headlines, property lines, and item lines, to make
290 shift selection work there as well. If this is what you want, you can
291 use the following alternative commands: `C-c C-t' and `C-c ,' to
292 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
293 TODO sets, `C-c -' to cycle item bullet types, and properties can be
294 edited by hand or in column view.
296 However, when the cursor is on a timestamp, shift-cursor commands
297 will still edit the time stamp - this is just too good to give up.
299 XEmacs user should have this variable set to nil, because shift-select-mode
300 is Emacs 23 only."
301 :group 'org
302 :type '(choice
303 (const :tag "Never" nil)
304 (const :tag "When outside special context" t)
305 (const :tag "Everywhere except timestamps" always)))
307 (defgroup org-startup nil
308 "Options concerning startup of Org-mode."
309 :tag "Org Startup"
310 :group 'org)
312 (defcustom org-startup-folded t
313 "Non-nil means entering Org-mode will switch to OVERVIEW.
314 This can also be configured on a per-file basis by adding one of
315 the following lines anywhere in the buffer:
317 #+STARTUP: fold (or `overview', this is equivalent)
318 #+STARTUP: nofold (or `showall', this is equivalent)
319 #+STARTUP: content
320 #+STARTUP: showeverything"
321 :group 'org-startup
322 :type '(choice
323 (const :tag "nofold: show all" nil)
324 (const :tag "fold: overview" t)
325 (const :tag "content: all headlines" content)
326 (const :tag "show everything, even drawers" showeverything)))
328 (defcustom org-startup-truncated t
329 "Non-nil means entering Org-mode will set `truncate-lines'.
330 This is useful since some lines containing links can be very long and
331 uninteresting. Also tables look terrible when wrapped."
332 :group 'org-startup
333 :type 'boolean)
335 (defcustom org-startup-indented nil
336 "Non-nil means turn on `org-indent-mode' on startup.
337 This can also be configured on a per-file basis by adding one of
338 the following lines anywhere in the buffer:
340 #+STARTUP: indent
341 #+STARTUP: noindent"
342 :group 'org-structure
343 :type '(choice
344 (const :tag "Not" nil)
345 (const :tag "Globally (slow on startup in large files)" t)))
347 (defcustom org-startup-with-beamer-mode nil
348 "Non-nil means turn on `org-beamer-mode' on startup.
349 This can also be configured on a per-file basis by adding one of
350 the following lines anywhere in the buffer:
352 #+STARTUP: beamer"
353 :group 'org-startup
354 :type 'boolean)
356 (defcustom org-startup-align-all-tables nil
357 "Non-nil means align all tables when visiting a file.
358 This is useful when the column width in tables is forced with <N> cookies
359 in table fields. Such tables will look correct only after the first re-align.
360 This can also be configured on a per-file basis by adding one of
361 the following lines anywhere in the buffer:
362 #+STARTUP: align
363 #+STARTUP: noalign"
364 :group 'org-startup
365 :type 'boolean)
367 (defcustom org-insert-mode-line-in-empty-file nil
368 "Non-nil means insert the first line setting Org-mode in empty files.
369 When the function `org-mode' is called interactively in an empty file, this
370 normally means that the file name does not automatically trigger Org-mode.
371 To ensure that the file will always be in Org-mode in the future, a
372 line enforcing Org-mode will be inserted into the buffer, if this option
373 has been set."
374 :group 'org-startup
375 :type 'boolean)
377 (defcustom org-replace-disputed-keys nil
378 "Non-nil means use alternative key bindings for some keys.
379 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
380 These keys are also used by other packages like shift-selection-mode'
381 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
382 If you want to use Org-mode together with one of these other modes,
383 or more generally if you would like to move some Org-mode commands to
384 other keys, set this variable and configure the keys with the variable
385 `org-disputed-keys'.
387 This option is only relevant at load-time of Org-mode, and must be set
388 *before* org.el is loaded. Changing it requires a restart of Emacs to
389 become effective."
390 :group 'org-startup
391 :type 'boolean)
393 (defcustom org-use-extra-keys nil
394 "Non-nil means use extra key sequence definitions for certain
395 commands. This happens automatically if you run XEmacs or if
396 window-system is nil. This variable lets you do the same
397 manually. You must set it before loading org.
399 Example: on Carbon Emacs 22 running graphically, with an external
400 keyboard on a Powerbook, the default way of setting M-left might
401 not work for either Alt or ESC. Setting this variable will make
402 it work for ESC."
403 :group 'org-startup
404 :type 'boolean)
406 (if (fboundp 'defvaralias)
407 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
409 (defcustom org-disputed-keys
410 '(([(shift up)] . [(meta p)])
411 ([(shift down)] . [(meta n)])
412 ([(shift left)] . [(meta -)])
413 ([(shift right)] . [(meta +)])
414 ([(control shift right)] . [(meta shift +)])
415 ([(control shift left)] . [(meta shift -)]))
416 "Keys for which Org-mode and other modes compete.
417 This is an alist, cars are the default keys, second element specifies
418 the alternative to use when `org-replace-disputed-keys' is t.
420 Keys can be specified in any syntax supported by `define-key'.
421 The value of this option takes effect only at Org-mode's startup,
422 therefore you'll have to restart Emacs to apply it after changing."
423 :group 'org-startup
424 :type 'alist)
426 (defun org-key (key)
427 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
428 Or return the original if not disputed.
429 Also apply the trnaslations defined in `org-xemacs-key-equivalents'."
430 (when org-replace-disputed-keys
431 (let* ((nkey (key-description key))
432 (x (org-find-if (lambda (x)
433 (equal (key-description (car x)) nkey))
434 org-disputed-keys)))
435 (setq key (if x (cdr x) key))))
436 (when (featurep 'xemacs)
437 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
438 key)
440 (defun org-find-if (predicate seq)
441 (catch 'exit
442 (while seq
443 (if (funcall predicate (car seq))
444 (throw 'exit (car seq))
445 (pop seq)))))
447 (defun org-defkey (keymap key def)
448 "Define a key, possibly translated, as returned by `org-key'."
449 (define-key keymap (org-key key) def))
451 (defcustom org-ellipsis nil
452 "The ellipsis to use in the Org-mode outline.
453 When nil, just use the standard three dots. When a string, use that instead,
454 When a face, use the standard 3 dots, but with the specified face.
455 The change affects only Org-mode (which will then use its own display table).
456 Changing this requires executing `M-x org-mode' in a buffer to become
457 effective."
458 :group 'org-startup
459 :type '(choice (const :tag "Default" nil)
460 (face :tag "Face" :value org-warning)
461 (string :tag "String" :value "...#")))
463 (defvar org-display-table nil
464 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
466 (defgroup org-keywords nil
467 "Keywords in Org-mode."
468 :tag "Org Keywords"
469 :group 'org)
471 (defcustom org-deadline-string "DEADLINE:"
472 "String to mark deadline entries.
473 A deadline is this string, followed by a time stamp. Should be a word,
474 terminated by a colon. You can insert a schedule keyword and
475 a timestamp with \\[org-deadline].
476 Changes become only effective after restarting Emacs."
477 :group 'org-keywords
478 :type 'string)
480 (defcustom org-scheduled-string "SCHEDULED:"
481 "String to mark scheduled TODO entries.
482 A schedule is this string, followed by a time stamp. Should be a word,
483 terminated by a colon. You can insert a schedule keyword and
484 a timestamp with \\[org-schedule].
485 Changes become only effective after restarting Emacs."
486 :group 'org-keywords
487 :type 'string)
489 (defcustom org-closed-string "CLOSED:"
490 "String used as the prefix for timestamps logging closing a TODO entry."
491 :group 'org-keywords
492 :type 'string)
494 (defcustom org-clock-string "CLOCK:"
495 "String used as prefix for timestamps clocking work hours on an item."
496 :group 'org-keywords
497 :type 'string)
499 (defcustom org-comment-string "COMMENT"
500 "Entries starting with this keyword will never be exported.
501 An entry can be toggled between COMMENT and normal with
502 \\[org-toggle-comment].
503 Changes become only effective after restarting Emacs."
504 :group 'org-keywords
505 :type 'string)
507 (defcustom org-quote-string "QUOTE"
508 "Entries starting with this keyword will be exported in fixed-width font.
509 Quoting applies only to the text in the entry following the headline, and does
510 not extend beyond the next headline, even if that is lower level.
511 An entry can be toggled between QUOTE and normal with
512 \\[org-toggle-fixed-width-section]."
513 :group 'org-keywords
514 :type 'string)
516 (defconst org-repeat-re
517 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
518 "Regular expression for specifying repeated events.
519 After a match, group 1 contains the repeat expression.")
521 (defgroup org-structure nil
522 "Options concerning the general structure of Org-mode files."
523 :tag "Org Structure"
524 :group 'org)
526 (defgroup org-reveal-location nil
527 "Options about how to make context of a location visible."
528 :tag "Org Reveal Location"
529 :group 'org-structure)
531 (defconst org-context-choice
532 '(choice
533 (const :tag "Always" t)
534 (const :tag "Never" nil)
535 (repeat :greedy t :tag "Individual contexts"
536 (cons
537 (choice :tag "Context"
538 (const agenda)
539 (const org-goto)
540 (const occur-tree)
541 (const tags-tree)
542 (const link-search)
543 (const mark-goto)
544 (const bookmark-jump)
545 (const isearch)
546 (const default))
547 (boolean))))
548 "Contexts for the reveal options.")
550 (defcustom org-show-hierarchy-above '((default . t))
551 "Non-nil means show full hierarchy when revealing a location.
552 Org-mode often shows locations in an org-mode file which might have
553 been invisible before. When this is set, the hierarchy of headings
554 above the exposed location is shown.
555 Turning this off for example for sparse trees makes them very compact.
556 Instead of t, this can also be an alist specifying this option for different
557 contexts. Valid contexts are
558 agenda when exposing an entry from the agenda
559 org-goto when using the command `org-goto' on key C-c C-j
560 occur-tree when using the command `org-occur' on key C-c /
561 tags-tree when constructing a sparse tree based on tags matches
562 link-search when exposing search matches associated with a link
563 mark-goto when exposing the jump goal of a mark
564 bookmark-jump when exposing a bookmark location
565 isearch when exiting from an incremental search
566 default default for all contexts not set explicitly"
567 :group 'org-reveal-location
568 :type org-context-choice)
570 (defcustom org-show-following-heading '((default . nil))
571 "Non-nil means show following heading when revealing a location.
572 Org-mode often shows locations in an org-mode file which might have
573 been invisible before. When this is set, the heading following the
574 match is shown.
575 Turning this off for example for sparse trees makes them very compact,
576 but makes it harder to edit the location of the match. In such a case,
577 use the command \\[org-reveal] to show more context.
578 Instead of t, this can also be an alist specifying this option for different
579 contexts. See `org-show-hierarchy-above' for valid contexts."
580 :group 'org-reveal-location
581 :type org-context-choice)
583 (defcustom org-show-siblings '((default . nil) (isearch t))
584 "Non-nil means show all sibling heading when revealing a location.
585 Org-mode often shows locations in an org-mode file which might have
586 been invisible before. When this is set, the sibling of the current entry
587 heading are all made visible. If `org-show-hierarchy-above' is t,
588 the same happens on each level of the hierarchy above the current entry.
590 By default this is on for the isearch context, off for all other contexts.
591 Turning this off for example for sparse trees makes them very compact,
592 but makes it harder to edit the location of the match. In such a case,
593 use the command \\[org-reveal] to show more context.
594 Instead of t, this can also be an alist specifying this option for different
595 contexts. See `org-show-hierarchy-above' for valid contexts."
596 :group 'org-reveal-location
597 :type org-context-choice)
599 (defcustom org-show-entry-below '((default . nil))
600 "Non-nil means show the entry below a headline when revealing a location.
601 Org-mode often shows locations in an org-mode file which might have
602 been invisible before. When this is set, the text below the headline that is
603 exposed is also shown.
605 By default this is off for all contexts.
606 Instead of t, this can also be an alist specifying this option for different
607 contexts. See `org-show-hierarchy-above' for valid contexts."
608 :group 'org-reveal-location
609 :type org-context-choice)
611 (defcustom org-indirect-buffer-display 'other-window
612 "How should indirect tree buffers be displayed?
613 This applies to indirect buffers created with the commands
614 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
615 Valid values are:
616 current-window Display in the current window
617 other-window Just display in another window.
618 dedicated-frame Create one new frame, and re-use it each time.
619 new-frame Make a new frame each time. Note that in this case
620 previously-made indirect buffers are kept, and you need to
621 kill these buffers yourself."
622 :group 'org-structure
623 :group 'org-agenda-windows
624 :type '(choice
625 (const :tag "In current window" current-window)
626 (const :tag "In current frame, other window" other-window)
627 (const :tag "Each time a new frame" new-frame)
628 (const :tag "One dedicated frame" dedicated-frame)))
630 (defcustom org-use-speed-commands nil
631 "Non-nil means activate single letter commands at beginning of a headline.
632 This may also be a function to test for appropriate locations where speed
633 commands should be active."
634 :group 'org-structure
635 :type '(choice
636 (const :tag "Never" nil)
637 (const :tag "At beginning of headline stars" t)
638 (function)))
640 (defcustom org-speed-commands-user nil
641 "Alist of additional speed commands.
642 This list will be checked before `org-speed-commands-default'
643 when the variable `org-use-speed-commands' is non-nil
644 and when the cursor is at the beginning of a headline.
645 The car if each entry is a string with a single letter, which must
646 be assigned to `self-insert-command' in the global map.
647 The cdr is either a command to be called interactively, a function
648 to be called, or a form to be evaluated.
649 An entry that is just a list with a single string will be interpreted
650 as a descriptive headline that will be added when listing the speed
651 copmmands in the Help buffer using the `?' speed command."
652 :group 'org-structure
653 :type '(repeat :value ("k" . ignore)
654 (choice :value ("k" . ignore)
655 (list :tag "Descriptive Headline" (string :tag "Headline"))
656 (cons :tag "Letter and Command"
657 (string :tag "Command letter")
658 (choice
659 (function)
660 (sexp))))))
662 (defgroup org-cycle nil
663 "Options concerning visibility cycling in Org-mode."
664 :tag "Org Cycle"
665 :group 'org-structure)
667 (defcustom org-cycle-skip-children-state-if-no-children t
668 "Non-nil means skip CHILDREN state in entries that don't have any."
669 :group 'org-cycle
670 :type 'boolean)
672 (defcustom org-cycle-max-level nil
673 "Maximum level which should still be subject to visibility cycling.
674 Levels higher than this will, for cycling, be treated as text, not a headline.
675 When `org-odd-levels-only' is set, a value of N in this variable actually
676 means 2N-1 stars as the limiting headline.
677 When nil, cycle all levels.
678 Note that the limiting level of cycling is also influenced by
679 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
680 `org-inlinetask-min-level' is, cycling will be limited to levels one less
681 than its value."
682 :group 'org-cycle
683 :type '(choice
684 (const :tag "No limit" nil)
685 (integer :tag "Maximum level")))
687 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
688 "Names of drawers. Drawers are not opened by cycling on the headline above.
689 Drawers only open with a TAB on the drawer line itself. A drawer looks like
690 this:
691 :DRAWERNAME:
692 .....
693 :END:
694 The drawer \"PROPERTIES\" is special for capturing properties through
695 the property API.
697 Drawers can be defined on the per-file basis with a line like:
699 #+DRAWERS: HIDDEN STATE PROPERTIES"
700 :group 'org-structure
701 :group 'org-cycle
702 :type '(repeat (string :tag "Drawer Name")))
704 (defcustom org-hide-block-startup nil
705 "Non-nil means entering Org-mode will fold all blocks.
706 This can also be set in on a per-file basis with
708 #+STARTUP: hideblocks
709 #+STARTUP: showblocks"
710 :group 'org-startup
711 :group 'org-cycle
712 :type 'boolean)
714 (defcustom org-cycle-global-at-bob nil
715 "Cycle globally if cursor is at beginning of buffer and not at a headline.
716 This makes it possible to do global cycling without having to use S-TAB or
717 C-u TAB. For this special case to work, the first line of the buffer
718 must not be a headline - it may be empty or some other text. When used in
719 this way, `org-cycle-hook' is disables temporarily, to make sure the
720 cursor stays at the beginning of the buffer.
721 When this option is nil, don't do anything special at the beginning
722 of the buffer."
723 :group 'org-cycle
724 :type 'boolean)
726 (defcustom org-cycle-level-after-item/entry-creation t
727 "Non-nil means cycle entry level or item indentation in new empty entries.
729 When the cursor is at the end of an empty headline, i.e with only stars
730 and maybe a TODO keyword, TAB will then switch the entry to become a child,
731 and then all possible anchestor states, before returning to the original state.
732 This makes data entry extremely fast: M-RET to create a new headline,
733 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
735 When the cursor is at the end of an empty plain list item, one TAB will
736 make it a subitem, two or more tabs will back up to make this an item
737 higher up in the item hierarchy."
738 :group 'org-cycle
739 :type 'boolean)
741 (defcustom org-cycle-emulate-tab t
742 "Where should `org-cycle' emulate TAB.
743 nil Never
744 white Only in completely white lines
745 whitestart Only at the beginning of lines, before the first non-white char
746 t Everywhere except in headlines
747 exc-hl-bol Everywhere except at the start of a headline
748 If TAB is used in a place where it does not emulate TAB, the current subtree
749 visibility is cycled."
750 :group 'org-cycle
751 :type '(choice (const :tag "Never" nil)
752 (const :tag "Only in completely white lines" white)
753 (const :tag "Before first char in a line" whitestart)
754 (const :tag "Everywhere except in headlines" t)
755 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
758 (defcustom org-cycle-separator-lines 2
759 "Number of empty lines needed to keep an empty line between collapsed trees.
760 If you leave an empty line between the end of a subtree and the following
761 headline, this empty line is hidden when the subtree is folded.
762 Org-mode will leave (exactly) one empty line visible if the number of
763 empty lines is equal or larger to the number given in this variable.
764 So the default 2 means at least 2 empty lines after the end of a subtree
765 are needed to produce free space between a collapsed subtree and the
766 following headline.
768 If the number is negative, and the number of empty lines is at least -N,
769 all empty lines are shown.
771 Special case: when 0, never leave empty lines in collapsed view."
772 :group 'org-cycle
773 :type 'integer)
774 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
776 (defcustom org-pre-cycle-hook nil
777 "Hook that is run before visibility cycling is happening.
778 The function(s) in this hook must accept a single argument which indicates
779 the new state that will be set right after running this hook. The
780 argument is a symbol. Before a global state change, it can have the values
781 `overview', `content', or `all'. Before a local state change, it can have
782 the values `folded', `children', or `subtree'."
783 :group 'org-cycle
784 :type 'hook)
786 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
787 org-cycle-hide-drawers
788 org-cycle-show-empty-lines
789 org-optimize-window-after-visibility-change)
790 "Hook that is run after `org-cycle' has changed the buffer visibility.
791 The function(s) in this hook must accept a single argument which indicates
792 the new state that was set by the most recent `org-cycle' command. The
793 argument is a symbol. After a global state change, it can have the values
794 `overview', `content', or `all'. After a local state change, it can have
795 the values `folded', `children', or `subtree'."
796 :group 'org-cycle
797 :type 'hook)
799 (defgroup org-edit-structure nil
800 "Options concerning structure editing in Org-mode."
801 :tag "Org Edit Structure"
802 :group 'org-structure)
804 (defcustom org-odd-levels-only nil
805 "Non-nil means skip even levels and only use odd levels for the outline.
806 This has the effect that two stars are being added/taken away in
807 promotion/demotion commands. It also influences how levels are
808 handled by the exporters.
809 Changing it requires restart of `font-lock-mode' to become effective
810 for fontification also in regions already fontified.
811 You may also set this on a per-file basis by adding one of the following
812 lines to the buffer:
814 #+STARTUP: odd
815 #+STARTUP: oddeven"
816 :group 'org-edit-structure
817 :group 'org-appearance
818 :type 'boolean)
820 (defcustom org-adapt-indentation t
821 "Non-nil means adapt indentation to outline node level.
823 When this variable is set, Org assumes that you write outlines by
824 indenting text in each node to align with the headline (after the stars).
825 The following issues are influenced by this variable:
827 - When this is set and the *entire* text in an entry is indented, the
828 indentation is increased by one space in a demotion command, and
829 decreased by one in a promotion command. If any line in the entry
830 body starts with text at column 0, indentation is not changed at all.
832 - Property drawers and planning information is inserted indented when
833 this variable s set. When nil, they will not be indented.
835 - TAB indents a line relative to context. The lines below a headline
836 will be indented when this variable is set.
838 Note that this is all about true indentation, by adding and removing
839 space characters. See also `org-indent.el' which does level-dependent
840 indentation in a virtual way, i.e. at display time in Emacs."
841 :group 'org-edit-structure
842 :type 'boolean)
844 (defcustom org-special-ctrl-a/e nil
845 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
847 When t, `C-a' will bring back the cursor to the beginning of the
848 headline text, i.e. after the stars and after a possible TODO keyword.
849 In an item, this will be the position after the bullet.
850 When the cursor is already at that position, another `C-a' will bring
851 it to the beginning of the line.
853 `C-e' will jump to the end of the headline, ignoring the presence of tags
854 in the headline. A second `C-e' will then jump to the true end of the
855 line, after any tags. This also means that, when this variable is
856 non-nil, `C-e' also will never jump beyond the end of the heading of a
857 folded section, i.e. not after the ellipses.
859 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
860 going to the true line boundary first. Only a directly following, identical
861 keypress will bring the cursor to the special positions.
863 This may also be a cons cell where the behavior for `C-a' and `C-e' is
864 set separately."
865 :group 'org-edit-structure
866 :type '(choice
867 (const :tag "off" nil)
868 (const :tag "on: after stars/bullet and before tags first" t)
869 (const :tag "reversed: true line boundary first" reversed)
870 (cons :tag "Set C-a and C-e separately"
871 (choice :tag "Special C-a"
872 (const :tag "off" nil)
873 (const :tag "on: after stars/bullet first" t)
874 (const :tag "reversed: before stars/bullet first" reversed))
875 (choice :tag "Special C-e"
876 (const :tag "off" nil)
877 (const :tag "on: before tags first" t)
878 (const :tag "reversed: after tags first" reversed)))))
879 (if (fboundp 'defvaralias)
880 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
882 (defcustom org-special-ctrl-k nil
883 "Non-nil means `C-k' will behave specially in headlines.
884 When nil, `C-k' will call the default `kill-line' command.
885 When t, the following will happen while the cursor is in the headline:
887 - When the cursor is at the beginning of a headline, kill the entire
888 line and possible the folded subtree below the line.
889 - When in the middle of the headline text, kill the headline up to the tags.
890 - When after the headline text, kill the tags."
891 :group 'org-edit-structure
892 :type 'boolean)
894 (defcustom org-yank-folded-subtrees t
895 "Non-nil means when yanking subtrees, fold them.
896 If the kill is a single subtree, or a sequence of subtrees, i.e. if
897 it starts with a heading and all other headings in it are either children
898 or siblings, then fold all the subtrees. However, do this only if no
899 text after the yank would be swallowed into a folded tree by this action."
900 :group 'org-edit-structure
901 :type 'boolean)
903 (defcustom org-yank-adjusted-subtrees nil
904 "Non-nil means when yanking subtrees, adjust the level.
905 With this setting, `org-paste-subtree' is used to insert the subtree, see
906 this function for details."
907 :group 'org-edit-structure
908 :type 'boolean)
910 (defcustom org-M-RET-may-split-line '((default . t))
911 "Non-nil means M-RET will split the line at the cursor position.
912 When nil, it will go to the end of the line before making a
913 new line.
914 You may also set this option in a different way for different
915 contexts. Valid contexts are:
917 headline when creating a new headline
918 item when creating a new item
919 table in a table field
920 default the value to be used for all contexts not explicitly
921 customized"
922 :group 'org-structure
923 :group 'org-table
924 :type '(choice
925 (const :tag "Always" t)
926 (const :tag "Never" nil)
927 (repeat :greedy t :tag "Individual contexts"
928 (cons
929 (choice :tag "Context"
930 (const headline)
931 (const item)
932 (const table)
933 (const default))
934 (boolean)))))
937 (defcustom org-insert-heading-respect-content nil
938 "Non-nil means insert new headings after the current subtree.
939 When nil, the new heading is created directly after the current line.
940 The commands \\[org-insert-heading-respect-content] and
941 \\[org-insert-todo-heading-respect-content] turn this variable on
942 for the duration of the command."
943 :group 'org-structure
944 :type 'boolean)
946 (defcustom org-blank-before-new-entry '((heading . auto)
947 (plain-list-item . auto))
948 "Should `org-insert-heading' leave a blank line before new heading/item?
949 The value is an alist, with `heading' and `plain-list-item' as car,
950 and a boolean flag as cdr. For plain lists, if the variable
951 `org-empty-line-terminates-plain-lists' is set, the setting here
952 is ignored and no empty line is inserted, to keep the list in tact."
953 :group 'org-edit-structure
954 :type '(list
955 (cons (const heading)
956 (choice (const :tag "Never" nil)
957 (const :tag "Always" t)
958 (const :tag "Auto" auto)))
959 (cons (const plain-list-item)
960 (choice (const :tag "Never" nil)
961 (const :tag "Always" t)
962 (const :tag "Auto" auto)))))
964 (defcustom org-insert-heading-hook nil
965 "Hook being run after inserting a new heading."
966 :group 'org-edit-structure
967 :type 'hook)
969 (defcustom org-enable-fixed-width-editor t
970 "Non-nil means lines starting with \":\" are treated as fixed-width.
971 This currently only means they are never auto-wrapped.
972 When nil, such lines will be treated like ordinary lines.
973 See also the QUOTE keyword."
974 :group 'org-edit-structure
975 :type 'boolean)
978 (defcustom org-goto-auto-isearch t
979 "Non-nil means typing characters in org-goto starts incremental search."
980 :group 'org-edit-structure
981 :type 'boolean)
983 (defgroup org-sparse-trees nil
984 "Options concerning sparse trees in Org-mode."
985 :tag "Org Sparse Trees"
986 :group 'org-structure)
988 (defcustom org-highlight-sparse-tree-matches t
989 "Non-nil means highlight all matches that define a sparse tree.
990 The highlights will automatically disappear the next time the buffer is
991 changed by an edit command."
992 :group 'org-sparse-trees
993 :type 'boolean)
995 (defcustom org-remove-highlights-with-change t
996 "Non-nil means any change to the buffer will remove temporary highlights.
997 Such highlights are created by `org-occur' and `org-clock-display'.
998 When nil, `C-c C-c needs to be used to get rid of the highlights.
999 The highlights created by `org-preview-latex-fragment' always need
1000 `C-c C-c' to be removed."
1001 :group 'org-sparse-trees
1002 :group 'org-time
1003 :type 'boolean)
1006 (defcustom org-occur-hook '(org-first-headline-recenter)
1007 "Hook that is run after `org-occur' has constructed a sparse tree.
1008 This can be used to recenter the window to show as much of the structure
1009 as possible."
1010 :group 'org-sparse-trees
1011 :type 'hook)
1013 (defgroup org-imenu-and-speedbar nil
1014 "Options concerning imenu and speedbar in Org-mode."
1015 :tag "Org Imenu and Speedbar"
1016 :group 'org-structure)
1018 (defcustom org-imenu-depth 2
1019 "The maximum level for Imenu access to Org-mode headlines.
1020 This also applied for speedbar access."
1021 :group 'org-imenu-and-speedbar
1022 :type 'integer)
1024 (defgroup org-table nil
1025 "Options concerning tables in Org-mode."
1026 :tag "Org Table"
1027 :group 'org)
1029 (defcustom org-enable-table-editor 'optimized
1030 "Non-nil means lines starting with \"|\" are handled by the table editor.
1031 When nil, such lines will be treated like ordinary lines.
1033 When equal to the symbol `optimized', the table editor will be optimized to
1034 do the following:
1035 - Automatic overwrite mode in front of whitespace in table fields.
1036 This makes the structure of the table stay in tact as long as the edited
1037 field does not exceed the column width.
1038 - Minimize the number of realigns. Normally, the table is aligned each time
1039 TAB or RET are pressed to move to another field. With optimization this
1040 happens only if changes to a field might have changed the column width.
1041 Optimization requires replacing the functions `self-insert-command',
1042 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1043 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1044 very good at guessing when a re-align will be necessary, but you can always
1045 force one with \\[org-ctrl-c-ctrl-c].
1047 If you would like to use the optimized version in Org-mode, but the
1048 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1050 This variable can be used to turn on and off the table editor during a session,
1051 but in order to toggle optimization, a restart is required.
1053 See also the variable `org-table-auto-blank-field'."
1054 :group 'org-table
1055 :type '(choice
1056 (const :tag "off" nil)
1057 (const :tag "on" t)
1058 (const :tag "on, optimized" optimized)))
1060 (defcustom org-self-insert-cluster-for-undo t
1061 "Non-nil means cluster self-insert commands for undo when possible.
1062 If this is set, then, like in the Emacs command loop, 20 consecutive
1063 characters will be undone together.
1064 This is configurable, because there is some impact on typing performance."
1065 :group 'org-table
1066 :type 'boolean)
1068 (defcustom org-table-tab-recognizes-table.el t
1069 "Non-nil means TAB will automatically notice a table.el table.
1070 When it sees such a table, it moves point into it and - if necessary -
1071 calls `table-recognize-table'."
1072 :group 'org-table-editing
1073 :type 'boolean)
1075 (defgroup org-link nil
1076 "Options concerning links in Org-mode."
1077 :tag "Org Link"
1078 :group 'org)
1080 (defvar org-link-abbrev-alist-local nil
1081 "Buffer-local version of `org-link-abbrev-alist', which see.
1082 The value of this is taken from the #+LINK lines.")
1083 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1085 (defcustom org-link-abbrev-alist nil
1086 "Alist of link abbreviations.
1087 The car of each element is a string, to be replaced at the start of a link.
1088 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1089 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1091 [[linkkey:tag][description]]
1093 The 'linkkey' must be a word word, starting with a letter, followed
1094 by letters, numbers, '-' or '_'.
1096 If REPLACE is a string, the tag will simply be appended to create the link.
1097 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1098 the placeholder \"%h\" will cause a url-encoded version of the tag to
1099 be inserted at that point (see the function `url-hexify-string').
1101 REPLACE may also be a function that will be called with the tag as the
1102 only argument to create the link, which should be returned as a string.
1104 See the manual for examples."
1105 :group 'org-link
1106 :type '(repeat
1107 (cons
1108 (string :tag "Protocol")
1109 (choice
1110 (string :tag "Format")
1111 (function)))))
1113 (defcustom org-descriptive-links t
1114 "Non-nil means hide link part and only show description of bracket links.
1115 Bracket links are like [[link][description]]. This variable sets the initial
1116 state in new org-mode buffers. The setting can then be toggled on a
1117 per-buffer basis from the Org->Hyperlinks menu."
1118 :group 'org-link
1119 :type 'boolean)
1121 (defcustom org-link-file-path-type 'adaptive
1122 "How the path name in file links should be stored.
1123 Valid values are:
1125 relative Relative to the current directory, i.e. the directory of the file
1126 into which the link is being inserted.
1127 absolute Absolute path, if possible with ~ for home directory.
1128 noabbrev Absolute path, no abbreviation of home directory.
1129 adaptive Use relative path for files in the current directory and sub-
1130 directories of it. For other files, use an absolute path."
1131 :group 'org-link
1132 :type '(choice
1133 (const relative)
1134 (const absolute)
1135 (const noabbrev)
1136 (const adaptive)))
1138 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1139 "Types of links that should be activated in Org-mode files.
1140 This is a list of symbols, each leading to the activation of a certain link
1141 type. In principle, it does not hurt to turn on most link types - there may
1142 be a small gain when turning off unused link types. The types are:
1144 bracket The recommended [[link][description]] or [[link]] links with hiding.
1145 angular Links in angular brackets that may contain whitespace like
1146 <bbdb:Carsten Dominik>.
1147 plain Plain links in normal text, no whitespace, like http://google.com.
1148 radio Text that is matched by a radio target, see manual for details.
1149 tag Tag settings in a headline (link to tag search).
1150 date Time stamps (link to calendar).
1151 footnote Footnote labels.
1153 Changing this variable requires a restart of Emacs to become effective."
1154 :group 'org-link
1155 :type '(set :greedy t
1156 (const :tag "Double bracket links (new style)" bracket)
1157 (const :tag "Angular bracket links (old style)" angular)
1158 (const :tag "Plain text links" plain)
1159 (const :tag "Radio target matches" radio)
1160 (const :tag "Tags" tag)
1161 (const :tag "Timestamps" date)
1162 (const :tag "Footnotes" footnote)))
1164 (defcustom org-make-link-description-function nil
1165 "Function to use to generate link descriptions from links. If
1166 nil the link location will be used. This function must take two
1167 parameters; the first is the link and the second the description
1168 org-insert-link has generated, and should return the description
1169 to use."
1170 :group 'org-link
1171 :type 'function)
1173 (defgroup org-link-store nil
1174 "Options concerning storing links in Org-mode."
1175 :tag "Org Store Link"
1176 :group 'org-link)
1178 (defcustom org-email-link-description-format "Email %c: %.30s"
1179 "Format of the description part of a link to an email or usenet message.
1180 The following %-escapes will be replaced by corresponding information:
1182 %F full \"From\" field
1183 %f name, taken from \"From\" field, address if no name
1184 %T full \"To\" field
1185 %t first name in \"To\" field, address if no name
1186 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1187 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1188 %s subject
1189 %m message-id.
1191 You may use normal field width specification between the % and the letter.
1192 This is for example useful to limit the length of the subject.
1194 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1195 :group 'org-link-store
1196 :type 'string)
1198 (defcustom org-from-is-user-regexp
1199 (let (r1 r2)
1200 (when (and user-mail-address (not (string= user-mail-address "")))
1201 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1202 (when (and user-full-name (not (string= user-full-name "")))
1203 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1204 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1205 "Regexp matched against the \"From:\" header of an email or usenet message.
1206 It should match if the message is from the user him/herself."
1207 :group 'org-link-store
1208 :type 'regexp)
1210 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1211 "Non-nil means storing a link to an Org file will use entry IDs.
1213 Note that before this variable is even considered, org-id must be loaded,
1214 so please customize `org-modules' and turn it on.
1216 The variable can have the following values:
1218 t Create an ID if needed to make a link to the current entry.
1220 create-if-interactive
1221 If `org-store-link' is called directly (interactively, as a user
1222 command), do create an ID to support the link. But when doing the
1223 job for remember, only use the ID if it already exists. The
1224 purpose of this setting is to avoid proliferation of unwanted
1225 IDs, just because you happen to be in an Org file when you
1226 call `org-remember' that automatically and preemptively
1227 creates a link. If you do want to get an ID link in a remember
1228 template to an entry not having an ID, create it first by
1229 explicitly creating a link to it, using `C-c C-l' first.
1231 create-if-interactive-and-no-custom-id
1232 Like create-if-interactive, but do not create an ID if there is
1233 a CUSTOM_ID property defined in the entry. This is the default.
1235 use-existing
1236 Use existing ID, do not create one.
1238 nil Never use an ID to make a link, instead link using a text search for
1239 the headline text."
1240 :group 'org-link-store
1241 :type '(choice
1242 (const :tag "Create ID to make link" t)
1243 (const :tag "Create if storing link interactively"
1244 create-if-interactive)
1245 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1246 create-if-interactive-and-no-custom-id)
1247 (const :tag "Only use existing" use-existing)
1248 (const :tag "Do not use ID to create link" nil)))
1250 (defcustom org-context-in-file-links t
1251 "Non-nil means file links from `org-store-link' contain context.
1252 A search string will be added to the file name with :: as separator and
1253 used to find the context when the link is activated by the command
1254 `org-open-at-point'.
1255 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1256 negates this setting for the duration of the command."
1257 :group 'org-link-store
1258 :type 'boolean)
1260 (defcustom org-keep-stored-link-after-insertion nil
1261 "Non-nil means keep link in list for entire session.
1263 The command `org-store-link' adds a link pointing to the current
1264 location to an internal list. These links accumulate during a session.
1265 The command `org-insert-link' can be used to insert links into any
1266 Org-mode file (offering completion for all stored links). When this
1267 option is nil, every link which has been inserted once using \\[org-insert-link]
1268 will be removed from the list, to make completing the unused links
1269 more efficient."
1270 :group 'org-link-store
1271 :type 'boolean)
1273 (defgroup org-link-follow nil
1274 "Options concerning following links in Org-mode."
1275 :tag "Org Follow Link"
1276 :group 'org-link)
1278 (defcustom org-link-translation-function nil
1279 "Function to translate links with different syntax to Org syntax.
1280 This can be used to translate links created for example by the Planner
1281 or emacs-wiki packages to Org syntax.
1282 The function must accept two parameters, a TYPE containing the link
1283 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1284 which is everything after the link protocol. It should return a cons
1285 with possibly modified values of type and path.
1286 Org contains a function for this, so if you set this variable to
1287 `org-translate-link-from-planner', you should be able follow many
1288 links created by planner."
1289 :group 'org-link-follow
1290 :type 'function)
1292 (defcustom org-follow-link-hook nil
1293 "Hook that is run after a link has been followed."
1294 :group 'org-link-follow
1295 :type 'hook)
1297 (defcustom org-tab-follows-link nil
1298 "Non-nil means on links TAB will follow the link.
1299 Needs to be set before org.el is loaded.
1300 This really should not be used, it does not make sense, and the
1301 implementation is bad."
1302 :group 'org-link-follow
1303 :type 'boolean)
1305 (defcustom org-return-follows-link nil
1306 "Non-nil means on links RET will follow the link."
1307 :group 'org-link-follow
1308 :type 'boolean)
1310 (defcustom org-mouse-1-follows-link
1311 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1312 "Non-nil means mouse-1 on a link will follow the link.
1313 A longer mouse click will still set point. Does not work on XEmacs.
1314 Needs to be set before org.el is loaded."
1315 :group 'org-link-follow
1316 :type 'boolean)
1318 (defcustom org-mark-ring-length 4
1319 "Number of different positions to be recorded in the ring
1320 Changing this requires a restart of Emacs to work correctly."
1321 :group 'org-link-follow
1322 :type 'integer)
1324 (defcustom org-link-frame-setup
1325 '((vm . vm-visit-folder-other-frame)
1326 (gnus . gnus-other-frame)
1327 (file . find-file-other-window))
1328 "Setup the frame configuration for following links.
1329 When following a link with Emacs, it may often be useful to display
1330 this link in another window or frame. This variable can be used to
1331 set this up for the different types of links.
1332 For VM, use any of
1333 `vm-visit-folder'
1334 `vm-visit-folder-other-frame'
1335 For Gnus, use any of
1336 `gnus'
1337 `gnus-other-frame'
1338 `org-gnus-no-new-news'
1339 For FILE, use any of
1340 `find-file'
1341 `find-file-other-window'
1342 `find-file-other-frame'
1343 For the calendar, use the variable `calendar-setup'.
1344 For BBDB, it is currently only possible to display the matches in
1345 another window."
1346 :group 'org-link-follow
1347 :type '(list
1348 (cons (const vm)
1349 (choice
1350 (const vm-visit-folder)
1351 (const vm-visit-folder-other-window)
1352 (const vm-visit-folder-other-frame)))
1353 (cons (const gnus)
1354 (choice
1355 (const gnus)
1356 (const gnus-other-frame)
1357 (const org-gnus-no-new-news)))
1358 (cons (const file)
1359 (choice
1360 (const find-file)
1361 (const find-file-other-window)
1362 (const find-file-other-frame)))))
1364 (defcustom org-display-internal-link-with-indirect-buffer nil
1365 "Non-nil means use indirect buffer to display infile links.
1366 Activating internal links (from one location in a file to another location
1367 in the same file) normally just jumps to the location. When the link is
1368 activated with a C-u prefix (or with mouse-3), the link is displayed in
1369 another window. When this option is set, the other window actually displays
1370 an indirect buffer clone of the current buffer, to avoid any visibility
1371 changes to the current buffer."
1372 :group 'org-link-follow
1373 :type 'boolean)
1375 (defcustom org-open-non-existing-files nil
1376 "Non-nil means `org-open-file' will open non-existing files.
1377 When nil, an error will be generated.
1378 This variable applies only to external applications because they
1379 might choke on non-existing files. If the link is to a file that
1380 will be opened in Emacs, the variable is ignored."
1381 :group 'org-link-follow
1382 :type 'boolean)
1384 (defcustom org-open-directory-means-index-dot-org nil
1385 "Non-nil means a link to a directory really means to index.org.
1386 When nil, following a directory link will run dired or open a finder/explorer
1387 window on that directory."
1388 :group 'org-link-follow
1389 :type 'boolean)
1391 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1392 "Function and arguments to call for following mailto links.
1393 This is a list with the first element being a lisp function, and the
1394 remaining elements being arguments to the function. In string arguments,
1395 %a will be replaced by the address, and %s will be replaced by the subject
1396 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1397 :group 'org-link-follow
1398 :type '(choice
1399 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1400 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1401 (const :tag "message-mail" (message-mail "%a" "%s"))
1402 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1404 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1405 "Non-nil means ask for confirmation before executing shell links.
1406 Shell links can be dangerous: just think about a link
1408 [[shell:rm -rf ~/*][Google Search]]
1410 This link would show up in your Org-mode document as \"Google Search\",
1411 but really it would remove your entire home directory.
1412 Therefore we advise against setting this variable to nil.
1413 Just change it to `y-or-n-p' if you want to confirm with a
1414 single keystroke rather than having to type \"yes\"."
1415 :group 'org-link-follow
1416 :type '(choice
1417 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1418 (const :tag "with y-or-n (faster)" y-or-n-p)
1419 (const :tag "no confirmation (dangerous)" nil)))
1421 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1422 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1423 Elisp links can be dangerous: just think about a link
1425 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1427 This link would show up in your Org-mode document as \"Google Search\",
1428 but really it would remove your entire home directory.
1429 Therefore we advise against setting this variable to nil.
1430 Just change it to `y-or-n-p' if you want to confirm with a
1431 single keystroke rather than having to type \"yes\"."
1432 :group 'org-link-follow
1433 :type '(choice
1434 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1435 (const :tag "with y-or-n (faster)" y-or-n-p)
1436 (const :tag "no confirmation (dangerous)" nil)))
1438 (defconst org-file-apps-defaults-gnu
1439 '((remote . emacs)
1440 (system . mailcap)
1441 (t . mailcap))
1442 "Default file applications on a UNIX or GNU/Linux system.
1443 See `org-file-apps'.")
1445 (defconst org-file-apps-defaults-macosx
1446 '((remote . emacs)
1447 (t . "open %s")
1448 (system . "open %s")
1449 ("ps.gz" . "gv %s")
1450 ("eps.gz" . "gv %s")
1451 ("dvi" . "xdvi %s")
1452 ("fig" . "xfig %s"))
1453 "Default file applications on a MacOS X system.
1454 The system \"open\" is known as a default, but we use X11 applications
1455 for some files for which the OS does not have a good default.
1456 See `org-file-apps'.")
1458 (defconst org-file-apps-defaults-windowsnt
1459 (list
1460 '(remote . emacs)
1461 (cons t
1462 (list (if (featurep 'xemacs)
1463 'mswindows-shell-execute
1464 'w32-shell-execute)
1465 "open" 'file))
1466 (cons 'system
1467 (list (if (featurep 'xemacs)
1468 'mswindows-shell-execute
1469 'w32-shell-execute)
1470 "open" 'file)))
1471 "Default file applications on a Windows NT system.
1472 The system \"open\" is used for most files.
1473 See `org-file-apps'.")
1475 (defcustom org-file-apps
1477 (auto-mode . emacs)
1478 ("\\.mm\\'" . default)
1479 ("\\.x?html?\\'" . default)
1480 ("\\.pdf\\'" . default)
1482 "External applications for opening `file:path' items in a document.
1483 Org-mode uses system defaults for different file types, but
1484 you can use this variable to set the application for a given file
1485 extension. The entries in this list are cons cells where the car identifies
1486 files and the cdr the corresponding command. Possible values for the
1487 file identifier are
1488 \"string\" A string as a file identifier can be interpreted in different
1489 ways, depending on its contents:
1491 - Alphanumeric characters only:
1492 Match links with this file extension.
1493 Example: (\"pdf\" . \"evince %s\")
1494 to open PDFs with evince.
1496 - Regular expression: Match links where the
1497 filename matches the regexp. If you want to
1498 use groups here, use shy groups.
1500 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1501 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1502 to open *.html and *.xhtml with firefox.
1504 - Regular expression which contains (non-shy) groups:
1505 Match links where the whole link, including \"::\", and
1506 anything after that, matches the regexp.
1507 In a custom command string, %1, %2, etc. are replaced with
1508 the parts of the link that were matched by the groups.
1509 For backwards compatibility, if a command string is given
1510 that does not use any of the group matches, this case is
1511 handled identically to the second one (i.e. match against
1512 file name only).
1514 In a custom lisp form, you can access the group matches with
1515 (match-string n link).
1517 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1518 to open [[file:document.pdf::5]] with evince at page 5.
1520 `directory' Matches a directory
1521 `remote' Matches a remote file, accessible through tramp or efs.
1522 Remote files most likely should be visited through Emacs
1523 because external applications cannot handle such paths.
1524 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1525 so all files Emacs knows how to handle. Using this with
1526 command `emacs' will open most files in Emacs. Beware that this
1527 will also open html files inside Emacs, unless you add
1528 (\"html\" . default) to the list as well.
1529 t Default for files not matched by any of the other options.
1530 `system' The system command to open files, like `open' on Windows
1531 and Mac OS X, and mailcap under GNU/Linux. This is the command
1532 that will be selected if you call `C-c C-o' with a double
1533 `C-u C-u' prefix.
1535 Possible values for the command are:
1536 `emacs' The file will be visited by the current Emacs process.
1537 `default' Use the default application for this file type, which is the
1538 association for t in the list, most likely in the system-specific
1539 part.
1540 This can be used to overrule an unwanted setting in the
1541 system-specific variable.
1542 `system' Use the system command for opening files, like \"open\".
1543 This command is specified by the entry whose car is `system'.
1544 Most likely, the system-specific version of this variable
1545 does define this command, but you can overrule/replace it
1546 here.
1547 string A command to be executed by a shell; %s will be replaced
1548 by the path to the file.
1549 sexp A Lisp form which will be evaluated. The file path will
1550 be available in the Lisp variable `file'.
1551 For more examples, see the system specific constants
1552 `org-file-apps-defaults-macosx'
1553 `org-file-apps-defaults-windowsnt'
1554 `org-file-apps-defaults-gnu'."
1555 :group 'org-link-follow
1556 :type '(repeat
1557 (cons (choice :value ""
1558 (string :tag "Extension")
1559 (const :tag "System command to open files" system)
1560 (const :tag "Default for unrecognized files" t)
1561 (const :tag "Remote file" remote)
1562 (const :tag "Links to a directory" directory)
1563 (const :tag "Any files that have Emacs modes"
1564 auto-mode))
1565 (choice :value ""
1566 (const :tag "Visit with Emacs" emacs)
1567 (const :tag "Use default" default)
1568 (const :tag "Use the system command" system)
1569 (string :tag "Command")
1570 (sexp :tag "Lisp form")))))
1574 (defgroup org-refile nil
1575 "Options concerning refiling entries in Org-mode."
1576 :tag "Org Refile"
1577 :group 'org)
1579 (defcustom org-directory "~/org"
1580 "Directory with org files.
1581 This is just a default location to look for Org files. There is no need
1582 at all to put your files into this directory. It is only used in the
1583 following situations:
1585 1. When a remember template specifies a target file that is not an
1586 absolute path. The path will then be interpreted relative to
1587 `org-directory'
1588 2. When a remember note is filed away in an interactive way (when exiting the
1589 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1590 with `org-directory' as the default path."
1591 :group 'org-refile
1592 :group 'org-remember
1593 :type 'directory)
1595 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1596 "Default target for storing notes.
1597 Used by the hooks for remember.el. This can be a string, or nil to mean
1598 the value of `remember-data-file'.
1599 You can set this on a per-template basis with the variable
1600 `org-remember-templates'."
1601 :group 'org-refile
1602 :group 'org-remember
1603 :type '(choice
1604 (const :tag "Default from remember-data-file" nil)
1605 file))
1607 (defcustom org-goto-interface 'outline
1608 "The default interface to be used for `org-goto'.
1609 Allowed values are:
1610 outline The interface shows an outline of the relevant file
1611 and the correct heading is found by moving through
1612 the outline or by searching with incremental search.
1613 outline-path-completion Headlines in the current buffer are offered via
1614 completion. This is the interface also used by
1615 the refile command."
1616 :group 'org-refile
1617 :type '(choice
1618 (const :tag "Outline" outline)
1619 (const :tag "Outline-path-completion" outline-path-completion)))
1621 (defcustom org-goto-max-level 5
1622 "Maximum level to be considered when running org-goto with refile interface."
1623 :group 'org-refile
1624 :type 'integer)
1626 (defcustom org-reverse-note-order nil
1627 "Non-nil means store new notes at the beginning of a file or entry.
1628 When nil, new notes will be filed to the end of a file or entry.
1629 This can also be a list with cons cells of regular expressions that
1630 are matched against file names, and values."
1631 :group 'org-remember
1632 :group 'org-refile
1633 :type '(choice
1634 (const :tag "Reverse always" t)
1635 (const :tag "Reverse never" nil)
1636 (repeat :tag "By file name regexp"
1637 (cons regexp boolean))))
1639 (defcustom org-log-refile nil
1640 "Information to record when a task is refiled.
1642 Possible values are:
1644 nil Don't add anything
1645 time Add a time stamp to the task
1646 note Prompt for a note and add it with template `org-log-note-headings'
1648 This option can also be set with on a per-file-basis with
1650 #+STARTUP: nologrefile
1651 #+STARTUP: logrefile
1652 #+STARTUP: lognoterefile
1654 You can have local logging settings for a subtree by setting the LOGGING
1655 property to one or more of these keywords.
1657 When bulk-refiling from the agenda, the value `note' is forbidden and
1658 will temporarily be changed to `time'."
1659 :group 'org-refile
1660 :group 'org-progress
1661 :type '(choice
1662 (const :tag "No logging" nil)
1663 (const :tag "Record timestamp" time)
1664 (const :tag "Record timestamp with note." note)))
1666 (defcustom org-refile-targets nil
1667 "Targets for refiling entries with \\[org-refile].
1668 This is list of cons cells. Each cell contains:
1669 - a specification of the files to be considered, either a list of files,
1670 or a symbol whose function or variable value will be used to retrieve
1671 a file name or a list of file names. If you use `org-agenda-files' for
1672 that, all agenda files will be scanned for targets. Nil means consider
1673 headings in the current buffer.
1674 - A specification of how to find candidate refile targets. This may be
1675 any of:
1676 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1677 This tag has to be present in all target headlines, inheritance will
1678 not be considered.
1679 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1680 todo keyword.
1681 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1682 headlines that are refiling targets.
1683 - a cons cell (:level . N). Any headline of level N is considered a target.
1684 Note that, when `org-odd-levels-only' is set, level corresponds to
1685 order in hierarchy, not to the number of stars.
1686 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1687 Note that, when `org-odd-levels-only' is set, level corresponds to
1688 order in hierarchy, not to the number of stars.
1690 You can set the variable `org-refile-target-verify-function' to a function
1691 to verify each headline found by the simple critery above.
1693 When this variable is nil, all top-level headlines in the current buffer
1694 are used, equivalent to the value `((nil . (:level . 1))'."
1695 :group 'org-refile
1696 :type '(repeat
1697 (cons
1698 (choice :value org-agenda-files
1699 (const :tag "All agenda files" org-agenda-files)
1700 (const :tag "Current buffer" nil)
1701 (function) (variable) (file))
1702 (choice :tag "Identify target headline by"
1703 (cons :tag "Specific tag" (const :value :tag) (string))
1704 (cons :tag "TODO keyword" (const :value :todo) (string))
1705 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1706 (cons :tag "Level number" (const :value :level) (integer))
1707 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1709 (defcustom org-refile-target-verify-function nil
1710 "Function to verify if the headline at point should be a refile target.
1711 The function will be called without arguments, with point at the
1712 beginning of the headline. It should return t and leave point
1713 where it is if the headline is a valid target for refiling.
1715 If the target should not be selected, the function must return nil.
1716 In addition to this, it may move point to a place from where the search
1717 should be continued. For example, the function may decide that the entire
1718 subtree of the current entry should be excluded and move point to the end
1719 of the subtree."
1720 :group 'org-refile
1721 :type 'function)
1723 (defcustom org-refile-use-cache nil
1724 "Non-nil means cache refile targets to speed up the process.
1725 The cache for a particular file will be updated automatically when
1726 the buffer has been killed, or when any of the marker used for flagging
1727 refile targets no longer points at a live buffer.
1728 If you have added new entries to a buffer that might themselves be targets,
1729 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1730 find that easier, `C-u C-u C-u C-c C-w'."
1731 :group 'org-refile
1732 :type 'boolean)
1734 (defcustom org-refile-use-outline-path nil
1735 "Non-nil means provide refile targets as paths.
1736 So a level 3 headline will be available as level1/level2/level3.
1738 When the value is `file', also include the file name (without directory)
1739 into the path. In this case, you can also stop the completion after
1740 the file name, to get entries inserted as top level in the file.
1742 When `full-file-path', include the full file path."
1743 :group 'org-refile
1744 :type '(choice
1745 (const :tag "Not" nil)
1746 (const :tag "Yes" t)
1747 (const :tag "Start with file name" file)
1748 (const :tag "Start with full file path" full-file-path)))
1750 (defcustom org-outline-path-complete-in-steps t
1751 "Non-nil means complete the outline path in hierarchical steps.
1752 When Org-mode uses the refile interface to select an outline path
1753 \(see variable `org-refile-use-outline-path'), the completion of
1754 the path can be done is a single go, or if can be done in steps down
1755 the headline hierarchy. Going in steps is probably the best if you
1756 do not use a special completion package like `ido' or `icicles'.
1757 However, when using these packages, going in one step can be very
1758 fast, while still showing the whole path to the entry."
1759 :group 'org-refile
1760 :type 'boolean)
1762 (defcustom org-refile-allow-creating-parent-nodes nil
1763 "Non-nil means allow to create new nodes as refile targets.
1764 New nodes are then created by adding \"/new node name\" to the completion
1765 of an existing node. When the value of this variable is `confirm',
1766 new node creation must be confirmed by the user (recommended)
1767 When nil, the completion must match an existing entry.
1769 Note that, if the new heading is not seen by the criteria
1770 listed in `org-refile-targets', multiple instances of the same
1771 heading would be created by trying again to file under the new
1772 heading."
1773 :group 'org-refile
1774 :type '(choice
1775 (const :tag "Never" nil)
1776 (const :tag "Always" t)
1777 (const :tag "Prompt for confirmation" confirm)))
1779 (defgroup org-todo nil
1780 "Options concerning TODO items in Org-mode."
1781 :tag "Org TODO"
1782 :group 'org)
1784 (defgroup org-progress nil
1785 "Options concerning Progress logging in Org-mode."
1786 :tag "Org Progress"
1787 :group 'org-time)
1789 (defvar org-todo-interpretation-widgets
1791 (:tag "Sequence (cycling hits every state)" sequence)
1792 (:tag "Type (cycling directly to DONE)" type))
1793 "The available interpretation symbols for customizing
1794 `org-todo-keywords'.
1795 Interested libraries should add to this list.")
1797 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1798 "List of TODO entry keyword sequences and their interpretation.
1799 \\<org-mode-map>This is a list of sequences.
1801 Each sequence starts with a symbol, either `sequence' or `type',
1802 indicating if the keywords should be interpreted as a sequence of
1803 action steps, or as different types of TODO items. The first
1804 keywords are states requiring action - these states will select a headline
1805 for inclusion into the global TODO list Org-mode produces. If one of
1806 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1807 signify that no further action is necessary. If \"|\" is not found,
1808 the last keyword is treated as the only DONE state of the sequence.
1810 The command \\[org-todo] cycles an entry through these states, and one
1811 additional state where no keyword is present. For details about this
1812 cycling, see the manual.
1814 TODO keywords and interpretation can also be set on a per-file basis with
1815 the special #+SEQ_TODO and #+TYP_TODO lines.
1817 Each keyword can optionally specify a character for fast state selection
1818 \(in combination with the variable `org-use-fast-todo-selection')
1819 and specifiers for state change logging, using the same syntax
1820 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1821 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1822 indicates to record a time stamp each time this state is selected.
1824 Each keyword may also specify if a timestamp or a note should be
1825 recorded when entering or leaving the state, by adding additional
1826 characters in the parenthesis after the keyword. This looks like this:
1827 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1828 record only the time of the state change. With X and Y being either
1829 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1830 Y when leaving the state if and only if the *target* state does not
1831 define X. You may omit any of the fast-selection key or X or /Y,
1832 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1834 For backward compatibility, this variable may also be just a list
1835 of keywords - in this case the interpretation (sequence or type) will be
1836 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1837 :group 'org-todo
1838 :group 'org-keywords
1839 :type '(choice
1840 (repeat :tag "Old syntax, just keywords"
1841 (string :tag "Keyword"))
1842 (repeat :tag "New syntax"
1843 (cons
1844 (choice
1845 :tag "Interpretation"
1846 ;;Quick and dirty way to see
1847 ;;`org-todo-interpretations'. This takes the
1848 ;;place of item arguments
1849 :convert-widget
1850 (lambda (widget)
1851 (widget-put widget
1852 :args (mapcar
1853 #'(lambda (x)
1854 (widget-convert
1855 (cons 'const x)))
1856 org-todo-interpretation-widgets))
1857 widget))
1858 (repeat
1859 (string :tag "Keyword"))))))
1861 (defvar org-todo-keywords-1 nil
1862 "All TODO and DONE keywords active in a buffer.")
1863 (make-variable-buffer-local 'org-todo-keywords-1)
1864 (defvar org-todo-keywords-for-agenda nil)
1865 (defvar org-done-keywords-for-agenda nil)
1866 (defvar org-drawers-for-agenda nil)
1867 (defvar org-todo-keyword-alist-for-agenda nil)
1868 (defvar org-tag-alist-for-agenda nil)
1869 (defvar org-agenda-contributing-files nil)
1870 (defvar org-not-done-keywords nil)
1871 (make-variable-buffer-local 'org-not-done-keywords)
1872 (defvar org-done-keywords nil)
1873 (make-variable-buffer-local 'org-done-keywords)
1874 (defvar org-todo-heads nil)
1875 (make-variable-buffer-local 'org-todo-heads)
1876 (defvar org-todo-sets nil)
1877 (make-variable-buffer-local 'org-todo-sets)
1878 (defvar org-todo-log-states nil)
1879 (make-variable-buffer-local 'org-todo-log-states)
1880 (defvar org-todo-kwd-alist nil)
1881 (make-variable-buffer-local 'org-todo-kwd-alist)
1882 (defvar org-todo-key-alist nil)
1883 (make-variable-buffer-local 'org-todo-key-alist)
1884 (defvar org-todo-key-trigger nil)
1885 (make-variable-buffer-local 'org-todo-key-trigger)
1887 (defcustom org-todo-interpretation 'sequence
1888 "Controls how TODO keywords are interpreted.
1889 This variable is in principle obsolete and is only used for
1890 backward compatibility, if the interpretation of todo keywords is
1891 not given already in `org-todo-keywords'. See that variable for
1892 more information."
1893 :group 'org-todo
1894 :group 'org-keywords
1895 :type '(choice (const sequence)
1896 (const type)))
1898 (defcustom org-use-fast-todo-selection t
1899 "Non-nil means use the fast todo selection scheme with C-c C-t.
1900 This variable describes if and under what circumstances the cycling
1901 mechanism for TODO keywords will be replaced by a single-key, direct
1902 selection scheme.
1904 When nil, fast selection is never used.
1906 When the symbol `prefix', it will be used when `org-todo' is called with
1907 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1908 in an agenda buffer.
1910 When t, fast selection is used by default. In this case, the prefix
1911 argument forces cycling instead.
1913 In all cases, the special interface is only used if access keys have actually
1914 been assigned by the user, i.e. if keywords in the configuration are followed
1915 by a letter in parenthesis, like TODO(t)."
1916 :group 'org-todo
1917 :type '(choice
1918 (const :tag "Never" nil)
1919 (const :tag "By default" t)
1920 (const :tag "Only with C-u C-c C-t" prefix)))
1922 (defcustom org-provide-todo-statistics t
1923 "Non-nil means update todo statistics after insert and toggle.
1924 ALL-HEADLINES means update todo statistics by including headlines
1925 with no TODO keyword as well, counting them as not done.
1926 A list of TODO keywords means the same, but skip keywords that are
1927 not in this list.
1929 When this is set, todo statistics is updated in the parent of the
1930 current entry each time a todo state is changed."
1931 :group 'org-todo
1932 :type '(choice
1933 (const :tag "Yes, only for TODO entries" t)
1934 (const :tag "Yes, including all entries" 'all-headlines)
1935 (repeat :tag "Yes, for TODOs in this list"
1936 (string :tag "TODO keyword"))
1937 (other :tag "No TODO statistics" nil)))
1939 (defcustom org-hierarchical-todo-statistics t
1940 "Non-nil means TODO statistics covers just direct children.
1941 When nil, all entries in the subtree are considered.
1942 This has only an effect if `org-provide-todo-statistics' is set.
1943 To set this to nil for only a single subtree, use a COOKIE_DATA
1944 property and include the word \"recursive\" into the value."
1945 :group 'org-todo
1946 :type 'boolean)
1948 (defcustom org-after-todo-state-change-hook nil
1949 "Hook which is run after the state of a TODO item was changed.
1950 The new state (a string with a TODO keyword, or nil) is available in the
1951 Lisp variable `state'."
1952 :group 'org-todo
1953 :type 'hook)
1955 (defvar org-blocker-hook nil
1956 "Hook for functions that are allowed to block a state change.
1958 Each function gets as its single argument a property list, see
1959 `org-trigger-hook' for more information about this list.
1961 If any of the functions in this hook returns nil, the state change
1962 is blocked.")
1964 (defvar org-trigger-hook nil
1965 "Hook for functions that are triggered by a state change.
1967 Each function gets as its single argument a property list with at least
1968 the following elements:
1970 (:type type-of-change :position pos-at-entry-start
1971 :from old-state :to new-state)
1973 Depending on the type, more properties may be present.
1975 This mechanism is currently implemented for:
1977 TODO state changes
1978 ------------------
1979 :type todo-state-change
1980 :from previous state (keyword as a string), or nil, or a symbol
1981 'todo' or 'done', to indicate the general type of state.
1982 :to new state, like in :from")
1984 (defcustom org-enforce-todo-dependencies nil
1985 "Non-nil means undone TODO entries will block switching the parent to DONE.
1986 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1987 be blocked if any prior sibling is not yet done.
1988 Finally, if the parent is blocked because of ordered siblings of its own,
1989 the child will also be blocked.
1990 This variable needs to be set before org.el is loaded, and you need to
1991 restart Emacs after a change to make the change effective. The only way
1992 to change is while Emacs is running is through the customize interface."
1993 :set (lambda (var val)
1994 (set var val)
1995 (if val
1996 (add-hook 'org-blocker-hook
1997 'org-block-todo-from-children-or-siblings-or-parent)
1998 (remove-hook 'org-blocker-hook
1999 'org-block-todo-from-children-or-siblings-or-parent)))
2000 :group 'org-todo
2001 :type 'boolean)
2003 (defcustom org-enforce-todo-checkbox-dependencies nil
2004 "Non-nil means unchecked boxes will block switching the parent to DONE.
2005 When this is nil, checkboxes have no influence on switching TODO states.
2006 When non-nil, you first need to check off all check boxes before the TODO
2007 entry can be switched to DONE.
2008 This variable needs to be set before org.el is loaded, and you need to
2009 restart Emacs after a change to make the change effective. The only way
2010 to change is while Emacs is running is through the customize interface."
2011 :set (lambda (var val)
2012 (set var val)
2013 (if val
2014 (add-hook 'org-blocker-hook
2015 'org-block-todo-from-checkboxes)
2016 (remove-hook 'org-blocker-hook
2017 'org-block-todo-from-checkboxes)))
2018 :group 'org-todo
2019 :type 'boolean)
2021 (defcustom org-treat-insert-todo-heading-as-state-change nil
2022 "Non-nil means inserting a TODO heading is treated as state change.
2023 So when the command \\[org-insert-todo-heading] is used, state change
2024 logging will apply if appropriate. When nil, the new TODO item will
2025 be inserted directly, and no logging will take place."
2026 :group 'org-todo
2027 :type 'boolean)
2029 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2030 "Non-nil means switching TODO states with S-cursor counts as state change.
2031 This is the default behavior. However, setting this to nil allows a
2032 convenient way to select a TODO state and bypass any logging associated
2033 with that."
2034 :group 'org-todo
2035 :type 'boolean)
2037 (defcustom org-todo-state-tags-triggers nil
2038 "Tag changes that should be triggered by TODO state changes.
2039 This is a list. Each entry is
2041 (state-change (tag . flag) .......)
2043 State-change can be a string with a state, and empty string to indicate the
2044 state that has no TODO keyword, or it can be one of the symbols `todo'
2045 or `done', meaning any not-done or done state, respectively."
2046 :group 'org-todo
2047 :group 'org-tags
2048 :type '(repeat
2049 (cons (choice :tag "When changing to"
2050 (const :tag "Not-done state" todo)
2051 (const :tag "Done state" done)
2052 (string :tag "State"))
2053 (repeat
2054 (cons :tag "Tag action"
2055 (string :tag "Tag")
2056 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2058 (defcustom org-log-done nil
2059 "Information to record when a task moves to the DONE state.
2061 Possible values are:
2063 nil Don't add anything, just change the keyword
2064 time Add a time stamp to the task
2065 note Prompt for a note and add it with template `org-log-note-headings'
2067 This option can also be set with on a per-file-basis with
2069 #+STARTUP: nologdone
2070 #+STARTUP: logdone
2071 #+STARTUP: lognotedone
2073 You can have local logging settings for a subtree by setting the LOGGING
2074 property to one or more of these keywords."
2075 :group 'org-todo
2076 :group 'org-progress
2077 :type '(choice
2078 (const :tag "No logging" nil)
2079 (const :tag "Record CLOSED timestamp" time)
2080 (const :tag "Record CLOSED timestamp with note." note)))
2082 ;; Normalize old uses of org-log-done.
2083 (cond
2084 ((eq org-log-done t) (setq org-log-done 'time))
2085 ((and (listp org-log-done) (memq 'done org-log-done))
2086 (setq org-log-done 'note)))
2088 (defcustom org-log-reschedule nil
2089 "Information to record when the scheduling date of a tasks is modified.
2091 Possible values are:
2093 nil Don't add anything, just change the date
2094 time Add a time stamp to the task
2095 note Prompt for a note and add it with template `org-log-note-headings'
2097 This option can also be set with on a per-file-basis with
2099 #+STARTUP: nologreschedule
2100 #+STARTUP: logreschedule
2101 #+STARTUP: lognotereschedule"
2102 :group 'org-todo
2103 :group 'org-progress
2104 :type '(choice
2105 (const :tag "No logging" nil)
2106 (const :tag "Record timestamp" time)
2107 (const :tag "Record timestamp with note." note)))
2109 (defcustom org-log-redeadline nil
2110 "Information to record when the deadline date of a tasks is modified.
2112 Possible values are:
2114 nil Don't add anything, just change the date
2115 time Add a time stamp to the task
2116 note Prompt for a note and add it with template `org-log-note-headings'
2118 This option can also be set with on a per-file-basis with
2120 #+STARTUP: nologredeadline
2121 #+STARTUP: logredeadline
2122 #+STARTUP: lognoteredeadline
2124 You can have local logging settings for a subtree by setting the LOGGING
2125 property to one or more of these keywords."
2126 :group 'org-todo
2127 :group 'org-progress
2128 :type '(choice
2129 (const :tag "No logging" nil)
2130 (const :tag "Record timestamp" time)
2131 (const :tag "Record timestamp with note." note)))
2133 (defcustom org-log-note-clock-out nil
2134 "Non-nil means record a note when clocking out of an item.
2135 This can also be configured on a per-file basis by adding one of
2136 the following lines anywhere in the buffer:
2138 #+STARTUP: lognoteclock-out
2139 #+STARTUP: nolognoteclock-out"
2140 :group 'org-todo
2141 :group 'org-progress
2142 :type 'boolean)
2144 (defcustom org-log-done-with-time t
2145 "Non-nil means the CLOSED time stamp will contain date and time.
2146 When nil, only the date will be recorded."
2147 :group 'org-progress
2148 :type 'boolean)
2150 (defcustom org-log-note-headings
2151 '((done . "CLOSING NOTE %t")
2152 (state . "State %-12s from %-12S %t")
2153 (note . "Note taken on %t")
2154 (reschedule . "Rescheduled from %S on %t")
2155 (delschedule . "Not scheduled, was %S on %t")
2156 (redeadline . "New deadline from %S on %t")
2157 (deldeadline . "Removed deadline, was %S on %t")
2158 (refile . "Refiled on %t")
2159 (clock-out . ""))
2160 "Headings for notes added to entries.
2161 The value is an alist, with the car being a symbol indicating the note
2162 context, and the cdr is the heading to be used. The heading may also be the
2163 empty string.
2164 %t in the heading will be replaced by a time stamp.
2165 %T will be an acive time stamp instead the default inacive one
2166 %s will be replaced by the new TODO state, in double quotes.
2167 %S will be replaced by the old TODO state, in double quotes.
2168 %u will be replaced by the user name.
2169 %U will be replaced by the full user name.
2171 In fact, it is not a good idea to change the `state' entry, because
2172 agenda log mode depends on the format of these entries."
2173 :group 'org-todo
2174 :group 'org-progress
2175 :type '(list :greedy t
2176 (cons (const :tag "Heading when closing an item" done) string)
2177 (cons (const :tag
2178 "Heading when changing todo state (todo sequence only)"
2179 state) string)
2180 (cons (const :tag "Heading when just taking a note" note) string)
2181 (cons (const :tag "Heading when clocking out" clock-out) string)
2182 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2183 (cons (const :tag "Heading when rescheduling" reschedule) string)
2184 (cons (const :tag "Heading when changing deadline" redeadline) string)
2185 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2186 (cons (const :tag "Heading when refiling" refile) string)))
2188 (unless (assq 'note org-log-note-headings)
2189 (push '(note . "%t") org-log-note-headings))
2191 (defcustom org-log-into-drawer nil
2192 "Non-nil means insert state change notes and time stamps into a drawer.
2193 When nil, state changes notes will be inserted after the headline and
2194 any scheduling and clock lines, but not inside a drawer.
2196 The value of this variable should be the name of the drawer to use.
2197 LOGBOOK is proposed at the default drawer for this purpose, you can
2198 also set this to a string to define the drawer of your choice.
2200 A value of t is also allowed, representing \"LOGBOOK\".
2202 If this variable is set, `org-log-state-notes-insert-after-drawers'
2203 will be ignored.
2205 You can set the property LOG_INTO_DRAWER to overrule this setting for
2206 a subtree."
2207 :group 'org-todo
2208 :group 'org-progress
2209 :type '(choice
2210 (const :tag "Not into a drawer" nil)
2211 (const :tag "LOGBOOK" t)
2212 (string :tag "Other")))
2214 (if (fboundp 'defvaralias)
2215 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2217 (defun org-log-into-drawer ()
2218 "Return the value of `org-log-into-drawer', but let properties overrule.
2219 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2220 used instead of the default value."
2221 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2222 (cond
2223 ((or (not p) (equal p "nil")) org-log-into-drawer)
2224 ((equal p "t") "LOGBOOK")
2225 (t p))))
2227 (defcustom org-log-state-notes-insert-after-drawers nil
2228 "Non-nil means insert state change notes after any drawers in entry.
2229 Only the drawers that *immediately* follow the headline and the
2230 deadline/scheduled line are skipped.
2231 When nil, insert notes right after the heading and perhaps the line
2232 with deadline/scheduling if present.
2234 This variable will have no effect if `org-log-into-drawer' is
2235 set."
2236 :group 'org-todo
2237 :group 'org-progress
2238 :type 'boolean)
2240 (defcustom org-log-states-order-reversed t
2241 "Non-nil means the latest state note will be directly after heading.
2242 When nil, the state change notes will be ordered according to time."
2243 :group 'org-todo
2244 :group 'org-progress
2245 :type 'boolean)
2247 (defcustom org-todo-repeat-to-state nil
2248 "The TODO state to which a repeater should return the repeating task.
2249 By default this is the first task in a TODO sequence, or the previous state
2250 in a TODO_TYP set. But you can specify another task here.
2251 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2252 :group 'org-todo
2253 :type '(choice (const :tag "Head of sequence" nil)
2254 (string :tag "Specific state")))
2256 (defcustom org-log-repeat 'time
2257 "Non-nil means record moving through the DONE state when triggering repeat.
2258 An auto-repeating task is immediately switched back to TODO when
2259 marked DONE. If you are not logging state changes (by adding \"@\"
2260 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2261 record a closing note, there will be no record of the task moving
2262 through DONE. This variable forces taking a note anyway.
2264 nil Don't force a record
2265 time Record a time stamp
2266 note Record a note
2268 This option can also be set with on a per-file-basis with
2270 #+STARTUP: logrepeat
2271 #+STARTUP: lognoterepeat
2272 #+STARTUP: nologrepeat
2274 You can have local logging settings for a subtree by setting the LOGGING
2275 property to one or more of these keywords."
2276 :group 'org-todo
2277 :group 'org-progress
2278 :type '(choice
2279 (const :tag "Don't force a record" nil)
2280 (const :tag "Force recording the DONE state" time)
2281 (const :tag "Force recording a note with the DONE state" note)))
2284 (defgroup org-priorities nil
2285 "Priorities in Org-mode."
2286 :tag "Org Priorities"
2287 :group 'org-todo)
2289 (defcustom org-enable-priority-commands t
2290 "Non-nil means priority commands are active.
2291 When nil, these commands will be disabled, so that you never accidentally
2292 set a priority."
2293 :group 'org-priorities
2294 :type 'boolean)
2296 (defcustom org-highest-priority ?A
2297 "The highest priority of TODO items. A character like ?A, ?B etc.
2298 Must have a smaller ASCII number than `org-lowest-priority'."
2299 :group 'org-priorities
2300 :type 'character)
2302 (defcustom org-lowest-priority ?C
2303 "The lowest priority of TODO items. A character like ?A, ?B etc.
2304 Must have a larger ASCII number than `org-highest-priority'."
2305 :group 'org-priorities
2306 :type 'character)
2308 (defcustom org-default-priority ?B
2309 "The default priority of TODO items.
2310 This is the priority an item get if no explicit priority is given."
2311 :group 'org-priorities
2312 :type 'character)
2314 (defcustom org-priority-start-cycle-with-default t
2315 "Non-nil means start with default priority when starting to cycle.
2316 When this is nil, the first step in the cycle will be (depending on the
2317 command used) one higher or lower that the default priority."
2318 :group 'org-priorities
2319 :type 'boolean)
2321 (defgroup org-time nil
2322 "Options concerning time stamps and deadlines in Org-mode."
2323 :tag "Org Time"
2324 :group 'org)
2326 (defcustom org-insert-labeled-timestamps-at-point nil
2327 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2328 When nil, these labeled time stamps are forces into the second line of an
2329 entry, just after the headline. When scheduling from the global TODO list,
2330 the time stamp will always be forced into the second line."
2331 :group 'org-time
2332 :type 'boolean)
2334 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2335 "Formats for `format-time-string' which are used for time stamps.
2336 It is not recommended to change this constant.")
2338 (defcustom org-time-stamp-rounding-minutes '(0 5)
2339 "Number of minutes to round time stamps to.
2340 These are two values, the first applies when first creating a time stamp.
2341 The second applies when changing it with the commands `S-up' and `S-down'.
2342 When changing the time stamp, this means that it will change in steps
2343 of N minutes, as given by the second value.
2345 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2346 numbers should be factors of 60, so for example 5, 10, 15.
2348 When this is larger than 1, you can still force an exact time-stamp by using
2349 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2350 and by using a prefix arg to `S-up/down' to specify the exact number
2351 of minutes to shift."
2352 :group 'org-time
2353 :get '(lambda (var) ; Make sure both elements are there
2354 (if (integerp (default-value var))
2355 (list (default-value var) 5)
2356 (default-value var)))
2357 :type '(list
2358 (integer :tag "when inserting times")
2359 (integer :tag "when modifying times")))
2361 ;; Normalize old customizations of this variable.
2362 (when (integerp org-time-stamp-rounding-minutes)
2363 (setq org-time-stamp-rounding-minutes
2364 (list org-time-stamp-rounding-minutes
2365 org-time-stamp-rounding-minutes)))
2367 (defcustom org-display-custom-times nil
2368 "Non-nil means overlay custom formats over all time stamps.
2369 The formats are defined through the variable `org-time-stamp-custom-formats'.
2370 To turn this on on a per-file basis, insert anywhere in the file:
2371 #+STARTUP: customtime"
2372 :group 'org-time
2373 :set 'set-default
2374 :type 'sexp)
2375 (make-variable-buffer-local 'org-display-custom-times)
2377 (defcustom org-time-stamp-custom-formats
2378 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2379 "Custom formats for time stamps. See `format-time-string' for the syntax.
2380 These are overlayed over the default ISO format if the variable
2381 `org-display-custom-times' is set. Time like %H:%M should be at the
2382 end of the second format. The custom formats are also honored by export
2383 commands, if custom time display is turned on at the time of export."
2384 :group 'org-time
2385 :type 'sexp)
2387 (defun org-time-stamp-format (&optional long inactive)
2388 "Get the right format for a time string."
2389 (let ((f (if long (cdr org-time-stamp-formats)
2390 (car org-time-stamp-formats))))
2391 (if inactive
2392 (concat "[" (substring f 1 -1) "]")
2393 f)))
2395 (defcustom org-time-clocksum-format "%d:%02d"
2396 "The format string used when creating CLOCKSUM lines, or when
2397 org-mode generates a time duration."
2398 :group 'org-time
2399 :type 'string)
2401 (defcustom org-time-clocksum-use-fractional nil
2402 "If non-nil, \\[org-clock-display] uses fractional times.
2403 org-mode generates a time duration."
2404 :group 'org-time
2405 :type 'boolean)
2407 (defcustom org-time-clocksum-fractional-format "%.2f"
2408 "The format string used when creating CLOCKSUM lines, or when
2409 org-mode generates a time duration."
2410 :group 'org-time
2411 :type 'string)
2413 (defcustom org-deadline-warning-days 14
2414 "No. of days before expiration during which a deadline becomes active.
2415 This variable governs the display in sparse trees and in the agenda.
2416 When 0 or negative, it means use this number (the absolute value of it)
2417 even if a deadline has a different individual lead time specified.
2419 Custom commands can set this variable in the options section."
2420 :group 'org-time
2421 :group 'org-agenda-daily/weekly
2422 :type 'integer)
2424 (defcustom org-read-date-prefer-future t
2425 "Non-nil means assume future for incomplete date input from user.
2426 This affects the following situations:
2427 1. The user gives a month but not a year.
2428 For example, if it is april and you enter \"feb 2\", this will be read
2429 as feb 2, *next* year. \"May 5\", however, will be this year.
2430 2. The user gives a day, but no month.
2431 For example, if today is the 15th, and you enter \"3\", Org-mode will
2432 read this as the third of *next* month. However, if you enter \"17\",
2433 it will be considered as *this* month.
2435 If you set this variable to the symbol `time', then also the following
2436 will work:
2438 3. If the user gives a time, but no day. If the time is before now,
2439 to will be interpreted as tomorrow.
2441 Currently none of this works for ISO week specifications.
2443 When this option is nil, the current day, month and year will always be
2444 used as defaults."
2445 :group 'org-time
2446 :type '(choice
2447 (const :tag "Never" nil)
2448 (const :tag "Check month and day" t)
2449 (const :tag "Check month, day, and time" time)))
2451 (defcustom org-read-date-display-live t
2452 "Non-nil means display current interpretation of date prompt live.
2453 This display will be in an overlay, in the minibuffer."
2454 :group 'org-time
2455 :type 'boolean)
2457 (defcustom org-read-date-popup-calendar t
2458 "Non-nil means pop up a calendar when prompting for a date.
2459 In the calendar, the date can be selected with mouse-1. However, the
2460 minibuffer will also be active, and you can simply enter the date as well.
2461 When nil, only the minibuffer will be available."
2462 :group 'org-time
2463 :type 'boolean)
2464 (if (fboundp 'defvaralias)
2465 (defvaralias 'org-popup-calendar-for-date-prompt
2466 'org-read-date-popup-calendar))
2468 (defcustom org-read-date-minibuffer-setup-hook nil
2469 "Hook to be used to set up keys for the date/time interface.
2470 Add key definitions to `minibuffer-local-map', which will be a temporary
2471 copy."
2472 :group 'org-time
2473 :type 'hook)
2475 (defcustom org-extend-today-until 0
2476 "The hour when your day really ends. Must be an integer.
2477 This has influence for the following applications:
2478 - When switching the agenda to \"today\". It it is still earlier than
2479 the time given here, the day recognized as TODAY is actually yesterday.
2480 - When a date is read from the user and it is still before the time given
2481 here, the current date and time will be assumed to be yesterday, 23:59.
2482 Also, timestamps inserted in remember templates follow this rule.
2484 IMPORTANT: This is a feature whose implementation is and likely will
2485 remain incomplete. Really, it is only here because past midnight seems to
2486 be the favorite working time of John Wiegley :-)"
2487 :group 'org-time
2488 :type 'integer)
2490 (defcustom org-edit-timestamp-down-means-later nil
2491 "Non-nil means S-down will increase the time in a time stamp.
2492 When nil, S-up will increase."
2493 :group 'org-time
2494 :type 'boolean)
2496 (defcustom org-calendar-follow-timestamp-change t
2497 "Non-nil means make the calendar window follow timestamp changes.
2498 When a timestamp is modified and the calendar window is visible, it will be
2499 moved to the new date."
2500 :group 'org-time
2501 :type 'boolean)
2503 (defgroup org-tags nil
2504 "Options concerning tags in Org-mode."
2505 :tag "Org Tags"
2506 :group 'org)
2508 (defcustom org-tag-alist nil
2509 "List of tags allowed in Org-mode files.
2510 When this list is nil, Org-mode will base TAG input on what is already in the
2511 buffer.
2512 The value of this variable is an alist, the car of each entry must be a
2513 keyword as a string, the cdr may be a character that is used to select
2514 that tag through the fast-tag-selection interface.
2515 See the manual for details."
2516 :group 'org-tags
2517 :type '(repeat
2518 (choice
2519 (cons (string :tag "Tag name")
2520 (character :tag "Access char"))
2521 (list :tag "Start radio group"
2522 (const :startgroup)
2523 (option (string :tag "Group description")))
2524 (list :tag "End radio group"
2525 (const :endgroup)
2526 (option (string :tag "Group description")))
2527 (const :tag "New line" (:newline)))))
2529 (defcustom org-tag-persistent-alist nil
2530 "List of tags that will always appear in all Org-mode files.
2531 This is in addition to any in buffer settings or customizations
2532 of `org-tag-alist'.
2533 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2534 The value of this variable is an alist, the car of each entry must be a
2535 keyword as a string, the cdr may be a character that is used to select
2536 that tag through the fast-tag-selection interface.
2537 See the manual for details.
2538 To disable these tags on a per-file basis, insert anywhere in the file:
2539 #+STARTUP: noptag"
2540 :group 'org-tags
2541 :type '(repeat
2542 (choice
2543 (cons (string :tag "Tag name")
2544 (character :tag "Access char"))
2545 (const :tag "Start radio group" (:startgroup))
2546 (const :tag "End radio group" (:endgroup))
2547 (const :tag "New line" (:newline)))))
2549 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2550 "If non-nil, always offer completion for all tags of all agenda files.
2551 Instead of customizing this variable directly, you might want to
2552 set it locally for remember buffers, because there no list of
2553 tags in that file can be created dynamically (there are none).
2555 (add-hook 'org-remember-mode-hook
2556 (lambda ()
2557 (set (make-local-variable
2558 'org-complete-tags-always-offer-all-agenda-tags)
2559 t)))"
2560 :group 'org-tags
2561 :type 'boolean)
2563 (defvar org-file-tags nil
2564 "List of tags that can be inherited by all entries in the file.
2565 The tags will be inherited if the variable `org-use-tag-inheritance'
2566 says they should be.
2567 This variable is populated from #+FILETAGS lines.")
2569 (defcustom org-use-fast-tag-selection 'auto
2570 "Non-nil means use fast tag selection scheme.
2571 This is a special interface to select and deselect tags with single keys.
2572 When nil, fast selection is never used.
2573 When the symbol `auto', fast selection is used if and only if selection
2574 characters for tags have been configured, either through the variable
2575 `org-tag-alist' or through a #+TAGS line in the buffer.
2576 When t, fast selection is always used and selection keys are assigned
2577 automatically if necessary."
2578 :group 'org-tags
2579 :type '(choice
2580 (const :tag "Always" t)
2581 (const :tag "Never" nil)
2582 (const :tag "When selection characters are configured" 'auto)))
2584 (defcustom org-fast-tag-selection-single-key nil
2585 "Non-nil means fast tag selection exits after first change.
2586 When nil, you have to press RET to exit it.
2587 During fast tag selection, you can toggle this flag with `C-c'.
2588 This variable can also have the value `expert'. In this case, the window
2589 displaying the tags menu is not even shown, until you press C-c again."
2590 :group 'org-tags
2591 :type '(choice
2592 (const :tag "No" nil)
2593 (const :tag "Yes" t)
2594 (const :tag "Expert" expert)))
2596 (defvar org-fast-tag-selection-include-todo nil
2597 "Non-nil means fast tags selection interface will also offer TODO states.
2598 This is an undocumented feature, you should not rely on it.")
2600 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2601 "The column to which tags should be indented in a headline.
2602 If this number is positive, it specifies the column. If it is negative,
2603 it means that the tags should be flushright to that column. For example,
2604 -80 works well for a normal 80 character screen."
2605 :group 'org-tags
2606 :type 'integer)
2608 (defcustom org-auto-align-tags t
2609 "Non-nil means realign tags after pro/demotion of TODO state change.
2610 These operations change the length of a headline and therefore shift
2611 the tags around. With this options turned on, after each such operation
2612 the tags are again aligned to `org-tags-column'."
2613 :group 'org-tags
2614 :type 'boolean)
2616 (defcustom org-use-tag-inheritance t
2617 "Non-nil means tags in levels apply also for sublevels.
2618 When nil, only the tags directly given in a specific line apply there.
2619 This may also be a list of tags that should be inherited, or a regexp that
2620 matches tags that should be inherited. Additional control is possible
2621 with the variable `org-tags-exclude-from-inheritance' which gives an
2622 explicit list of tags to be excluded from inheritance., even if the value of
2623 `org-use-tag-inheritance' would select it for inheritance.
2625 If this option is t, a match early-on in a tree can lead to a large
2626 number of matches in the subtree when constructing the agenda or creating
2627 a sparse tree. If you only want to see the first match in a tree during
2628 a search, check out the variable `org-tags-match-list-sublevels'."
2629 :group 'org-tags
2630 :type '(choice
2631 (const :tag "Not" nil)
2632 (const :tag "Always" t)
2633 (repeat :tag "Specific tags" (string :tag "Tag"))
2634 (regexp :tag "Tags matched by regexp")))
2636 (defcustom org-tags-exclude-from-inheritance nil
2637 "List of tags that should never be inherited.
2638 This is a way to exclude a few tags from inheritance. For way to do
2639 the opposite, to actively allow inheritance for selected tags,
2640 see the variable `org-use-tag-inheritance'."
2641 :group 'org-tags
2642 :type '(repeat (string :tag "Tag")))
2644 (defun org-tag-inherit-p (tag)
2645 "Check if TAG is one that should be inherited."
2646 (cond
2647 ((member tag org-tags-exclude-from-inheritance) nil)
2648 ((eq org-use-tag-inheritance t) t)
2649 ((not org-use-tag-inheritance) nil)
2650 ((stringp org-use-tag-inheritance)
2651 (string-match org-use-tag-inheritance tag))
2652 ((listp org-use-tag-inheritance)
2653 (member tag org-use-tag-inheritance))
2654 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2656 (defcustom org-tags-match-list-sublevels t
2657 "Non-nil means list also sublevels of headlines matching a search.
2658 This variable applies to tags/property searches, and also to stuck
2659 projects because this search is based on a tags match as well.
2661 When set to the symbol `indented', sublevels are indented with
2662 leading dots.
2664 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2665 the sublevels of a headline matching a tag search often also match
2666 the same search. Listing all of them can create very long lists.
2667 Setting this variable to nil causes subtrees of a match to be skipped.
2669 This variable is semi-obsolete and probably should always be true. It
2670 is better to limit inheritance to certain tags using the variables
2671 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2672 :group 'org-tags
2673 :type '(choice
2674 (const :tag "No, don't list them" nil)
2675 (const :tag "Yes, do list them" t)
2676 (const :tag "List them, indented with leading dots" indented)))
2678 (defcustom org-tags-sort-function nil
2679 "When set, tags are sorted using this function as a comparator"
2680 :group 'org-tags
2681 :type '(choice
2682 (const :tag "No sorting" nil)
2683 (const :tag "Alphabetical" string<)
2684 (const :tag "Reverse alphabetical" string>)
2685 (function :tag "Custom function" nil)))
2687 (defvar org-tags-history nil
2688 "History of minibuffer reads for tags.")
2689 (defvar org-last-tags-completion-table nil
2690 "The last used completion table for tags.")
2691 (defvar org-after-tags-change-hook nil
2692 "Hook that is run after the tags in a line have changed.")
2694 (defgroup org-properties nil
2695 "Options concerning properties in Org-mode."
2696 :tag "Org Properties"
2697 :group 'org)
2699 (defcustom org-property-format "%-10s %s"
2700 "How property key/value pairs should be formatted by `indent-line'.
2701 When `indent-line' hits a property definition, it will format the line
2702 according to this format, mainly to make sure that the values are
2703 lined-up with respect to each other."
2704 :group 'org-properties
2705 :type 'string)
2707 (defcustom org-use-property-inheritance nil
2708 "Non-nil means properties apply also for sublevels.
2710 This setting is chiefly used during property searches. Turning it on can
2711 cause significant overhead when doing a search, which is why it is not
2712 on by default.
2714 When nil, only the properties directly given in the current entry count.
2715 When t, every property is inherited. The value may also be a list of
2716 properties that should have inheritance, or a regular expression matching
2717 properties that should be inherited.
2719 However, note that some special properties use inheritance under special
2720 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2721 and the properties ending in \"_ALL\" when they are used as descriptor
2722 for valid values of a property.
2724 Note for programmers:
2725 When querying an entry with `org-entry-get', you can control if inheritance
2726 should be used. By default, `org-entry-get' looks only at the local
2727 properties. You can request inheritance by setting the inherit argument
2728 to t (to force inheritance) or to `selective' (to respect the setting
2729 in this variable)."
2730 :group 'org-properties
2731 :type '(choice
2732 (const :tag "Not" nil)
2733 (const :tag "Always" t)
2734 (repeat :tag "Specific properties" (string :tag "Property"))
2735 (regexp :tag "Properties matched by regexp")))
2737 (defun org-property-inherit-p (property)
2738 "Check if PROPERTY is one that should be inherited."
2739 (cond
2740 ((eq org-use-property-inheritance t) t)
2741 ((not org-use-property-inheritance) nil)
2742 ((stringp org-use-property-inheritance)
2743 (string-match org-use-property-inheritance property))
2744 ((listp org-use-property-inheritance)
2745 (member property org-use-property-inheritance))
2746 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2748 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2749 "The default column format, if no other format has been defined.
2750 This variable can be set on the per-file basis by inserting a line
2752 #+COLUMNS: %25ITEM ....."
2753 :group 'org-properties
2754 :type 'string)
2756 (defcustom org-columns-ellipses ".."
2757 "The ellipses to be used when a field in column view is truncated.
2758 When this is the empty string, as many characters as possible are shown,
2759 but then there will be no visual indication that the field has been truncated.
2760 When this is a string of length N, the last N characters of a truncated
2761 field are replaced by this string. If the column is narrower than the
2762 ellipses string, only part of the ellipses string will be shown."
2763 :group 'org-properties
2764 :type 'string)
2766 (defcustom org-columns-modify-value-for-display-function nil
2767 "Function that modifies values for display in column view.
2768 For example, it can be used to cut out a certain part from a time stamp.
2769 The function must take 2 arguments:
2771 column-title The title of the column (*not* the property name)
2772 value The value that should be modified.
2774 The function should return the value that should be displayed,
2775 or nil if the normal value should be used."
2776 :group 'org-properties
2777 :type 'function)
2779 (defcustom org-effort-property "Effort"
2780 "The property that is being used to keep track of effort estimates.
2781 Effort estimates given in this property need to have the format H:MM."
2782 :group 'org-properties
2783 :group 'org-progress
2784 :type '(string :tag "Property"))
2786 (defconst org-global-properties-fixed
2787 '(("VISIBILITY_ALL" . "folded children content all")
2788 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2789 "List of property/value pairs that can be inherited by any entry.
2791 These are fixed values, for the preset properties. The user variable
2792 that can be used to add to this list is `org-global-properties'.
2794 The entries in this list are cons cells where the car is a property
2795 name and cdr is a string with the value. If the value represents
2796 multiple items like an \"_ALL\" property, separate the items by
2797 spaces.")
2799 (defcustom org-global-properties nil
2800 "List of property/value pairs that can be inherited by any entry.
2802 This list will be combined with the constant `org-global-properties-fixed'.
2804 The entries in this list are cons cells where the car is a property
2805 name and cdr is a string with the value.
2807 You can set buffer-local values for the same purpose in the variable
2808 `org-file-properties' this by adding lines like
2810 #+PROPERTY: NAME VALUE"
2811 :group 'org-properties
2812 :type '(repeat
2813 (cons (string :tag "Property")
2814 (string :tag "Value"))))
2816 (defvar org-file-properties nil
2817 "List of property/value pairs that can be inherited by any entry.
2818 Valid for the current buffer.
2819 This variable is populated from #+PROPERTY lines.")
2820 (make-variable-buffer-local 'org-file-properties)
2822 (defgroup org-agenda nil
2823 "Options concerning agenda views in Org-mode."
2824 :tag "Org Agenda"
2825 :group 'org)
2827 (defvar org-category nil
2828 "Variable used by org files to set a category for agenda display.
2829 Such files should use a file variable to set it, for example
2831 # -*- mode: org; org-category: \"ELisp\"
2833 or contain a special line
2835 #+CATEGORY: ELisp
2837 If the file does not specify a category, then file's base name
2838 is used instead.")
2839 (make-variable-buffer-local 'org-category)
2840 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2842 (defcustom org-agenda-files nil
2843 "The files to be used for agenda display.
2844 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2845 \\[org-remove-file]. You can also use customize to edit the list.
2847 If an entry is a directory, all files in that directory that are matched by
2848 `org-agenda-file-regexp' will be part of the file list.
2850 If the value of the variable is not a list but a single file name, then
2851 the list of agenda files is actually stored and maintained in that file, one
2852 agenda file per line. In this file paths can be given relative to
2853 `org-directory'. Tilde expansion and environment variable substitution
2854 are also made."
2855 :group 'org-agenda
2856 :type '(choice
2857 (repeat :tag "List of files and directories" file)
2858 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2860 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2861 "Regular expression to match files for `org-agenda-files'.
2862 If any element in the list in that variable contains a directory instead
2863 of a normal file, all files in that directory that are matched by this
2864 regular expression will be included."
2865 :group 'org-agenda
2866 :type 'regexp)
2868 (defcustom org-agenda-text-search-extra-files nil
2869 "List of extra files to be searched by text search commands.
2870 These files will be search in addition to the agenda files by the
2871 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2872 Note that these files will only be searched for text search commands,
2873 not for the other agenda views like todo lists, tag searches or the weekly
2874 agenda. This variable is intended to list notes and possibly archive files
2875 that should also be searched by these two commands.
2876 In fact, if the first element in the list is the symbol `agenda-archives',
2877 than all archive files of all agenda files will be added to the search
2878 scope."
2879 :group 'org-agenda
2880 :type '(set :greedy t
2881 (const :tag "Agenda Archives" agenda-archives)
2882 (repeat :inline t (file))))
2884 (if (fboundp 'defvaralias)
2885 (defvaralias 'org-agenda-multi-occur-extra-files
2886 'org-agenda-text-search-extra-files))
2888 (defcustom org-agenda-skip-unavailable-files nil
2889 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2890 A nil value means to remove them, after a query, from the list."
2891 :group 'org-agenda
2892 :type 'boolean)
2894 (defcustom org-calendar-to-agenda-key [?c]
2895 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2896 The command `org-calendar-goto-agenda' will be bound to this key. The
2897 default is the character `c' because then `c' can be used to switch back and
2898 forth between agenda and calendar."
2899 :group 'org-agenda
2900 :type 'sexp)
2902 (defcustom org-calendar-agenda-action-key [?k]
2903 "The key to be installed in `calendar-mode-map' for agenda-action.
2904 The command `org-agenda-action' will be bound to this key. The
2905 default is the character `k' because we use the same key in the agenda."
2906 :group 'org-agenda
2907 :type 'sexp)
2909 (defcustom org-calendar-insert-diary-entry-key [?i]
2910 "The key to be installed in `calendar-mode-map' for adding diary entries.
2911 This option is irrelevant until `org-agenda-diary-file' has been configured
2912 to point to an Org-mode file. When that is the case, the command
2913 `org-agenda-diary-entry' will be bound to the key given here, by default
2914 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2915 if you want to continue doing this, you need to change this to a different
2916 key."
2917 :group 'org-agenda
2918 :type 'sexp)
2920 (defcustom org-agenda-diary-file 'diary-file
2921 "File to which to add new entries with the `i' key in agenda and calendar.
2922 When this is the symbol `diary-file', the functionality in the Emacs
2923 calendar will be used to add entries to the `diary-file'. But when this
2924 points to a file, `org-agenda-diary-entry' will be used instead."
2925 :group 'org-agenda
2926 :type '(choice
2927 (const :tag "The standard Emacs diary file" diary-file)
2928 (file :tag "Special Org file diary entries")))
2930 (eval-after-load "calendar"
2931 '(progn
2932 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2933 'org-calendar-goto-agenda)
2934 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2935 'org-agenda-action)
2936 (add-hook 'calendar-mode-hook
2937 (lambda ()
2938 (unless (eq org-agenda-diary-file 'diary-file)
2939 (define-key calendar-mode-map
2940 org-calendar-insert-diary-entry-key
2941 'org-agenda-diary-entry))))))
2943 (defgroup org-latex nil
2944 "Options for embedding LaTeX code into Org-mode."
2945 :tag "Org LaTeX"
2946 :group 'org)
2948 (defcustom org-format-latex-options
2949 '(:foreground default :background default :scale 1.0
2950 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2951 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2952 "Options for creating images from LaTeX fragments.
2953 This is a property list with the following properties:
2954 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2955 `default' means use the foreground of the default face.
2956 :background the background color, or \"Transparent\".
2957 `default' means use the background of the default face.
2958 :scale a scaling factor for the size of the images.
2959 :html-foreground, :html-background, :html-scale
2960 the same numbers for HTML export.
2961 :matchers a list indicating which matchers should be used to
2962 find LaTeX fragments. Valid members of this list are:
2963 \"begin\" find environments
2964 \"$1\" find single characters surrounded by $.$
2965 \"$\" find math expressions surrounded by $...$
2966 \"$$\" find math expressions surrounded by $$....$$
2967 \"\\(\" find math expressions surrounded by \\(...\\)
2968 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2969 :group 'org-latex
2970 :type 'plist)
2972 (defcustom org-format-latex-signal-error t
2973 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2974 When nil, just push out a message."
2975 :group 'org-latex
2976 :type 'boolean)
2978 (defcustom org-format-latex-header "\\documentclass{article}
2979 \\usepackage[usenames]{color}
2980 \\usepackage{amsmath}
2981 \\usepackage[mathscr]{eucal}
2982 \\pagestyle{empty} % do not remove
2983 \[PACKAGES]
2984 \[DEFAULT-PACKAGES]
2985 % The settings below are copied from fullpage.sty
2986 \\setlength{\\textwidth}{\\paperwidth}
2987 \\addtolength{\\textwidth}{-3cm}
2988 \\setlength{\\oddsidemargin}{1.5cm}
2989 \\addtolength{\\oddsidemargin}{-2.54cm}
2990 \\setlength{\\evensidemargin}{\\oddsidemargin}
2991 \\setlength{\\textheight}{\\paperheight}
2992 \\addtolength{\\textheight}{-\\headheight}
2993 \\addtolength{\\textheight}{-\\headsep}
2994 \\addtolength{\\textheight}{-\\footskip}
2995 \\addtolength{\\textheight}{-3cm}
2996 \\setlength{\\topmargin}{1.5cm}
2997 \\addtolength{\\topmargin}{-2.54cm}"
2998 "The document header used for processing LaTeX fragments.
2999 It is imperative that this header make sure that no page number
3000 appears on the page. The package defined in the variables
3001 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3002 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3003 will be appended."
3004 :group 'org-latex
3005 :type 'string)
3007 (defvar org-format-latex-header-extra nil)
3009 (defun org-set-packages-alist (var val)
3010 "Set the packages alist and make sure it has 3 elements per entry."
3011 (set var (mapcar (lambda (x)
3012 (if (and (consp x) (= (length x) 2))
3013 (list (car x) (nth 1 x) t)
3015 val)))
3017 (defun org-get-packages-alist (var)
3019 "Get the packages alist and make sure it has 3 elements per entry."
3020 (mapcar (lambda (x)
3021 (if (and (consp x) (= (length x) 2))
3022 (list (car x) (nth 1 x) t)
3024 (default-value var)))
3026 ;; The following variables are defined here because is it also used
3027 ;; when formatting latex fragments. Originally it was part of the
3028 ;; LaTeX exporter, which is why the name includes "export".
3029 (defcustom org-export-latex-default-packages-alist
3030 '(("AUTO" "inputenc" t)
3031 ("T1" "fontenc" t)
3032 ("" "fixltx2e" nil)
3033 ("" "graphicx" t)
3034 ("" "longtable" nil)
3035 ("" "float" nil)
3036 ("" "wrapfig" nil)
3037 ("" "soul" t)
3038 ("" "t1enc" t)
3039 ("" "textcomp" t)
3040 ("" "marvosym" t)
3041 ("" "wasysym" t)
3042 ("" "latexsym" t)
3043 ("" "amssymb" t)
3044 ("" "hyperref" nil)
3045 "\\tolerance=1000"
3047 "Alist of default packages to be inserted in the header.
3048 Change this only if one of the packages here causes an incompatibility
3049 with another package you are using.
3050 The packages in this list are needed by one part or another of Org-mode
3051 to function properly.
3053 - inputenc, fontenc, t1enc: for basic font and character selection
3054 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3055 for interpreting the entities in `org-entities'. You can skip some of these
3056 packages if you don't use any of the symbols in it.
3057 - graphicx: for including images
3058 - float, wrapfig: for figure placement
3059 - longtable: for long tables
3060 - hyperref: for cross references
3062 Therefore you should not modify this variable unless you know what you
3063 are doing. The one reason to change it anyway is that you might be loading
3064 some other package that conflicts with one of the default packages.
3065 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3066 If SNIPPET-FLAG is t, the package also needs to be included when
3067 compiling LaTeX snippets into images for inclusion into HTML."
3068 :group 'org-export-latex
3069 :set 'org-set-packages-alist
3070 :get 'org-get-packages-alist
3071 :type '(repeat
3072 (choice
3073 (list :tag "options/package pair"
3074 (string :tag "options")
3075 (string :tag "package")
3076 (boolean :tag "Snippet"))
3077 (string :tag "A line of LaTeX"))))
3079 (defcustom org-export-latex-packages-alist nil
3080 "Alist of packages to be inserted in every LaTeX header.
3081 These will be inserted after `org-export-latex-default-packages-alist'.
3082 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3083 SNIPPET-FLAG, when t, indicates that this package is also needed when
3084 turning LaTeX snippets into images for inclusion into HTML.
3085 Make sure that you only list packages here which:
3086 - you want in every file
3087 - do not conflict with the default packages in
3088 `org-export-latex-default-packages-alist'
3089 - do not conflict with the setup in `org-format-latex-header'."
3090 :group 'org-export-latex
3091 :set 'org-set-packages-alist
3092 :get 'org-get-packages-alist
3093 :type '(repeat
3094 (choice
3095 (list :tag "options/package pair"
3096 (string :tag "options")
3097 (string :tag "package")
3098 (boolean :tag "Snippet"))
3099 (string :tag "A line of LaTeX"))))
3102 (defgroup org-appearance nil
3103 "Settings for Org-mode appearance."
3104 :tag "Org Appearance"
3105 :group 'org)
3107 (defcustom org-level-color-stars-only nil
3108 "Non-nil means fontify only the stars in each headline.
3109 When nil, the entire headline is fontified.
3110 Changing it requires restart of `font-lock-mode' to become effective
3111 also in regions already fontified."
3112 :group 'org-appearance
3113 :type 'boolean)
3115 (defcustom org-hide-leading-stars nil
3116 "Non-nil means hide the first N-1 stars in a headline.
3117 This works by using the face `org-hide' for these stars. This
3118 face is white for a light background, and black for a dark
3119 background. You may have to customize the face `org-hide' to
3120 make this work.
3121 Changing it requires restart of `font-lock-mode' to become effective
3122 also in regions already fontified.
3123 You may also set this on a per-file basis by adding one of the following
3124 lines to the buffer:
3126 #+STARTUP: hidestars
3127 #+STARTUP: showstars"
3128 :group 'org-appearance
3129 :type 'boolean)
3131 (defcustom org-hidden-keywords nil
3132 "List of keywords that should be hidden when typed in the org buffer.
3133 For example, add #+TITLE to this list in order to make the
3134 document title appear in the buffer without the initial #+TITLE:
3135 keyword."
3136 :group 'org-appearance
3137 :type '(set (const :tag "#+AUTHOR" author)
3138 (const :tag "#+DATE" date)
3139 (const :tag "#+EMAIL" email)
3140 (const :tag "#+TITLE" title)))
3142 (defcustom org-fontify-done-headline nil
3143 "Non-nil means change the face of a headline if it is marked DONE.
3144 Normally, only the TODO/DONE keyword indicates the state of a headline.
3145 When this is non-nil, the headline after the keyword is set to the
3146 `org-headline-done' as an additional indication."
3147 :group 'org-appearance
3148 :type 'boolean)
3150 (defcustom org-fontify-emphasized-text t
3151 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3152 Changing this variable requires a restart of Emacs to take effect."
3153 :group 'org-appearance
3154 :type 'boolean)
3156 (defcustom org-fontify-whole-heading-line nil
3157 "Non-nil means fontify the whole line for headings.
3158 This is useful when setting a background color for the
3159 org-level-* faces."
3160 :group 'org-appearance
3161 :type 'boolean)
3163 (defcustom org-highlight-latex-fragments-and-specials nil
3164 "Non-nil means fontify what is treated specially by the exporters."
3165 :group 'org-appearance
3166 :type 'boolean)
3168 (defcustom org-hide-emphasis-markers nil
3169 "Non-nil mean font-lock should hide the emphasis marker characters."
3170 :group 'org-appearance
3171 :type 'boolean)
3173 (defcustom org-pretty-entities nil
3174 "Non-nil means show entities as UTF8 characters.
3175 When nil, the \\name form remains in the buffer."
3176 :group 'org-appearance
3177 :type 'boolean)
3179 (defvar org-emph-re nil
3180 "Regular expression for matching emphasis.
3181 After a match, the match groups contain these elements:
3182 1 The character before the proper match, or empty at beginning of line
3183 2 The proper match, including the leading and trailing markers
3184 3 The leading marker like * or /, indicating the type of highlighting
3185 4 The text between the emphasis markers, not including the markers
3186 5 The character after the match, empty at the end of a line")
3187 (defvar org-verbatim-re nil
3188 "Regular expression for matching verbatim text.")
3189 (defvar org-emphasis-regexp-components) ; defined just below
3190 (defvar org-emphasis-alist) ; defined just below
3191 (defun org-set-emph-re (var val)
3192 "Set variable and compute the emphasis regular expression."
3193 (set var val)
3194 (when (and (boundp 'org-emphasis-alist)
3195 (boundp 'org-emphasis-regexp-components)
3196 org-emphasis-alist org-emphasis-regexp-components)
3197 (let* ((e org-emphasis-regexp-components)
3198 (pre (car e))
3199 (post (nth 1 e))
3200 (border (nth 2 e))
3201 (body (nth 3 e))
3202 (nl (nth 4 e))
3203 (body1 (concat body "*?"))
3204 (markers (mapconcat 'car org-emphasis-alist ""))
3205 (vmarkers (mapconcat
3206 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3207 org-emphasis-alist "")))
3208 ;; make sure special characters appear at the right position in the class
3209 (if (string-match "\\^" markers)
3210 (setq markers (concat (replace-match "" t t markers) "^")))
3211 (if (string-match "-" markers)
3212 (setq markers (concat (replace-match "" t t markers) "-")))
3213 (if (string-match "\\^" vmarkers)
3214 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3215 (if (string-match "-" vmarkers)
3216 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3217 (if (> nl 0)
3218 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3219 (int-to-string nl) "\\}")))
3220 ;; Make the regexp
3221 (setq org-emph-re
3222 (concat "\\([" pre "]\\|^\\)"
3223 "\\("
3224 "\\([" markers "]\\)"
3225 "\\("
3226 "[^" border "]\\|"
3227 "[^" border "]"
3228 body1
3229 "[^" border "]"
3230 "\\)"
3231 "\\3\\)"
3232 "\\([" post "]\\|$\\)"))
3233 (setq org-verbatim-re
3234 (concat "\\([" pre "]\\|^\\)"
3235 "\\("
3236 "\\([" vmarkers "]\\)"
3237 "\\("
3238 "[^" border "]\\|"
3239 "[^" border "]"
3240 body1
3241 "[^" border "]"
3242 "\\)"
3243 "\\3\\)"
3244 "\\([" post "]\\|$\\)")))))
3246 (defcustom org-emphasis-regexp-components
3247 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3248 "Components used to build the regular expression for emphasis.
3249 This is a list with 6 entries. Terminology: In an emphasis string
3250 like \" *strong word* \", we call the initial space PREMATCH, the final
3251 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3252 and \"trong wor\" is the body. The different components in this variable
3253 specify what is allowed/forbidden in each part:
3255 pre Chars allowed as prematch. Beginning of line will be allowed too.
3256 post Chars allowed as postmatch. End of line will be allowed too.
3257 border The chars *forbidden* as border characters.
3258 body-regexp A regexp like \".\" to match a body character. Don't use
3259 non-shy groups here, and don't allow newline here.
3260 newline The maximum number of newlines allowed in an emphasis exp.
3262 Use customize to modify this, or restart Emacs after changing it."
3263 :group 'org-appearance
3264 :set 'org-set-emph-re
3265 :type '(list
3266 (sexp :tag "Allowed chars in pre ")
3267 (sexp :tag "Allowed chars in post ")
3268 (sexp :tag "Forbidden chars in border ")
3269 (sexp :tag "Regexp for body ")
3270 (integer :tag "number of newlines allowed")
3271 (option (boolean :tag "Please ignore this button"))))
3273 (defcustom org-emphasis-alist
3274 `(("*" bold "<b>" "</b>")
3275 ("/" italic "<i>" "</i>")
3276 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3277 ("=" org-code "<code>" "</code>" verbatim)
3278 ("~" org-verbatim "<code>" "</code>" verbatim)
3279 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3280 "<del>" "</del>")
3282 "Special syntax for emphasized text.
3283 Text starting and ending with a special character will be emphasized, for
3284 example *bold*, _underlined_ and /italic/. This variable sets the marker
3285 characters, the face to be used by font-lock for highlighting in Org-mode
3286 Emacs buffers, and the HTML tags to be used for this.
3287 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3288 Use customize to modify this, or restart Emacs after changing it."
3289 :group 'org-appearance
3290 :set 'org-set-emph-re
3291 :type '(repeat
3292 (list
3293 (string :tag "Marker character")
3294 (choice
3295 (face :tag "Font-lock-face")
3296 (plist :tag "Face property list"))
3297 (string :tag "HTML start tag")
3298 (string :tag "HTML end tag")
3299 (option (const verbatim)))))
3301 (defvar org-protecting-blocks
3302 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3303 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3304 This is needed for font-lock setup.")
3306 ;;; Miscellaneous options
3308 (defgroup org-completion nil
3309 "Completion in Org-mode."
3310 :tag "Org Completion"
3311 :group 'org)
3313 (defcustom org-completion-use-ido nil
3314 "Non-nil means use ido completion wherever possible.
3315 Note that `ido-mode' must be active for this variable to be relevant.
3316 If you decide to turn this variable on, you might well want to turn off
3317 `org-outline-path-complete-in-steps'.
3318 See also `org-completion-use-iswitchb'."
3319 :group 'org-completion
3320 :type 'boolean)
3322 (defcustom org-completion-use-iswitchb nil
3323 "Non-nil means use iswitchb completion wherever possible.
3324 Note that `iswitchb-mode' must be active for this variable to be relevant.
3325 If you decide to turn this variable on, you might well want to turn off
3326 `org-outline-path-complete-in-steps'.
3327 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3328 :group 'org-completion
3329 :type 'boolean)
3331 (defcustom org-completion-fallback-command 'hippie-expand
3332 "The expansion command called by \\[org-complete] in normal context.
3333 Normal means no org-mode-specific context."
3334 :group 'org-completion
3335 :type 'function)
3337 ;;; Functions and variables from their packages
3338 ;; Declared here to avoid compiler warnings
3340 ;; XEmacs only
3341 (defvar outline-mode-menu-heading)
3342 (defvar outline-mode-menu-show)
3343 (defvar outline-mode-menu-hide)
3344 (defvar zmacs-regions) ; XEmacs regions
3346 ;; Emacs only
3347 (defvar mark-active)
3349 ;; Various packages
3350 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3351 (declare-function calendar-forward-day "cal-move" (arg))
3352 (declare-function calendar-goto-date "cal-move" (date))
3353 (declare-function calendar-goto-today "cal-move" ())
3354 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3355 (defvar calc-embedded-close-formula)
3356 (defvar calc-embedded-open-formula)
3357 (declare-function cdlatex-tab "ext:cdlatex" ())
3358 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3359 (defvar font-lock-unfontify-region-function)
3360 (declare-function iswitchb-read-buffer "iswitchb"
3361 (prompt &optional default require-match start matches-set))
3362 (defvar iswitchb-temp-buflist)
3363 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3364 (defvar org-agenda-tags-todo-honor-ignore-options)
3365 (declare-function org-agenda-skip "org-agenda" ())
3366 (declare-function
3367 org-format-agenda-item "org-agenda"
3368 (extra txt &optional category tags dotime noprefix remove-re habitp))
3369 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3370 (declare-function org-agenda-change-all-lines "org-agenda"
3371 (newhead hdmarker &optional fixface just-this))
3372 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3373 (declare-function org-agenda-maybe-redo "org-agenda" ())
3374 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3375 (beg end))
3376 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3377 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3378 "org-agenda" (&optional end))
3379 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3380 (declare-function org-indent-mode "org-indent" (&optional arg))
3381 (declare-function parse-time-string "parse-time" (string))
3382 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3383 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3384 (defvar remember-data-file)
3385 (defvar texmathp-why)
3386 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3387 (declare-function table--at-cell-p "table" (position &optional object at-column))
3389 (defvar w3m-current-url)
3390 (defvar w3m-current-title)
3392 (defvar org-latex-regexps)
3394 ;;; Autoload and prepare some org modules
3396 ;; Some table stuff that needs to be defined here, because it is used
3397 ;; by the functions setting up org-mode or checking for table context.
3399 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3400 "Detects an org-type or table-type table.")
3401 (defconst org-table-line-regexp "^[ \t]*|"
3402 "Detects an org-type table line.")
3403 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3404 "Detects an org-type table line.")
3405 (defconst org-table-hline-regexp "^[ \t]*|-"
3406 "Detects an org-type table hline.")
3407 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3408 "Detects a table-type table hline.")
3409 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3410 "Searching from within a table (any type) this finds the first line
3411 outside the table.")
3413 ;; Autoload the functions in org-table.el that are needed by functions here.
3415 (eval-and-compile
3416 (org-autoload "org-table"
3417 '(org-table-align org-table-begin org-table-blank-field
3418 org-table-convert org-table-convert-region org-table-copy-down
3419 org-table-copy-region org-table-create
3420 org-table-create-or-convert-from-region
3421 org-table-create-with-table.el org-table-current-dline
3422 org-table-cut-region org-table-delete-column org-table-edit-field
3423 org-table-edit-formulas org-table-end org-table-eval-formula
3424 org-table-export org-table-field-info
3425 org-table-get-stored-formulas org-table-goto-column
3426 org-table-hline-and-move org-table-import org-table-insert-column
3427 org-table-insert-hline org-table-insert-row org-table-iterate
3428 org-table-justify-field-maybe org-table-kill-row
3429 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3430 org-table-move-column org-table-move-column-left
3431 org-table-move-column-right org-table-move-row
3432 org-table-move-row-down org-table-move-row-up
3433 org-table-next-field org-table-next-row org-table-paste-rectangle
3434 org-table-previous-field org-table-recalculate
3435 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3436 org-table-toggle-coordinate-overlays
3437 org-table-toggle-formula-debugger org-table-wrap-region
3438 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3440 (defun org-at-table-p (&optional table-type)
3441 "Return t if the cursor is inside an org-type table.
3442 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3443 (if org-enable-table-editor
3444 (save-excursion
3445 (beginning-of-line 1)
3446 (looking-at (if table-type org-table-any-line-regexp
3447 org-table-line-regexp)))
3448 nil))
3449 (defsubst org-table-p () (org-at-table-p))
3451 (defun org-at-table.el-p ()
3452 "Return t if and only if we are at a table.el table."
3453 (and (org-at-table-p 'any)
3454 (save-excursion
3455 (goto-char (org-table-begin 'any))
3456 (looking-at org-table1-hline-regexp))))
3457 (defun org-table-recognize-table.el ()
3458 "If there is a table.el table nearby, recognize it and move into it."
3459 (if org-table-tab-recognizes-table.el
3460 (if (org-at-table.el-p)
3461 (progn
3462 (beginning-of-line 1)
3463 (if (looking-at org-table-dataline-regexp)
3465 (if (looking-at org-table1-hline-regexp)
3466 (progn
3467 (beginning-of-line 2)
3468 (if (looking-at org-table-any-border-regexp)
3469 (beginning-of-line -1)))))
3470 (if (re-search-forward "|" (org-table-end t) t)
3471 (progn
3472 (require 'table)
3473 (if (table--at-cell-p (point))
3475 (message "recognizing table.el table...")
3476 (table-recognize-table)
3477 (message "recognizing table.el table...done")))
3478 (error "This should not happen..."))
3480 nil)
3481 nil))
3483 (defun org-at-table-hline-p ()
3484 "Return t if the cursor is inside a hline in a table."
3485 (if org-enable-table-editor
3486 (save-excursion
3487 (beginning-of-line 1)
3488 (looking-at org-table-hline-regexp))
3489 nil))
3491 (defvar org-table-clean-did-remove-column nil)
3493 (defun org-table-map-tables (function &optional quietly)
3494 "Apply FUNCTION to the start of all tables in the buffer."
3495 (save-excursion
3496 (save-restriction
3497 (widen)
3498 (goto-char (point-min))
3499 (while (re-search-forward org-table-any-line-regexp nil t)
3500 (unless quietly
3501 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3502 (beginning-of-line 1)
3503 (when (looking-at org-table-line-regexp)
3504 (save-excursion (funcall function))
3505 (or (looking-at org-table-line-regexp)
3506 (forward-char 1)))
3507 (re-search-forward org-table-any-border-regexp nil 1))))
3508 (unless quietly (message "Mapping tables: done")))
3510 ;; Declare and autoload functions from org-exp.el & Co
3512 (declare-function org-default-export-plist "org-exp")
3513 (declare-function org-infile-export-plist "org-exp")
3514 (declare-function org-get-current-options "org-exp")
3515 (eval-and-compile
3516 (org-autoload "org-exp"
3517 '(org-export org-export-visible
3518 org-insert-export-options-template
3519 org-table-clean-before-export))
3520 (org-autoload "org-ascii"
3521 '(org-export-as-ascii org-export-ascii-preprocess
3522 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3523 org-export-region-as-ascii))
3524 (org-autoload "org-latex"
3525 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3526 org-replace-region-by-latex org-export-region-as-latex
3527 org-export-as-latex org-export-as-pdf
3528 org-export-as-pdf-and-open))
3529 (org-autoload "org-html"
3530 '(org-export-as-html-and-open
3531 org-export-as-html-batch org-export-as-html-to-buffer
3532 org-replace-region-by-html org-export-region-as-html
3533 org-export-as-html))
3534 (org-autoload "org-docbook"
3535 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3536 org-replace-region-by-docbook org-export-region-as-docbook
3537 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3538 org-export-as-docbook))
3539 (org-autoload "org-icalendar"
3540 '(org-export-icalendar-this-file
3541 org-export-icalendar-all-agenda-files
3542 org-export-icalendar-combine-agenda-files))
3543 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3544 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3546 ;; Declare and autoload functions from org-agenda.el
3548 (eval-and-compile
3549 (org-autoload "org-agenda"
3550 '(org-agenda org-agenda-list org-search-view
3551 org-todo-list org-tags-view org-agenda-list-stuck-projects
3552 org-diary org-agenda-to-appt
3553 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3555 ;; Autoload org-remember
3557 (eval-and-compile
3558 (org-autoload "org-remember"
3559 '(org-remember-insinuate org-remember-annotation
3560 org-remember-apply-template org-remember org-remember-handler)))
3562 ;; Autoload org-clock.el
3565 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3566 (beg end))
3567 (declare-function org-clock-update-mode-line "org-clock" ())
3568 (declare-function org-resolve-clocks "org-clock"
3569 (&optional also-non-dangling-p prompt last-valid))
3570 (defvar org-clock-start-time)
3571 (defvar org-clock-marker (make-marker)
3572 "Marker recording the last clock-in.")
3573 (defvar org-clock-hd-marker (make-marker)
3574 "Marker recording the last clock-in, but the headline position.")
3575 (defvar org-clock-heading ""
3576 "The heading of the current clock entry.")
3577 (defun org-clock-is-active ()
3578 "Return non-nil if clock is currently running.
3579 The return value is actually the clock marker."
3580 (marker-buffer org-clock-marker))
3582 (eval-and-compile
3583 (org-autoload
3584 "org-clock"
3585 '(org-clock-in org-clock-out org-clock-cancel
3586 org-clock-goto org-clock-sum org-clock-display
3587 org-clock-remove-overlays org-clock-report
3588 org-clocktable-shift org-dblock-write:clocktable
3589 org-get-clocktable org-resolve-clocks)))
3591 (defun org-clock-update-time-maybe ()
3592 "If this is a CLOCK line, update it and return t.
3593 Otherwise, return nil."
3594 (interactive)
3595 (save-excursion
3596 (beginning-of-line 1)
3597 (skip-chars-forward " \t")
3598 (when (looking-at org-clock-string)
3599 (let ((re (concat "[ \t]*" org-clock-string
3600 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3601 "\\([ \t]*=>.*\\)?\\)?"))
3602 ts te h m s neg)
3603 (cond
3604 ((not (looking-at re))
3605 nil)
3606 ((not (match-end 2))
3607 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3608 (> org-clock-marker (point))
3609 (<= org-clock-marker (point-at-eol)))
3610 ;; The clock is running here
3611 (setq org-clock-start-time
3612 (apply 'encode-time
3613 (org-parse-time-string (match-string 1))))
3614 (org-clock-update-mode-line)))
3616 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3617 (end-of-line 1)
3618 (setq ts (match-string 1)
3619 te (match-string 3))
3620 (setq s (- (org-float-time
3621 (apply 'encode-time (org-parse-time-string te)))
3622 (org-float-time
3623 (apply 'encode-time (org-parse-time-string ts))))
3624 neg (< s 0)
3625 s (abs s)
3626 h (floor (/ s 3600))
3627 s (- s (* 3600 h))
3628 m (floor (/ s 60))
3629 s (- s (* 60 s)))
3630 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3631 t))))))
3633 (defun org-check-running-clock ()
3634 "Check if the current buffer contains the running clock.
3635 If yes, offer to stop it and to save the buffer with the changes."
3636 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3637 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3638 (buffer-name))))
3639 (org-clock-out)
3640 (when (y-or-n-p "Save changed buffer?")
3641 (save-buffer))))
3643 (defun org-clocktable-try-shift (dir n)
3644 "Check if this line starts a clock table, if yes, shift the time block."
3645 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3646 (org-clocktable-shift dir n)))
3648 ;; Autoload org-timer.el
3650 (eval-and-compile
3651 (org-autoload
3652 "org-timer"
3653 '(org-timer-start org-timer org-timer-item
3654 org-timer-change-times-in-region
3655 org-timer-set-timer
3656 org-timer-reset-timers
3657 org-timer-show-remaining-time)))
3659 ;; Autoload org-feed.el
3661 (eval-and-compile
3662 (org-autoload
3663 "org-feed"
3664 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3667 ;; Autoload org-indent.el
3669 ;; Define the variable already here, to make sure we have it.
3670 (defvar org-indent-mode nil
3671 "Non-nil if Org-Indent mode is enabled.
3672 Use the command `org-indent-mode' to change this variable.")
3674 (eval-and-compile
3675 (org-autoload
3676 "org-indent"
3677 '(org-indent-mode)))
3679 ;; Autoload org-mobile.el
3681 (eval-and-compile
3682 (org-autoload
3683 "org-mobile"
3684 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3686 ;; Autoload archiving code
3687 ;; The stuff that is needed for cycling and tags has to be defined here.
3689 (defgroup org-archive nil
3690 "Options concerning archiving in Org-mode."
3691 :tag "Org Archive"
3692 :group 'org-structure)
3694 (defcustom org-archive-location "%s_archive::"
3695 "The location where subtrees should be archived.
3697 The value of this variable is a string, consisting of two parts,
3698 separated by a double-colon. The first part is a filename and
3699 the second part is a headline.
3701 When the filename is omitted, archiving happens in the same file.
3702 %s in the filename will be replaced by the current file
3703 name (without the directory part). Archiving to a different file
3704 is useful to keep archived entries from contributing to the
3705 Org-mode Agenda.
3707 The archived entries will be filed as subtrees of the specified
3708 headline. When the headline is omitted, the subtrees are simply
3709 filed away at the end of the file, as top-level entries. Also in
3710 the heading you can use %s to represent the file name, this can be
3711 useful when using the same archive for a number of different files.
3713 Here are a few examples:
3714 \"%s_archive::\"
3715 If the current file is Projects.org, archive in file
3716 Projects.org_archive, as top-level trees. This is the default.
3718 \"::* Archived Tasks\"
3719 Archive in the current file, under the top-level headline
3720 \"* Archived Tasks\".
3722 \"~/org/archive.org::\"
3723 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3725 \"~/org/archive.org::From %s\"
3726 Archive in file ~/org/archive.org (absolute path), under headlines
3727 \"From FILENAME\" where file name is the current file name.
3729 \"basement::** Finished Tasks\"
3730 Archive in file ./basement (relative path), as level 3 trees
3731 below the level 2 heading \"** Finished Tasks\".
3733 You may set this option on a per-file basis by adding to the buffer a
3734 line like
3736 #+ARCHIVE: basement::** Finished Tasks
3738 You may also define it locally for a subtree by setting an ARCHIVE property
3739 in the entry. If such a property is found in an entry, or anywhere up
3740 the hierarchy, it will be used."
3741 :group 'org-archive
3742 :type 'string)
3744 (defcustom org-archive-tag "ARCHIVE"
3745 "The tag that marks a subtree as archived.
3746 An archived subtree does not open during visibility cycling, and does
3747 not contribute to the agenda listings.
3748 After changing this, font-lock must be restarted in the relevant buffers to
3749 get the proper fontification."
3750 :group 'org-archive
3751 :group 'org-keywords
3752 :type 'string)
3754 (defcustom org-agenda-skip-archived-trees t
3755 "Non-nil means the agenda will skip any items located in archived trees.
3756 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3757 variable is no longer recommended, you should leave it at the value t.
3758 Instead, use the key `v' to cycle the archives-mode in the agenda."
3759 :group 'org-archive
3760 :group 'org-agenda-skip
3761 :type 'boolean)
3763 (defcustom org-columns-skip-archived-trees t
3764 "Non-nil means ignore archived trees when creating column view."
3765 :group 'org-archive
3766 :group 'org-properties
3767 :type 'boolean)
3769 (defcustom org-cycle-open-archived-trees nil
3770 "Non-nil means `org-cycle' will open archived trees.
3771 An archived tree is a tree marked with the tag ARCHIVE.
3772 When nil, archived trees will stay folded. You can still open them with
3773 normal outline commands like `show-all', but not with the cycling commands."
3774 :group 'org-archive
3775 :group 'org-cycle
3776 :type 'boolean)
3778 (defcustom org-sparse-tree-open-archived-trees nil
3779 "Non-nil means sparse tree construction shows matches in archived trees.
3780 When nil, matches in these trees are highlighted, but the trees are kept in
3781 collapsed state."
3782 :group 'org-archive
3783 :group 'org-sparse-trees
3784 :type 'boolean)
3786 (defun org-cycle-hide-archived-subtrees (state)
3787 "Re-hide all archived subtrees after a visibility state change."
3788 (when (and (not org-cycle-open-archived-trees)
3789 (not (memq state '(overview folded))))
3790 (save-excursion
3791 (let* ((globalp (memq state '(contents all)))
3792 (beg (if globalp (point-min) (point)))
3793 (end (if globalp (point-max) (org-end-of-subtree t))))
3794 (org-hide-archived-subtrees beg end)
3795 (goto-char beg)
3796 (if (looking-at (concat ".*:" org-archive-tag ":"))
3797 (message "%s" (substitute-command-keys
3798 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3800 (defun org-force-cycle-archived ()
3801 "Cycle subtree even if it is archived."
3802 (interactive)
3803 (setq this-command 'org-cycle)
3804 (let ((org-cycle-open-archived-trees t))
3805 (call-interactively 'org-cycle)))
3807 (defun org-hide-archived-subtrees (beg end)
3808 "Re-hide all archived subtrees after a visibility state change."
3809 (save-excursion
3810 (let* ((re (concat ":" org-archive-tag ":")))
3811 (goto-char beg)
3812 (while (re-search-forward re end t)
3813 (when (org-on-heading-p)
3814 (org-flag-subtree t)
3815 (org-end-of-subtree t))))))
3817 (defun org-flag-subtree (flag)
3818 (save-excursion
3819 (org-back-to-heading t)
3820 (outline-end-of-heading)
3821 (outline-flag-region (point)
3822 (progn (org-end-of-subtree t) (point))
3823 flag)))
3825 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3827 (eval-and-compile
3828 (org-autoload "org-archive"
3829 '(org-add-archive-files org-archive-subtree
3830 org-archive-to-archive-sibling org-toggle-archive-tag
3831 org-archive-subtree-default
3832 org-archive-subtree-default-with-confirmation)))
3834 ;; Autoload Column View Code
3836 (declare-function org-columns-number-to-string "org-colview")
3837 (declare-function org-columns-get-format-and-top-level "org-colview")
3838 (declare-function org-columns-compute "org-colview")
3840 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3841 '(org-columns-number-to-string org-columns-get-format-and-top-level
3842 org-columns-compute org-agenda-columns org-columns-remove-overlays
3843 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3845 ;; Autoload ID code
3847 (declare-function org-id-store-link "org-id")
3848 (declare-function org-id-locations-load "org-id")
3849 (declare-function org-id-locations-save "org-id")
3850 (defvar org-id-track-globally)
3851 (org-autoload "org-id"
3852 '(org-id-get-create org-id-new org-id-copy org-id-get
3853 org-id-get-with-outline-path-completion
3854 org-id-get-with-outline-drilling
3855 org-id-goto org-id-find org-id-store-link))
3857 ;; Autoload Plotting Code
3859 (org-autoload "org-plot"
3860 '(org-plot/gnuplot))
3862 ;;; Variables for pre-computed regular expressions, all buffer local
3864 (defvar org-drawer-regexp nil
3865 "Matches first line of a hidden block.")
3866 (make-variable-buffer-local 'org-drawer-regexp)
3867 (defvar org-todo-regexp nil
3868 "Matches any of the TODO state keywords.")
3869 (make-variable-buffer-local 'org-todo-regexp)
3870 (defvar org-not-done-regexp nil
3871 "Matches any of the TODO state keywords except the last one.")
3872 (make-variable-buffer-local 'org-not-done-regexp)
3873 (defvar org-not-done-heading-regexp nil
3874 "Matches a TODO headline that is not done.")
3875 (make-variable-buffer-local 'org-not-done-regexp)
3876 (defvar org-todo-line-regexp nil
3877 "Matches a headline and puts TODO state into group 2 if present.")
3878 (make-variable-buffer-local 'org-todo-line-regexp)
3879 (defvar org-complex-heading-regexp nil
3880 "Matches a headline and puts everything into groups:
3881 group 1: the stars
3882 group 2: The todo keyword, maybe
3883 group 3: Priority cookie
3884 group 4: True headline
3885 group 5: Tags")
3886 (make-variable-buffer-local 'org-complex-heading-regexp)
3887 (defvar org-complex-heading-regexp-format nil)
3888 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3889 (defvar org-todo-line-tags-regexp nil
3890 "Matches a headline and puts TODO state into group 2 if present.
3891 Also put tags into group 4 if tags are present.")
3892 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3893 (defvar org-nl-done-regexp nil
3894 "Matches newline followed by a headline with the DONE keyword.")
3895 (make-variable-buffer-local 'org-nl-done-regexp)
3896 (defvar org-looking-at-done-regexp nil
3897 "Matches the DONE keyword a point.")
3898 (make-variable-buffer-local 'org-looking-at-done-regexp)
3899 (defvar org-ds-keyword-length 12
3900 "Maximum length of the Deadline and SCHEDULED keywords.")
3901 (make-variable-buffer-local 'org-ds-keyword-length)
3902 (defvar org-deadline-regexp nil
3903 "Matches the DEADLINE keyword.")
3904 (make-variable-buffer-local 'org-deadline-regexp)
3905 (defvar org-deadline-time-regexp nil
3906 "Matches the DEADLINE keyword together with a time stamp.")
3907 (make-variable-buffer-local 'org-deadline-time-regexp)
3908 (defvar org-deadline-line-regexp nil
3909 "Matches the DEADLINE keyword and the rest of the line.")
3910 (make-variable-buffer-local 'org-deadline-line-regexp)
3911 (defvar org-scheduled-regexp nil
3912 "Matches the SCHEDULED keyword.")
3913 (make-variable-buffer-local 'org-scheduled-regexp)
3914 (defvar org-scheduled-time-regexp nil
3915 "Matches the SCHEDULED keyword together with a time stamp.")
3916 (make-variable-buffer-local 'org-scheduled-time-regexp)
3917 (defvar org-closed-time-regexp nil
3918 "Matches the CLOSED keyword together with a time stamp.")
3919 (make-variable-buffer-local 'org-closed-time-regexp)
3921 (defvar org-keyword-time-regexp nil
3922 "Matches any of the 4 keywords, together with the time stamp.")
3923 (make-variable-buffer-local 'org-keyword-time-regexp)
3924 (defvar org-keyword-time-not-clock-regexp nil
3925 "Matches any of the 3 keywords, together with the time stamp.")
3926 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3927 (defvar org-maybe-keyword-time-regexp nil
3928 "Matches a timestamp, possibly preceeded by a keyword.")
3929 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3930 (defvar org-planning-or-clock-line-re nil
3931 "Matches a line with planning or clock info.")
3932 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3933 (defvar org-all-time-keywords nil
3934 "List of time keywords.")
3935 (make-variable-buffer-local 'org-all-time-keywords)
3937 (defconst org-plain-time-of-day-regexp
3938 (concat
3939 "\\(\\<[012]?[0-9]"
3940 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3941 "\\(--?"
3942 "\\(\\<[012]?[0-9]"
3943 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3944 "\\)?")
3945 "Regular expression to match a plain time or time range.
3946 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3947 groups carry important information:
3948 0 the full match
3949 1 the first time, range or not
3950 8 the second time, if it is a range.")
3952 (defconst org-plain-time-extension-regexp
3953 (concat
3954 "\\(\\<[012]?[0-9]"
3955 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3956 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3957 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3958 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3959 groups carry important information:
3960 0 the full match
3961 7 hours of duration
3962 9 minutes of duration")
3964 (defconst org-stamp-time-of-day-regexp
3965 (concat
3966 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3967 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3968 "\\(--?"
3969 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3970 "Regular expression to match a timestamp time or time range.
3971 After a match, the following groups carry important information:
3972 0 the full match
3973 1 date plus weekday, for back referencing to make sure both times are on the same day
3974 2 the first time, range or not
3975 4 the second time, if it is a range.")
3977 (defconst org-startup-options
3978 '(("fold" org-startup-folded t)
3979 ("overview" org-startup-folded t)
3980 ("nofold" org-startup-folded nil)
3981 ("showall" org-startup-folded nil)
3982 ("showeverything" org-startup-folded showeverything)
3983 ("content" org-startup-folded content)
3984 ("indent" org-startup-indented t)
3985 ("noindent" org-startup-indented nil)
3986 ("hidestars" org-hide-leading-stars t)
3987 ("showstars" org-hide-leading-stars nil)
3988 ("odd" org-odd-levels-only t)
3989 ("oddeven" org-odd-levels-only nil)
3990 ("align" org-startup-align-all-tables t)
3991 ("noalign" org-startup-align-all-tables nil)
3992 ("customtime" org-display-custom-times t)
3993 ("logdone" org-log-done time)
3994 ("lognotedone" org-log-done note)
3995 ("nologdone" org-log-done nil)
3996 ("lognoteclock-out" org-log-note-clock-out t)
3997 ("nolognoteclock-out" org-log-note-clock-out nil)
3998 ("logrepeat" org-log-repeat state)
3999 ("lognoterepeat" org-log-repeat note)
4000 ("nologrepeat" org-log-repeat nil)
4001 ("logreschedule" org-log-reschedule time)
4002 ("lognotereschedule" org-log-reschedule note)
4003 ("nologreschedule" org-log-reschedule nil)
4004 ("logredeadline" org-log-redeadline time)
4005 ("lognoteredeadline" org-log-redeadline note)
4006 ("nologredeadline" org-log-redeadline nil)
4007 ("logrefile" org-log-refile time)
4008 ("lognoterefile" org-log-refile note)
4009 ("nologrefile" org-log-refile nil)
4010 ("fninline" org-footnote-define-inline t)
4011 ("nofninline" org-footnote-define-inline nil)
4012 ("fnlocal" org-footnote-section nil)
4013 ("fnauto" org-footnote-auto-label t)
4014 ("fnprompt" org-footnote-auto-label nil)
4015 ("fnconfirm" org-footnote-auto-label confirm)
4016 ("fnplain" org-footnote-auto-label plain)
4017 ("fnadjust" org-footnote-auto-adjust t)
4018 ("nofnadjust" org-footnote-auto-adjust nil)
4019 ("constcgs" constants-unit-system cgs)
4020 ("constSI" constants-unit-system SI)
4021 ("noptag" org-tag-persistent-alist nil)
4022 ("hideblocks" org-hide-block-startup t)
4023 ("nohideblocks" org-hide-block-startup nil)
4024 ("beamer" org-startup-with-beamer-mode t)
4025 ("entitiespretty" org-pretty-entities t)
4026 ("entitiesplain" org-pretty-entities nil))
4027 "Variable associated with STARTUP options for org-mode.
4028 Each element is a list of three items: The startup options as written
4029 in the #+STARTUP line, the corresponding variable, and the value to
4030 set this variable to if the option is found. An optional forth element PUSH
4031 means to push this value onto the list in the variable.")
4033 (defun org-set-regexps-and-options ()
4034 "Precompute regular expressions for current buffer."
4035 (when (org-mode-p)
4036 (org-set-local 'org-todo-kwd-alist nil)
4037 (org-set-local 'org-todo-key-alist nil)
4038 (org-set-local 'org-todo-key-trigger nil)
4039 (org-set-local 'org-todo-keywords-1 nil)
4040 (org-set-local 'org-done-keywords nil)
4041 (org-set-local 'org-todo-heads nil)
4042 (org-set-local 'org-todo-sets nil)
4043 (org-set-local 'org-todo-log-states nil)
4044 (org-set-local 'org-file-properties nil)
4045 (org-set-local 'org-file-tags nil)
4046 (let ((re (org-make-options-regexp
4047 '("CATEGORY" "TODO" "COLUMNS"
4048 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4049 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
4050 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4051 (splitre "[ \t]+")
4052 kwds kws0 kwsa key log value cat arch tags const links hw dws
4053 tail sep kws1 prio props ftags drawers beamer-p
4054 ext-setup-or-nil setup-contents (start 0))
4055 (save-excursion
4056 (save-restriction
4057 (widen)
4058 (goto-char (point-min))
4059 (while (or (and ext-setup-or-nil
4060 (string-match re ext-setup-or-nil start)
4061 (setq start (match-end 0)))
4062 (and (setq ext-setup-or-nil nil start 0)
4063 (re-search-forward re nil t)))
4064 (setq key (upcase (match-string 1 ext-setup-or-nil))
4065 value (org-match-string-no-properties 2 ext-setup-or-nil))
4066 (if (stringp value) (setq value (org-trim value)))
4067 (cond
4068 ((equal key "CATEGORY")
4069 (setq cat value))
4070 ((member key '("SEQ_TODO" "TODO"))
4071 (push (cons 'sequence (org-split-string value splitre)) kwds))
4072 ((equal key "TYP_TODO")
4073 (push (cons 'type (org-split-string value splitre)) kwds))
4074 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4075 ;; general TODO-like setup
4076 (push (cons (intern (downcase (match-string 1 key)))
4077 (org-split-string value splitre)) kwds))
4078 ((equal key "TAGS")
4079 (setq tags (append tags (if tags '("\\n") nil)
4080 (org-split-string value splitre))))
4081 ((equal key "COLUMNS")
4082 (org-set-local 'org-columns-default-format value))
4083 ((equal key "LINK")
4084 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4085 (push (cons (match-string 1 value)
4086 (org-trim (match-string 2 value)))
4087 links)))
4088 ((equal key "PRIORITIES")
4089 (setq prio (org-split-string value " +")))
4090 ((equal key "PROPERTY")
4091 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4092 (push (cons (match-string 1 value) (match-string 2 value))
4093 props)))
4094 ((equal key "FILETAGS")
4095 (when (string-match "\\S-" value)
4096 (setq ftags
4097 (append
4098 ftags
4099 (apply 'append
4100 (mapcar (lambda (x) (org-split-string x ":"))
4101 (org-split-string value)))))))
4102 ((equal key "DRAWERS")
4103 (setq drawers (org-split-string value splitre)))
4104 ((equal key "CONSTANTS")
4105 (setq const (append const (org-split-string value splitre))))
4106 ((equal key "STARTUP")
4107 (let ((opts (org-split-string value splitre))
4108 l var val)
4109 (while (setq l (pop opts))
4110 (when (setq l (assoc l org-startup-options))
4111 (setq var (nth 1 l) val (nth 2 l))
4112 (if (not (nth 3 l))
4113 (set (make-local-variable var) val)
4114 (if (not (listp (symbol-value var)))
4115 (set (make-local-variable var) nil))
4116 (set (make-local-variable var) (symbol-value var))
4117 (add-to-list var val))))))
4118 ((equal key "ARCHIVE")
4119 (setq arch value)
4120 (remove-text-properties 0 (length arch)
4121 '(face t fontified t) arch))
4122 ((equal key "LATEX_CLASS")
4123 (setq beamer-p (equal value "beamer")))
4124 ((equal key "SETUPFILE")
4125 (setq setup-contents (org-file-contents
4126 (expand-file-name
4127 (org-remove-double-quotes value))
4128 'noerror))
4129 (if (not ext-setup-or-nil)
4130 (setq ext-setup-or-nil setup-contents start 0)
4131 (setq ext-setup-or-nil
4132 (concat (substring ext-setup-or-nil 0 start)
4133 "\n" setup-contents "\n"
4134 (substring ext-setup-or-nil start)))))
4135 ))))
4136 (when cat
4137 (org-set-local 'org-category (intern cat))
4138 (push (cons "CATEGORY" cat) props))
4139 (when prio
4140 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4141 (setq prio (mapcar 'string-to-char prio))
4142 (org-set-local 'org-highest-priority (nth 0 prio))
4143 (org-set-local 'org-lowest-priority (nth 1 prio))
4144 (org-set-local 'org-default-priority (nth 2 prio)))
4145 (and props (org-set-local 'org-file-properties (nreverse props)))
4146 (and ftags (org-set-local 'org-file-tags
4147 (mapcar 'org-add-prop-inherited ftags)))
4148 (and drawers (org-set-local 'org-drawers drawers))
4149 (and arch (org-set-local 'org-archive-location arch))
4150 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4151 ;; Process the TODO keywords
4152 (unless kwds
4153 ;; Use the global values as if they had been given locally.
4154 (setq kwds (default-value 'org-todo-keywords))
4155 (if (stringp (car kwds))
4156 (setq kwds (list (cons org-todo-interpretation
4157 (default-value 'org-todo-keywords)))))
4158 (setq kwds (reverse kwds)))
4159 (setq kwds (nreverse kwds))
4160 (let (inter kws kw)
4161 (while (setq kws (pop kwds))
4162 (let ((kws (or
4163 (run-hook-with-args-until-success
4164 'org-todo-setup-filter-hook kws)
4165 kws)))
4166 (setq inter (pop kws) sep (member "|" kws)
4167 kws0 (delete "|" (copy-sequence kws))
4168 kwsa nil
4169 kws1 (mapcar
4170 (lambda (x)
4171 ;; 1 2
4172 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4173 (progn
4174 (setq kw (match-string 1 x)
4175 key (and (match-end 2) (match-string 2 x))
4176 log (org-extract-log-state-settings x))
4177 (push (cons kw (and key (string-to-char key))) kwsa)
4178 (and log (push log org-todo-log-states))
4180 (error "Invalid TODO keyword %s" x)))
4181 kws0)
4182 kwsa (if kwsa (append '((:startgroup))
4183 (nreverse kwsa)
4184 '((:endgroup))))
4185 hw (car kws1)
4186 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4187 tail (list inter hw (car dws) (org-last dws))))
4188 (add-to-list 'org-todo-heads hw 'append)
4189 (push kws1 org-todo-sets)
4190 (setq org-done-keywords (append org-done-keywords dws nil))
4191 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4192 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4193 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4194 (setq org-todo-sets (nreverse org-todo-sets)
4195 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4196 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4197 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4198 ;; Process the constants
4199 (when const
4200 (let (e cst)
4201 (while (setq e (pop const))
4202 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4203 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4204 (setq org-table-formula-constants-local cst)))
4206 ;; Process the tags.
4207 (when tags
4208 (let (e tgs)
4209 (while (setq e (pop tags))
4210 (cond
4211 ((equal e "{") (push '(:startgroup) tgs))
4212 ((equal e "}") (push '(:endgroup) tgs))
4213 ((equal e "\\n") (push '(:newline) tgs))
4214 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4215 (push (cons (match-string 1 e)
4216 (string-to-char (match-string 2 e)))
4217 tgs))
4218 (t (push (list e) tgs))))
4219 (org-set-local 'org-tag-alist nil)
4220 (while (setq e (pop tgs))
4221 (or (and (stringp (car e))
4222 (assoc (car e) org-tag-alist))
4223 (push e org-tag-alist)))))
4225 ;; Compute the regular expressions and other local variables
4226 (if (not org-done-keywords)
4227 (setq org-done-keywords (and org-todo-keywords-1
4228 (list (org-last org-todo-keywords-1)))))
4229 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4230 (length org-scheduled-string)
4231 (length org-clock-string)
4232 (length org-closed-string)))
4233 org-drawer-regexp
4234 (concat "^[ \t]*:\\("
4235 (mapconcat 'regexp-quote org-drawers "\\|")
4236 "\\):[ \t]*$")
4237 org-not-done-keywords
4238 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4239 org-todo-regexp
4240 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4241 "\\|") "\\)\\>")
4242 org-not-done-regexp
4243 (concat "\\<\\("
4244 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4245 "\\)\\>")
4246 org-not-done-heading-regexp
4247 (concat "^\\(\\*+\\)[ \t]+\\("
4248 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4249 "\\)\\>")
4250 org-todo-line-regexp
4251 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4252 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4253 "\\)\\>\\)?[ \t]*\\(.*\\)")
4254 org-complex-heading-regexp
4255 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4256 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4257 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4258 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4259 org-complex-heading-regexp-format
4260 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4261 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4262 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4263 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4264 org-nl-done-regexp
4265 (concat "\n\\*+[ \t]+"
4266 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4267 "\\)" "\\>")
4268 org-todo-line-tags-regexp
4269 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4270 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4271 (org-re
4272 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4273 org-looking-at-done-regexp
4274 (concat "^" "\\(?:"
4275 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4276 "\\>")
4277 org-deadline-regexp (concat "\\<" org-deadline-string)
4278 org-deadline-time-regexp
4279 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4280 org-deadline-line-regexp
4281 (concat "\\<\\(" org-deadline-string "\\).*")
4282 org-scheduled-regexp
4283 (concat "\\<" org-scheduled-string)
4284 org-scheduled-time-regexp
4285 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4286 org-closed-time-regexp
4287 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4288 org-keyword-time-regexp
4289 (concat "\\<\\(" org-scheduled-string
4290 "\\|" org-deadline-string
4291 "\\|" org-closed-string
4292 "\\|" org-clock-string "\\)"
4293 " *[[<]\\([^]>]+\\)[]>]")
4294 org-keyword-time-not-clock-regexp
4295 (concat "\\<\\(" org-scheduled-string
4296 "\\|" org-deadline-string
4297 "\\|" org-closed-string
4298 "\\)"
4299 " *[[<]\\([^]>]+\\)[]>]")
4300 org-maybe-keyword-time-regexp
4301 (concat "\\(\\<\\(" org-scheduled-string
4302 "\\|" org-deadline-string
4303 "\\|" org-closed-string
4304 "\\|" org-clock-string "\\)\\)?"
4305 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4306 org-planning-or-clock-line-re
4307 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4308 "\\|" org-deadline-string
4309 "\\|" org-closed-string "\\|" org-clock-string
4310 "\\)\\>\\)")
4311 org-all-time-keywords
4312 (mapcar (lambda (w) (substring w 0 -1))
4313 (list org-scheduled-string org-deadline-string
4314 org-clock-string org-closed-string))
4316 (org-compute-latex-and-specials-regexp)
4317 (org-set-font-lock-defaults))))
4319 (defun org-file-contents (file &optional noerror)
4320 "Return the contents of FILE, as a string."
4321 (if (or (not file)
4322 (not (file-readable-p file)))
4323 (if noerror
4324 (progn
4325 (message "Cannot read file \"%s\"" file)
4326 (ding) (sit-for 2)
4328 (error "Cannot read file \"%s\"" file))
4329 (with-temp-buffer
4330 (insert-file-contents file)
4331 (buffer-string))))
4333 (defun org-extract-log-state-settings (x)
4334 "Extract the log state setting from a TODO keyword string.
4335 This will extract info from a string like \"WAIT(w@/!)\"."
4336 (let (kw key log1 log2)
4337 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4338 (setq kw (match-string 1 x)
4339 key (and (match-end 2) (match-string 2 x))
4340 log1 (and (match-end 3) (match-string 3 x))
4341 log2 (and (match-end 4) (match-string 4 x)))
4342 (and (or log1 log2)
4343 (list kw
4344 (and log1 (if (equal log1 "!") 'time 'note))
4345 (and log2 (if (equal log2 "!") 'time 'note)))))))
4347 (defun org-remove-keyword-keys (list)
4348 "Remove a pair of parenthesis at the end of each string in LIST."
4349 (mapcar (lambda (x)
4350 (if (string-match "(.*)$" x)
4351 (substring x 0 (match-beginning 0))
4353 list))
4355 (defun org-assign-fast-keys (alist)
4356 "Assign fast keys to a keyword-key alist.
4357 Respect keys that are already there."
4358 (let (new e (alt ?0))
4359 (while (setq e (pop alist))
4360 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4361 (cdr e)) ;; Key already assigned.
4362 (push e new)
4363 (let ((clist (string-to-list (downcase (car e))))
4364 (used (append new alist)))
4365 (when (= (car clist) ?@)
4366 (pop clist))
4367 (while (and clist (rassoc (car clist) used))
4368 (pop clist))
4369 (unless clist
4370 (while (rassoc alt used)
4371 (incf alt)))
4372 (push (cons (car e) (or (car clist) alt)) new))))
4373 (nreverse new)))
4375 ;;; Some variables used in various places
4377 (defvar org-window-configuration nil
4378 "Used in various places to store a window configuration.")
4379 (defvar org-selected-window nil
4380 "Used in various places to store a window configuration.")
4381 (defvar org-finish-function nil
4382 "Function to be called when `C-c C-c' is used.
4383 This is for getting out of special buffers like remember.")
4386 ;; FIXME: Occasionally check by commenting these, to make sure
4387 ;; no other functions uses these, forgetting to let-bind them.
4388 (defvar entry)
4389 (defvar last-state)
4390 (defvar date)
4392 ;; Defined somewhere in this file, but used before definition.
4393 (defvar org-entities) ;; defined in org-entities.el
4394 (defvar org-struct-menu)
4395 (defvar org-org-menu)
4396 (defvar org-tbl-menu)
4398 ;;;; Define the Org-mode
4400 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4401 (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."))
4404 ;; We use a before-change function to check if a table might need
4405 ;; an update.
4406 (defvar org-table-may-need-update t
4407 "Indicates that a table might need an update.
4408 This variable is set by `org-before-change-function'.
4409 `org-table-align' sets it back to nil.")
4410 (defun org-before-change-function (beg end)
4411 "Every change indicates that a table might need an update."
4412 (setq org-table-may-need-update t))
4413 (defvar org-mode-map)
4414 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4415 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4416 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4417 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4418 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4419 (defvar org-table-buffer-is-an nil)
4420 (defconst org-outline-regexp "\\*+ ")
4422 ;;;###autoload
4423 (define-derived-mode org-mode outline-mode "Org"
4424 "Outline-based notes management and organizer, alias
4425 \"Carsten's outline-mode for keeping track of everything.\"
4427 Org-mode develops organizational tasks around a NOTES file which
4428 contains information about projects as plain text. Org-mode is
4429 implemented on top of outline-mode, which is ideal to keep the content
4430 of large files well structured. It supports ToDo items, deadlines and
4431 time stamps, which magically appear in the diary listing of the Emacs
4432 calendar. Tables are easily created with a built-in table editor.
4433 Plain text URL-like links connect to websites, emails (VM), Usenet
4434 messages (Gnus), BBDB entries, and any files related to the project.
4435 For printing and sharing of notes, an Org-mode file (or a part of it)
4436 can be exported as a structured ASCII or HTML file.
4438 The following commands are available:
4440 \\{org-mode-map}"
4442 ;; Get rid of Outline menus, they are not needed
4443 ;; Need to do this here because define-derived-mode sets up
4444 ;; the keymap so late. Still, it is a waste to call this each time
4445 ;; we switch another buffer into org-mode.
4446 (if (featurep 'xemacs)
4447 (when (boundp 'outline-mode-menu-heading)
4448 ;; Assume this is Greg's port, it uses easymenu
4449 (easy-menu-remove outline-mode-menu-heading)
4450 (easy-menu-remove outline-mode-menu-show)
4451 (easy-menu-remove outline-mode-menu-hide))
4452 (define-key org-mode-map [menu-bar headings] 'undefined)
4453 (define-key org-mode-map [menu-bar hide] 'undefined)
4454 (define-key org-mode-map [menu-bar show] 'undefined))
4456 (org-load-modules-maybe)
4457 (easy-menu-add org-org-menu)
4458 (easy-menu-add org-tbl-menu)
4459 (org-install-agenda-files-menu)
4460 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4461 (add-to-invisibility-spec '(org-cwidth))
4462 (add-to-invisibility-spec '(org-hide-block . t))
4463 (when (featurep 'xemacs)
4464 (org-set-local 'line-move-ignore-invisible t))
4465 (org-set-local 'outline-regexp org-outline-regexp)
4466 (org-set-local 'outline-level 'org-outline-level)
4467 (when (and org-ellipsis
4468 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4469 (fboundp 'make-glyph-code))
4470 (unless org-display-table
4471 (setq org-display-table (make-display-table)))
4472 (set-display-table-slot
4473 org-display-table 4
4474 (vconcat (mapcar
4475 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4476 org-ellipsis)))
4477 (if (stringp org-ellipsis) org-ellipsis "..."))))
4478 (setq buffer-display-table org-display-table))
4479 (org-set-regexps-and-options)
4480 (when (and org-tag-faces (not org-tags-special-faces-re))
4481 ;; tag faces set outside customize.... force initialization.
4482 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4483 ;; Calc embedded
4484 (org-set-local 'calc-embedded-open-mode "# ")
4485 (modify-syntax-entry ?@ "w")
4486 (if org-startup-truncated (setq truncate-lines t))
4487 (org-set-local 'font-lock-unfontify-region-function
4488 'org-unfontify-region)
4489 ;; Activate before-change-function
4490 (org-set-local 'org-table-may-need-update t)
4491 (org-add-hook 'before-change-functions 'org-before-change-function nil
4492 'local)
4493 ;; Check for running clock before killing a buffer
4494 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4495 ;; Paragraphs and auto-filling
4496 (org-set-autofill-regexps)
4497 (setq indent-line-function 'org-indent-line-function)
4498 (org-update-radio-target-regexp)
4499 ;; Beginning/end of defun
4500 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4501 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4502 ;; Make sure dependence stuff works reliably, even for users who set it
4503 ;; too late :-(
4504 (if org-enforce-todo-dependencies
4505 (add-hook 'org-blocker-hook
4506 'org-block-todo-from-children-or-siblings-or-parent)
4507 (remove-hook 'org-blocker-hook
4508 'org-block-todo-from-children-or-siblings-or-parent))
4509 (if org-enforce-todo-checkbox-dependencies
4510 (add-hook 'org-blocker-hook
4511 'org-block-todo-from-checkboxes)
4512 (remove-hook 'org-blocker-hook
4513 'org-block-todo-from-checkboxes))
4515 ;; Comment characters
4516 ;; (org-set-local 'comment-start "#")
4517 (org-set-local 'comment-padding " ")
4518 (modify-syntax-entry ?# "<")
4519 ;; (modify-syntax-entry ?\n ">")
4521 ;; Align options lines
4522 (org-set-local
4523 'align-mode-rules-list
4524 '((org-in-buffer-settings
4525 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4526 (modes . '(org-mode)))))
4528 ;; Imenu
4529 (org-set-local 'imenu-create-index-function
4530 'org-imenu-get-tree)
4532 ;; Make isearch reveal context
4533 (if (or (featurep 'xemacs)
4534 (not (boundp 'outline-isearch-open-invisible-function)))
4535 ;; Emacs 21 and XEmacs make use of the hook
4536 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4537 ;; Emacs 22 deals with this through a special variable
4538 (org-set-local 'outline-isearch-open-invisible-function
4539 (lambda (&rest ignore) (org-show-context 'isearch))))
4541 ;; Turn on org-beamer-mode?
4542 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4544 ;; If empty file that did not turn on org-mode automatically, make it to.
4545 (if (and org-insert-mode-line-in-empty-file
4546 (interactive-p)
4547 (= (point-min) (point-max)))
4548 (insert "# -*- mode: org -*-\n\n"))
4549 (unless org-inhibit-startup
4550 (when org-startup-align-all-tables
4551 (let ((bmp (buffer-modified-p)))
4552 (org-table-map-tables 'org-table-align 'quietly)
4553 (set-buffer-modified-p bmp)))
4554 (when org-startup-indented
4555 (require 'org-indent)
4556 (org-indent-mode 1))
4557 (unless org-inhibit-startup-visibility-stuff
4558 (org-set-startup-visibility))))
4560 (when (fboundp 'abbrev-table-put)
4561 (abbrev-table-put org-mode-abbrev-table
4562 :parents (list text-mode-abbrev-table)))
4564 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4566 (defun org-current-time ()
4567 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4568 (if (> (car org-time-stamp-rounding-minutes) 1)
4569 (let ((r (car org-time-stamp-rounding-minutes))
4570 (time (decode-time)))
4571 (apply 'encode-time
4572 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4573 (nthcdr 2 time))))
4574 (current-time)))
4576 ;;;; Font-Lock stuff, including the activators
4578 (defvar org-mouse-map (make-sparse-keymap))
4579 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4580 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4581 (when org-mouse-1-follows-link
4582 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4583 (when org-tab-follows-link
4584 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4585 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4587 (require 'font-lock)
4589 (defconst org-non-link-chars "]\t\n\r<>")
4590 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4591 "shell" "elisp" "doi"))
4592 (defvar org-link-types-re nil
4593 "Matches a link that has a url-like prefix like \"http:\"")
4594 (defvar org-link-re-with-space nil
4595 "Matches a link with spaces, optional angular brackets around it.")
4596 (defvar org-link-re-with-space2 nil
4597 "Matches a link with spaces, optional angular brackets around it.")
4598 (defvar org-link-re-with-space3 nil
4599 "Matches a link with spaces, only for internal part in bracket links.")
4600 (defvar org-angle-link-re nil
4601 "Matches link with angular brackets, spaces are allowed.")
4602 (defvar org-plain-link-re nil
4603 "Matches plain link, without spaces.")
4604 (defvar org-bracket-link-regexp nil
4605 "Matches a link in double brackets.")
4606 (defvar org-bracket-link-analytic-regexp nil
4607 "Regular expression used to analyze links.
4608 Here is what the match groups contain after a match:
4609 1: http:
4610 2: http
4611 3: path
4612 4: [desc]
4613 5: desc")
4614 (defvar org-bracket-link-analytic-regexp++ nil
4615 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4616 (defvar org-any-link-re nil
4617 "Regular expression matching any link.")
4619 (defun org-make-link-regexps ()
4620 "Update the link regular expressions.
4621 This should be called after the variable `org-link-types' has changed."
4622 (setq org-link-types-re
4623 (concat
4624 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4625 org-link-re-with-space
4626 (concat
4627 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4628 "\\([^" org-non-link-chars " ]"
4629 "[^" org-non-link-chars "]*"
4630 "[^" org-non-link-chars " ]\\)>?")
4631 org-link-re-with-space2
4632 (concat
4633 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4634 "\\([^" org-non-link-chars " ]"
4635 "[^\t\n\r]*"
4636 "[^" org-non-link-chars " ]\\)>?")
4637 org-link-re-with-space3
4638 (concat
4639 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4640 "\\([^" org-non-link-chars " ]"
4641 "[^\t\n\r]*\\)")
4642 org-angle-link-re
4643 (concat
4644 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4645 "\\([^" org-non-link-chars " ]"
4646 "[^" org-non-link-chars "]*"
4647 "\\)>")
4648 org-plain-link-re
4649 (concat
4650 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4651 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4652 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4653 org-bracket-link-regexp
4654 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4655 org-bracket-link-analytic-regexp
4656 (concat
4657 "\\[\\["
4658 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4659 "\\([^]]+\\)"
4660 "\\]"
4661 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4662 "\\]")
4663 org-bracket-link-analytic-regexp++
4664 (concat
4665 "\\[\\["
4666 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4667 "\\([^]]+\\)"
4668 "\\]"
4669 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4670 "\\]")
4671 org-any-link-re
4672 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4673 org-angle-link-re "\\)\\|\\("
4674 org-plain-link-re "\\)")))
4676 (org-make-link-regexps)
4678 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4679 "Regular expression for fast time stamp matching.")
4680 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4681 "Regular expression for fast time stamp matching.")
4682 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4683 "Regular expression matching time strings for analysis.
4684 This one does not require the space after the date, so it can be used
4685 on a string that terminates immediately after the date.")
4686 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4687 "Regular expression matching time strings for analysis.")
4688 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4689 "Regular expression matching time stamps, with groups.")
4690 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4691 "Regular expression matching time stamps (also [..]), with groups.")
4692 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4693 "Regular expression matching a time stamp range.")
4694 (defconst org-tr-regexp-both
4695 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4696 "Regular expression matching a time stamp range.")
4697 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4698 org-ts-regexp "\\)?")
4699 "Regular expression matching a time stamp or time stamp range.")
4700 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4701 org-ts-regexp-both "\\)?")
4702 "Regular expression matching a time stamp or time stamp range.
4703 The time stamps may be either active or inactive.")
4705 (defvar org-emph-face nil)
4707 (defun org-do-emphasis-faces (limit)
4708 "Run through the buffer and add overlays to links."
4709 (let (rtn a)
4710 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4711 (if (not (= (char-after (match-beginning 3))
4712 (char-after (match-beginning 4))))
4713 (progn
4714 (setq rtn t)
4715 (setq a (assoc (match-string 3) org-emphasis-alist))
4716 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4717 'face
4718 (nth 1 a))
4719 (and (nth 4 a)
4720 (org-remove-flyspell-overlays-in
4721 (match-beginning 0) (match-end 0)))
4722 (add-text-properties (match-beginning 2) (match-end 2)
4723 '(font-lock-multiline t))
4724 (when org-hide-emphasis-markers
4725 (add-text-properties (match-end 4) (match-beginning 5)
4726 '(invisible org-link))
4727 (add-text-properties (match-beginning 3) (match-end 3)
4728 '(invisible org-link)))))
4729 (backward-char 1))
4730 rtn))
4732 (defun org-emphasize (&optional char)
4733 "Insert or change an emphasis, i.e. a font like bold or italic.
4734 If there is an active region, change that region to a new emphasis.
4735 If there is no region, just insert the marker characters and position
4736 the cursor between them.
4737 CHAR should be either the marker character, or the first character of the
4738 HTML tag associated with that emphasis. If CHAR is a space, the means
4739 to remove the emphasis of the selected region.
4740 If char is not given (for example in an interactive call) it
4741 will be prompted for."
4742 (interactive)
4743 (let ((eal org-emphasis-alist) e det
4744 (erc org-emphasis-regexp-components)
4745 (prompt "")
4746 (string "") beg end move tag c s)
4747 (if (org-region-active-p)
4748 (setq beg (region-beginning) end (region-end)
4749 string (buffer-substring beg end))
4750 (setq move t))
4752 (while (setq e (pop eal))
4753 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4754 c (aref tag 0))
4755 (push (cons c (string-to-char (car e))) det)
4756 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4757 (substring tag 1)))))
4758 (setq det (nreverse det))
4759 (unless char
4760 (message "%s" (concat "Emphasis marker or tag:" prompt))
4761 (setq char (read-char-exclusive)))
4762 (setq char (or (cdr (assoc char det)) char))
4763 (if (equal char ?\ )
4764 (setq s "" move nil)
4765 (unless (assoc (char-to-string char) org-emphasis-alist)
4766 (error "No such emphasis marker: \"%c\"" char))
4767 (setq s (char-to-string char)))
4768 (while (and (> (length string) 1)
4769 (equal (substring string 0 1) (substring string -1))
4770 (assoc (substring string 0 1) org-emphasis-alist))
4771 (setq string (substring string 1 -1)))
4772 (setq string (concat s string s))
4773 (if beg (delete-region beg end))
4774 (unless (or (bolp)
4775 (string-match (concat "[" (nth 0 erc) "\n]")
4776 (char-to-string (char-before (point)))))
4777 (insert " "))
4778 (unless (or (eobp)
4779 (string-match (concat "[" (nth 1 erc) "\n]")
4780 (char-to-string (char-after (point)))))
4781 (insert " ") (backward-char 1))
4782 (insert string)
4783 (and move (backward-char 1))))
4785 (defconst org-nonsticky-props
4786 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4788 (defsubst org-rear-nonsticky-at (pos)
4789 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4791 (defun org-activate-plain-links (limit)
4792 "Run through the buffer and add overlays to links."
4793 (catch 'exit
4794 (let (f)
4795 (if (re-search-forward org-plain-link-re limit t)
4796 (progn
4797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4798 (setq f (get-text-property (match-beginning 0) 'face))
4799 (if (or (eq f 'org-tag)
4800 (and (listp f) (memq 'org-tag f)))
4802 (add-text-properties (match-beginning 0) (match-end 0)
4803 (list 'mouse-face 'highlight
4804 'face 'org-link
4805 'keymap org-mouse-map))
4806 (org-rear-nonsticky-at (match-end 0)))
4807 t)))))
4809 (defun org-activate-code (limit)
4810 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4811 (progn
4812 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4813 (remove-text-properties (match-beginning 0) (match-end 0)
4814 '(display t invisible t intangible t))
4815 t)))
4817 (defun org-fontify-meta-lines-and-blocks (limit)
4818 "Fontify #+ lines and blocks, in the correct ways."
4819 (let ((case-fold-search t))
4820 (if (re-search-forward
4821 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4822 limit t)
4823 (let ((beg (match-beginning 0))
4824 (beg1 (line-beginning-position 2))
4825 (dc1 (downcase (match-string 2)))
4826 (dc3 (downcase (match-string 3)))
4827 end end1 quoting block-type)
4828 (cond
4829 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4830 ;; a single line of backend-specific content
4831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4832 (remove-text-properties (match-beginning 0) (match-end 0)
4833 '(display t invisible t intangible t))
4834 (add-text-properties (match-beginning 1) (match-end 3)
4835 '(font-lock-fontified t face org-meta-line))
4836 (add-text-properties (match-beginning 6) (match-end 6)
4837 '(font-lock-fontified t face org-block))
4839 ((and (match-end 4) (equal dc3 "begin"))
4840 ;; Truly a block
4841 (setq block-type (downcase (match-string 5))
4842 quoting (member block-type org-protecting-blocks))
4843 (when (re-search-forward
4844 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4845 nil t) ;; on purpose, we look further than LIMIT
4846 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4847 (when quoting
4848 (remove-text-properties beg end
4849 '(display t invisible t intangible t)))
4850 (add-text-properties
4851 beg end
4852 '(font-lock-fontified t font-lock-multiline t))
4853 (add-text-properties beg beg1 '(face org-meta-line))
4854 (add-text-properties end1 end '(face org-meta-line))
4855 (cond
4856 (quoting
4857 (add-text-properties beg1 end1 '(face org-block)))
4858 ((not org-fontify-quote-and-verse-blocks))
4859 ((string= block-type "quote")
4860 (add-text-properties beg1 end1 '(face org-quote)))
4861 ((string= block-type "verse")
4862 (add-text-properties beg1 end1 '(face org-verse))))
4864 ((member dc1 '("title:" "author:" "email:" "date:"))
4865 (add-text-properties
4866 beg (match-end 3)
4867 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4868 '(font-lock-fontified t invisible t)
4869 '(font-lock-fontified t face org-document-info-keyword)))
4870 (add-text-properties
4871 (match-beginning 6) (match-end 6)
4872 (if (string-equal dc1 "title:")
4873 '(font-lock-fontified t face org-document-title)
4874 '(font-lock-fontified t face org-document-info))))
4875 ((not (member (char-after beg) '(?\ ?\t)))
4876 ;; just any other in-buffer setting, but not indented
4877 (add-text-properties
4878 beg (match-end 0)
4879 '(font-lock-fontified t face org-meta-line))
4881 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4882 "orgtbl:" "tblfm:" "tblname:"))
4883 (and (match-end 4) (equal dc3 "attr")))
4884 (add-text-properties
4885 beg (match-end 0)
4886 '(font-lock-fontified t face org-meta-line))
4888 ((member dc3 '(" " ""))
4889 (add-text-properties
4890 beg (match-end 0)
4891 '(font-lock-fontified t face font-lock-comment-face)))
4892 (t nil))))))
4894 (defun org-activate-angle-links (limit)
4895 "Run through the buffer and add overlays to links."
4896 (if (re-search-forward org-angle-link-re limit t)
4897 (progn
4898 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4899 (add-text-properties (match-beginning 0) (match-end 0)
4900 (list 'mouse-face 'highlight
4901 'keymap org-mouse-map))
4902 (org-rear-nonsticky-at (match-end 0))
4903 t)))
4905 (defun org-activate-footnote-links (limit)
4906 "Run through the buffer and add overlays to links."
4907 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4908 limit t)
4909 (progn
4910 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4911 (add-text-properties (match-beginning 2) (match-end 2)
4912 (list 'mouse-face 'highlight
4913 'keymap org-mouse-map
4914 'help-echo
4915 (if (= (point-at-bol) (match-beginning 2))
4916 "Footnote definition"
4917 "Footnote reference")
4919 (org-rear-nonsticky-at (match-end 2))
4920 t)))
4922 (defun org-activate-bracket-links (limit)
4923 "Run through the buffer and add overlays to bracketed links."
4924 (if (re-search-forward org-bracket-link-regexp limit t)
4925 (let* ((help (concat "LINK: "
4926 (org-match-string-no-properties 1)))
4927 ;; FIXME: above we should remove the escapes.
4928 ;; but that requires another match, protecting match data,
4929 ;; a lot of overhead for font-lock.
4930 (ip (org-maybe-intangible
4931 (list 'invisible 'org-link
4932 'keymap org-mouse-map 'mouse-face 'highlight
4933 'font-lock-multiline t 'help-echo help)))
4934 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4935 'font-lock-multiline t 'help-echo help)))
4936 ;; We need to remove the invisible property here. Table narrowing
4937 ;; may have made some of this invisible.
4938 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4939 (remove-text-properties (match-beginning 0) (match-end 0)
4940 '(invisible nil))
4941 (if (match-end 3)
4942 (progn
4943 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4944 (org-rear-nonsticky-at (match-beginning 3))
4945 (add-text-properties (match-beginning 3) (match-end 3) vp)
4946 (org-rear-nonsticky-at (match-end 3))
4947 (add-text-properties (match-end 3) (match-end 0) ip)
4948 (org-rear-nonsticky-at (match-end 0)))
4949 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4950 (org-rear-nonsticky-at (match-beginning 1))
4951 (add-text-properties (match-beginning 1) (match-end 1) vp)
4952 (org-rear-nonsticky-at (match-end 1))
4953 (add-text-properties (match-end 1) (match-end 0) ip)
4954 (org-rear-nonsticky-at (match-end 0)))
4955 t)))
4957 (defun org-activate-dates (limit)
4958 "Run through the buffer and add overlays to dates."
4959 (if (re-search-forward org-tsr-regexp-both limit t)
4960 (progn
4961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4962 (add-text-properties (match-beginning 0) (match-end 0)
4963 (list 'mouse-face 'highlight
4964 'keymap org-mouse-map))
4965 (org-rear-nonsticky-at (match-end 0))
4966 (when org-display-custom-times
4967 (if (match-end 3)
4968 (org-display-custom-time (match-beginning 3) (match-end 3)))
4969 (org-display-custom-time (match-beginning 1) (match-end 1)))
4970 t)))
4972 (defvar org-target-link-regexp nil
4973 "Regular expression matching radio targets in plain text.")
4974 (make-variable-buffer-local 'org-target-link-regexp)
4975 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4976 "Regular expression matching a link target.")
4977 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4978 "Regular expression matching a radio target.")
4979 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4980 "Regular expression matching any target.")
4982 (defun org-activate-target-links (limit)
4983 "Run through the buffer and add overlays to target matches."
4984 (when org-target-link-regexp
4985 (let ((case-fold-search t))
4986 (if (re-search-forward org-target-link-regexp limit t)
4987 (progn
4988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4989 (add-text-properties (match-beginning 0) (match-end 0)
4990 (list 'mouse-face 'highlight
4991 'keymap org-mouse-map
4992 'help-echo "Radio target link"
4993 'org-linked-text t))
4994 (org-rear-nonsticky-at (match-end 0))
4995 t)))))
4997 (defun org-update-radio-target-regexp ()
4998 "Find all radio targets in this file and update the regular expression."
4999 (interactive)
5000 (when (memq 'radio org-activate-links)
5001 (setq org-target-link-regexp
5002 (org-make-target-link-regexp (org-all-targets 'radio)))
5003 (org-restart-font-lock)))
5005 (defun org-hide-wide-columns (limit)
5006 (let (s e)
5007 (setq s (text-property-any (point) (or limit (point-max))
5008 'org-cwidth t))
5009 (when s
5010 (setq e (next-single-property-change s 'org-cwidth))
5011 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5012 (goto-char e)
5013 t)))
5015 (defvar org-latex-and-specials-regexp nil
5016 "Regular expression for highlighting export special stuff.")
5017 (defvar org-match-substring-regexp)
5018 (defvar org-match-substring-with-braces-regexp)
5020 ;; This should be with the exporter code, but we also use if for font-locking
5021 (defconst org-export-html-special-string-regexps
5022 '(("\\\\-" . "&shy;")
5023 ("---\\([^-]\\)" . "&mdash;\\1")
5024 ("--\\([^-]\\)" . "&ndash;\\1")
5025 ("\\.\\.\\." . "&hellip;"))
5026 "Regular expressions for special string conversion.")
5029 (defun org-compute-latex-and-specials-regexp ()
5030 "Compute regular expression for stuff treated specially by exporters."
5031 (if (not org-highlight-latex-fragments-and-specials)
5032 (org-set-local 'org-latex-and-specials-regexp nil)
5033 (require 'org-exp)
5034 (let*
5035 ((matchers (plist-get org-format-latex-options :matchers))
5036 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5037 org-latex-regexps)))
5038 (org-export-allow-BIND nil)
5039 (options (org-combine-plists (org-default-export-plist)
5040 (org-infile-export-plist)))
5041 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5042 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5043 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5044 (org-export-html-expand (plist-get options :expand-quoted-html))
5045 (org-export-with-special-strings (plist-get options :special-strings))
5046 (re-sub
5047 (cond
5048 ((equal org-export-with-sub-superscripts '{})
5049 (list org-match-substring-with-braces-regexp))
5050 (org-export-with-sub-superscripts
5051 (list org-match-substring-regexp))
5052 (t nil)))
5053 (re-latex
5054 (if org-export-with-LaTeX-fragments
5055 (mapcar (lambda (x) (nth 1 x)) latexs)))
5056 (re-macros
5057 (if org-export-with-TeX-macros
5058 (list (concat "\\\\"
5059 (regexp-opt
5060 (append (mapcar 'car (append org-entities-user
5061 org-entities))
5062 (if (boundp 'org-latex-entities)
5063 (mapcar (lambda (x)
5064 (or (car-safe x) x))
5065 org-latex-entities)
5066 nil))
5067 'words))) ; FIXME
5069 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5070 (re-special (if org-export-with-special-strings
5071 (mapcar (lambda (x) (car x))
5072 org-export-html-special-string-regexps)))
5073 (re-rest
5074 (delq nil
5075 (list
5076 (if org-export-html-expand "@<[^>\n]+>")
5077 ))))
5078 (org-set-local
5079 'org-latex-and-specials-regexp
5080 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5081 re-rest) "\\|")))))
5083 (defun org-do-latex-and-special-faces (limit)
5084 "Run through the buffer and add overlays to links."
5085 (when org-latex-and-specials-regexp
5086 (let (rtn d)
5087 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5088 limit t))
5089 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5090 'face))
5091 '(org-code org-verbatim underline)))
5092 (progn
5093 (setq rtn t
5094 d (cond ((member (char-after (1+ (match-beginning 0)))
5095 '(?_ ?^)) 1)
5096 (t 0)))
5097 (font-lock-prepend-text-property
5098 (+ d (match-beginning 0)) (match-end 0)
5099 'face 'org-latex-and-export-specials)
5100 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5101 '(font-lock-multiline t)))))
5102 rtn)))
5104 (defun org-restart-font-lock ()
5105 "Restart font-lock-mode, to force refontification."
5106 (when (and (boundp 'font-lock-mode) font-lock-mode)
5107 (font-lock-mode -1)
5108 (font-lock-mode 1)))
5110 (defun org-all-targets (&optional radio)
5111 "Return a list of all targets in this file.
5112 With optional argument RADIO, only find radio targets."
5113 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5114 rtn)
5115 (save-excursion
5116 (goto-char (point-min))
5117 (while (re-search-forward re nil t)
5118 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5119 rtn)))
5121 (defun org-make-target-link-regexp (targets)
5122 "Make regular expression matching all strings in TARGETS.
5123 The regular expression finds the targets also if there is a line break
5124 between words."
5125 (and targets
5126 (concat
5127 "\\<\\("
5128 (mapconcat
5129 (lambda (x)
5130 (while (string-match " +" x)
5131 (setq x (replace-match "\\s-+" t t x)))
5133 targets
5134 "\\|")
5135 "\\)\\>")))
5137 (defun org-activate-tags (limit)
5138 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5139 (progn
5140 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5141 (add-text-properties (match-beginning 1) (match-end 1)
5142 (list 'mouse-face 'highlight
5143 'keymap org-mouse-map))
5144 (org-rear-nonsticky-at (match-end 1))
5145 t)))
5147 (defun org-outline-level ()
5148 "Compute the outline level of the heading at point.
5149 This function assumes that the cursor is at the beginning of a line matched
5150 by outline-regexp. Otherwise it returns garbage.
5151 If this is called at a normal headline, the level is the number of stars.
5152 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5153 For plain list items, if they are matched by `outline-regexp', this returns
5154 1000 plus the line indentation."
5155 (save-excursion
5156 (looking-at outline-regexp)
5157 (if (match-beginning 1)
5158 (+ (org-get-string-indentation (match-string 1)) 1000)
5159 (1- (- (match-end 0) (match-beginning 0))))))
5161 (defvar org-font-lock-keywords nil)
5163 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5164 "Regular expression matching a property line.")
5166 (defvar org-font-lock-hook nil
5167 "Functions to be called for special font lock stuff.")
5169 (defun org-font-lock-hook (limit)
5170 (run-hook-with-args 'org-font-lock-hook limit))
5172 (defun org-set-font-lock-defaults ()
5173 (let* ((em org-fontify-emphasized-text)
5174 (lk org-activate-links)
5175 (org-font-lock-extra-keywords
5176 (list
5177 ;; Call the hook
5178 '(org-font-lock-hook)
5179 ;; Headlines
5180 `(,(if org-fontify-whole-heading-line
5181 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5182 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5183 (1 (org-get-level-face 1))
5184 (2 (org-get-level-face 2))
5185 (3 (org-get-level-face 3)))
5186 ;; Table lines
5187 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5188 (1 'org-table t))
5189 ;; Table internals
5190 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5191 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5192 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5193 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5194 ;; Drawers
5195 (list org-drawer-regexp '(0 'org-special-keyword t))
5196 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5197 ;; Properties
5198 (list org-property-re
5199 '(1 'org-special-keyword t)
5200 '(3 'org-property-value t))
5201 ;; Links
5202 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5203 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5204 (if (memq 'plain lk) '(org-activate-plain-links))
5205 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5206 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5207 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5208 (if (memq 'footnote lk) '(org-activate-footnote-links
5209 (2 'org-footnote t)))
5210 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5211 '(org-hide-wide-columns (0 nil append))
5212 ;; TODO lines
5213 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5214 '(1 (org-get-todo-face 1) t))
5215 ;; DONE
5216 (if org-fontify-done-headline
5217 (list (concat "^[*]+ +\\<\\("
5218 (mapconcat 'regexp-quote org-done-keywords "\\|")
5219 "\\)\\(.*\\)")
5220 '(2 'org-headline-done t))
5221 nil)
5222 ;; Priorities
5223 '(org-font-lock-add-priority-faces)
5224 ;; Tags
5225 '(org-font-lock-add-tag-faces)
5226 ;; Special keywords
5227 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5228 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5229 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5230 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5231 ;; Emphasis
5232 (if em
5233 (if (featurep 'xemacs)
5234 '(org-do-emphasis-faces (0 nil append))
5235 '(org-do-emphasis-faces)))
5236 ;; Checkboxes
5237 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5238 2 'org-checkbox prepend)
5239 (if org-provide-checkbox-statistics
5240 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5241 (0 (org-get-checkbox-statistics-face) t)))
5242 ;; Description list items
5243 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5244 2 'bold prepend)
5245 ;; ARCHIVEd headings
5246 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5247 '(1 'org-archived prepend))
5248 ;; Specials
5249 '(org-do-latex-and-special-faces)
5250 '(org-fontify-entities)
5251 ;; Code
5252 '(org-activate-code (1 'org-code t))
5253 ;; COMMENT
5254 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5255 "\\|" org-quote-string "\\)\\>")
5256 '(1 'org-special-keyword t))
5257 '("^#.*" (0 'font-lock-comment-face t))
5258 ;; Blocks and meta lines
5259 '(org-fontify-meta-lines-and-blocks)
5261 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5262 ;; Now set the full font-lock-keywords
5263 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5264 (org-set-local 'font-lock-defaults
5265 '(org-font-lock-keywords t nil nil backward-paragraph))
5266 (kill-local-variable 'font-lock-keywords) nil))
5268 (defun org-toggle-pretty-entities ()
5269 "Toggle the compostion display of entities as UTF8 characters."
5270 (interactive)
5271 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5272 (org-restart-font-lock)
5273 (if org-pretty-entities
5274 (message "Entities are displayed as UTF8 characers")
5275 (save-restriction
5276 (widen)
5277 (decompose-region (point-min) (point-max))
5278 (message "Entities are displayed plain"))))
5280 (defun org-fontify-entities (limit)
5281 "Find an entity to fontify."
5282 (let (ee)
5283 (when org-pretty-entities
5284 (catch 'match
5285 (while (re-search-forward "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)[^[:alnum:]]"
5286 limit t)
5287 (if (and (setq ee (org-entity-get (match-string 1)))
5288 (= (length (nth 6 ee)) 1))
5289 (progn
5290 (add-text-properties
5291 (match-beginning 0) (match-end 1)
5292 (list 'font-lock-fontified t))
5293 (compose-region (match-beginning 0) (match-end 1)
5294 (nth 6 ee) nil)
5295 (backward-char 1)
5296 (throw 'match t))))
5297 nil))))
5299 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5300 "Fontify string S like in Org-mode"
5301 (with-temp-buffer
5302 (insert s)
5303 (let ((org-odd-levels-only odd-levels))
5304 (org-mode)
5305 (font-lock-fontify-buffer)
5306 (buffer-string))))
5308 (defvar org-m nil)
5309 (defvar org-l nil)
5310 (defvar org-f nil)
5311 (defun org-get-level-face (n)
5312 "Get the right face for match N in font-lock matching of headlines."
5313 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5314 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5315 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5316 (cond
5317 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5318 ((eq n 2) org-f)
5319 (t (if org-level-color-stars-only nil org-f))))
5321 (defun org-get-todo-face (kwd)
5322 "Get the right face for a TODO keyword KWD.
5323 If KWD is a number, get the corresponding match group."
5324 (if (numberp kwd) (setq kwd (match-string kwd)))
5325 (or (org-face-from-face-or-color
5326 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5327 (and (member kwd org-done-keywords) 'org-done)
5328 'org-todo))
5330 (defun org-face-from-face-or-color (context inherit face-or-color)
5331 "Create a face list that inherits INHERIT, but sets the foreground color.
5332 When FACE-OR-COLOR is not a string, just return it."
5333 (if (stringp face-or-color)
5334 (list :inherit inherit
5335 (cdr (assoc context org-faces-easy-properties))
5336 face-or-color)
5337 face-or-color))
5339 (defun org-font-lock-add-tag-faces (limit)
5340 "Add the special tag faces."
5341 (when (and org-tag-faces org-tags-special-faces-re)
5342 (while (re-search-forward org-tags-special-faces-re limit t)
5343 (add-text-properties (match-beginning 1) (match-end 1)
5344 (list 'face (org-get-tag-face 1)
5345 'font-lock-fontified t))
5346 (backward-char 1))))
5348 (defun org-font-lock-add-priority-faces (limit)
5349 "Add the special priority faces."
5350 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5351 (add-text-properties
5352 (match-beginning 0) (match-end 0)
5353 (list 'face (or (org-face-from-face-or-color
5354 'priority 'org-special-keyword
5355 (cdr (assoc (char-after (match-beginning 1))
5356 org-priority-faces)))
5357 'org-special-keyword)
5358 'font-lock-fontified t))))
5360 (defun org-get-tag-face (kwd)
5361 "Get the right face for a TODO keyword KWD.
5362 If KWD is a number, get the corresponding match group."
5363 (if (numberp kwd) (setq kwd (match-string kwd)))
5364 (or (org-face-from-face-or-color
5365 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5366 'org-tag))
5368 (defun org-unfontify-region (beg end &optional maybe_loudly)
5369 "Remove fontification and activation overlays from links."
5370 (font-lock-default-unfontify-region beg end)
5371 (let* ((buffer-undo-list t)
5372 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5373 (inhibit-modification-hooks t)
5374 deactivate-mark buffer-file-name buffer-file-truename)
5375 (remove-text-properties
5376 beg end
5377 (if org-indent-mode
5378 ;; also remove line-prefix and wrap-prefix properties
5379 '(mouse-face t keymap t org-linked-text t
5380 invisible t intangible t
5381 line-prefix t wrap-prefix t
5382 org-no-flyspell t)
5383 '(mouse-face t keymap t org-linked-text t
5384 invisible t intangible t
5385 org-no-flyspell t)))))
5387 ;;;; Visibility cycling, including org-goto and indirect buffer
5389 ;;; Cycling
5391 (defvar org-cycle-global-status nil)
5392 (make-variable-buffer-local 'org-cycle-global-status)
5393 (defvar org-cycle-subtree-status nil)
5394 (make-variable-buffer-local 'org-cycle-subtree-status)
5396 ;;;###autoload
5398 (defvar org-inlinetask-min-level)
5400 (defun org-cycle (&optional arg)
5401 "TAB-action and visibility cycling for Org-mode.
5403 This is the command invoked in Org-mode by the TAB key. Its main purpose
5404 is outline visibility cycling, but it also invokes other actions
5405 in special contexts.
5407 - When this function is called with a prefix argument, rotate the entire
5408 buffer through 3 states (global cycling)
5409 1. OVERVIEW: Show only top-level headlines.
5410 2. CONTENTS: Show all headlines of all levels, but no body text.
5411 3. SHOW ALL: Show everything.
5412 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5413 determined by the variable `org-startup-folded', and by any VISIBILITY
5414 properties in the buffer.
5415 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5416 including any drawers.
5418 - When inside a table, re-align the table and move to the next field.
5420 - When point is at the beginning of a headline, rotate the subtree started
5421 by this line through 3 different states (local cycling)
5422 1. FOLDED: Only the main headline is shown.
5423 2. CHILDREN: The main headline and the direct children are shown.
5424 From this state, you can move to one of the children
5425 and zoom in further.
5426 3. SUBTREE: Show the entire subtree, including body text.
5427 If there is no subtree, switch directly from CHILDREN to FOLDED.
5429 - When point is at the beginning of an empty headline and the variable
5430 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5431 of the headline by demoting and promoting it to likely levels. This
5432 speeds up creation document structure by presing TAB once or several
5433 times right after creating a new headline.
5435 - When there is a numeric prefix, go up to a heading with level ARG, do
5436 a `show-subtree' and return to the previous cursor position. If ARG
5437 is negative, go up that many levels.
5439 - When point is not at the beginning of a headline, execute the global
5440 binding for TAB, which is re-indenting the line. See the option
5441 `org-cycle-emulate-tab' for details.
5443 - Special case: if point is at the beginning of the buffer and there is
5444 no headline in line 1, this function will act as if called with prefix arg.
5445 But only if also the variable `org-cycle-global-at-bob' is t."
5446 (interactive "P")
5447 (org-load-modules-maybe)
5448 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5449 (and org-cycle-level-after-item/entry-creation
5450 (or (org-cycle-level)
5451 (org-cycle-item-indentation))))
5452 (let* ((limit-level
5453 (or org-cycle-max-level
5454 (and (boundp 'org-inlinetask-min-level)
5455 org-inlinetask-min-level
5456 (1- org-inlinetask-min-level))))
5457 (nstars (and limit-level
5458 (if org-odd-levels-only
5459 (and limit-level (1- (* limit-level 2)))
5460 limit-level)))
5461 (outline-regexp
5462 (cond
5463 ((not (org-mode-p)) outline-regexp)
5464 ((or (eq org-cycle-include-plain-lists 'integrate)
5465 (and org-cycle-include-plain-lists (org-at-item-p)))
5466 (concat "\\(?:\\*"
5467 (if nstars (format "\\{1,%d\\}" nstars) "+")
5468 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5469 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5470 (bob-special (and org-cycle-global-at-bob (bobp)
5471 (not (looking-at outline-regexp))))
5472 (org-cycle-hook
5473 (if bob-special
5474 (delq 'org-optimize-window-after-visibility-change
5475 (copy-sequence org-cycle-hook))
5476 org-cycle-hook))
5477 (pos (point)))
5479 (if (or bob-special (equal arg '(4)))
5480 ;; special case: use global cycling
5481 (setq arg t))
5483 (cond
5485 ((equal arg '(16))
5486 (org-set-startup-visibility)
5487 (message "Startup visibility, plus VISIBILITY properties"))
5489 ((equal arg '(64))
5490 (show-all)
5491 (message "Entire buffer visible, including drawers"))
5493 ((org-at-table-p 'any)
5494 ;; Enter the table or move to the next field in the table
5495 (if (org-at-table.el-p)
5496 (message "Use C-c ' to edit table.el tables")
5497 (if arg (org-table-edit-field t)
5498 (org-table-justify-field-maybe)
5499 (call-interactively 'org-table-next-field))))
5501 ((run-hook-with-args-until-success
5502 'org-tab-after-check-for-table-hook))
5504 ((eq arg t) ;; Global cycling
5505 (org-cycle-internal-global))
5507 ((and org-drawers org-drawer-regexp
5508 (save-excursion
5509 (beginning-of-line 1)
5510 (looking-at org-drawer-regexp)))
5511 ;; Toggle block visibility
5512 (org-flag-drawer
5513 (not (get-char-property (match-end 0) 'invisible))))
5515 ((integerp arg)
5516 ;; Show-subtree, ARG levels up from here.
5517 (save-excursion
5518 (org-back-to-heading)
5519 (outline-up-heading (if (< arg 0) (- arg)
5520 (- (funcall outline-level) arg)))
5521 (org-show-subtree)))
5523 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5524 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5526 (org-cycle-internal-local))
5528 ;; TAB emulation and template completion
5529 (buffer-read-only (org-back-to-heading))
5531 ((run-hook-with-args-until-success
5532 'org-tab-after-check-for-cycling-hook))
5534 ((org-try-structure-completion))
5536 ((org-try-cdlatex-tab))
5538 ((run-hook-with-args-until-success
5539 'org-tab-before-tab-emulation-hook))
5541 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5542 (or (not (bolp))
5543 (not (looking-at outline-regexp))))
5544 (call-interactively (global-key-binding "\t")))
5546 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5547 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5548 (or (and (eq org-cycle-emulate-tab 'white)
5549 (= (match-end 0) (point-at-eol)))
5550 (and (eq org-cycle-emulate-tab 'whitestart)
5551 (>= (match-end 0) pos))))
5553 (eq org-cycle-emulate-tab t))
5554 (call-interactively (global-key-binding "\t")))
5556 (t (save-excursion
5557 (org-back-to-heading)
5558 (org-cycle)))))))
5560 (defun org-cycle-internal-global ()
5561 "Do the global cycling action."
5562 (cond
5563 ((and (eq last-command this-command)
5564 (eq org-cycle-global-status 'overview))
5565 ;; We just created the overview - now do table of contents
5566 ;; This can be slow in very large buffers, so indicate action
5567 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5568 (message "CONTENTS...")
5569 (org-content)
5570 (message "CONTENTS...done")
5571 (setq org-cycle-global-status 'contents)
5572 (run-hook-with-args 'org-cycle-hook 'contents))
5574 ((and (eq last-command this-command)
5575 (eq org-cycle-global-status 'contents))
5576 ;; We just showed the table of contents - now show everything
5577 (run-hook-with-args 'org-pre-cycle-hook 'all)
5578 (show-all)
5579 (message "SHOW ALL")
5580 (setq org-cycle-global-status 'all)
5581 (run-hook-with-args 'org-cycle-hook 'all))
5584 ;; Default action: go to overview
5585 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5586 (org-overview)
5587 (message "OVERVIEW")
5588 (setq org-cycle-global-status 'overview)
5589 (run-hook-with-args 'org-cycle-hook 'overview))))
5591 (defun org-cycle-internal-local ()
5592 "Do the local cycling action."
5593 (org-back-to-heading)
5594 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5595 ;; First, some boundaries
5596 (save-excursion
5597 (org-back-to-heading)
5598 (setq level (funcall outline-level))
5599 (save-excursion
5600 (beginning-of-line 2)
5601 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5602 ; XEmacs does not have `next-single-char-property-change'
5603 ; I'm not sure about Emacs 21.
5604 (while (and (not (eobp)) ;; this is like `next-line'
5605 (get-char-property (1- (point)) 'invisible))
5606 (beginning-of-line 2))
5607 (while (and (not (eobp)) ;; this is like `next-line'
5608 (get-char-property (1- (point)) 'invisible))
5609 (goto-char (next-single-char-property-change (point) 'invisible))
5610 (and (eolp) (beginning-of-line 2))))
5611 (setq eol (point)))
5612 (outline-end-of-heading) (setq eoh (point))
5613 (save-excursion
5614 (outline-next-heading)
5615 (setq has-children (and (org-at-heading-p t)
5616 (> (funcall outline-level) level))))
5617 (org-end-of-subtree t)
5618 (unless (eobp)
5619 (skip-chars-forward " \t\n")
5620 (beginning-of-line 1) ; in case this is an item
5622 (setq eos (if (eobp) (point) (1- (point)))))
5623 ;; Find out what to do next and set `this-command'
5624 (cond
5625 ((= eos eoh)
5626 ;; Nothing is hidden behind this heading
5627 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5628 (message "EMPTY ENTRY")
5629 (setq org-cycle-subtree-status nil)
5630 (save-excursion
5631 (goto-char eos)
5632 (outline-next-heading)
5633 (if (org-invisible-p) (org-flag-heading nil))))
5634 ((and (or (>= eol eos)
5635 (not (string-match "\\S-" (buffer-substring eol eos))))
5636 (or has-children
5637 (not (setq children-skipped
5638 org-cycle-skip-children-state-if-no-children))))
5639 ;; Entire subtree is hidden in one line: children view
5640 (run-hook-with-args 'org-pre-cycle-hook 'children)
5641 (org-show-entry)
5642 (show-children)
5643 (message "CHILDREN")
5644 (save-excursion
5645 (goto-char eos)
5646 (outline-next-heading)
5647 (if (org-invisible-p) (org-flag-heading nil)))
5648 (setq org-cycle-subtree-status 'children)
5649 (run-hook-with-args 'org-cycle-hook 'children))
5650 ((or children-skipped
5651 (and (eq last-command this-command)
5652 (eq org-cycle-subtree-status 'children)))
5653 ;; We just showed the children, or no children are there,
5654 ;; now show everything.
5655 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5656 (org-show-subtree)
5657 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5658 (setq org-cycle-subtree-status 'subtree)
5659 (run-hook-with-args 'org-cycle-hook 'subtree))
5661 ;; Default action: hide the subtree.
5662 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5663 (hide-subtree)
5664 (message "FOLDED")
5665 (setq org-cycle-subtree-status 'folded)
5666 (run-hook-with-args 'org-cycle-hook 'folded)))))
5668 ;;;###autoload
5669 (defun org-global-cycle (&optional arg)
5670 "Cycle the global visibility. For details see `org-cycle'.
5671 With C-u prefix arg, switch to startup visibility.
5672 With a numeric prefix, show all headlines up to that level."
5673 (interactive "P")
5674 (let ((org-cycle-include-plain-lists
5675 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5676 (cond
5677 ((integerp arg)
5678 (show-all)
5679 (hide-sublevels arg)
5680 (setq org-cycle-global-status 'contents))
5681 ((equal arg '(4))
5682 (org-set-startup-visibility)
5683 (message "Startup visibility, plus VISIBILITY properties."))
5685 (org-cycle '(4))))))
5687 (defun org-set-startup-visibility ()
5688 "Set the visibility required by startup options and properties."
5689 (cond
5690 ((eq org-startup-folded t)
5691 (org-cycle '(4)))
5692 ((eq org-startup-folded 'content)
5693 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5694 (org-cycle '(4)) (org-cycle '(4)))))
5695 (unless (eq org-startup-folded 'showeverything)
5696 (if org-hide-block-startup (org-hide-block-all))
5697 (org-set-visibility-according-to-property 'no-cleanup)
5698 (org-cycle-hide-archived-subtrees 'all)
5699 (org-cycle-hide-drawers 'all)
5700 (org-cycle-show-empty-lines t)))
5702 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5703 "Switch subtree visibilities according to :VISIBILITY: property."
5704 (interactive)
5705 (let (org-show-entry-below state)
5706 (save-excursion
5707 (goto-char (point-min))
5708 (while (re-search-forward
5709 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5710 nil t)
5711 (setq state (match-string 1))
5712 (save-excursion
5713 (org-back-to-heading t)
5714 (hide-subtree)
5715 (org-reveal)
5716 (cond
5717 ((equal state '("fold" "folded"))
5718 (hide-subtree))
5719 ((equal state "children")
5720 (org-show-hidden-entry)
5721 (show-children))
5722 ((equal state "content")
5723 (save-excursion
5724 (save-restriction
5725 (org-narrow-to-subtree)
5726 (org-content))))
5727 ((member state '("all" "showall"))
5728 (show-subtree)))))
5729 (unless no-cleanup
5730 (org-cycle-hide-archived-subtrees 'all)
5731 (org-cycle-hide-drawers 'all)
5732 (org-cycle-show-empty-lines 'all)))))
5734 (defun org-overview ()
5735 "Switch to overview mode, showing only top-level headlines.
5736 Really, this shows all headlines with level equal or greater than the level
5737 of the first headline in the buffer. This is important, because if the
5738 first headline is not level one, then (hide-sublevels 1) gives confusing
5739 results."
5740 (interactive)
5741 (let ((level (save-excursion
5742 (goto-char (point-min))
5743 (if (re-search-forward (concat "^" outline-regexp) nil t)
5744 (progn
5745 (goto-char (match-beginning 0))
5746 (funcall outline-level))))))
5747 (and level (hide-sublevels level))))
5749 (defun org-content (&optional arg)
5750 "Show all headlines in the buffer, like a table of contents.
5751 With numerical argument N, show content up to level N."
5752 (interactive "P")
5753 (save-excursion
5754 ;; Visit all headings and show their offspring
5755 (and (integerp arg) (org-overview))
5756 (goto-char (point-max))
5757 (catch 'exit
5758 (while (and (progn (condition-case nil
5759 (outline-previous-visible-heading 1)
5760 (error (goto-char (point-min))))
5762 (looking-at outline-regexp))
5763 (if (integerp arg)
5764 (show-children (1- arg))
5765 (show-branches))
5766 (if (bobp) (throw 'exit nil))))))
5769 (defun org-optimize-window-after-visibility-change (state)
5770 "Adjust the window after a change in outline visibility.
5771 This function is the default value of the hook `org-cycle-hook'."
5772 (when (get-buffer-window (current-buffer))
5773 (cond
5774 ((eq state 'content) nil)
5775 ((eq state 'all) nil)
5776 ((eq state 'folded) nil)
5777 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5778 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5780 (defun org-remove-empty-overlays-at (pos)
5781 "Remove outline overlays that do not contain non-white stuff."
5782 (mapc
5783 (lambda (o)
5784 (and (eq 'outline (overlay-get o 'invisible))
5785 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5786 (overlay-end o))))
5787 (delete-overlay o)))
5788 (overlays-at pos)))
5790 (defun org-clean-visibility-after-subtree-move ()
5791 "Fix visibility issues after moving a subtree."
5792 ;; First, find a reasonable region to look at:
5793 ;; Start two siblings above, end three below
5794 (let* ((beg (save-excursion
5795 (and (org-get-last-sibling)
5796 (org-get-last-sibling))
5797 (point)))
5798 (end (save-excursion
5799 (and (org-get-next-sibling)
5800 (org-get-next-sibling)
5801 (org-get-next-sibling))
5802 (if (org-at-heading-p)
5803 (point-at-eol)
5804 (point))))
5805 (level (looking-at "\\*+"))
5806 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5807 (save-excursion
5808 (save-restriction
5809 (narrow-to-region beg end)
5810 (when re
5811 ;; Properly fold already folded siblings
5812 (goto-char (point-min))
5813 (while (re-search-forward re nil t)
5814 (if (and (not (org-invisible-p))
5815 (save-excursion
5816 (goto-char (point-at-eol)) (org-invisible-p)))
5817 (hide-entry))))
5818 (org-cycle-show-empty-lines 'overview)
5819 (org-cycle-hide-drawers 'overview)))))
5821 (defun org-cycle-show-empty-lines (state)
5822 "Show empty lines above all visible headlines.
5823 The region to be covered depends on STATE when called through
5824 `org-cycle-hook'. Lisp program can use t for STATE to get the
5825 entire buffer covered. Note that an empty line is only shown if there
5826 are at least `org-cycle-separator-lines' empty lines before the headline."
5827 (when (not (= org-cycle-separator-lines 0))
5828 (save-excursion
5829 (let* ((n (abs org-cycle-separator-lines))
5830 (re (cond
5831 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5832 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5833 (t (let ((ns (number-to-string (- n 2))))
5834 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5835 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5836 beg end b e)
5837 (cond
5838 ((memq state '(overview contents t))
5839 (setq beg (point-min) end (point-max)))
5840 ((memq state '(children folded))
5841 (setq beg (point) end (progn (org-end-of-subtree t t)
5842 (beginning-of-line 2)
5843 (point)))))
5844 (when beg
5845 (goto-char beg)
5846 (while (re-search-forward re end t)
5847 (unless (get-char-property (match-end 1) 'invisible)
5848 (setq e (match-end 1))
5849 (if (< org-cycle-separator-lines 0)
5850 (setq b (save-excursion
5851 (goto-char (match-beginning 0))
5852 (org-back-over-empty-lines)
5853 (if (save-excursion
5854 (goto-char (max (point-min) (1- (point))))
5855 (org-on-heading-p))
5856 (1- (point))
5857 (point))))
5858 (setq b (match-beginning 1)))
5859 (outline-flag-region b e nil)))))))
5860 ;; Never hide empty lines at the end of the file.
5861 (save-excursion
5862 (goto-char (point-max))
5863 (outline-previous-heading)
5864 (outline-end-of-heading)
5865 (if (and (looking-at "[ \t\n]+")
5866 (= (match-end 0) (point-max)))
5867 (outline-flag-region (point) (match-end 0) nil))))
5869 (defun org-show-empty-lines-in-parent ()
5870 "Move to the parent and re-show empty lines before visible headlines."
5871 (save-excursion
5872 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5873 (org-cycle-show-empty-lines context))))
5875 (defun org-files-list ()
5876 "Return `org-agenda-files' list, plus all open org-mode files.
5877 This is useful for operations that need to scan all of a user's
5878 open and agenda-wise Org files."
5879 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5880 (dolist (buf (buffer-list))
5881 (with-current-buffer buf
5882 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5883 (let ((file (expand-file-name (buffer-file-name))))
5884 (unless (member file files)
5885 (push file files))))))
5886 files))
5888 (defsubst org-entry-beginning-position ()
5889 "Return the beginning position of the current entry."
5890 (save-excursion (outline-back-to-heading t) (point)))
5892 (defsubst org-entry-end-position ()
5893 "Return the end position of the current entry."
5894 (save-excursion (outline-next-heading) (point)))
5896 (defun org-cycle-hide-drawers (state)
5897 "Re-hide all drawers after a visibility state change."
5898 (when (and (org-mode-p)
5899 (not (memq state '(overview folded contents))))
5900 (save-excursion
5901 (let* ((globalp (memq state '(contents all)))
5902 (beg (if globalp (point-min) (point)))
5903 (end (if globalp (point-max)
5904 (if (eq state 'children)
5905 (save-excursion (outline-next-heading) (point))
5906 (org-end-of-subtree t)))))
5907 (goto-char beg)
5908 (while (re-search-forward org-drawer-regexp end t)
5909 (org-flag-drawer t))))))
5911 (defun org-flag-drawer (flag)
5912 (save-excursion
5913 (beginning-of-line 1)
5914 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5915 (let ((b (match-end 0))
5916 (outline-regexp org-outline-regexp))
5917 (if (re-search-forward
5918 "^[ \t]*:END:"
5919 (save-excursion (outline-next-heading) (point)) t)
5920 (outline-flag-region b (point-at-eol) flag)
5921 (error ":END: line missing at position %s" b))))))
5923 (defun org-subtree-end-visible-p ()
5924 "Is the end of the current subtree visible?"
5925 (pos-visible-in-window-p
5926 (save-excursion (org-end-of-subtree t) (point))))
5928 (defun org-first-headline-recenter (&optional N)
5929 "Move cursor to the first headline and recenter the headline.
5930 Optional argument N means put the headline into the Nth line of the window."
5931 (goto-char (point-min))
5932 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5933 (beginning-of-line)
5934 (recenter (prefix-numeric-value N))))
5936 ;;; Saving and restoring visibility
5938 (defun org-outline-overlay-data (&optional use-markers)
5939 "Return a list of the locations of all outline overlays.
5940 The are overlays with the `invisible' property value `outline'.
5941 The return valus is a list of cons cells, with start and stop
5942 positions for each overlay.
5943 If USE-MARKERS is set, return the positions as markers."
5944 (let (beg end)
5945 (save-excursion
5946 (save-restriction
5947 (widen)
5948 (delq nil
5949 (mapcar (lambda (o)
5950 (when (eq (overlay-get o 'invisible) 'outline)
5951 (setq beg (overlay-start o)
5952 end (overlay-end o))
5953 (and beg end (> end beg)
5954 (if use-markers
5955 (cons (move-marker (make-marker) beg)
5956 (move-marker (make-marker) end))
5957 (cons beg end)))))
5958 (overlays-in (point-min) (point-max))))))))
5960 (defun org-set-outline-overlay-data (data)
5961 "Create visibility overlays for all positions in DATA.
5962 DATA should have been made by `org-outline-overlay-data'."
5963 (let (o)
5964 (save-excursion
5965 (save-restriction
5966 (widen)
5967 (show-all)
5968 (mapc (lambda (c)
5969 (setq o (make-overlay (car c) (cdr c)))
5970 (overlay-put o 'invisible 'outline))
5971 data)))))
5973 (defmacro org-save-outline-visibility (use-markers &rest body)
5974 "Save and restore outline visibility around BODY.
5975 If USE-MARKERS is non-nil, use markers for the positions.
5976 This means that the buffer may change while running BODY,
5977 but it also means that the buffer should stay alive
5978 during the operation, because otherwise all these markers will
5979 point nowhere."
5980 `(let ((data (org-outline-overlay-data ,use-markers)))
5981 (unwind-protect
5982 (progn
5983 ,@body
5984 (org-set-outline-overlay-data data))
5985 (when ,use-markers
5986 (mapc (lambda (c)
5987 (and (markerp (car c)) (move-marker (car c) nil))
5988 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5989 data)))))
5992 ;;; Folding of blocks
5994 (defconst org-block-regexp
5996 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5997 "Regular expression for hiding blocks.")
5999 (defvar org-hide-block-overlays nil
6000 "Overlays hiding blocks.")
6001 (make-variable-buffer-local 'org-hide-block-overlays)
6003 (defun org-block-map (function &optional start end)
6004 "Call func at the head of all source blocks in the current
6005 buffer. Optional arguments START and END can be used to limit
6006 the range."
6007 (let ((start (or start (point-min)))
6008 (end (or end (point-max))))
6009 (save-excursion
6010 (goto-char start)
6011 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6012 (save-excursion
6013 (save-match-data
6014 (goto-char (match-beginning 0))
6015 (funcall function)))))))
6017 (defun org-hide-block-toggle-all ()
6018 "Toggle the visibility of all blocks in the current buffer."
6019 (org-block-map #'org-hide-block-toggle))
6021 (defun org-hide-block-all ()
6022 "Fold all blocks in the current buffer."
6023 (interactive)
6024 (org-show-block-all)
6025 (org-block-map #'org-hide-block-toggle-maybe))
6027 (defun org-show-block-all ()
6028 "Unfold all blocks in the current buffer."
6029 (mapc 'delete-overlay org-hide-block-overlays)
6030 (setq org-hide-block-overlays nil))
6032 (defun org-hide-block-toggle-maybe ()
6033 "Toggle visibility of block at point."
6034 (interactive)
6035 (let ((case-fold-search t))
6036 (if (save-excursion
6037 (beginning-of-line 1)
6038 (looking-at org-block-regexp))
6039 (progn (org-hide-block-toggle)
6040 t) ;; to signal that we took action
6041 nil))) ;; to signal that we did not
6043 (defun org-hide-block-toggle (&optional force)
6044 "Toggle the visibility of the current block."
6045 (interactive)
6046 (save-excursion
6047 (beginning-of-line)
6048 (if (re-search-forward org-block-regexp nil t)
6049 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6050 (end (match-end 0)) ;; end of entire body
6052 (if (memq t (mapcar (lambda (overlay)
6053 (eq (overlay-get overlay 'invisible)
6054 'org-hide-block))
6055 (overlays-at start)))
6056 (if (or (not force) (eq force 'off))
6057 (mapc (lambda (ov)
6058 (when (member ov org-hide-block-overlays)
6059 (setq org-hide-block-overlays
6060 (delq ov org-hide-block-overlays)))
6061 (when (eq (overlay-get ov 'invisible)
6062 'org-hide-block)
6063 (delete-overlay ov)))
6064 (overlays-at start)))
6065 (setq ov (make-overlay start end))
6066 (overlay-put ov 'invisible 'org-hide-block)
6067 ;; make the block accessible to isearch
6068 (overlay-put
6069 ov 'isearch-open-invisible
6070 (lambda (ov)
6071 (when (member ov org-hide-block-overlays)
6072 (setq org-hide-block-overlays
6073 (delq ov org-hide-block-overlays)))
6074 (when (eq (overlay-get ov 'invisible)
6075 'org-hide-block)
6076 (delete-overlay ov))))
6077 (push ov org-hide-block-overlays)))
6078 (error "Not looking at a source block"))))
6080 ;; org-tab-after-check-for-cycling-hook
6081 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6082 ;; Remove overlays when changing major mode
6083 (add-hook 'org-mode-hook
6084 (lambda () (org-add-hook 'change-major-mode-hook
6085 'org-show-block-all 'append 'local)))
6087 ;;; Org-goto
6089 (defvar org-goto-window-configuration nil)
6090 (defvar org-goto-marker nil)
6091 (defvar org-goto-map
6092 (let ((map (make-sparse-keymap)))
6093 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6094 (while (setq cmd (pop cmds))
6095 (substitute-key-definition cmd cmd map global-map)))
6096 (suppress-keymap map)
6097 (org-defkey map "\C-m" 'org-goto-ret)
6098 (org-defkey map [(return)] 'org-goto-ret)
6099 (org-defkey map [(left)] 'org-goto-left)
6100 (org-defkey map [(right)] 'org-goto-right)
6101 (org-defkey map [(control ?g)] 'org-goto-quit)
6102 (org-defkey map "\C-i" 'org-cycle)
6103 (org-defkey map [(tab)] 'org-cycle)
6104 (org-defkey map [(down)] 'outline-next-visible-heading)
6105 (org-defkey map [(up)] 'outline-previous-visible-heading)
6106 (if org-goto-auto-isearch
6107 (if (fboundp 'define-key-after)
6108 (define-key-after map [t] 'org-goto-local-auto-isearch)
6109 nil)
6110 (org-defkey map "q" 'org-goto-quit)
6111 (org-defkey map "n" 'outline-next-visible-heading)
6112 (org-defkey map "p" 'outline-previous-visible-heading)
6113 (org-defkey map "f" 'outline-forward-same-level)
6114 (org-defkey map "b" 'outline-backward-same-level)
6115 (org-defkey map "u" 'outline-up-heading))
6116 (org-defkey map "/" 'org-occur)
6117 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6118 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6119 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6120 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6121 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6122 map))
6124 (defconst org-goto-help
6125 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6126 RET=jump to location [Q]uit and return to previous location
6127 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6129 (defvar org-goto-start-pos) ; dynamically scoped parameter
6131 ;; FIXME: Docstring does not mention both interfaces
6132 (defun org-goto (&optional alternative-interface)
6133 "Look up a different location in the current file, keeping current visibility.
6135 When you want look-up or go to a different location in a document, the
6136 fastest way is often to fold the entire buffer and then dive into the tree.
6137 This method has the disadvantage, that the previous location will be folded,
6138 which may not be what you want.
6140 This command works around this by showing a copy of the current buffer
6141 in an indirect buffer, in overview mode. You can dive into the tree in
6142 that copy, use org-occur and incremental search to find a location.
6143 When pressing RET or `Q', the command returns to the original buffer in
6144 which the visibility is still unchanged. After RET is will also jump to
6145 the location selected in the indirect buffer and expose the
6146 the headline hierarchy above."
6147 (interactive "P")
6148 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6149 (org-refile-use-outline-path t)
6150 (org-refile-target-verify-function nil)
6151 (interface
6152 (if (not alternative-interface)
6153 org-goto-interface
6154 (if (eq org-goto-interface 'outline)
6155 'outline-path-completion
6156 'outline)))
6157 (org-goto-start-pos (point))
6158 (selected-point
6159 (if (eq interface 'outline)
6160 (car (org-get-location (current-buffer) org-goto-help))
6161 (nth 3 (org-refile-get-location "Goto: ")))))
6162 (if selected-point
6163 (progn
6164 (org-mark-ring-push org-goto-start-pos)
6165 (goto-char selected-point)
6166 (if (or (org-invisible-p) (org-invisible-p2))
6167 (org-show-context 'org-goto)))
6168 (message "Quit"))))
6170 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6171 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6172 (defvar org-goto-local-auto-isearch-map) ; defined below
6174 (defun org-get-location (buf help)
6175 "Let the user select a location in the Org-mode buffer BUF.
6176 This function uses a recursive edit. It returns the selected position
6177 or nil."
6178 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6179 (isearch-hide-immediately nil)
6180 (isearch-search-fun-function
6181 (lambda () 'org-goto-local-search-headings))
6182 (org-goto-selected-point org-goto-exit-command)
6183 (pop-up-frames nil)
6184 (special-display-buffer-names nil)
6185 (special-display-regexps nil)
6186 (special-display-function nil))
6187 (save-excursion
6188 (save-window-excursion
6189 (delete-other-windows)
6190 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6191 (switch-to-buffer
6192 (condition-case nil
6193 (make-indirect-buffer (current-buffer) "*org-goto*")
6194 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6195 (with-output-to-temp-buffer "*Help*"
6196 (princ help))
6197 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6198 (setq buffer-read-only nil)
6199 (let ((org-startup-truncated t)
6200 (org-startup-folded nil)
6201 (org-startup-align-all-tables nil))
6202 (org-mode)
6203 (org-overview))
6204 (setq buffer-read-only t)
6205 (if (and (boundp 'org-goto-start-pos)
6206 (integer-or-marker-p org-goto-start-pos))
6207 (let ((org-show-hierarchy-above t)
6208 (org-show-siblings t)
6209 (org-show-following-heading t))
6210 (goto-char org-goto-start-pos)
6211 (and (org-invisible-p) (org-show-context)))
6212 (goto-char (point-min)))
6213 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6214 (message "Select location and press RET")
6215 (use-local-map org-goto-map)
6216 (recursive-edit)
6218 (kill-buffer "*org-goto*")
6219 (cons org-goto-selected-point org-goto-exit-command)))
6221 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6222 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6223 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6224 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6226 (defun org-goto-local-search-headings (string bound noerror)
6227 "Search and make sure that any matches are in headlines."
6228 (catch 'return
6229 (while (if isearch-forward
6230 (search-forward string bound noerror)
6231 (search-backward string bound noerror))
6232 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6233 (and (member :headline context)
6234 (not (member :tags context))))
6235 (throw 'return (point))))))
6237 (defun org-goto-local-auto-isearch ()
6238 "Start isearch."
6239 (interactive)
6240 (goto-char (point-min))
6241 (let ((keys (this-command-keys)))
6242 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6243 (isearch-mode t)
6244 (isearch-process-search-char (string-to-char keys)))))
6246 (defun org-goto-ret (&optional arg)
6247 "Finish `org-goto' by going to the new location."
6248 (interactive "P")
6249 (setq org-goto-selected-point (point)
6250 org-goto-exit-command 'return)
6251 (throw 'exit nil))
6253 (defun org-goto-left ()
6254 "Finish `org-goto' by going to the new location."
6255 (interactive)
6256 (if (org-on-heading-p)
6257 (progn
6258 (beginning-of-line 1)
6259 (setq org-goto-selected-point (point)
6260 org-goto-exit-command 'left)
6261 (throw 'exit nil))
6262 (error "Not on a heading")))
6264 (defun org-goto-right ()
6265 "Finish `org-goto' by going to the new location."
6266 (interactive)
6267 (if (org-on-heading-p)
6268 (progn
6269 (setq org-goto-selected-point (point)
6270 org-goto-exit-command 'right)
6271 (throw 'exit nil))
6272 (error "Not on a heading")))
6274 (defun org-goto-quit ()
6275 "Finish `org-goto' without cursor motion."
6276 (interactive)
6277 (setq org-goto-selected-point nil)
6278 (setq org-goto-exit-command 'quit)
6279 (throw 'exit nil))
6281 ;;; Indirect buffer display of subtrees
6283 (defvar org-indirect-dedicated-frame nil
6284 "This is the frame being used for indirect tree display.")
6285 (defvar org-last-indirect-buffer nil)
6287 (defun org-tree-to-indirect-buffer (&optional arg)
6288 "Create indirect buffer and narrow it to current subtree.
6289 With numerical prefix ARG, go up to this level and then take that tree.
6290 If ARG is negative, go up that many levels.
6291 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6292 indirect buffer previously made with this command, to avoid proliferation of
6293 indirect buffers. However, when you call the command with a `C-u' prefix, or
6294 when `org-indirect-buffer-display' is `new-frame', the last buffer
6295 is kept so that you can work with several indirect buffers at the same time.
6296 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6297 requests that a new frame be made for the new buffer, so that the dedicated
6298 frame is not changed."
6299 (interactive "P")
6300 (let ((cbuf (current-buffer))
6301 (cwin (selected-window))
6302 (pos (point))
6303 beg end level heading ibuf)
6304 (save-excursion
6305 (org-back-to-heading t)
6306 (when (numberp arg)
6307 (setq level (org-outline-level))
6308 (if (< arg 0) (setq arg (+ level arg)))
6309 (while (> (setq level (org-outline-level)) arg)
6310 (outline-up-heading 1 t)))
6311 (setq beg (point)
6312 heading (org-get-heading))
6313 (org-end-of-subtree t t)
6314 (if (org-on-heading-p) (backward-char 1))
6315 (setq end (point)))
6316 (if (and (buffer-live-p org-last-indirect-buffer)
6317 (not (eq org-indirect-buffer-display 'new-frame))
6318 (not arg))
6319 (kill-buffer org-last-indirect-buffer))
6320 (setq ibuf (org-get-indirect-buffer cbuf)
6321 org-last-indirect-buffer ibuf)
6322 (cond
6323 ((or (eq org-indirect-buffer-display 'new-frame)
6324 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6325 (select-frame (make-frame))
6326 (delete-other-windows)
6327 (switch-to-buffer ibuf)
6328 (org-set-frame-title heading))
6329 ((eq org-indirect-buffer-display 'dedicated-frame)
6330 (raise-frame
6331 (select-frame (or (and org-indirect-dedicated-frame
6332 (frame-live-p org-indirect-dedicated-frame)
6333 org-indirect-dedicated-frame)
6334 (setq org-indirect-dedicated-frame (make-frame)))))
6335 (delete-other-windows)
6336 (switch-to-buffer ibuf)
6337 (org-set-frame-title (concat "Indirect: " heading)))
6338 ((eq org-indirect-buffer-display 'current-window)
6339 (switch-to-buffer ibuf))
6340 ((eq org-indirect-buffer-display 'other-window)
6341 (pop-to-buffer ibuf))
6342 (t (error "Invalid value")))
6343 (if (featurep 'xemacs)
6344 (save-excursion (org-mode) (turn-on-font-lock)))
6345 (narrow-to-region beg end)
6346 (show-all)
6347 (goto-char pos)
6348 (and (window-live-p cwin) (select-window cwin))))
6350 (defun org-get-indirect-buffer (&optional buffer)
6351 (setq buffer (or buffer (current-buffer)))
6352 (let ((n 1) (base (buffer-name buffer)) bname)
6353 (while (buffer-live-p
6354 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6355 (setq n (1+ n)))
6356 (condition-case nil
6357 (make-indirect-buffer buffer bname 'clone)
6358 (error (make-indirect-buffer buffer bname)))))
6360 (defun org-set-frame-title (title)
6361 "Set the title of the current frame to the string TITLE."
6362 ;; FIXME: how to name a single frame in XEmacs???
6363 (unless (featurep 'xemacs)
6364 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6366 ;;;; Structure editing
6368 ;;; Inserting headlines
6370 (defun org-previous-line-empty-p ()
6371 (save-excursion
6372 (and (not (bobp))
6373 (or (beginning-of-line 0) t)
6374 (save-match-data
6375 (looking-at "[ \t]*$")))))
6377 (defun org-insert-heading (&optional force-heading invisible-ok)
6378 "Insert a new heading or item with same depth at point.
6379 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6380 If point is at the beginning of a headline, insert a sibling before the
6381 current headline. If point is not at the beginning, do not split the line,
6382 but create the new headline after the current line.
6383 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6384 This is important for non-interactive uses of the command."
6385 (interactive "P")
6386 (if (or (= (buffer-size) 0)
6387 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6388 (org-on-heading-p))))
6389 (not (org-in-item-p))))
6390 (insert "\n* ")
6391 (when (or force-heading (not (org-insert-item)))
6392 (let* ((empty-line-p nil)
6393 (head (save-excursion
6394 (condition-case nil
6395 (progn
6396 (org-back-to-heading invisible-ok)
6397 (setq empty-line-p (org-previous-line-empty-p))
6398 (match-string 0))
6399 (error "*"))))
6400 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6401 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6402 pos hide-previous previous-pos)
6403 (cond
6404 ((and (org-on-heading-p) (bolp)
6405 (or (bobp)
6406 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6407 ;; insert before the current line
6408 (open-line (if blank 2 1)))
6409 ((and (bolp)
6410 (not org-insert-heading-respect-content)
6411 (or (bobp)
6412 (save-excursion
6413 (backward-char 1) (not (org-invisible-p)))))
6414 ;; insert right here
6415 nil)
6417 ;; somewhere in the line
6418 (save-excursion
6419 (setq previous-pos (point-at-bol))
6420 (end-of-line)
6421 (setq hide-previous (org-invisible-p)))
6422 (and org-insert-heading-respect-content (org-show-subtree))
6423 (let ((split
6424 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6425 (save-excursion
6426 (let ((p (point)))
6427 (goto-char (point-at-bol))
6428 (and (looking-at org-complex-heading-regexp)
6429 (> p (match-beginning 4)))))))
6430 tags pos)
6431 (cond
6432 (org-insert-heading-respect-content
6433 (org-end-of-subtree nil t)
6434 (or (bolp) (newline))
6435 (or (org-previous-line-empty-p)
6436 (and blank (newline)))
6437 (open-line 1))
6438 ((org-on-heading-p)
6439 (when hide-previous
6440 (show-children)
6441 (org-show-entry))
6442 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6443 (setq tags (and (match-end 2) (match-string 2)))
6444 (and (match-end 1)
6445 (delete-region (match-beginning 1) (match-end 1)))
6446 (setq pos (point-at-bol))
6447 (or split (end-of-line 1))
6448 (delete-horizontal-space)
6449 (if (string-match "\\`\\*+\\'"
6450 (buffer-substring (point-at-bol) (point)))
6451 (insert " "))
6452 (newline (if blank 2 1))
6453 (when tags
6454 (save-excursion
6455 (goto-char pos)
6456 (end-of-line 1)
6457 (insert " " tags)
6458 (org-set-tags nil 'align))))
6460 (or split (end-of-line 1))
6461 (newline (if blank 2 1)))))))
6462 (insert head) (just-one-space)
6463 (setq pos (point))
6464 (end-of-line 1)
6465 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6466 (when (and org-insert-heading-respect-content hide-previous)
6467 (save-excursion
6468 (goto-char previous-pos)
6469 (hide-subtree)))
6470 (run-hooks 'org-insert-heading-hook)))))
6472 (defun org-get-heading (&optional no-tags)
6473 "Return the heading of the current entry, without the stars."
6474 (save-excursion
6475 (org-back-to-heading t)
6476 (if (looking-at
6477 (if no-tags
6478 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6479 "\\*+[ \t]+\\([^\r\n]*\\)"))
6480 (match-string 1) "")))
6482 (defun org-heading-components ()
6483 "Return the components of the current heading.
6484 This is a list with the following elements:
6485 - the level as an integer
6486 - the reduced level, different if `org-odd-levels-only' is set.
6487 - the TODO keyword, or nil
6488 - the priority character, like ?A, or nil if no priority is given
6489 - the headline text itself, or the tags string if no headline text
6490 - the tags string, or nil."
6491 (save-excursion
6492 (org-back-to-heading t)
6493 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6494 (list (length (match-string 1))
6495 (org-reduced-level (length (match-string 1)))
6496 (org-match-string-no-properties 2)
6497 (and (match-end 3) (aref (match-string 3) 2))
6498 (org-match-string-no-properties 4)
6499 (org-match-string-no-properties 5)))))
6501 (defun org-get-entry ()
6502 "Get the entry text, after heading, entire subtree."
6503 (save-excursion
6504 (org-back-to-heading t)
6505 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6507 (defun org-insert-heading-after-current ()
6508 "Insert a new heading with same level as current, after current subtree."
6509 (interactive)
6510 (org-back-to-heading)
6511 (org-insert-heading)
6512 (org-move-subtree-down)
6513 (end-of-line 1))
6515 (defun org-insert-heading-respect-content ()
6516 (interactive)
6517 (let ((org-insert-heading-respect-content t))
6518 (org-insert-heading t)))
6520 (defun org-insert-todo-heading-respect-content (&optional force-state)
6521 (interactive "P")
6522 (let ((org-insert-heading-respect-content t))
6523 (org-insert-todo-heading force-state t)))
6525 (defun org-insert-todo-heading (arg &optional force-heading)
6526 "Insert a new heading with the same level and TODO state as current heading.
6527 If the heading has no TODO state, or if the state is DONE, use the first
6528 state (TODO by default). Also with prefix arg, force first state."
6529 (interactive "P")
6530 (when (or force-heading (not (org-insert-item 'checkbox)))
6531 (org-insert-heading force-heading)
6532 (save-excursion
6533 (org-back-to-heading)
6534 (outline-previous-heading)
6535 (looking-at org-todo-line-regexp))
6536 (let*
6537 ((new-mark-x
6538 (if (or arg
6539 (not (match-beginning 2))
6540 (member (match-string 2) org-done-keywords))
6541 (car org-todo-keywords-1)
6542 (match-string 2)))
6543 (new-mark
6545 (run-hook-with-args-until-success
6546 'org-todo-get-default-hook new-mark-x nil)
6547 new-mark-x)))
6548 (beginning-of-line 1)
6549 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6550 (if org-treat-insert-todo-heading-as-state-change
6551 (org-todo new-mark)
6552 (insert new-mark " "))))
6553 (when org-provide-todo-statistics
6554 (org-update-parent-todo-statistics))))
6556 (defun org-insert-subheading (arg)
6557 "Insert a new subheading and demote it.
6558 Works for outline headings and for plain lists alike."
6559 (interactive "P")
6560 (org-insert-heading arg)
6561 (cond
6562 ((org-on-heading-p) (org-do-demote))
6563 ((org-at-item-p) (org-indent-item 1))))
6565 (defun org-insert-todo-subheading (arg)
6566 "Insert a new subheading with TODO keyword or checkbox and demote it.
6567 Works for outline headings and for plain lists alike."
6568 (interactive "P")
6569 (org-insert-todo-heading arg)
6570 (cond
6571 ((org-on-heading-p) (org-do-demote))
6572 ((org-at-item-p) (org-indent-item 1))))
6574 ;;; Promotion and Demotion
6576 (defvar org-after-demote-entry-hook nil
6577 "Hook run after an entry has been demoted.
6578 The cursor will be at the beginning of the entry.
6579 When a subtree is being demoted, the hook will be called for each node.")
6581 (defvar org-after-promote-entry-hook nil
6582 "Hook run after an entry has been promoted.
6583 The cursor will be at the beginning of the entry.
6584 When a subtree is being promoted, the hook will be called for each node.")
6586 (defun org-promote-subtree ()
6587 "Promote the entire subtree.
6588 See also `org-promote'."
6589 (interactive)
6590 (save-excursion
6591 (org-map-tree 'org-promote))
6592 (org-fix-position-after-promote))
6594 (defun org-demote-subtree ()
6595 "Demote the entire subtree. See `org-demote'.
6596 See also `org-promote'."
6597 (interactive)
6598 (save-excursion
6599 (org-map-tree 'org-demote))
6600 (org-fix-position-after-promote))
6603 (defun org-do-promote ()
6604 "Promote the current heading higher up the tree.
6605 If the region is active in `transient-mark-mode', promote all headings
6606 in the region."
6607 (interactive)
6608 (save-excursion
6609 (if (org-region-active-p)
6610 (org-map-region 'org-promote (region-beginning) (region-end))
6611 (org-promote)))
6612 (org-fix-position-after-promote))
6614 (defun org-do-demote ()
6615 "Demote the current heading lower down the tree.
6616 If the region is active in `transient-mark-mode', demote all headings
6617 in the region."
6618 (interactive)
6619 (save-excursion
6620 (if (org-region-active-p)
6621 (org-map-region 'org-demote (region-beginning) (region-end))
6622 (org-demote)))
6623 (org-fix-position-after-promote))
6625 (defun org-fix-position-after-promote ()
6626 "Make sure that after pro/demotion cursor position is right."
6627 (let ((pos (point)))
6628 (when (save-excursion
6629 (beginning-of-line 1)
6630 (looking-at org-todo-line-regexp)
6631 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6632 (cond ((eobp) (insert " "))
6633 ((eolp) (insert " "))
6634 ((equal (char-after) ?\ ) (forward-char 1))))))
6636 (defun org-current-level ()
6637 "Return the level of the current entry, or nil if before the first headline.
6638 The level is the number of stars at the beginning of the headline."
6639 (save-excursion
6640 (condition-case nil
6641 (progn
6642 (org-back-to-heading t)
6643 (funcall outline-level))
6644 (error nil))))
6646 (defun org-get-previous-line-level ()
6647 "Return the outline depth of the last headline before the current line.
6648 Returns 0 for the first headline in the buffer, and nil if before the
6649 first headline."
6650 (let ((current-level (org-current-level))
6651 (prev-level (when (> (line-number-at-pos) 1)
6652 (save-excursion
6653 (beginning-of-line 0)
6654 (org-current-level)))))
6655 (cond ((null current-level) nil) ; Before first headline
6656 ((null prev-level) 0) ; At first headline
6657 (prev-level))))
6659 (defun org-reduced-level (l)
6660 "Compute the effective level of a heading.
6661 This takes into account the setting of `org-odd-levels-only'."
6662 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6664 (defun org-level-increment ()
6665 "Return the number of stars that will be added or removed at a
6666 time to headlines when structure editing, based on the value of
6667 `org-odd-levels-only'."
6668 (if org-odd-levels-only 2 1))
6670 (defun org-get-valid-level (level &optional change)
6671 "Rectify a level change under the influence of `org-odd-levels-only'
6672 LEVEL is a current level, CHANGE is by how much the level should be
6673 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6674 even level numbers will become the next higher odd number."
6675 (if org-odd-levels-only
6676 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6677 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6678 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6679 (max 1 (+ level (or change 0)))))
6681 (if (boundp 'define-obsolete-function-alias)
6682 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6683 (define-obsolete-function-alias 'org-get-legal-level
6684 'org-get-valid-level)
6685 (define-obsolete-function-alias 'org-get-legal-level
6686 'org-get-valid-level "23.1")))
6688 (defun org-promote ()
6689 "Promote the current heading higher up the tree.
6690 If the region is active in `transient-mark-mode', promote all headings
6691 in the region."
6692 (org-back-to-heading t)
6693 (let* ((level (save-match-data (funcall outline-level)))
6694 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6695 (diff (abs (- level (length up-head) -1))))
6696 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6697 (replace-match up-head nil t)
6698 ;; Fixup tag positioning
6699 (and org-auto-align-tags (org-set-tags nil t))
6700 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6701 (run-hooks 'org-after-promote-entry-hook)))
6703 (defun org-demote ()
6704 "Demote the current heading lower down the tree.
6705 If the region is active in `transient-mark-mode', demote all headings
6706 in the region."
6707 (org-back-to-heading t)
6708 (let* ((level (save-match-data (funcall outline-level)))
6709 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6710 (diff (abs (- level (length down-head) -1))))
6711 (replace-match down-head nil t)
6712 ;; Fixup tag positioning
6713 (and org-auto-align-tags (org-set-tags nil t))
6714 (if org-adapt-indentation (org-fixup-indentation diff))
6715 (run-hooks 'org-after-demote-entry-hook)))
6717 (defun org-cycle-level ()
6718 "Cycle the level of an empty headline through possible states.
6719 This goes first to child, then to parent, level, then up the hierarchy.
6720 After top level, it switches back to sibling level."
6721 (interactive)
6722 (let ((org-adapt-indentation nil))
6723 (when (org-point-at-end-of-empty-headline)
6724 (setq this-command 'org-cycle-level) ; Only needed for caching
6725 (let ((cur-level (org-current-level))
6726 (prev-level (org-get-previous-line-level)))
6727 (cond
6728 ;; If first headline in file, promote to top-level.
6729 ((= prev-level 0)
6730 (loop repeat (/ (- cur-level 1) (org-level-increment))
6731 do (org-do-promote)))
6732 ;; If same level as prev, demote one.
6733 ((= prev-level cur-level)
6734 (org-do-demote))
6735 ;; If parent is top-level, promote to top level if not already.
6736 ((= prev-level 1)
6737 (loop repeat (/ (- cur-level 1) (org-level-increment))
6738 do (org-do-promote)))
6739 ;; If top-level, return to prev-level.
6740 ((= cur-level 1)
6741 (loop repeat (/ (- prev-level 1) (org-level-increment))
6742 do (org-do-demote)))
6743 ;; If less than prev-level, promote one.
6744 ((< cur-level prev-level)
6745 (org-do-promote))
6746 ;; If deeper than prev-level, promote until higher than
6747 ;; prev-level.
6748 ((> cur-level prev-level)
6749 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6750 do (org-do-promote))))
6751 t))))
6753 (defun org-map-tree (fun)
6754 "Call FUN for every heading underneath the current one."
6755 (org-back-to-heading)
6756 (let ((level (funcall outline-level)))
6757 (save-excursion
6758 (funcall fun)
6759 (while (and (progn
6760 (outline-next-heading)
6761 (> (funcall outline-level) level))
6762 (not (eobp)))
6763 (funcall fun)))))
6765 (defun org-map-region (fun beg end)
6766 "Call FUN for every heading between BEG and END."
6767 (let ((org-ignore-region t))
6768 (save-excursion
6769 (setq end (copy-marker end))
6770 (goto-char beg)
6771 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6772 (< (point) end))
6773 (funcall fun))
6774 (while (and (progn
6775 (outline-next-heading)
6776 (< (point) end))
6777 (not (eobp)))
6778 (funcall fun)))))
6780 (defun org-fixup-indentation (diff)
6781 "Change the indentation in the current entry by DIFF
6782 However, if any line in the current entry has no indentation, or if it
6783 would end up with no indentation after the change, nothing at all is done."
6784 (save-excursion
6785 (let ((end (save-excursion (outline-next-heading)
6786 (point-marker)))
6787 (prohibit (if (> diff 0)
6788 "^\\S-"
6789 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6790 col)
6791 (unless (save-excursion (end-of-line 1)
6792 (re-search-forward prohibit end t))
6793 (while (and (< (point) end)
6794 (re-search-forward "^[ \t]+" end t))
6795 (goto-char (match-end 0))
6796 (setq col (current-column))
6797 (if (< diff 0) (replace-match ""))
6798 (org-indent-to-column (+ diff col))))
6799 (move-marker end nil))))
6801 (defun org-convert-to-odd-levels ()
6802 "Convert an org-mode file with all levels allowed to one with odd levels.
6803 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6804 level 5 etc."
6805 (interactive)
6806 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6807 (let ((outline-regexp org-outline-regexp)
6808 (outline-level 'org-outline-level)
6809 (org-odd-levels-only nil) n)
6810 (save-excursion
6811 (goto-char (point-min))
6812 (while (re-search-forward "^\\*\\*+ " nil t)
6813 (setq n (- (length (match-string 0)) 2))
6814 (while (>= (setq n (1- n)) 0)
6815 (org-demote))
6816 (end-of-line 1))))))
6818 (defun org-convert-to-oddeven-levels ()
6819 "Convert an org-mode file with only odd levels to one with odd and even levels.
6820 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6821 section with an even level, conversion would destroy the structure of the file. An error
6822 is signaled in this case."
6823 (interactive)
6824 (goto-char (point-min))
6825 ;; First check if there are no even levels
6826 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6827 (org-show-context t)
6828 (error "Not all levels are odd in this file. Conversion not possible"))
6829 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6830 (let ((outline-regexp org-outline-regexp)
6831 (outline-level 'org-outline-level)
6832 (org-odd-levels-only nil) n)
6833 (save-excursion
6834 (goto-char (point-min))
6835 (while (re-search-forward "^\\*\\*+ " nil t)
6836 (setq n (/ (1- (length (match-string 0))) 2))
6837 (while (>= (setq n (1- n)) 0)
6838 (org-promote))
6839 (end-of-line 1))))))
6841 (defun org-tr-level (n)
6842 "Make N odd if required."
6843 (if org-odd-levels-only (1+ (/ n 2)) n))
6845 ;;; Vertical tree motion, cutting and pasting of subtrees
6847 (defun org-move-subtree-up (&optional arg)
6848 "Move the current subtree up past ARG headlines of the same level."
6849 (interactive "p")
6850 (org-move-subtree-down (- (prefix-numeric-value arg))))
6852 (defun org-move-subtree-down (&optional arg)
6853 "Move the current subtree down past ARG headlines of the same level."
6854 (interactive "p")
6855 (setq arg (prefix-numeric-value arg))
6856 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6857 'org-get-last-sibling))
6858 (ins-point (make-marker))
6859 (cnt (abs arg))
6860 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6861 ;; Select the tree
6862 (org-back-to-heading)
6863 (setq beg0 (point))
6864 (save-excursion
6865 (setq ne-beg (org-back-over-empty-lines))
6866 (setq beg (point)))
6867 (save-match-data
6868 (save-excursion (outline-end-of-heading)
6869 (setq folded (org-invisible-p)))
6870 (outline-end-of-subtree))
6871 (outline-next-heading)
6872 (setq ne-end (org-back-over-empty-lines))
6873 (setq end (point))
6874 (goto-char beg0)
6875 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6876 ;; include less whitespace
6877 (save-excursion
6878 (goto-char beg)
6879 (forward-line (- ne-beg ne-end))
6880 (setq beg (point))))
6881 ;; Find insertion point, with error handling
6882 (while (> cnt 0)
6883 (or (and (funcall movfunc) (looking-at outline-regexp))
6884 (progn (goto-char beg0)
6885 (error "Cannot move past superior level or buffer limit")))
6886 (setq cnt (1- cnt)))
6887 (if (> arg 0)
6888 ;; Moving forward - still need to move over subtree
6889 (progn (org-end-of-subtree t t)
6890 (save-excursion
6891 (org-back-over-empty-lines)
6892 (or (bolp) (newline)))))
6893 (setq ne-ins (org-back-over-empty-lines))
6894 (move-marker ins-point (point))
6895 (setq txt (buffer-substring beg end))
6896 (org-save-markers-in-region beg end)
6897 (delete-region beg end)
6898 (org-remove-empty-overlays-at beg)
6899 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6900 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6901 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6902 (let ((bbb (point)))
6903 (insert-before-markers txt)
6904 (org-reinstall-markers-in-region bbb)
6905 (move-marker ins-point bbb))
6906 (or (bolp) (insert "\n"))
6907 (setq ins-end (point))
6908 (goto-char ins-point)
6909 (org-skip-whitespace)
6910 (when (and (< arg 0)
6911 (org-first-sibling-p)
6912 (> ne-ins ne-beg))
6913 ;; Move whitespace back to beginning
6914 (save-excursion
6915 (goto-char ins-end)
6916 (let ((kill-whole-line t))
6917 (kill-line (- ne-ins ne-beg)) (point)))
6918 (insert (make-string (- ne-ins ne-beg) ?\n)))
6919 (move-marker ins-point nil)
6920 (if folded
6921 (hide-subtree)
6922 (org-show-entry)
6923 (show-children)
6924 (org-cycle-hide-drawers 'children))
6925 (org-clean-visibility-after-subtree-move)))
6927 (defvar org-subtree-clip ""
6928 "Clipboard for cut and paste of subtrees.
6929 This is actually only a copy of the kill, because we use the normal kill
6930 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6932 (defvar org-subtree-clip-folded nil
6933 "Was the last copied subtree folded?
6934 This is used to fold the tree back after pasting.")
6936 (defun org-cut-subtree (&optional n)
6937 "Cut the current subtree into the clipboard.
6938 With prefix arg N, cut this many sequential subtrees.
6939 This is a short-hand for marking the subtree and then cutting it."
6940 (interactive "p")
6941 (org-copy-subtree n 'cut))
6943 (defun org-copy-subtree (&optional n cut force-store-markers)
6944 "Cut the current subtree into the clipboard.
6945 With prefix arg N, cut this many sequential subtrees.
6946 This is a short-hand for marking the subtree and then copying it.
6947 If CUT is non-nil, actually cut the subtree.
6948 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6949 of some markers in the region, even if CUT is non-nil. This is
6950 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6951 (interactive "p")
6952 (let (beg end folded (beg0 (point)))
6953 (if (interactive-p)
6954 (org-back-to-heading nil) ; take what looks like a subtree
6955 (org-back-to-heading t)) ; take what is really there
6956 (org-back-over-empty-lines)
6957 (setq beg (point))
6958 (skip-chars-forward " \t\r\n")
6959 (save-match-data
6960 (save-excursion (outline-end-of-heading)
6961 (setq folded (org-invisible-p)))
6962 (condition-case nil
6963 (org-forward-same-level (1- n) t)
6964 (error nil))
6965 (org-end-of-subtree t t))
6966 (org-back-over-empty-lines)
6967 (setq end (point))
6968 (goto-char beg0)
6969 (when (> end beg)
6970 (setq org-subtree-clip-folded folded)
6971 (when (or cut force-store-markers)
6972 (org-save-markers-in-region beg end))
6973 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6974 (setq org-subtree-clip (current-kill 0))
6975 (message "%s: Subtree(s) with %d characters"
6976 (if cut "Cut" "Copied")
6977 (length org-subtree-clip)))))
6979 (defun org-paste-subtree (&optional level tree for-yank)
6980 "Paste the clipboard as a subtree, with modification of headline level.
6981 The entire subtree is promoted or demoted in order to match a new headline
6982 level.
6984 If the cursor is at the beginning of a headline, the same level as
6985 that headline is used to paste the tree
6987 If not, the new level is derived from the *visible* headings
6988 before and after the insertion point, and taken to be the inferior headline
6989 level of the two. So if the previous visible heading is level 3 and the
6990 next is level 4 (or vice versa), level 4 will be used for insertion.
6991 This makes sure that the subtree remains an independent subtree and does
6992 not swallow low level entries.
6994 You can also force a different level, either by using a numeric prefix
6995 argument, or by inserting the heading marker by hand. For example, if the
6996 cursor is after \"*****\", then the tree will be shifted to level 5.
6998 If optional TREE is given, use this text instead of the kill ring.
7000 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7001 move back over whitespace before inserting, and move point to the end of
7002 the inserted text when done."
7003 (interactive "P")
7004 (setq tree (or tree (and kill-ring (current-kill 0))))
7005 (unless (org-kill-is-subtree-p tree)
7006 (error "%s"
7007 (substitute-command-keys
7008 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7009 (let* ((visp (not (org-invisible-p)))
7010 (txt tree)
7011 (^re (concat "^\\(" outline-regexp "\\)"))
7012 (re (concat "\\(" outline-regexp "\\)"))
7013 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7015 (old-level (if (string-match ^re txt)
7016 (- (match-end 0) (match-beginning 0) 1)
7017 -1))
7018 (force-level (cond (level (prefix-numeric-value level))
7019 ((and (looking-at "[ \t]*$")
7020 (string-match
7021 ^re_ (buffer-substring
7022 (point-at-bol) (point))))
7023 (- (match-end 1) (match-beginning 1)))
7024 ((and (bolp)
7025 (looking-at org-outline-regexp))
7026 (- (match-end 0) (point) 1))
7027 (t nil)))
7028 (previous-level (save-excursion
7029 (condition-case nil
7030 (progn
7031 (outline-previous-visible-heading 1)
7032 (if (looking-at re)
7033 (- (match-end 0) (match-beginning 0) 1)
7035 (error 1))))
7036 (next-level (save-excursion
7037 (condition-case nil
7038 (progn
7039 (or (looking-at outline-regexp)
7040 (outline-next-visible-heading 1))
7041 (if (looking-at re)
7042 (- (match-end 0) (match-beginning 0) 1)
7044 (error 1))))
7045 (new-level (or force-level (max previous-level next-level)))
7046 (shift (if (or (= old-level -1)
7047 (= new-level -1)
7048 (= old-level new-level))
7050 (- new-level old-level)))
7051 (delta (if (> shift 0) -1 1))
7052 (func (if (> shift 0) 'org-demote 'org-promote))
7053 (org-odd-levels-only nil)
7054 beg end newend)
7055 ;; Remove the forced level indicator
7056 (if force-level
7057 (delete-region (point-at-bol) (point)))
7058 ;; Paste
7059 (beginning-of-line 1)
7060 (unless for-yank (org-back-over-empty-lines))
7061 (setq beg (point))
7062 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7063 (insert-before-markers txt)
7064 (unless (string-match "\n\\'" txt) (insert "\n"))
7065 (setq newend (point))
7066 (org-reinstall-markers-in-region beg)
7067 (setq end (point))
7068 (goto-char beg)
7069 (skip-chars-forward " \t\n\r")
7070 (setq beg (point))
7071 (if (and (org-invisible-p) visp)
7072 (save-excursion (outline-show-heading)))
7073 ;; Shift if necessary
7074 (unless (= shift 0)
7075 (save-restriction
7076 (narrow-to-region beg end)
7077 (while (not (= shift 0))
7078 (org-map-region func (point-min) (point-max))
7079 (setq shift (+ delta shift)))
7080 (goto-char (point-min))
7081 (setq newend (point-max))))
7082 (when (or (interactive-p) for-yank)
7083 (message "Clipboard pasted as level %d subtree" new-level))
7084 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7085 kill-ring
7086 (eq org-subtree-clip (current-kill 0))
7087 org-subtree-clip-folded)
7088 ;; The tree was folded before it was killed/copied
7089 (hide-subtree))
7090 (and for-yank (goto-char newend))))
7092 (defun org-kill-is-subtree-p (&optional txt)
7093 "Check if the current kill is an outline subtree, or a set of trees.
7094 Returns nil if kill does not start with a headline, or if the first
7095 headline level is not the largest headline level in the tree.
7096 So this will actually accept several entries of equal levels as well,
7097 which is OK for `org-paste-subtree'.
7098 If optional TXT is given, check this string instead of the current kill."
7099 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7100 (start-level (and kill
7101 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7102 org-outline-regexp "\\)")
7103 kill)
7104 (- (match-end 2) (match-beginning 2) 1)))
7105 (re (concat "^" org-outline-regexp))
7106 (start (1+ (or (match-beginning 2) -1))))
7107 (if (not start-level)
7108 (progn
7109 nil) ;; does not even start with a heading
7110 (catch 'exit
7111 (while (setq start (string-match re kill (1+ start)))
7112 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7113 (throw 'exit nil)))
7114 t))))
7116 (defvar org-markers-to-move nil
7117 "Markers that should be moved with a cut-and-paste operation.
7118 Those markers are stored together with their positions relative to
7119 the start of the region.")
7121 (defun org-save-markers-in-region (beg end)
7122 "Check markers in region.
7123 If these markers are between BEG and END, record their position relative
7124 to BEG, so that after moving the block of text, we can put the markers back
7125 into place.
7126 This function gets called just before an entry or tree gets cut from the
7127 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7128 called immediately, to move the markers with the entries."
7129 (setq org-markers-to-move nil)
7130 (when (featurep 'org-clock)
7131 (org-clock-save-markers-for-cut-and-paste beg end))
7132 (when (featurep 'org-agenda)
7133 (org-agenda-save-markers-for-cut-and-paste beg end)))
7135 (defun org-check-and-save-marker (marker beg end)
7136 "Check if MARKER is between BEG and END.
7137 If yes, remember the marker and the distance to BEG."
7138 (when (and (marker-buffer marker)
7139 (equal (marker-buffer marker) (current-buffer)))
7140 (if (and (>= marker beg) (< marker end))
7141 (push (cons marker (- marker beg)) org-markers-to-move))))
7143 (defun org-reinstall-markers-in-region (beg)
7144 "Move all remembered markers to their position relative to BEG."
7145 (mapc (lambda (x)
7146 (move-marker (car x) (+ beg (cdr x))))
7147 org-markers-to-move)
7148 (setq org-markers-to-move nil))
7150 (defun org-narrow-to-subtree ()
7151 "Narrow buffer to the current subtree."
7152 (interactive)
7153 (save-excursion
7154 (save-match-data
7155 (narrow-to-region
7156 (progn (org-back-to-heading t) (point))
7157 (progn (org-end-of-subtree t t)
7158 (if (org-on-heading-p) (backward-char 1))
7159 (point))))))
7161 (eval-when-compile
7162 (defvar org-property-drawer-re))
7164 (defun org-clone-subtree-with-time-shift (n &optional shift)
7165 "Clone the task (subtree) at point N times.
7166 The clones will be inserted as siblings.
7168 In interactive use, the user will be prompted for the number of
7169 clones to be produced, and for a time SHIFT, which may be a
7170 repeater as used in time stamps, for example `+3d'.
7172 When a valid repeater is given and the entry contains any time
7173 stamps, the clones will become a sequence in time, with time
7174 stamps in the subtree shifted for each clone produced. If SHIFT
7175 is nil or the empty string, time stamps will be left alone. The
7176 ID property of the original subtree is removed.
7178 If the original subtree did contain time stamps with a repeater,
7179 the following will happen:
7180 - the repeater will be removed in each clone
7181 - an additional clone will be produced, with the current, unshifted
7182 date(s) in the entry.
7183 - the original entry will be placed *after* all the clones, with
7184 repeater intact.
7185 - the start days in the repeater in the original entry will be shifted
7186 to past the last clone.
7187 I this way you can spell out a number of instances of a repeating task,
7188 and still retain the repeater to cover future instances of the task."
7189 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7190 (let (beg end template task idprop
7191 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7192 (if (not (and (integerp n) (> n 0)))
7193 (error "Invalid number of replications %s" n))
7194 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7195 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7196 shift)))
7197 (error "Invalid shift specification %s" shift))
7198 (when doshift
7199 (setq shift-n (string-to-number (match-string 1 shift))
7200 shift-what (cdr (assoc (match-string 2 shift)
7201 '(("d" . day) ("w" . week)
7202 ("m" . month) ("y" . year))))))
7203 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7204 (setq nmin 1 nmax n)
7205 (org-back-to-heading t)
7206 (setq beg (point))
7207 (setq idprop (org-entry-get nil "ID"))
7208 (org-end-of-subtree t t)
7209 (or (bolp) (insert "\n"))
7210 (setq end (point))
7211 (setq template (buffer-substring beg end))
7212 (when (and doshift
7213 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7214 (delete-region beg end)
7215 (setq end beg)
7216 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7217 (goto-char end)
7218 (loop for n from nmin to nmax do
7219 (if (not doshift)
7220 (setq task (if (not idprop) template
7221 (with-temp-buffer
7222 (insert template)
7223 (org-mode)
7224 (goto-char (point-min))
7225 (if org-clone-delete-id
7226 (org-entry-delete nil "ID")
7227 (org-id-get-create t))
7228 (while (re-search-forward
7229 org-property-drawer-re nil t)
7230 (org-remove-empty-drawer-at
7231 "PROPERTIES" (point)))
7232 (buffer-string))))
7233 (with-temp-buffer
7234 (insert template)
7235 (org-mode)
7236 (goto-char (point-min))
7237 (and idprop (if org-clone-delete-id
7238 (org-entry-delete nil "ID")
7239 (org-id-get-create t)))
7240 (while (re-search-forward org-property-drawer-re nil t)
7241 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7242 (goto-char (point-min))
7243 (while (re-search-forward org-ts-regexp-both nil t)
7244 (org-timestamp-change (* n shift-n) shift-what))
7245 (unless (= n n-no-remove)
7246 (goto-char (point-min))
7247 (while (re-search-forward org-ts-regexp nil t)
7248 (save-excursion
7249 (goto-char (match-beginning 0))
7250 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7251 (delete-region (match-beginning 1) (match-end 1))))))
7252 (setq task (buffer-string))))
7253 (insert task))
7254 (goto-char beg)))
7256 ;;; Outline Sorting
7258 (defun org-sort (with-case)
7259 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7260 Optional argument WITH-CASE means sort case-sensitively.
7261 With a double prefix argument, also remove duplicate entries."
7262 (interactive "P")
7263 (if (org-at-table-p)
7264 (org-call-with-arg 'org-table-sort-lines with-case)
7265 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7267 (defun org-sort-remove-invisible (s)
7268 (remove-text-properties 0 (length s) org-rm-props s)
7269 (while (string-match org-bracket-link-regexp s)
7270 (setq s (replace-match (if (match-end 2)
7271 (match-string 3 s)
7272 (match-string 1 s)) t t s)))
7275 (defvar org-priority-regexp) ; defined later in the file
7277 (defvar org-after-sorting-entries-or-items-hook nil
7278 "Hook that is run after a bunch of entries or items have been sorted.
7279 When children are sorted, the cursor is in the parent line when this
7280 hook gets called. When a region or a plain list is sorted, the cursor
7281 will be in the first entry of the sorted region/list.")
7283 (defun org-sort-entries-or-items
7284 (&optional with-case sorting-type getkey-func compare-func property)
7285 "Sort entries on a certain level of an outline tree, or plain list items.
7286 If there is an active region, the entries in the region are sorted.
7287 Else, if the cursor is before the first entry, sort the top-level items.
7288 Else, the children of the entry at point are sorted.
7289 If the cursor is at the first item in a plain list, the list items will be
7290 sorted.
7292 Sorting can be alphabetically, numerically, by date/time as given by
7293 a time stamp, by a property or by priority.
7295 The command prompts for the sorting type unless it has been given to the
7296 function through the SORTING-TYPE argument, which needs to be a character,
7297 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7298 precise meaning of each character:
7300 n Numerically, by converting the beginning of the entry/item to a number.
7301 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7302 t By date/time, either the first active time stamp in the entry, or, if
7303 none exist, by the first inactive one.
7304 In items, only the first line will be checked.
7305 s By the scheduled date/time.
7306 d By deadline date/time.
7307 c By creation time, which is assumed to be the first inactive time stamp
7308 at the beginning of a line.
7309 p By priority according to the cookie.
7310 r By the value of a property.
7312 Capital letters will reverse the sort order.
7314 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7315 called with point at the beginning of the record. It must return either
7316 a string or a number that should serve as the sorting key for that record.
7318 Comparing entries ignores case by default. However, with an optional argument
7319 WITH-CASE, the sorting considers case as well."
7320 (interactive "P")
7321 (let ((case-func (if with-case 'identity 'downcase))
7322 start beg end stars re re2
7323 txt what tmp plain-list-p)
7324 ;; Find beginning and end of region to sort
7325 (cond
7326 ((org-region-active-p)
7327 ;; we will sort the region
7328 (setq end (region-end)
7329 what "region")
7330 (goto-char (region-beginning))
7331 (if (not (org-on-heading-p)) (outline-next-heading))
7332 (setq start (point)))
7333 ((org-at-item-p)
7334 ;; we will sort this plain list
7335 (org-beginning-of-item-list) (setq start (point))
7336 (org-end-of-item-list)
7337 (or (bolp) (insert "\n"))
7338 (setq end (point))
7339 (goto-char start)
7340 (setq plain-list-p t
7341 what "plain list"))
7342 ((or (org-on-heading-p)
7343 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7344 ;; we will sort the children of the current headline
7345 (org-back-to-heading)
7346 (setq start (point)
7347 end (progn (org-end-of-subtree t t)
7348 (or (bolp) (insert "\n"))
7349 (org-back-over-empty-lines)
7350 (point))
7351 what "children")
7352 (goto-char start)
7353 (show-subtree)
7354 (outline-next-heading))
7356 ;; we will sort the top-level entries in this file
7357 (goto-char (point-min))
7358 (or (org-on-heading-p) (outline-next-heading))
7359 (setq start (point))
7360 (goto-char (point-max))
7361 (beginning-of-line 1)
7362 (when (looking-at ".*?\\S-")
7363 ;; File ends in a non-white line
7364 (end-of-line 1)
7365 (insert "\n"))
7366 (setq end (point-max))
7367 (setq what "top-level")
7368 (goto-char start)
7369 (show-all)))
7371 (setq beg (point))
7372 (if (>= beg end) (error "Nothing to sort"))
7374 (unless plain-list-p
7375 (looking-at "\\(\\*+\\)")
7376 (setq stars (match-string 1)
7377 re (concat "^" (regexp-quote stars) " +")
7378 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7379 txt (buffer-substring beg end))
7380 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7381 (if (and (not (equal stars "*")) (string-match re2 txt))
7382 (error "Region to sort contains a level above the first entry")))
7384 (unless sorting-type
7385 (message
7386 (if plain-list-p
7387 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7388 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7389 [t]ime [s]cheduled [d]eadline [c]reated
7390 A/N/T/S/D/C/P/O/F means reversed:")
7391 what)
7392 (setq sorting-type (read-char-exclusive))
7394 (and (= (downcase sorting-type) ?f)
7395 (setq getkey-func
7396 (org-icompleting-read "Sort using function: "
7397 obarray 'fboundp t nil nil))
7398 (setq getkey-func (intern getkey-func)))
7400 (and (= (downcase sorting-type) ?r)
7401 (setq property
7402 (org-icompleting-read "Property: "
7403 (mapcar 'list (org-buffer-property-keys t))
7404 nil t))))
7406 (message "Sorting entries...")
7408 (save-restriction
7409 (narrow-to-region start end)
7411 (let ((dcst (downcase sorting-type))
7412 (case-fold-search nil)
7413 (now (current-time)))
7414 (sort-subr
7415 (/= dcst sorting-type)
7416 ;; This function moves to the beginning character of the "record" to
7417 ;; be sorted.
7418 (if plain-list-p
7419 (lambda nil
7420 (if (org-at-item-p) t (goto-char (point-max))))
7421 (lambda nil
7422 (if (re-search-forward re nil t)
7423 (goto-char (match-beginning 0))
7424 (goto-char (point-max)))))
7425 ;; This function moves to the last character of the "record" being
7426 ;; sorted.
7427 (if plain-list-p
7428 'org-end-of-item
7429 (lambda nil
7430 (save-match-data
7431 (condition-case nil
7432 (outline-forward-same-level 1)
7433 (error
7434 (goto-char (point-max)))))))
7436 ;; This function returns the value that gets sorted against.
7437 (if plain-list-p
7438 (lambda nil
7439 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7440 (cond
7441 ((= dcst ?n)
7442 (string-to-number (buffer-substring (match-end 0)
7443 (point-at-eol))))
7444 ((= dcst ?a)
7445 (buffer-substring (match-end 0) (point-at-eol)))
7446 ((= dcst ?t)
7447 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7448 (re-search-forward org-ts-regexp-both
7449 (point-at-eol) t))
7450 (org-time-string-to-seconds (match-string 0))
7451 (org-float-time now)))
7452 ((= dcst ?f)
7453 (if getkey-func
7454 (progn
7455 (setq tmp (funcall getkey-func))
7456 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7457 tmp)
7458 (error "Invalid key function `%s'" getkey-func)))
7459 (t (error "Invalid sorting type `%c'" sorting-type)))))
7460 (lambda nil
7461 (cond
7462 ((= dcst ?n)
7463 (if (looking-at org-complex-heading-regexp)
7464 (string-to-number (match-string 4))
7465 nil))
7466 ((= dcst ?a)
7467 (if (looking-at org-complex-heading-regexp)
7468 (funcall case-func (match-string 4))
7469 nil))
7470 ((= dcst ?t)
7471 (let ((end (save-excursion (outline-next-heading) (point))))
7472 (if (or (re-search-forward org-ts-regexp end t)
7473 (re-search-forward org-ts-regexp-both end t))
7474 (org-time-string-to-seconds (match-string 0))
7475 (org-float-time now))))
7476 ((= dcst ?c)
7477 (let ((end (save-excursion (outline-next-heading) (point))))
7478 (if (re-search-forward
7479 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7480 end t)
7481 (org-time-string-to-seconds (match-string 0))
7482 (org-float-time now))))
7483 ((= dcst ?s)
7484 (let ((end (save-excursion (outline-next-heading) (point))))
7485 (if (re-search-forward org-scheduled-time-regexp end t)
7486 (org-time-string-to-seconds (match-string 1))
7487 (org-float-time now))))
7488 ((= dcst ?d)
7489 (let ((end (save-excursion (outline-next-heading) (point))))
7490 (if (re-search-forward org-deadline-time-regexp end t)
7491 (org-time-string-to-seconds (match-string 1))
7492 (org-float-time now))))
7493 ((= dcst ?p)
7494 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7495 (string-to-char (match-string 2))
7496 org-default-priority))
7497 ((= dcst ?r)
7498 (or (org-entry-get nil property) ""))
7499 ((= dcst ?o)
7500 (if (looking-at org-complex-heading-regexp)
7501 (- 9999 (length (member (match-string 2)
7502 org-todo-keywords-1)))))
7503 ((= dcst ?f)
7504 (if getkey-func
7505 (progn
7506 (setq tmp (funcall getkey-func))
7507 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7508 tmp)
7509 (error "Invalid key function `%s'" getkey-func)))
7510 (t (error "Invalid sorting type `%c'" sorting-type)))))
7512 (cond
7513 ((= dcst ?a) 'string<)
7514 ((= dcst ?f) compare-func)
7515 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7516 (t nil)))))
7517 (run-hooks 'org-after-sorting-entries-or-items-hook)
7518 (message "Sorting entries...done")))
7520 (defun org-do-sort (table what &optional with-case sorting-type)
7521 "Sort TABLE of WHAT according to SORTING-TYPE.
7522 The user will be prompted for the SORTING-TYPE if the call to this
7523 function does not specify it. WHAT is only for the prompt, to indicate
7524 what is being sorted. The sorting key will be extracted from
7525 the car of the elements of the table.
7526 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7527 (unless sorting-type
7528 (message
7529 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7530 what)
7531 (setq sorting-type (read-char-exclusive)))
7532 (let ((dcst (downcase sorting-type))
7533 extractfun comparefun)
7534 ;; Define the appropriate functions
7535 (cond
7536 ((= dcst ?n)
7537 (setq extractfun 'string-to-number
7538 comparefun (if (= dcst sorting-type) '< '>)))
7539 ((= dcst ?a)
7540 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7541 (lambda(x) (downcase (org-sort-remove-invisible x))))
7542 comparefun (if (= dcst sorting-type)
7543 'string<
7544 (lambda (a b) (and (not (string< a b))
7545 (not (string= a b)))))))
7546 ((= dcst ?t)
7547 (setq extractfun
7548 (lambda (x)
7549 (if (or (string-match org-ts-regexp x)
7550 (string-match org-ts-regexp-both x))
7551 (org-float-time
7552 (org-time-string-to-time (match-string 0 x)))
7554 comparefun (if (= dcst sorting-type) '< '>)))
7555 (t (error "Invalid sorting type `%c'" sorting-type)))
7557 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7558 table)
7559 (lambda (a b) (funcall comparefun (car a) (car b))))))
7562 ;;; The orgstruct minor mode
7564 ;; Define a minor mode which can be used in other modes in order to
7565 ;; integrate the org-mode structure editing commands.
7567 ;; This is really a hack, because the org-mode structure commands use
7568 ;; keys which normally belong to the major mode. Here is how it
7569 ;; works: The minor mode defines all the keys necessary to operate the
7570 ;; structure commands, but wraps the commands into a function which
7571 ;; tests if the cursor is currently at a headline or a plain list
7572 ;; item. If that is the case, the structure command is used,
7573 ;; temporarily setting many Org-mode variables like regular
7574 ;; expressions for filling etc. However, when any of those keys is
7575 ;; used at a different location, function uses `key-binding' to look
7576 ;; up if the key has an associated command in another currently active
7577 ;; keymap (minor modes, major mode, global), and executes that
7578 ;; command. There might be problems if any of the keys is otherwise
7579 ;; used as a prefix key.
7581 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7582 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7583 ;; addresses this by checking explicitly for both bindings.
7585 (defvar orgstruct-mode-map (make-sparse-keymap)
7586 "Keymap for the minor `orgstruct-mode'.")
7588 (defvar org-local-vars nil
7589 "List of local variables, for use by `orgstruct-mode'")
7591 ;;;###autoload
7592 (define-minor-mode orgstruct-mode
7593 "Toggle the minor mode `orgstruct-mode'.
7594 This mode is for using Org-mode structure commands in other
7595 modes. The following keys behave as if Org-mode were active, if
7596 the cursor is on a headline, or on a plain list item (both as
7597 defined by Org-mode).
7599 M-up Move entry/item up
7600 M-down Move entry/item down
7601 M-left Promote
7602 M-right Demote
7603 M-S-up Move entry/item up
7604 M-S-down Move entry/item down
7605 M-S-left Promote subtree
7606 M-S-right Demote subtree
7607 M-q Fill paragraph and items like in Org-mode
7608 C-c ^ Sort entries
7609 C-c - Cycle list bullet
7610 TAB Cycle item visibility
7611 M-RET Insert new heading/item
7612 S-M-RET Insert new TODO heading / Checkbox item
7613 C-c C-c Set tags / toggle checkbox"
7614 nil " OrgStruct" nil
7615 (org-load-modules-maybe)
7616 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7618 ;;;###autoload
7619 (defun turn-on-orgstruct ()
7620 "Unconditionally turn on `orgstruct-mode'."
7621 (orgstruct-mode 1))
7623 (defun orgstruct++-mode (&optional arg)
7624 "Toggle `orgstruct-mode', the enhanced version of it.
7625 In addition to setting orgstruct-mode, this also exports all indentation
7626 and autofilling variables from org-mode into the buffer. It will also
7627 recognize item context in multiline items.
7628 Note that turning off orgstruct-mode will *not* remove the
7629 indentation/paragraph settings. This can only be done by refreshing the
7630 major mode, for example with \\[normal-mode]."
7631 (interactive "P")
7632 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7633 (if (< arg 1)
7634 (orgstruct-mode -1)
7635 (orgstruct-mode 1)
7636 (let (var val)
7637 (mapc
7638 (lambda (x)
7639 (when (string-match
7640 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7641 (symbol-name (car x)))
7642 (setq var (car x) val (nth 1 x))
7643 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7644 org-local-vars)
7645 (org-set-local 'orgstruct-is-++ t))))
7647 (defvar orgstruct-is-++ nil
7648 "Is orgstruct-mode in ++ version in the current-buffer?")
7649 (make-variable-buffer-local 'orgstruct-is-++)
7651 ;;;###autoload
7652 (defun turn-on-orgstruct++ ()
7653 "Unconditionally turn on `orgstruct++-mode'."
7654 (orgstruct++-mode 1))
7656 (defun orgstruct-error ()
7657 "Error when there is no default binding for a structure key."
7658 (interactive)
7659 (error "This key has no function outside structure elements"))
7661 (defun orgstruct-setup ()
7662 "Setup orgstruct keymaps."
7663 (let ((nfunc 0)
7664 (bindings
7665 (list
7666 '([(meta up)] org-metaup)
7667 '([(meta down)] org-metadown)
7668 '([(meta left)] org-metaleft)
7669 '([(meta right)] org-metaright)
7670 '([(meta shift up)] org-shiftmetaup)
7671 '([(meta shift down)] org-shiftmetadown)
7672 '([(meta shift left)] org-shiftmetaleft)
7673 '([(meta shift right)] org-shiftmetaright)
7674 '([?\e (up)] org-metaup)
7675 '([?\e (down)] org-metadown)
7676 '([?\e (left)] org-metaleft)
7677 '([?\e (right)] org-metaright)
7678 '([?\e (shift up)] org-shiftmetaup)
7679 '([?\e (shift down)] org-shiftmetadown)
7680 '([?\e (shift left)] org-shiftmetaleft)
7681 '([?\e (shift right)] org-shiftmetaright)
7682 '([(shift up)] org-shiftup)
7683 '([(shift down)] org-shiftdown)
7684 '([(shift left)] org-shiftleft)
7685 '([(shift right)] org-shiftright)
7686 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7687 '("\M-q" fill-paragraph)
7688 '("\C-c^" org-sort)
7689 '("\C-c-" org-cycle-list-bullet)))
7690 elt key fun cmd)
7691 (while (setq elt (pop bindings))
7692 (setq nfunc (1+ nfunc))
7693 (setq key (org-key (car elt))
7694 fun (nth 1 elt)
7695 cmd (orgstruct-make-binding fun nfunc key))
7696 (org-defkey orgstruct-mode-map key cmd))
7698 ;; Special treatment needed for TAB and RET
7699 (org-defkey orgstruct-mode-map [(tab)]
7700 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7701 (org-defkey orgstruct-mode-map "\C-i"
7702 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7704 (org-defkey orgstruct-mode-map "\M-\C-m"
7705 (orgstruct-make-binding 'org-insert-heading 105
7706 "\M-\C-m" [(meta return)]))
7707 (org-defkey orgstruct-mode-map [(meta return)]
7708 (orgstruct-make-binding 'org-insert-heading 106
7709 [(meta return)] "\M-\C-m"))
7711 (org-defkey orgstruct-mode-map [(shift meta return)]
7712 (orgstruct-make-binding 'org-insert-todo-heading 107
7713 [(meta return)] "\M-\C-m"))
7715 (org-defkey orgstruct-mode-map "\e\C-m"
7716 (orgstruct-make-binding 'org-insert-heading 108
7717 "\e\C-m" [?\e (return)]))
7718 (org-defkey orgstruct-mode-map [?\e (return)]
7719 (orgstruct-make-binding 'org-insert-heading 109
7720 [?\e (return)] "\e\C-m"))
7721 (org-defkey orgstruct-mode-map [?\e (shift return)]
7722 (orgstruct-make-binding 'org-insert-todo-heading 110
7723 [?\e (return)] "\e\C-m"))
7725 (unless org-local-vars
7726 (setq org-local-vars (org-get-local-variables)))
7730 (defun orgstruct-make-binding (fun n &rest keys)
7731 "Create a function for binding in the structure minor mode.
7732 FUN is the command to call inside a table. N is used to create a unique
7733 command name. KEYS are keys that should be checked in for a command
7734 to execute outside of tables."
7735 (eval
7736 (list 'defun
7737 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7738 '(arg)
7739 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7740 "Outside of structure, run the binding of `"
7741 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7742 "'.")
7743 '(interactive "p")
7744 (list 'if
7745 `(org-context-p 'headline 'item
7746 (and orgstruct-is-++
7747 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7748 'item-body))
7749 (list 'org-run-like-in-org-mode (list 'quote fun))
7750 (list 'let '(orgstruct-mode)
7751 (list 'call-interactively
7752 (append '(or)
7753 (mapcar (lambda (k)
7754 (list 'key-binding k))
7755 keys)
7756 '('orgstruct-error))))))))
7758 (defun org-context-p (&rest contexts)
7759 "Check if local context is any of CONTEXTS.
7760 Possible values in the list of contexts are `table', `headline', and `item'."
7761 (let ((pos (point)))
7762 (goto-char (point-at-bol))
7763 (prog1 (or (and (memq 'table contexts)
7764 (looking-at "[ \t]*|"))
7765 (and (memq 'headline contexts)
7766 ;;????????? (looking-at "\\*+"))
7767 (looking-at outline-regexp))
7768 (and (memq 'item contexts)
7769 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7770 (and (memq 'item-body contexts)
7771 (org-in-item-p)))
7772 (goto-char pos))))
7774 (defun org-get-local-variables ()
7775 "Return a list of all local variables in an org-mode buffer."
7776 (let (varlist)
7777 (with-current-buffer (get-buffer-create "*Org tmp*")
7778 (erase-buffer)
7779 (org-mode)
7780 (setq varlist (buffer-local-variables)))
7781 (kill-buffer "*Org tmp*")
7782 (delq nil
7783 (mapcar
7784 (lambda (x)
7785 (setq x
7786 (if (symbolp x)
7787 (list x)
7788 (list (car x) (list 'quote (cdr x)))))
7789 (if (string-match
7790 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7791 (symbol-name (car x)))
7792 x nil))
7793 varlist))))
7795 ;;;###autoload
7796 (defun org-run-like-in-org-mode (cmd)
7797 "Run a command, pretending that the current buffer is in Org-mode.
7798 This will temporarily bind local variables that are typically bound in
7799 Org-mode to the values they have in Org-mode, and then interactively
7800 call CMD."
7801 (org-load-modules-maybe)
7802 (unless org-local-vars
7803 (setq org-local-vars (org-get-local-variables)))
7804 (eval (list 'let org-local-vars
7805 (list 'call-interactively (list 'quote cmd)))))
7807 ;;;; Archiving
7809 (defun org-get-category (&optional pos)
7810 "Get the category applying to position POS."
7811 (get-text-property (or pos (point)) 'org-category))
7813 (defun org-refresh-category-properties ()
7814 "Refresh category text properties in the buffer."
7815 (let ((def-cat (cond
7816 ((null org-category)
7817 (if buffer-file-name
7818 (file-name-sans-extension
7819 (file-name-nondirectory buffer-file-name))
7820 "???"))
7821 ((symbolp org-category) (symbol-name org-category))
7822 (t org-category)))
7823 beg end cat pos optionp)
7824 (org-unmodified
7825 (save-excursion
7826 (save-restriction
7827 (widen)
7828 (goto-char (point-min))
7829 (put-text-property (point) (point-max) 'org-category def-cat)
7830 (while (re-search-forward
7831 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7832 (setq pos (match-end 0)
7833 optionp (equal (char-after (match-beginning 0)) ?#)
7834 cat (org-trim (match-string 2)))
7835 (if optionp
7836 (setq beg (point-at-bol) end (point-max))
7837 (org-back-to-heading t)
7838 (setq beg (point) end (org-end-of-subtree t t)))
7839 (put-text-property beg end 'org-category cat)
7840 (goto-char pos)))))))
7843 ;;;; Link Stuff
7845 ;;; Link abbreviations
7847 (defun org-link-expand-abbrev (link)
7848 "Apply replacements as defined in `org-link-abbrev-alist."
7849 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7850 (let* ((key (match-string 1 link))
7851 (as (or (assoc key org-link-abbrev-alist-local)
7852 (assoc key org-link-abbrev-alist)))
7853 (tag (and (match-end 2) (match-string 3 link)))
7854 rpl)
7855 (if (not as)
7856 link
7857 (setq rpl (cdr as))
7858 (cond
7859 ((symbolp rpl) (funcall rpl tag))
7860 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7861 ((string-match "%h" rpl)
7862 (replace-match (url-hexify-string (or tag "")) t t rpl))
7863 (t (concat rpl tag)))))
7864 link))
7866 ;;; Storing and inserting links
7868 (defvar org-insert-link-history nil
7869 "Minibuffer history for links inserted with `org-insert-link'.")
7871 (defvar org-stored-links nil
7872 "Contains the links stored with `org-store-link'.")
7874 (defvar org-store-link-plist nil
7875 "Plist with info about the most recently link created with `org-store-link'.")
7877 (defvar org-link-protocols nil
7878 "Link protocols added to Org-mode using `org-add-link-type'.")
7880 (defvar org-store-link-functions nil
7881 "List of functions that are called to create and store a link.
7882 Each function will be called in turn until one returns a non-nil
7883 value. Each function should check if it is responsible for creating
7884 this link (for example by looking at the major mode).
7885 If not, it must exit and return nil.
7886 If yes, it should return a non-nil value after a calling
7887 `org-store-link-props' with a list of properties and values.
7888 Special properties are:
7890 :type The link prefix. like \"http\". This must be given.
7891 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7892 This is obligatory as well.
7893 :description Optional default description for the second pair
7894 of brackets in an Org-mode link. The user can still change
7895 this when inserting this link into an Org-mode buffer.
7897 In addition to these, any additional properties can be specified
7898 and then used in remember templates.")
7900 (defun org-add-link-type (type &optional follow export)
7901 "Add TYPE to the list of `org-link-types'.
7902 Re-compute all regular expressions depending on `org-link-types'
7904 FOLLOW and EXPORT are two functions.
7906 FOLLOW should take the link path as the single argument and do whatever
7907 is necessary to follow the link, for example find a file or display
7908 a mail message.
7910 EXPORT should format the link path for export to one of the export formats.
7911 It should be a function accepting three arguments:
7913 path the path of the link, the text after the prefix (like \"http:\")
7914 desc the description of the link, if any, nil if there was no description
7915 format the export format, a symbol like `html' or `latex'.
7917 The function may use the FORMAT information to return different values
7918 depending on the format. The return value will be put literally into
7919 the exported file.
7920 Org-mode has a built-in default for exporting links. If you are happy with
7921 this default, there is no need to define an export function for the link
7922 type. For a simple example of an export function, see `org-bbdb.el'."
7923 (add-to-list 'org-link-types type t)
7924 (org-make-link-regexps)
7925 (if (assoc type org-link-protocols)
7926 (setcdr (assoc type org-link-protocols) (list follow export))
7927 (push (list type follow export) org-link-protocols)))
7929 (defvar org-agenda-buffer-name)
7931 ;;;###autoload
7932 (defun org-store-link (arg)
7933 "\\<org-mode-map>Store an org-link to the current location.
7934 This link is added to `org-stored-links' and can later be inserted
7935 into an org-buffer with \\[org-insert-link].
7937 For some link types, a prefix arg is interpreted:
7938 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7939 For file links, arg negates `org-context-in-file-links'."
7940 (interactive "P")
7941 (org-load-modules-maybe)
7942 (setq org-store-link-plist nil) ; reset
7943 (let ((outline-regexp (org-get-limited-outline-regexp))
7944 link cpltxt desc description search txt custom-id)
7945 (cond
7947 ((run-hook-with-args-until-success 'org-store-link-functions)
7948 (setq link (plist-get org-store-link-plist :link)
7949 desc (or (plist-get org-store-link-plist :description) link)))
7951 ((equal (buffer-name) "*Org Edit Src Example*")
7952 (let (label gc)
7953 (while (or (not label)
7954 (save-excursion
7955 (save-restriction
7956 (widen)
7957 (goto-char (point-min))
7958 (re-search-forward
7959 (regexp-quote (format org-coderef-label-format label))
7960 nil t))))
7961 (when label (message "Label exists already") (sit-for 2))
7962 (setq label (read-string "Code line label: " label)))
7963 (end-of-line 1)
7964 (setq link (format org-coderef-label-format label))
7965 (setq gc (- 79 (length link)))
7966 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7967 (insert link)
7968 (setq link (concat "(" label ")") desc nil)))
7970 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7971 ;; We are in the agenda, link to referenced location
7972 (let ((m (or (get-text-property (point) 'org-hd-marker)
7973 (get-text-property (point) 'org-marker))))
7974 (when m
7975 (org-with-point-at m
7976 (call-interactively 'org-store-link)))))
7978 ((eq major-mode 'calendar-mode)
7979 (let ((cd (calendar-cursor-to-date)))
7980 (setq link
7981 (format-time-string
7982 (car org-time-stamp-formats)
7983 (apply 'encode-time
7984 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7985 nil nil nil))))
7986 (org-store-link-props :type "calendar" :date cd)))
7988 ((eq major-mode 'w3-mode)
7989 (setq cpltxt (if (and (buffer-name)
7990 (not (string-match "Untitled" (buffer-name))))
7991 (buffer-name)
7992 (url-view-url t))
7993 link (org-make-link (url-view-url t)))
7994 (org-store-link-props :type "w3" :url (url-view-url t)))
7996 ((eq major-mode 'w3m-mode)
7997 (setq cpltxt (or w3m-current-title w3m-current-url)
7998 link (org-make-link w3m-current-url))
7999 (org-store-link-props :type "w3m" :url (url-view-url t)))
8001 ((setq search (run-hook-with-args-until-success
8002 'org-create-file-search-functions))
8003 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8004 "::" search))
8005 (setq cpltxt (or description link)))
8007 ((eq major-mode 'image-mode)
8008 (setq cpltxt (concat "file:"
8009 (abbreviate-file-name buffer-file-name))
8010 link (org-make-link cpltxt))
8011 (org-store-link-props :type "image" :file buffer-file-name))
8013 ((eq major-mode 'dired-mode)
8014 ;; link to the file in the current line
8015 (let ((file (dired-get-filename nil t)))
8016 (setq file (if file
8017 (abbreviate-file-name
8018 (expand-file-name (dired-get-filename nil t)))
8019 ;; otherwise, no file so use current directory.
8020 default-directory))
8021 (setq cpltxt (concat "file:" file)
8022 link (org-make-link cpltxt))))
8024 ((and buffer-file-name (org-mode-p))
8025 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8026 (cond
8027 ((org-in-regexp "<<\\(.*?\\)>>")
8028 (setq cpltxt
8029 (concat "file:"
8030 (abbreviate-file-name buffer-file-name)
8031 "::" (match-string 1))
8032 link (org-make-link cpltxt)))
8033 ((and (featurep 'org-id)
8034 (or (eq org-link-to-org-use-id t)
8035 (and (eq org-link-to-org-use-id 'create-if-interactive)
8036 (interactive-p))
8037 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8038 (interactive-p)
8039 (not custom-id))
8040 (and org-link-to-org-use-id
8041 (condition-case nil
8042 (org-entry-get nil "ID")
8043 (error nil)))))
8044 ;; We can make a link using the ID.
8045 (setq link (condition-case nil
8046 (prog1 (org-id-store-link)
8047 (setq desc (plist-get org-store-link-plist
8048 :description)))
8049 (error
8050 ;; probably before first headline, link to file only
8051 (concat "file:"
8052 (abbreviate-file-name buffer-file-name))))))
8054 ;; Just link to current headline
8055 (setq cpltxt (concat "file:"
8056 (abbreviate-file-name buffer-file-name)))
8057 ;; Add a context search string
8058 (when (org-xor org-context-in-file-links arg)
8059 (setq txt (cond
8060 ((org-on-heading-p) nil)
8061 ((org-region-active-p)
8062 (buffer-substring (region-beginning) (region-end)))
8063 (t nil)))
8064 (when (or (null txt) (string-match "\\S-" txt))
8065 (setq cpltxt
8066 (concat cpltxt "::"
8067 (condition-case nil
8068 (org-make-org-heading-search-string txt)
8069 (error "")))
8070 desc (or (nth 4 (ignore-errors
8071 (org-heading-components))) "NONE"))))
8072 (if (string-match "::\\'" cpltxt)
8073 (setq cpltxt (substring cpltxt 0 -2)))
8074 (setq link (org-make-link cpltxt)))))
8076 ((buffer-file-name (buffer-base-buffer))
8077 ;; Just link to this file here.
8078 (setq cpltxt (concat "file:"
8079 (abbreviate-file-name
8080 (buffer-file-name (buffer-base-buffer)))))
8081 ;; Add a context string
8082 (when (org-xor org-context-in-file-links arg)
8083 (setq txt (if (org-region-active-p)
8084 (buffer-substring (region-beginning) (region-end))
8085 (buffer-substring (point-at-bol) (point-at-eol))))
8086 ;; Only use search option if there is some text.
8087 (when (string-match "\\S-" txt)
8088 (setq cpltxt
8089 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8090 desc "NONE")))
8091 (setq link (org-make-link cpltxt)))
8093 ((interactive-p)
8094 (error "Cannot link to a buffer which is not visiting a file"))
8096 (t (setq link nil)))
8098 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8099 (setq link (or link cpltxt)
8100 desc (or desc cpltxt))
8101 (if (equal desc "NONE") (setq desc nil))
8103 (if (and (or (interactive-p) executing-kbd-macro) link)
8104 (progn
8105 (setq org-stored-links
8106 (cons (list link desc) org-stored-links))
8107 (message "Stored: %s" (or desc link))
8108 (when custom-id
8109 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8110 "::#" custom-id))
8111 (setq org-stored-links
8112 (cons (list link desc) org-stored-links))))
8113 (and link (org-make-link-string link desc)))))
8115 (defun org-store-link-props (&rest plist)
8116 "Store link properties, extract names and addresses."
8117 (let (x adr)
8118 (when (setq x (plist-get plist :from))
8119 (setq adr (mail-extract-address-components x))
8120 (setq plist (plist-put plist :fromname (car adr)))
8121 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8122 (when (setq x (plist-get plist :to))
8123 (setq adr (mail-extract-address-components x))
8124 (setq plist (plist-put plist :toname (car adr)))
8125 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8126 (let ((from (plist-get plist :from))
8127 (to (plist-get plist :to)))
8128 (when (and from to org-from-is-user-regexp)
8129 (setq plist
8130 (plist-put plist :fromto
8131 (if (string-match org-from-is-user-regexp from)
8132 (concat "to %t")
8133 (concat "from %f"))))))
8134 (setq org-store-link-plist plist))
8136 (defun org-add-link-props (&rest plist)
8137 "Add these properties to the link property list."
8138 (let (key value)
8139 (while plist
8140 (setq key (pop plist) value (pop plist))
8141 (setq org-store-link-plist
8142 (plist-put org-store-link-plist key value)))))
8144 (defun org-email-link-description (&optional fmt)
8145 "Return the description part of an email link.
8146 This takes information from `org-store-link-plist' and formats it
8147 according to FMT (default from `org-email-link-description-format')."
8148 (setq fmt (or fmt org-email-link-description-format))
8149 (let* ((p org-store-link-plist)
8150 (to (plist-get p :toaddress))
8151 (from (plist-get p :fromaddress))
8152 (table
8153 (list
8154 (cons "%c" (plist-get p :fromto))
8155 (cons "%F" (plist-get p :from))
8156 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8157 (cons "%T" (plist-get p :to))
8158 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8159 (cons "%s" (plist-get p :subject))
8160 (cons "%m" (plist-get p :message-id)))))
8161 (when (string-match "%c" fmt)
8162 ;; Check if the user wrote this message
8163 (if (and org-from-is-user-regexp from to
8164 (save-match-data (string-match org-from-is-user-regexp from)))
8165 (setq fmt (replace-match "to %t" t t fmt))
8166 (setq fmt (replace-match "from %f" t t fmt))))
8167 (org-replace-escapes fmt table)))
8169 (defun org-make-org-heading-search-string (&optional string heading)
8170 "Make search string for STRING or current headline."
8171 (interactive)
8172 (let ((s (or string (org-get-heading))))
8173 (unless (and string (not heading))
8174 ;; We are using a headline, clean up garbage in there.
8175 (if (string-match org-todo-regexp s)
8176 (setq s (replace-match "" t t s)))
8177 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8178 (setq s (replace-match "" t t s)))
8179 (setq s (org-trim s))
8180 (if (string-match (concat "^\\(" org-quote-string "\\|"
8181 org-comment-string "\\)") s)
8182 (setq s (replace-match "" t t s)))
8183 (while (string-match org-ts-regexp s)
8184 (setq s (replace-match "" t t s))))
8185 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8186 (setq s (replace-match " " t t s)))
8187 (or string (setq s (concat "*" s))) ; Add * for headlines
8188 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8190 (defun org-make-link (&rest strings)
8191 "Concatenate STRINGS."
8192 (apply 'concat strings))
8194 (defun org-make-link-string (link &optional description)
8195 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8196 (unless (string-match "\\S-" link)
8197 (error "Empty link"))
8198 (when (and description
8199 (stringp description)
8200 (not (string-match "\\S-" description)))
8201 (setq description nil))
8202 (when (stringp description)
8203 ;; Remove brackets from the description, they are fatal.
8204 (while (string-match "\\[" description)
8205 (setq description (replace-match "{" t t description)))
8206 (while (string-match "\\]" description)
8207 (setq description (replace-match "}" t t description))))
8208 (when (equal (org-link-escape link) description)
8209 ;; No description needed, it is identical
8210 (setq description nil))
8211 (when (and (not description)
8212 (not (equal link (org-link-escape link))))
8213 (setq description (org-extract-attributes link)))
8214 (concat "[[" (org-link-escape link) "]"
8215 (if description (concat "[" description "]") "")
8216 "]"))
8218 (defconst org-link-escape-chars
8219 '((?\ . "%20")
8220 (?\[ . "%5B")
8221 (?\] . "%5D")
8222 (?\340 . "%E0") ; `a
8223 (?\342 . "%E2") ; ^a
8224 (?\347 . "%E7") ; ,c
8225 (?\350 . "%E8") ; `e
8226 (?\351 . "%E9") ; 'e
8227 (?\352 . "%EA") ; ^e
8228 (?\356 . "%EE") ; ^i
8229 (?\364 . "%F4") ; ^o
8230 (?\371 . "%F9") ; `u
8231 (?\373 . "%FB") ; ^u
8232 (?\; . "%3B")
8233 ;; (?? . "%3F")
8234 (?= . "%3D")
8235 (?+ . "%2B")
8237 "Association list of escapes for some characters problematic in links.
8238 This is the list that is used for internal purposes.")
8240 (defvar org-url-encoding-use-url-hexify nil)
8242 (defconst org-link-escape-chars-browser
8243 '((?\ . "%20")) ; 32 for the SPC char
8244 "Association list of escapes for some characters problematic in links.
8245 This is the list that is used before handing over to the browser.")
8247 (defun org-link-escape (text &optional table)
8248 "Escape characters in TEXT that are problematic for links."
8249 (if (and org-url-encoding-use-url-hexify (not table))
8250 (url-hexify-string text)
8251 (setq table (or table org-link-escape-chars))
8252 (when text
8253 (let ((re (mapconcat (lambda (x) (regexp-quote
8254 (char-to-string (car x))))
8255 table "\\|")))
8256 (while (string-match re text)
8257 (setq text
8258 (replace-match
8259 (cdr (assoc (string-to-char (match-string 0 text))
8260 table))
8261 t t text)))
8262 text))))
8264 (defun org-link-unescape (text &optional table)
8265 "Reverse the action of `org-link-escape'."
8266 (if (and org-url-encoding-use-url-hexify (not table))
8267 (url-unhex-string text)
8268 (setq table (or table org-link-escape-chars))
8269 (when text
8270 (let ((case-fold-search t)
8271 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8272 table "\\|")))
8273 (while (string-match re text)
8274 (setq text
8275 (replace-match
8276 (char-to-string (car (rassoc (upcase (match-string 0 text))
8277 table)))
8278 t t text)))
8279 text))))
8281 (defun org-xor (a b)
8282 "Exclusive or."
8283 (if a (not b) b))
8285 (defun org-fixup-message-id-for-http (s)
8286 "Replace special characters in a message id, so it can be used in an http query."
8287 (while (string-match "<" s)
8288 (setq s (replace-match "%3C" t t s)))
8289 (while (string-match ">" s)
8290 (setq s (replace-match "%3E" t t s)))
8291 (while (string-match "@" s)
8292 (setq s (replace-match "%40" t t s)))
8295 ;;;###autoload
8296 (defun org-insert-link-global ()
8297 "Insert a link like Org-mode does.
8298 This command can be called in any mode to insert a link in Org-mode syntax."
8299 (interactive)
8300 (org-load-modules-maybe)
8301 (org-run-like-in-org-mode 'org-insert-link))
8303 (defun org-insert-link (&optional complete-file link-location)
8304 "Insert a link. At the prompt, enter the link.
8306 Completion can be used to insert any of the link protocol prefixes like
8307 http or ftp in use.
8309 The history can be used to select a link previously stored with
8310 `org-store-link'. When the empty string is entered (i.e. if you just
8311 press RET at the prompt), the link defaults to the most recently
8312 stored link. As SPC triggers completion in the minibuffer, you need to
8313 use M-SPC or C-q SPC to force the insertion of a space character.
8315 You will also be prompted for a description, and if one is given, it will
8316 be displayed in the buffer instead of the link.
8318 If there is already a link at point, this command will allow you to edit link
8319 and description parts.
8321 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8322 be selected using completion. The path to the file will be relative to the
8323 current directory if the file is in the current directory or a subdirectory.
8324 Otherwise, the link will be the absolute path as completed in the minibuffer
8325 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8326 option `org-link-file-path-type'.
8328 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8329 the current directory or below.
8331 With three \\[universal-argument] prefixes, negate the meaning of
8332 `org-keep-stored-link-after-insertion'.
8334 If `org-make-link-description-function' is non-nil, this function will be
8335 called with the link target, and the result will be the default
8336 link description.
8338 If the LINK-LOCATION parameter is non-nil, this value will be
8339 used as the link location instead of reading one interactively."
8340 (interactive "P")
8341 (let* ((wcf (current-window-configuration))
8342 (region (if (org-region-active-p)
8343 (buffer-substring (region-beginning) (region-end))))
8344 (remove (and region (list (region-beginning) (region-end))))
8345 (desc region)
8346 tmphist ; byte-compile incorrectly complains about this
8347 (link link-location)
8348 entry file all-prefixes)
8349 (cond
8350 (link-location) ; specified by arg, just use it.
8351 ((org-in-regexp org-bracket-link-regexp 1)
8352 ;; We do have a link at point, and we are going to edit it.
8353 (setq remove (list (match-beginning 0) (match-end 0)))
8354 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8355 (setq link (read-string "Link: "
8356 (org-link-unescape
8357 (org-match-string-no-properties 1)))))
8358 ((or (org-in-regexp org-angle-link-re)
8359 (org-in-regexp org-plain-link-re))
8360 ;; Convert to bracket link
8361 (setq remove (list (match-beginning 0) (match-end 0))
8362 link (read-string "Link: "
8363 (org-remove-angle-brackets (match-string 0)))))
8364 ((member complete-file '((4) (16)))
8365 ;; Completing read for file names.
8366 (setq link (org-file-complete-link complete-file)))
8368 ;; Read link, with completion for stored links.
8369 (with-output-to-temp-buffer "*Org Links*"
8370 (princ "Insert a link.
8371 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8372 (when org-stored-links
8373 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8374 (princ (mapconcat
8375 (lambda (x)
8376 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8377 (reverse org-stored-links) "\n"))))
8378 (let ((cw (selected-window)))
8379 (select-window (get-buffer-window "*Org Links*" 'visible))
8380 (setq truncate-lines t)
8381 (unless (pos-visible-in-window-p (point-max))
8382 (org-fit-window-to-buffer))
8383 (and (window-live-p cw) (select-window cw)))
8384 ;; Fake a link history, containing the stored links.
8385 (setq tmphist (append (mapcar 'car org-stored-links)
8386 org-insert-link-history))
8387 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8388 (mapcar 'car org-link-abbrev-alist)
8389 org-link-types))
8390 (unwind-protect
8391 (progn
8392 (setq link
8393 (let ((org-completion-use-ido nil)
8394 (org-completion-use-iswitchb nil))
8395 (org-completing-read
8396 "Link: "
8397 (append
8398 (mapcar (lambda (x) (list (concat x ":")))
8399 all-prefixes)
8400 (mapcar 'car org-stored-links))
8401 nil nil nil
8402 'tmphist
8403 (car (car org-stored-links)))))
8404 (if (not (string-match "\\S-" link))
8405 (error "No link selected"))
8406 (if (or (member link all-prefixes)
8407 (and (equal ":" (substring link -1))
8408 (member (substring link 0 -1) all-prefixes)
8409 (setq link (substring link 0 -1))))
8410 (setq link (org-link-try-special-completion link))))
8411 (set-window-configuration wcf)
8412 (kill-buffer "*Org Links*"))
8413 (setq entry (assoc link org-stored-links))
8414 (or entry (push link org-insert-link-history))
8415 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8416 (not org-keep-stored-link-after-insertion))
8417 (setq org-stored-links (delq (assoc link org-stored-links)
8418 org-stored-links)))
8419 (setq desc (or desc (nth 1 entry)))))
8421 (if (string-match org-plain-link-re link)
8422 ;; URL-like link, normalize the use of angular brackets.
8423 (setq link (org-make-link (org-remove-angle-brackets link))))
8425 ;; Check if we are linking to the current file with a search option
8426 ;; If yes, simplify the link by using only the search option.
8427 (when (and buffer-file-name
8428 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8429 (let* ((path (match-string 1 link))
8430 (case-fold-search nil)
8431 (search (match-string 2 link)))
8432 (save-match-data
8433 (if (equal (file-truename buffer-file-name) (file-truename path))
8434 ;; We are linking to this same file, with a search option
8435 (setq link search)))))
8437 ;; Check if we can/should use a relative path. If yes, simplify the link
8438 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8439 (let* ((type (match-string 1 link))
8440 (path (match-string 2 link))
8441 (origpath path)
8442 (case-fold-search nil))
8443 (cond
8444 ((or (eq org-link-file-path-type 'absolute)
8445 (equal complete-file '(16)))
8446 (setq path (abbreviate-file-name (expand-file-name path))))
8447 ((eq org-link-file-path-type 'noabbrev)
8448 (setq path (expand-file-name path)))
8449 ((eq org-link-file-path-type 'relative)
8450 (setq path (file-relative-name path)))
8452 (save-match-data
8453 (if (string-match (concat "^" (regexp-quote
8454 (file-name-as-directory
8455 (expand-file-name "."))))
8456 (expand-file-name path))
8457 ;; We are linking a file with relative path name.
8458 (setq path (substring (expand-file-name path)
8459 (match-end 0)))
8460 (setq path (abbreviate-file-name (expand-file-name path)))))))
8461 (setq link (concat type path))
8462 (if (equal desc origpath)
8463 (setq desc path))))
8465 (if org-make-link-description-function
8466 (setq desc (funcall org-make-link-description-function link desc)))
8468 (setq desc (read-string "Description: " desc))
8469 (unless (string-match "\\S-" desc) (setq desc nil))
8470 (if remove (apply 'delete-region remove))
8471 (insert (org-make-link-string link desc))))
8473 (defun org-link-try-special-completion (type)
8474 "If there is completion support for link type TYPE, offer it."
8475 (let ((fun (intern (concat "org-" type "-complete-link"))))
8476 (if (functionp fun)
8477 (funcall fun)
8478 (read-string "Link (no completion support): " (concat type ":")))))
8480 (defun org-file-complete-link (&optional arg)
8481 "Create a file link using completion."
8482 (let (file link)
8483 (setq file (read-file-name "File: "))
8484 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8485 (pwd1 (file-name-as-directory (abbreviate-file-name
8486 (expand-file-name ".")))))
8487 (cond
8488 ((equal arg '(16))
8489 (setq link (org-make-link
8490 "file:"
8491 (abbreviate-file-name (expand-file-name file)))))
8492 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8493 (setq link (org-make-link "file:" (match-string 1 file))))
8494 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8495 (expand-file-name file))
8496 (setq link (org-make-link
8497 "file:" (match-string 1 (expand-file-name file)))))
8498 (t (setq link (org-make-link "file:" file)))))
8499 link))
8501 (defun org-completing-read (&rest args)
8502 "Completing-read with SPACE being a normal character."
8503 (let ((minibuffer-local-completion-map
8504 (copy-keymap minibuffer-local-completion-map)))
8505 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8506 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8507 (apply 'org-icompleting-read args)))
8509 (defun org-completing-read-no-i (&rest args)
8510 (let (org-completion-use-ido org-completion-use-iswitchb)
8511 (apply 'org-completing-read args)))
8513 (defun org-iswitchb-completing-read (prompt choices &rest args)
8514 "Use iswitch as a completing-read replacement to choose from choices.
8515 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8516 from."
8517 (let* ((iswitchb-use-virtual-buffers nil)
8518 (iswitchb-make-buflist-hook
8519 (lambda ()
8520 (setq iswitchb-temp-buflist choices))))
8521 (iswitchb-read-buffer prompt)))
8523 (defun org-icompleting-read (&rest args)
8524 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8525 (org-without-partial-completion
8526 (if (and org-completion-use-ido
8527 (fboundp 'ido-completing-read)
8528 (boundp 'ido-mode) ido-mode
8529 (listp (second args)))
8530 (let ((ido-enter-matching-directory nil))
8531 (apply 'ido-completing-read (concat (car args))
8532 (if (consp (car (nth 1 args)))
8533 (mapcar (lambda (x) (car x)) (nth 1 args))
8534 (nth 1 args))
8535 (cddr args)))
8536 (if (and org-completion-use-iswitchb
8537 (boundp 'iswitchb-mode) iswitchb-mode
8538 (listp (second args)))
8539 (apply 'org-iswitchb-completing-read (concat (car args))
8540 (if (consp (car (nth 1 args)))
8541 (mapcar (lambda (x) (car x)) (nth 1 args))
8542 (nth 1 args))
8543 (cddr args))
8544 (apply 'completing-read args)))))
8546 (defun org-extract-attributes (s)
8547 "Extract the attributes cookie from a string and set as text property."
8548 (let (a attr (start 0) key value)
8549 (save-match-data
8550 (when (string-match "{{\\([^}]+\\)}}$" s)
8551 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8552 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8553 (setq key (match-string 1 a) value (match-string 2 a)
8554 start (match-end 0)
8555 attr (plist-put attr (intern key) value))))
8556 (org-add-props s nil 'org-attr attr))
8559 (defun org-extract-attributes-from-string (tag)
8560 (let (key value attr)
8561 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8562 (setq key (match-string 1 tag) value (match-string 2 tag)
8563 tag (replace-match "" t t tag)
8564 attr (plist-put attr (intern key) value)))
8565 (cons tag attr)))
8567 (defun org-attributes-to-string (plist)
8568 "Format a property list into an HTML attribute list."
8569 (let ((s "") key value)
8570 (while plist
8571 (setq key (pop plist) value (pop plist))
8572 (and value
8573 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8576 ;;; Opening/following a link
8578 (defvar org-link-search-failed nil)
8580 (defvar org-open-link-functions nil
8581 "Hook for functions finding a plain text link.
8582 These functions must take a single argument, the link content.
8583 They will be called for links that look like [[link text][description]]
8584 when LINK TEXT does not have a protocol like \"http:\" and does not look
8585 like a filename (e.g. \"./blue.png\").
8587 These functions will be called *before* Org attempts to resolve the
8588 link by doing text searches in the current buffer - so if you want a
8589 link \"[[target]]\" to still find \"<<target>>\", your function should
8590 handle this as a special case.
8592 When the function does handle the link, it must return a non-nil value.
8593 If it decides that it is not responsible for this link, it must return
8594 nil to indicate that that Org-mode can continue with other options
8595 like exact and fuzzy text search.")
8597 (defun org-next-link ()
8598 "Move forward to the next link.
8599 If the link is in hidden text, expose it."
8600 (interactive)
8601 (when (and org-link-search-failed (eq this-command last-command))
8602 (goto-char (point-min))
8603 (message "Link search wrapped back to beginning of buffer"))
8604 (setq org-link-search-failed nil)
8605 (let* ((pos (point))
8606 (ct (org-context))
8607 (a (assoc :link ct)))
8608 (if a (goto-char (nth 2 a)))
8609 (if (re-search-forward org-any-link-re nil t)
8610 (progn
8611 (goto-char (match-beginning 0))
8612 (if (org-invisible-p) (org-show-context)))
8613 (goto-char pos)
8614 (setq org-link-search-failed t)
8615 (error "No further link found"))))
8617 (defun org-previous-link ()
8618 "Move backward to the previous link.
8619 If the link is in hidden text, expose it."
8620 (interactive)
8621 (when (and org-link-search-failed (eq this-command last-command))
8622 (goto-char (point-max))
8623 (message "Link search wrapped back to end of buffer"))
8624 (setq org-link-search-failed nil)
8625 (let* ((pos (point))
8626 (ct (org-context))
8627 (a (assoc :link ct)))
8628 (if a (goto-char (nth 1 a)))
8629 (if (re-search-backward org-any-link-re nil t)
8630 (progn
8631 (goto-char (match-beginning 0))
8632 (if (org-invisible-p) (org-show-context)))
8633 (goto-char pos)
8634 (setq org-link-search-failed t)
8635 (error "No further link found"))))
8637 (defun org-translate-link (s)
8638 "Translate a link string if a translation function has been defined."
8639 (if (and org-link-translation-function
8640 (fboundp org-link-translation-function)
8641 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8642 (progn
8643 (setq s (funcall org-link-translation-function
8644 (match-string 1) (match-string 2)))
8645 (concat (car s) ":" (cdr s)))
8648 (defun org-translate-link-from-planner (type path)
8649 "Translate a link from Emacs Planner syntax so that Org can follow it.
8650 This is still an experimental function, your mileage may vary."
8651 (cond
8652 ((member type '("http" "https" "news" "ftp"))
8653 ;; standard Internet links are the same.
8654 nil)
8655 ((and (equal type "irc") (string-match "^//" path))
8656 ;; Planner has two / at the beginning of an irc link, we have 1.
8657 ;; We should have zero, actually....
8658 (setq path (substring path 1)))
8659 ((and (equal type "lisp") (string-match "^/" path))
8660 ;; Planner has a slash, we do not.
8661 (setq type "elisp" path (substring path 1)))
8662 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8663 ;; A typical message link. Planner has the id after the final slash,
8664 ;; we separate it with a hash mark
8665 (setq path (concat (match-string 1 path) "#"
8666 (org-remove-angle-brackets (match-string 2 path)))))
8668 (cons type path))
8670 (defun org-find-file-at-mouse (ev)
8671 "Open file link or URL at mouse."
8672 (interactive "e")
8673 (mouse-set-point ev)
8674 (org-open-at-point 'in-emacs))
8676 (defun org-open-at-mouse (ev)
8677 "Open file link or URL at mouse."
8678 (interactive "e")
8679 (mouse-set-point ev)
8680 (if (eq major-mode 'org-agenda-mode)
8681 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8682 (org-open-at-point))
8684 (defvar org-window-config-before-follow-link nil
8685 "The window configuration before following a link.
8686 This is saved in case the need arises to restore it.")
8688 (defvar org-open-link-marker (make-marker)
8689 "Marker pointing to the location where `org-open-at-point; was called.")
8691 ;;;###autoload
8692 (defun org-open-at-point-global ()
8693 "Follow a link like Org-mode does.
8694 This command can be called in any mode to follow a link that has
8695 Org-mode syntax."
8696 (interactive)
8697 (org-run-like-in-org-mode 'org-open-at-point))
8699 ;;;###autoload
8700 (defun org-open-link-from-string (s &optional arg reference-buffer)
8701 "Open a link in the string S, as if it was in Org-mode."
8702 (interactive "sLink: \nP")
8703 (let ((reference-buffer (or reference-buffer (current-buffer))))
8704 (with-temp-buffer
8705 (let ((org-inhibit-startup t))
8706 (org-mode)
8707 (insert s)
8708 (goto-char (point-min))
8709 (when reference-buffer
8710 (setq org-link-abbrev-alist-local
8711 (with-current-buffer reference-buffer
8712 org-link-abbrev-alist-local)))
8713 (org-open-at-point arg reference-buffer)))))
8715 (defun org-open-at-point (&optional in-emacs reference-buffer)
8716 "Open link at or after point.
8717 If there is no link at point, this function will search forward up to
8718 the end of the current line.
8719 Normally, files will be opened by an appropriate application. If the
8720 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8721 With a double prefix argument, try to open outside of Emacs, in the
8722 application the system uses for this file type."
8723 (interactive "P")
8724 (org-load-modules-maybe)
8725 (move-marker org-open-link-marker (point))
8726 (setq org-window-config-before-follow-link (current-window-configuration))
8727 (org-remove-occur-highlights nil nil t)
8728 (cond
8729 ((and (org-on-heading-p)
8730 (not (org-in-regexp
8731 (concat org-plain-link-re "\\|"
8732 org-bracket-link-regexp "\\|"
8733 org-angle-link-re "\\|"
8734 "[ \t]:[^ \t\n]+:[ \t]*$")))
8735 (not (get-text-property (point) 'org-linked-text)))
8736 (or (org-offer-links-in-entry in-emacs)
8737 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8738 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8739 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8740 (org-footnote-action))
8742 (let (type path link line search (pos (point)))
8743 (catch 'match
8744 (save-excursion
8745 (skip-chars-forward "^]\n\r")
8746 (when (org-in-regexp org-bracket-link-regexp 1)
8747 (setq link (org-extract-attributes
8748 (org-link-unescape (org-match-string-no-properties 1))))
8749 (while (string-match " *\n *" link)
8750 (setq link (replace-match " " t t link)))
8751 (setq link (org-link-expand-abbrev link))
8752 (cond
8753 ((or (file-name-absolute-p link)
8754 (string-match "^\\.\\.?/" link))
8755 (setq type "file" path link))
8756 ((string-match org-link-re-with-space3 link)
8757 (setq type (match-string 1 link) path (match-string 2 link)))
8758 (t (setq type "thisfile" path link)))
8759 (throw 'match t)))
8761 (when (get-text-property (point) 'org-linked-text)
8762 (setq type "thisfile"
8763 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8764 (1+ (point)) (point))
8765 path (buffer-substring
8766 (previous-single-property-change pos 'org-linked-text)
8767 (next-single-property-change pos 'org-linked-text)))
8768 (throw 'match t))
8770 (save-excursion
8771 (when (or (org-in-regexp org-angle-link-re)
8772 (org-in-regexp org-plain-link-re))
8773 (setq type (match-string 1) path (match-string 2))
8774 (throw 'match t)))
8775 (save-excursion
8776 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8777 (setq type "tags"
8778 path (match-string 1))
8779 (while (string-match ":" path)
8780 (setq path (replace-match "+" t t path)))
8781 (throw 'match t)))
8782 (when (org-in-regexp "<\\([^><\n]+\\)>")
8783 (setq type "tree-match"
8784 path (match-string 1))
8785 (throw 'match t)))
8786 (unless path
8787 (error "No link found"))
8789 ;; switch back to reference buffer
8790 ;; needed when if called in a temporary buffer through
8791 ;; org-open-link-from-string
8792 (with-current-buffer (or reference-buffer (current-buffer))
8794 ;; Remove any trailing spaces in path
8795 (if (string-match " +\\'" path)
8796 (setq path (replace-match "" t t path)))
8797 (if (and org-link-translation-function
8798 (fboundp org-link-translation-function))
8799 ;; Check if we need to translate the link
8800 (let ((tmp (funcall org-link-translation-function type path)))
8801 (setq type (car tmp) path (cdr tmp))))
8803 (cond
8805 ((assoc type org-link-protocols)
8806 (funcall (nth 1 (assoc type org-link-protocols)) path))
8808 ((equal type "mailto")
8809 (let ((cmd (car org-link-mailto-program))
8810 (args (cdr org-link-mailto-program)) args1
8811 (address path) (subject "") a)
8812 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8813 (setq address (match-string 1 path)
8814 subject (org-link-escape (match-string 2 path))))
8815 (while args
8816 (cond
8817 ((not (stringp (car args))) (push (pop args) args1))
8818 (t (setq a (pop args))
8819 (if (string-match "%a" a)
8820 (setq a (replace-match address t t a)))
8821 (if (string-match "%s" a)
8822 (setq a (replace-match subject t t a)))
8823 (push a args1))))
8824 (apply cmd (nreverse args1))))
8826 ((member type '("http" "https" "ftp" "news"))
8827 (browse-url (concat type ":" (org-link-escape
8828 path org-link-escape-chars-browser))))
8830 ((string= type "doi")
8831 (browse-url (concat "http://dx.doi.org/"
8832 (org-link-escape
8833 path org-link-escape-chars-browser))))
8835 ((member type '("message"))
8836 (browse-url (concat type ":" path)))
8838 ((string= type "tags")
8839 (org-tags-view in-emacs path))
8841 ((string= type "tree-match")
8842 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8844 ((string= type "file")
8845 (if (string-match "::\\([0-9]+\\)\\'" path)
8846 (setq line (string-to-number (match-string 1 path))
8847 path (substring path 0 (match-beginning 0)))
8848 (if (string-match "::\\(.+\\)\\'" path)
8849 (setq search (match-string 1 path)
8850 path (substring path 0 (match-beginning 0)))))
8851 (if (string-match "[*?{]" (file-name-nondirectory path))
8852 (dired path)
8853 (org-open-file path in-emacs line search)))
8855 ((string= type "news")
8856 (require 'org-gnus)
8857 (org-gnus-follow-link path))
8859 ((string= type "shell")
8860 (let ((cmd path))
8861 (if (or (not org-confirm-shell-link-function)
8862 (funcall org-confirm-shell-link-function
8863 (format "Execute \"%s\" in shell? "
8864 (org-add-props cmd nil
8865 'face 'org-warning))))
8866 (progn
8867 (message "Executing %s" cmd)
8868 (shell-command cmd))
8869 (error "Abort"))))
8871 ((string= type "elisp")
8872 (let ((cmd path))
8873 (if (or (not org-confirm-elisp-link-function)
8874 (funcall org-confirm-elisp-link-function
8875 (format "Execute \"%s\" as elisp? "
8876 (org-add-props cmd nil
8877 'face 'org-warning))))
8878 (message "%s => %s" cmd
8879 (if (equal (string-to-char cmd) ?\()
8880 (eval (read cmd))
8881 (call-interactively (read cmd))))
8882 (error "Abort"))))
8884 ((and (string= type "thisfile")
8885 (run-hook-with-args-until-success
8886 'org-open-link-functions path)))
8888 ((string= type "thisfile")
8889 (if in-emacs
8890 (switch-to-buffer-other-window
8891 (org-get-buffer-for-internal-link (current-buffer)))
8892 (org-mark-ring-push))
8893 (let ((cmd `(org-link-search
8894 ,path
8895 ,(cond ((equal in-emacs '(4)) 'occur)
8896 ((equal in-emacs '(16)) 'org-occur)
8897 (t nil))
8898 ,pos)))
8899 (condition-case nil (eval cmd)
8900 (error (progn (widen) (eval cmd))))))
8903 (browse-url-at-point)))))))
8904 (move-marker org-open-link-marker nil)
8905 (run-hook-with-args 'org-follow-link-hook))
8907 (defun org-offer-links-in-entry (&optional nth zero)
8908 "Offer links in the current entry and follow the selected link.
8909 If there is only one link, follow it immediately as well.
8910 If NTH is an integer, immediately pick the NTH link found.
8911 If ZERO is a string, check also this string for a link, and if
8912 there is one, offer it as link number zero."
8913 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8914 "\\(" org-angle-link-re "\\)\\|"
8915 "\\(" org-plain-link-re "\\)"))
8916 (cnt ?0)
8917 (in-emacs (if (integerp nth) nil nth))
8918 have-zero end links link c)
8919 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8920 (push (match-string 0 zero) links)
8921 (setq cnt (1- cnt) have-zero t))
8922 (save-excursion
8923 (org-back-to-heading t)
8924 (setq end (save-excursion (outline-next-heading) (point)))
8925 (while (re-search-forward re end t)
8926 (push (match-string 0) links))
8927 (setq links (org-uniquify (reverse links))))
8929 (cond
8930 ((null links)
8931 (message "No links"))
8932 ((equal (length links) 1)
8933 (setq link (list (car links))))
8934 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8935 (setq link (nth (if have-zero nth (1- nth)) links)))
8936 (t ; we have to select a link
8937 (save-excursion
8938 (save-window-excursion
8939 (delete-other-windows)
8940 (with-output-to-temp-buffer "*Select Link*"
8941 (mapc (lambda (l)
8942 (if (not (string-match org-bracket-link-regexp l))
8943 (princ (format "[%c] %s\n" (incf cnt)
8944 (org-remove-angle-brackets l)))
8945 (if (match-end 3)
8946 (princ (format "[%c] %s (%s)\n" (incf cnt)
8947 (match-string 3 l) (match-string 1 l)))
8948 (princ (format "[%c] %s\n" (incf cnt)
8949 (match-string 1 l))))))
8950 links))
8951 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8952 (message "Select link to open, RET to open all:")
8953 (setq c (read-char-exclusive))
8954 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8955 (when (equal c ?q) (error "Abort"))
8956 (if (equal c ?\C-m)
8957 (setq link links)
8958 (setq nth (- c ?0))
8959 (if have-zero (setq nth (1+ nth)))
8960 (unless (and (integerp nth) (>= (length links) nth))
8961 (error "Invalid link selection"))
8962 (setq link (list (nth (1- nth) links))))))
8963 (if link
8964 (let ((buf (current-buffer)))
8965 (dolist (l link)
8966 (org-open-link-from-string l in-emacs buf))
8968 nil)))
8970 ;; Add special file links that specify the way of opening
8972 (org-add-link-type "file+sys" 'org-open-file-with-system)
8973 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8974 (defun org-open-file-with-system (path)
8975 "Open file at PATH using the system way of opeing it."
8976 (org-open-file path 'system))
8977 (defun org-open-file-with-emacs (path)
8978 "Open file at PATH in emacs."
8979 (org-open-file path 'emacs))
8980 (defun org-remove-file-link-modifiers ()
8981 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8982 (goto-char (point-min))
8983 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8984 (org-if-unprotected
8985 (replace-match "file:" t t))))
8986 (eval-after-load "org-exp"
8987 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8988 'org-remove-file-link-modifiers))
8990 ;;;; Time estimates
8992 (defun org-get-effort (&optional pom)
8993 "Get the effort estimate for the current entry."
8994 (org-entry-get pom org-effort-property))
8996 ;;; File search
8998 (defvar org-create-file-search-functions nil
8999 "List of functions to construct the right search string for a file link.
9000 These functions are called in turn with point at the location to
9001 which the link should point.
9003 A function in the hook should first test if it would like to
9004 handle this file type, for example by checking the major-mode or
9005 the file extension. If it decides not to handle this file, it
9006 should just return nil to give other functions a chance. If it
9007 does handle the file, it must return the search string to be used
9008 when following the link. The search string will be part of the
9009 file link, given after a double colon, and `org-open-at-point'
9010 will automatically search for it. If special measures must be
9011 taken to make the search successful, another function should be
9012 added to the companion hook `org-execute-file-search-functions',
9013 which see.
9015 A function in this hook may also use `setq' to set the variable
9016 `description' to provide a suggestion for the descriptive text to
9017 be used for this link when it gets inserted into an Org-mode
9018 buffer with \\[org-insert-link].")
9020 (defvar org-execute-file-search-functions nil
9021 "List of functions to execute a file search triggered by a link.
9023 Functions added to this hook must accept a single argument, the
9024 search string that was part of the file link, the part after the
9025 double colon. The function must first check if it would like to
9026 handle this search, for example by checking the major-mode or the
9027 file extension. If it decides not to handle this search, it
9028 should just return nil to give other functions a chance. If it
9029 does handle the search, it must return a non-nil value to keep
9030 other functions from trying.
9032 Each function can access the current prefix argument through the
9033 variable `current-prefix-argument'. Note that a single prefix is
9034 used to force opening a link in Emacs, so it may be good to only
9035 use a numeric or double prefix to guide the search function.
9037 In case this is needed, a function in this hook can also restore
9038 the window configuration before `org-open-at-point' was called using:
9040 (set-window-configuration org-window-config-before-follow-link)")
9042 (defun org-link-search (s &optional type avoid-pos)
9043 "Search for a link search option.
9044 If S is surrounded by forward slashes, it is interpreted as a
9045 regular expression. In org-mode files, this will create an `org-occur'
9046 sparse tree. In ordinary files, `occur' will be used to list matches.
9047 If the current buffer is in `dired-mode', grep will be used to search
9048 in all files. If AVOID-POS is given, ignore matches near that position."
9049 (let ((case-fold-search t)
9050 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9051 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9052 (append '(("") (" ") ("\t") ("\n"))
9053 org-emphasis-alist)
9054 "\\|") "\\)"))
9055 (pos (point))
9056 (pre nil) (post nil)
9057 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9058 (cond
9059 ;; First check if there are any special
9060 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9061 ;; Now try the builtin stuff
9062 ((and (equal (string-to-char s0) ?#)
9063 (> (length s0) 1)
9064 (save-excursion
9065 (goto-char (point-min))
9066 (and
9067 (re-search-forward
9068 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9069 (setq type 'dedicated
9070 pos (match-beginning 0))))
9071 ;; There is an exact target for this
9072 (goto-char pos)
9073 (org-back-to-heading t)))
9074 ((save-excursion
9075 (goto-char (point-min))
9076 (and
9077 (re-search-forward
9078 (concat "<<" (regexp-quote s0) ">>") nil t)
9079 (setq type 'dedicated
9080 pos (match-beginning 0))))
9081 ;; There is an exact target for this
9082 (goto-char pos))
9083 ((and (string-match "^(\\(.*\\))$" s0)
9084 (save-excursion
9085 (goto-char (point-min))
9086 (and
9087 (re-search-forward
9088 (concat "[^[]" (regexp-quote
9089 (format org-coderef-label-format
9090 (match-string 1 s0))))
9091 nil t)
9092 (setq type 'dedicated
9093 pos (1+ (match-beginning 0))))))
9094 ;; There is a coderef target for this
9095 (goto-char pos))
9096 ((string-match "^/\\(.*\\)/$" s)
9097 ;; A regular expression
9098 (cond
9099 ((org-mode-p)
9100 (org-occur (match-string 1 s)))
9101 ;;((eq major-mode 'dired-mode)
9102 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9103 (t (org-do-occur (match-string 1 s)))))
9105 ;; A normal search strings
9106 (when (equal (string-to-char s) ?*)
9107 ;; Anchor on headlines, post may include tags.
9108 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9109 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9110 s (substring s 1)))
9111 (remove-text-properties
9112 0 (length s)
9113 '(face nil mouse-face nil keymap nil fontified nil) s)
9114 ;; Make a series of regular expressions to find a match
9115 (setq words (org-split-string s "[ \n\r\t]+")
9117 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9118 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9119 "\\)" markers)
9120 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9121 re2a (concat "[ \t\r\n]" re2a_)
9122 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9123 re4 (concat "[^a-zA-Z_]" re4_)
9125 re1 (concat pre re2 post)
9126 re3 (concat pre (if pre re4_ re4) post)
9127 re5 (concat pre ".*" re4)
9128 re2 (concat pre re2)
9129 re2a (concat pre (if pre re2a_ re2a))
9130 re4 (concat pre (if pre re4_ re4))
9131 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9132 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9133 re5 "\\)"
9135 (cond
9136 ((eq type 'org-occur) (org-occur reall))
9137 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9138 (t (goto-char (point-min))
9139 (setq type 'fuzzy)
9140 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9141 (org-search-not-self 1 re1 nil t)
9142 (org-search-not-self 1 re2 nil t)
9143 (org-search-not-self 1 re2a nil t)
9144 (org-search-not-self 1 re3 nil t)
9145 (org-search-not-self 1 re4 nil t)
9146 (org-search-not-self 1 re5 nil t)
9148 (goto-char (match-beginning 1))
9149 (goto-char pos)
9150 (error "No match")))))
9152 ;; Normal string-search
9153 (goto-char (point-min))
9154 (if (search-forward s nil t)
9155 (goto-char (match-beginning 0))
9156 (error "No match"))))
9157 (and (org-mode-p) (org-show-context 'link-search))
9158 type))
9160 (defun org-search-not-self (group &rest args)
9161 "Execute `re-search-forward', but only accept matches that do not
9162 enclose the position of `org-open-link-marker'."
9163 (let ((m org-open-link-marker))
9164 (catch 'exit
9165 (while (apply 're-search-forward args)
9166 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9167 (goto-char (match-end group))
9168 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9169 (> (match-beginning 0) (marker-position m))
9170 (< (match-end 0) (marker-position m)))
9171 (save-match-data
9172 (or (not (org-in-regexp
9173 org-bracket-link-analytic-regexp 1))
9174 (not (match-end 4)) ; no description
9175 (and (<= (match-beginning 4) (point))
9176 (>= (match-end 4) (point))))))
9177 (throw 'exit (point))))))))
9179 (defun org-get-buffer-for-internal-link (buffer)
9180 "Return a buffer to be used for displaying the link target of internal links."
9181 (cond
9182 ((not org-display-internal-link-with-indirect-buffer)
9183 buffer)
9184 ((string-match "(Clone)$" (buffer-name buffer))
9185 (message "Buffer is already a clone, not making another one")
9186 ;; we also do not modify visibility in this case
9187 buffer)
9188 (t ; make a new indirect buffer for displaying the link
9189 (let* ((bn (buffer-name buffer))
9190 (ibn (concat bn "(Clone)"))
9191 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9192 (with-current-buffer ib (org-overview))
9193 ib))))
9195 (defun org-do-occur (regexp &optional cleanup)
9196 "Call the Emacs command `occur'.
9197 If CLEANUP is non-nil, remove the printout of the regular expression
9198 in the *Occur* buffer. This is useful if the regex is long and not useful
9199 to read."
9200 (occur regexp)
9201 (when cleanup
9202 (let ((cwin (selected-window)) win beg end)
9203 (when (setq win (get-buffer-window "*Occur*"))
9204 (select-window win))
9205 (goto-char (point-min))
9206 (when (re-search-forward "match[a-z]+" nil t)
9207 (setq beg (match-end 0))
9208 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9209 (setq end (1- (match-beginning 0)))))
9210 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9211 (goto-char (point-min))
9212 (select-window cwin))))
9214 ;;; The mark ring for links jumps
9216 (defvar org-mark-ring nil
9217 "Mark ring for positions before jumps in Org-mode.")
9218 (defvar org-mark-ring-last-goto nil
9219 "Last position in the mark ring used to go back.")
9220 ;; Fill and close the ring
9221 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9222 (loop for i from 1 to org-mark-ring-length do
9223 (push (make-marker) org-mark-ring))
9224 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9225 org-mark-ring)
9227 (defun org-mark-ring-push (&optional pos buffer)
9228 "Put the current position or POS into the mark ring and rotate it."
9229 (interactive)
9230 (setq pos (or pos (point)))
9231 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9232 (move-marker (car org-mark-ring)
9233 (or pos (point))
9234 (or buffer (current-buffer)))
9235 (message "%s"
9236 (substitute-command-keys
9237 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9239 (defun org-mark-ring-goto (&optional n)
9240 "Jump to the previous position in the mark ring.
9241 With prefix arg N, jump back that many stored positions. When
9242 called several times in succession, walk through the entire ring.
9243 Org-mode commands jumping to a different position in the current file,
9244 or to another Org-mode file, automatically push the old position
9245 onto the ring."
9246 (interactive "p")
9247 (let (p m)
9248 (if (eq last-command this-command)
9249 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9250 (setq p org-mark-ring))
9251 (setq org-mark-ring-last-goto p)
9252 (setq m (car p))
9253 (switch-to-buffer (marker-buffer m))
9254 (goto-char m)
9255 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9257 (defun org-remove-angle-brackets (s)
9258 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9259 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9261 (defun org-add-angle-brackets (s)
9262 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9263 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9265 (defun org-remove-double-quotes (s)
9266 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9267 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9270 ;;; Following specific links
9272 (defun org-follow-timestamp-link ()
9273 (cond
9274 ((org-at-date-range-p t)
9275 (let ((org-agenda-start-on-weekday)
9276 (t1 (match-string 1))
9277 (t2 (match-string 2)))
9278 (setq t1 (time-to-days (org-time-string-to-time t1))
9279 t2 (time-to-days (org-time-string-to-time t2)))
9280 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9281 ((org-at-timestamp-p t)
9282 (org-agenda-list nil (time-to-days (org-time-string-to-time
9283 (substring (match-string 1) 0 10)))
9285 (t (error "This should not happen"))))
9288 ;;; Following file links
9289 (defvar org-wait nil)
9290 (defun org-open-file (path &optional in-emacs line search)
9291 "Open the file at PATH.
9292 First, this expands any special file name abbreviations. Then the
9293 configuration variable `org-file-apps' is checked if it contains an
9294 entry for this file type, and if yes, the corresponding command is launched.
9296 If no application is found, Emacs simply visits the file.
9298 With optional prefix argument IN-EMACS, Emacs will visit the file.
9299 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9300 and to use an external application to visit the file.
9302 Optional LINE specifies a line to go to, optional SEARCH a string
9303 to search for. If LINE or SEARCH is given, the file will be
9304 opened in Emacs, unless an entry from org-file-apps that makes
9305 use of groups in a regexp matches.
9306 If the file does not exist, an error is thrown."
9307 (let* ((file (if (equal path "")
9308 buffer-file-name
9309 (substitute-in-file-name (expand-file-name path))))
9310 (file-apps (append org-file-apps (org-default-apps)))
9311 (apps (org-remove-if
9312 'org-file-apps-entry-match-against-dlink-p file-apps))
9313 (apps-dlink (org-remove-if-not
9314 'org-file-apps-entry-match-against-dlink-p file-apps))
9315 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9316 (dirp (if remp nil (file-directory-p file)))
9317 (file (if (and dirp org-open-directory-means-index-dot-org)
9318 (concat (file-name-as-directory file) "index.org")
9319 file))
9320 (a-m-a-p (assq 'auto-mode apps))
9321 (dfile (downcase file))
9322 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9323 (link (cond ((and (eq line nil)
9324 (eq search nil))
9325 file)
9326 (line
9327 (concat file "::" (number-to-string line)))
9328 (search
9329 (concat file "::" search))))
9330 (dlink (downcase link))
9331 (old-buffer (current-buffer))
9332 (old-pos (point))
9333 (old-mode major-mode)
9334 ext cmd link-match-data)
9335 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9336 (setq ext (match-string 1 dfile))
9337 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9338 (setq ext (match-string 1 dfile))))
9339 (cond
9340 ((member in-emacs '((16) system))
9341 (setq cmd (cdr (assoc 'system apps))))
9342 (in-emacs (setq cmd 'emacs))
9344 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9345 (and dirp (cdr (assoc 'directory apps)))
9346 ; first, try matching against apps-dlink
9347 ; if we get a match here, store the match data for later
9348 (let ((match (assoc-default dlink apps-dlink
9349 'string-match)))
9350 (if match
9351 (progn (setq link-match-data (match-data))
9352 match)
9353 (progn (setq in-emacs (or in-emacs line search))
9354 nil))) ; if we have no match in apps-dlink,
9355 ; always open the file in emacs if line or search
9356 ; is given (for backwards compatibility)
9357 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9358 'string-match)
9359 (cdr (assoc ext apps))
9360 (cdr (assoc t apps))))))
9361 (when (eq cmd 'system)
9362 (setq cmd (cdr (assoc 'system apps))))
9363 (when (eq cmd 'default)
9364 (setq cmd (cdr (assoc t apps))))
9365 (when (eq cmd 'mailcap)
9366 (require 'mailcap)
9367 (mailcap-parse-mailcaps)
9368 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9369 (command (mailcap-mime-info mime-type)))
9370 (if (stringp command)
9371 (setq cmd command)
9372 (setq cmd 'emacs))))
9373 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9374 (not (file-exists-p file))
9375 (not org-open-non-existing-files))
9376 (error "No such file: %s" file))
9377 (cond
9378 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9379 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9380 (while (string-match "['\"]%s['\"]" cmd)
9381 (setq cmd (replace-match "%s" t t cmd)))
9382 (while (string-match "%s" cmd)
9383 (setq cmd (replace-match
9384 (save-match-data
9385 (shell-quote-argument
9386 (convert-standard-filename file)))
9387 t t cmd)))
9389 ;; Replace "%1", "%2" etc. in command with group matches from regex
9390 (save-match-data
9391 (let ((match-index 1)
9392 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9393 (set-match-data link-match-data)
9394 (while (<= match-index number-of-groups)
9395 (let ((regex (concat "%" (number-to-string match-index)))
9396 (replace-with (match-string match-index dlink)))
9397 (while (string-match regex cmd)
9398 (setq cmd (replace-match replace-with t t cmd))))
9399 (setq match-index (+ match-index 1)))))
9401 (save-window-excursion
9402 (start-process-shell-command cmd nil cmd)
9403 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9405 ((or (stringp cmd)
9406 (eq cmd 'emacs))
9407 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9408 (widen)
9409 (if line (org-goto-line line)
9410 (if search (org-link-search search))))
9411 ((consp cmd)
9412 (let ((file (convert-standard-filename file)))
9413 (save-match-data
9414 (set-match-data link-match-data)
9415 (eval cmd))))
9416 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9417 (and (org-mode-p) (eq old-mode 'org-mode)
9418 (or (not (equal old-buffer (current-buffer)))
9419 (not (equal old-pos (point))))
9420 (org-mark-ring-push old-pos old-buffer))))
9422 (defun org-file-apps-entry-match-against-dlink-p (entry)
9423 "This function returns non-nil if `entry' uses a regular
9424 expression which should be matched against the whole link by
9425 org-open-file.
9427 It assumes that is the case when the entry uses a regular
9428 expression which has at least one grouping construct and the
9429 action is either a lisp form or a command string containing
9430 '%1', i.e. using at least one subexpression match as a
9431 parameter."
9432 (let ((selector (car entry))
9433 (action (cdr entry)))
9434 (if (stringp selector)
9435 (and (> (regexp-opt-depth selector) 0)
9436 (or (and (stringp action)
9437 (string-match "%[0-9]" action))
9438 (consp action)))
9439 nil)))
9441 (defun org-default-apps ()
9442 "Return the default applications for this operating system."
9443 (cond
9444 ((eq system-type 'darwin)
9445 org-file-apps-defaults-macosx)
9446 ((eq system-type 'windows-nt)
9447 org-file-apps-defaults-windowsnt)
9448 (t org-file-apps-defaults-gnu)))
9450 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9451 "Convert extensions to regular expressions in the cars of LIST.
9452 Also, weed out any non-string entries, because the return value is used
9453 only for regexp matching.
9454 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9455 point to the symbol `emacs', indicating that the file should
9456 be opened in Emacs."
9457 (append
9458 (delq nil
9459 (mapcar (lambda (x)
9460 (if (not (stringp (car x)))
9462 (if (string-match "\\W" (car x))
9464 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9465 list))
9466 (if add-auto-mode
9467 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9469 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9470 (defun org-file-remote-p (file)
9471 "Test whether FILE specifies a location on a remote system.
9472 Return non-nil if the location is indeed remote.
9474 For example, the filename \"/user@host:/foo\" specifies a location
9475 on the system \"/user@host:\"."
9476 (cond ((fboundp 'file-remote-p)
9477 (file-remote-p file))
9478 ((fboundp 'tramp-handle-file-remote-p)
9479 (tramp-handle-file-remote-p file))
9480 ((and (boundp 'ange-ftp-name-format)
9481 (string-match (car ange-ftp-name-format) file))
9483 (t nil)))
9486 ;;;; Refiling
9488 (defun org-get-org-file ()
9489 "Read a filename, with default directory `org-directory'."
9490 (let ((default (or org-default-notes-file remember-data-file)))
9491 (read-file-name (format "File name [%s]: " default)
9492 (file-name-as-directory org-directory)
9493 default)))
9495 (defun org-notes-order-reversed-p ()
9496 "Check if the current file should receive notes in reversed order."
9497 (cond
9498 ((not org-reverse-note-order) nil)
9499 ((eq t org-reverse-note-order) t)
9500 ((not (listp org-reverse-note-order)) nil)
9501 (t (catch 'exit
9502 (let ((all org-reverse-note-order)
9503 entry)
9504 (while (setq entry (pop all))
9505 (if (string-match (car entry) buffer-file-name)
9506 (throw 'exit (cdr entry))))
9507 nil)))))
9509 (defvar org-refile-target-table nil
9510 "The list of refile targets, created by `org-refile'.")
9512 (defvar org-agenda-new-buffers nil
9513 "Buffers created to visit agenda files.")
9515 (defvar org-refile-cache nil
9516 "Cache for refile targets.")
9519 (defvar org-refile-markers nil
9520 "All the markers used for caching refile locations.")
9522 (defun org-refile-marker (pos)
9523 "Get a new refile marker, but only if caching is in use."
9524 (if (not org-refile-use-cache)
9526 (let ((m (make-marker)))
9527 (move-marker m pos)
9528 (push m org-refile-markers)
9529 m)))
9531 (defun org-refile-cache-clear ()
9532 "Clear the refile cache and disable all the markers."
9533 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9534 (setq org-refile-markers nil)
9535 (setq org-refile-cache nil)
9536 (message "Refile cache has been cleared"))
9538 (defun org-refile-cache-check-set (set)
9539 "Check if all the markers in the cache still have live buffers."
9540 (catch 'exit
9541 (while set
9542 (if (not (marker-buffer (nth 3 (pop set))))
9543 (progn
9544 (message "not found") (sit-for 3)
9545 (throw 'exit nil))))
9548 (defun org-refile-cache-put (set &rest identifiers)
9549 "Push the refile targets SET into the cache, under IDENTIFIERS."
9550 (let* ((key (sha1 (prin1-to-string identifiers)))
9551 (entry (assoc key org-refile-cache)))
9552 (if entry
9553 (setcdr entry set)
9554 (push (cons key set) org-refile-cache))))
9556 (defun org-refile-cache-get (&rest identifiers)
9557 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9558 (cond
9559 ((not org-refile-cache) nil)
9560 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9562 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9563 org-refile-cache))))
9564 (and set (org-refile-cache-check-set set) set)))))
9566 (defun org-get-refile-targets (&optional default-buffer)
9567 "Produce a table with refile targets."
9568 (let ((case-fold-search nil)
9569 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9570 (entries (or org-refile-targets '((nil . (:level . 1)))))
9571 targets tgs txt re files f desc descre fast-path-p level pos0)
9572 (message "Getting targets...")
9573 (with-current-buffer (or default-buffer (current-buffer))
9574 (while (setq entry (pop entries))
9575 (setq files (car entry) desc (cdr entry))
9576 (setq fast-path-p nil)
9577 (cond
9578 ((null files) (setq files (list (current-buffer))))
9579 ((eq files 'org-agenda-files)
9580 (setq files (org-agenda-files 'unrestricted)))
9581 ((and (symbolp files) (fboundp files))
9582 (setq files (funcall files)))
9583 ((and (symbolp files) (boundp files))
9584 (setq files (symbol-value files))))
9585 (if (stringp files) (setq files (list files)))
9586 (cond
9587 ((eq (car desc) :tag)
9588 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9589 ((eq (car desc) :todo)
9590 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9591 ((eq (car desc) :regexp)
9592 (setq descre (cdr desc)))
9593 ((eq (car desc) :level)
9594 (setq descre (concat "^\\*\\{" (number-to-string
9595 (if org-odd-levels-only
9596 (1- (* 2 (cdr desc)))
9597 (cdr desc)))
9598 "\\}[ \t]")))
9599 ((eq (car desc) :maxlevel)
9600 (setq fast-path-p t)
9601 (setq descre (concat "^\\*\\{1," (number-to-string
9602 (if org-odd-levels-only
9603 (1- (* 2 (cdr desc)))
9604 (cdr desc)))
9605 "\\}[ \t]")))
9606 (t (error "Bad refiling target description %s" desc)))
9607 (while (setq f (pop files))
9608 (with-current-buffer
9609 (if (bufferp f) f (org-get-agenda-file-buffer f))
9611 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9612 (progn
9613 (if (bufferp f) (setq f (buffer-file-name
9614 (buffer-base-buffer f))))
9615 (setq f (and f (expand-file-name f)))
9616 (if (eq org-refile-use-outline-path 'file)
9617 (push (list (file-name-nondirectory f) f nil nil) tgs))
9618 (save-excursion
9619 (save-restriction
9620 (widen)
9621 (goto-char (point-min))
9622 (while (re-search-forward descre nil t)
9623 (goto-char (setq pos0 (point-at-bol)))
9624 (catch 'next
9625 (when org-refile-target-verify-function
9626 (save-match-data
9627 (or (funcall org-refile-target-verify-function)
9628 (throw 'next t))))
9629 (when (looking-at org-complex-heading-regexp)
9630 (setq level (org-reduced-level
9631 (- (match-end 1) (match-beginning 1)))
9632 txt (org-link-display-format (match-string 4))
9633 re (concat "^" (regexp-quote
9634 (buffer-substring
9635 (match-beginning 1)
9636 (match-end 4)))))
9637 (if (match-end 5) (setq re (concat
9638 re "[ \t]+"
9639 (regexp-quote
9640 (match-string 5)))))
9641 (setq re (concat re "[ \t]*$"))
9642 (when org-refile-use-outline-path
9643 (setq txt (mapconcat
9644 'org-protect-slash
9645 (append
9646 (if (eq org-refile-use-outline-path
9647 'file)
9648 (list (file-name-nondirectory
9649 (buffer-file-name
9650 (buffer-base-buffer))))
9651 (if (eq org-refile-use-outline-path
9652 'full-file-path)
9653 (list (buffer-file-name
9654 (buffer-base-buffer)))))
9655 (org-get-outline-path fast-path-p
9656 level txt)
9657 (list txt))
9658 "/")))
9659 (push (list txt f re (org-refile-marker (point)))
9660 tgs)))
9661 (when (= (point) pos0)
9662 ;; verification function has not moved point
9663 (goto-char (point-at-eol))))))))
9664 (when org-refile-use-cache
9665 (org-refile-cache-put tgs (buffer-file-name) descre))
9666 (setq targets (append tgs targets))
9667 ))))
9668 (message "Getting targets...done")
9669 (nreverse targets)))
9671 (defun org-protect-slash (s)
9672 (while (string-match "/" s)
9673 (setq s (replace-match "\\" t t s)))
9676 (defvar org-olpa (make-vector 20 nil))
9678 (defun org-get-outline-path (&optional fastp level heading)
9679 "Return the outline path to the current entry, as a list.
9680 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9681 routine which makes outline path derivations for an entire file,
9682 avoiding backtracing."
9683 (if fastp
9684 (progn
9685 (if (> level 19)
9686 (error "Outline path failure, more than 19 levels."))
9687 (loop for i from level upto 19 do
9688 (aset org-olpa i nil))
9689 (prog1
9690 (delq nil (append org-olpa nil))
9691 (aset org-olpa level heading)))
9692 (let (rtn case-fold-search)
9693 (save-excursion
9694 (save-restriction
9695 (widen)
9696 (while (org-up-heading-safe)
9697 (when (looking-at org-complex-heading-regexp)
9698 (push (org-match-string-no-properties 4) rtn)))
9699 rtn)))))
9701 (defun org-format-outline-path (path &optional width prefix)
9702 "Format the outlie path PATH for display.
9703 Width is the maximum number of characters that is available.
9704 Prefix is a prefix to be included in the returned string,
9705 such as the file name."
9706 (setq width (or width 79))
9707 (if prefix (setq width (- width (length prefix))))
9708 (if (not path)
9709 (or prefix "")
9710 (let* ((nsteps (length path))
9711 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9712 (maxwidth (if (<= total-width width)
9713 10000 ;; everything fits
9714 ;; we need to shorten the level headings
9715 (/ (- width nsteps) nsteps)))
9716 (org-odd-levels-only nil)
9717 (n 0)
9718 (total (1+ (length prefix))))
9719 (setq maxwidth (max maxwidth 10))
9720 (concat prefix
9721 (mapconcat
9722 (lambda (h)
9723 (setq n (1+ n))
9724 (if (and (= n nsteps) (< maxwidth 10000))
9725 (setq maxwidth (- total-width total)))
9726 (if (< (length h) maxwidth)
9727 (progn (setq total (+ total (length h) 1)) h)
9728 (setq h (substring h 0 (- maxwidth 2))
9729 total (+ total maxwidth 1))
9730 (if (string-match "[ \t]+\\'" h)
9731 (setq h (substring h 0 (match-beginning 0))))
9732 (setq h (concat h "..")))
9733 (org-add-props h nil 'face
9734 (nth (% (1- n) org-n-level-faces)
9735 org-level-faces))
9737 path "/")))))
9739 (defun org-display-outline-path (&optional file current)
9740 "Display the current outline path in the echo area."
9741 (interactive "P")
9742 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9743 (case-fold-search nil)
9744 (path (and (org-mode-p) (org-get-outline-path))))
9745 (if current (setq path (append path
9746 (save-excursion
9747 (org-back-to-heading t)
9748 (if (looking-at org-complex-heading-regexp)
9749 (list (match-string 4)))))))
9750 (message "%s"
9751 (org-format-outline-path
9752 path
9753 (1- (frame-width))
9754 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9756 (defvar org-refile-history nil
9757 "History for refiling operations.")
9759 (defvar org-after-refile-insert-hook nil
9760 "Hook run after `org-refile' has inserted its stuff at the new location.
9761 Note that this is still *before* the stuff will be removed from
9762 the *old* location.")
9764 (defun org-refile (&optional goto default-buffer rfloc)
9765 "Move the entry at point to another heading.
9766 The list of target headings is compiled using the information in
9767 `org-refile-targets', which see. This list is created before each use
9768 and will therefore always be up-to-date.
9770 At the target location, the entry is filed as a subitem of the target heading.
9771 Depending on `org-reverse-note-order', the new subitem will either be the
9772 first or the last subitem.
9774 If there is an active region, all entries in that region will be moved.
9775 However, the region must fulfil the requirement that the first heading
9776 is the first one sets the top-level of the moved text - at most siblings
9777 below it are allowed.
9779 With prefix arg GOTO, the command will only visit the target location,
9780 not actually move anything.
9781 With a double prefix `C-u C-u', go to the location where the last refiling
9782 operation has put the subtree.
9783 With a prefix argument of `2', refile to the running clock.
9785 RFLOC can be a refile location obtained in a different way.
9787 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
9789 If you are using target caching (see `org-refile-use-cache'),
9790 You have to clear the target cache in order to find new targets.
9791 This can be done with a 0 prefix: `C-0 C-c C-w'"
9792 (interactive "P")
9793 (if (member goto '(0 (64)))
9794 (org-refile-cache-clear)
9795 (let* ((cbuf (current-buffer))
9796 (regionp (org-region-active-p))
9797 (region-start (and regionp (region-beginning)))
9798 (region-end (and regionp (region-end)))
9799 (region-length (and regionp (- region-end region-start)))
9800 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9801 pos it nbuf file re level reversed)
9802 (setq last-command nil)
9803 (when regionp
9804 (goto-char region-start)
9805 (or (bolp) (goto-char (point-at-bol)))
9806 (setq region-start (point))
9807 (unless (org-kill-is-subtree-p
9808 (buffer-substring region-start region-end))
9809 (error "The region is not a (sequence of) subtree(s)")))
9810 (if (equal goto '(16))
9811 (org-refile-goto-last-stored)
9812 (when (or
9813 (and (equal goto 2)
9814 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9815 (prog1
9816 (setq it (list (or org-clock-heading "running clock")
9817 (buffer-file-name
9818 (marker-buffer org-clock-hd-marker))
9820 (marker-position org-clock-hd-marker)))
9821 (setq goto nil)))
9822 (setq it (or rfloc
9823 (save-excursion
9824 (org-refile-get-location
9825 (if goto "Goto: " "Refile to: ") default-buffer
9826 org-refile-allow-creating-parent-nodes)))))
9827 (setq file (nth 1 it)
9828 re (nth 2 it)
9829 pos (nth 3 it))
9830 (if (and (not goto)
9832 (equal (buffer-file-name) file)
9833 (if regionp
9834 (and (>= pos region-start)
9835 (<= pos region-end))
9836 (and (>= pos (point))
9837 (< pos (save-excursion
9838 (org-end-of-subtree t t))))))
9839 (error "Cannot refile to position inside the tree or region"))
9841 (setq nbuf (or (find-buffer-visiting file)
9842 (find-file-noselect file)))
9843 (if goto
9844 (progn
9845 (switch-to-buffer nbuf)
9846 (goto-char pos)
9847 (org-show-context 'org-goto))
9848 (if regionp
9849 (progn
9850 (org-kill-new (buffer-substring region-start region-end))
9851 (org-save-markers-in-region region-start region-end))
9852 (org-copy-subtree 1 nil t))
9853 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9854 (find-file-noselect file)))
9855 (setq reversed (org-notes-order-reversed-p))
9856 (save-excursion
9857 (save-restriction
9858 (widen)
9859 (if pos
9860 (progn
9861 (goto-char pos)
9862 (looking-at outline-regexp)
9863 (setq level (org-get-valid-level (funcall outline-level) 1))
9864 (goto-char
9865 (if reversed
9866 (or (outline-next-heading) (point-max))
9867 (or (save-excursion (org-get-next-sibling))
9868 (org-end-of-subtree t t)
9869 (point-max)))))
9870 (setq level 1)
9871 (if (not reversed)
9872 (goto-char (point-max))
9873 (goto-char (point-min))
9874 (or (outline-next-heading) (goto-char (point-max)))))
9875 (if (not (bolp)) (newline))
9876 (org-paste-subtree level)
9877 (when org-log-refile
9878 (org-add-log-setup 'refile nil nil 'findpos
9879 org-log-refile)
9880 (unless (eq org-log-refile 'note)
9881 (save-excursion (org-add-log-note))))
9882 (and org-auto-align-tags (org-set-tags nil t))
9883 (bookmark-set "org-refile-last-stored")
9884 (if (fboundp 'deactivate-mark) (deactivate-mark))
9885 (run-hooks 'org-after-refile-insert-hook))))
9886 (if regionp
9887 (delete-region (point) (+ (point) region-length))
9888 (org-cut-subtree))
9889 (when (featurep 'org-inlinetask)
9890 (org-inlinetask-remove-END-maybe))
9891 (setq org-markers-to-move nil)
9892 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
9894 (defun org-refile-goto-last-stored ()
9895 "Go to the location where the last refile was stored."
9896 (interactive)
9897 (bookmark-jump "org-refile-last-stored")
9898 (message "This is the location of the last refile"))
9900 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9901 "Prompt the user for a refile location, using PROMPT."
9902 (let ((org-refile-targets org-refile-targets)
9903 (org-refile-use-outline-path org-refile-use-outline-path))
9904 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9905 (unless org-refile-target-table
9906 (error "No refile targets"))
9907 (let* ((cbuf (current-buffer))
9908 (partial-completion-mode nil)
9909 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9910 (cfunc (if (and org-refile-use-outline-path
9911 org-outline-path-complete-in-steps)
9912 'org-olpath-completing-read
9913 'org-icompleting-read))
9914 (extra (if org-refile-use-outline-path "/" ""))
9915 (filename (and cfn (expand-file-name cfn)))
9916 (tbl (mapcar
9917 (lambda (x)
9918 (if (and (not (member org-refile-use-outline-path
9919 '(file full-file-path)))
9920 (not (equal filename (nth 1 x))))
9921 (cons (concat (car x) extra " ("
9922 (file-name-nondirectory (nth 1 x)) ")")
9923 (cdr x))
9924 (cons (concat (car x) extra) (cdr x))))
9925 org-refile-target-table))
9926 (completion-ignore-case t)
9927 pa answ parent-target child parent old-hist)
9928 (setq old-hist org-refile-history)
9929 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9930 nil 'org-refile-history))
9931 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9932 (if pa
9933 (progn
9934 (when (or (not org-refile-history)
9935 (not (eq old-hist org-refile-history))
9936 (not (equal (car pa) (car org-refile-history))))
9937 (setq org-refile-history
9938 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9939 org-refile-history
9940 (cdr org-refile-history))))
9941 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9942 (pop org-refile-history)))
9944 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9945 (progn
9946 (setq parent (match-string 1 answ)
9947 child (match-string 2 answ))
9948 (setq parent-target (or (assoc parent tbl)
9949 (assoc (concat parent "/") tbl)))
9950 (when (and parent-target
9951 (or (eq new-nodes t)
9952 (and (eq new-nodes 'confirm)
9953 (y-or-n-p (format "Create new node \"%s\"? "
9954 child)))))
9955 (org-refile-new-child parent-target child)))
9956 (error "Invalid target location")))))
9958 (defun org-refile-new-child (parent-target child)
9959 "Use refile target PARENT-TARGET to add new CHILD below it."
9960 (unless parent-target
9961 (error "Cannot find parent for new node"))
9962 (let ((file (nth 1 parent-target))
9963 (pos (nth 3 parent-target))
9964 level)
9965 (with-current-buffer (or (find-buffer-visiting file)
9966 (find-file-noselect file))
9967 (save-excursion
9968 (save-restriction
9969 (widen)
9970 (if pos
9971 (goto-char pos)
9972 (goto-char (point-max))
9973 (if (not (bolp)) (newline)))
9974 (when (looking-at outline-regexp)
9975 (setq level (funcall outline-level))
9976 (org-end-of-subtree t t))
9977 (org-back-over-empty-lines)
9978 (insert "\n" (make-string
9979 (if pos (org-get-valid-level level 1) 1) ?*)
9980 " " child "\n")
9981 (beginning-of-line 0)
9982 (list (concat (car parent-target) "/" child) file "" (point)))))))
9984 (defun org-olpath-completing-read (prompt collection &rest args)
9985 "Read an outline path like a file name."
9986 (let ((thetable collection)
9987 (org-completion-use-ido nil) ; does not work with ido.
9988 (org-completion-use-iswitchb nil)) ; or iswitchb
9989 (apply
9990 'org-icompleting-read prompt
9991 (lambda (string predicate &optional flag)
9992 (let (rtn r f (l (length string)))
9993 (cond
9994 ((eq flag nil)
9995 ;; try completion
9996 (try-completion string thetable))
9997 ((eq flag t)
9998 ;; all-completions
9999 (setq rtn (all-completions string thetable predicate))
10000 (mapcar
10001 (lambda (x)
10002 (setq r (substring x l))
10003 (if (string-match " ([^)]*)$" x)
10004 (setq f (match-string 0 x))
10005 (setq f ""))
10006 (if (string-match "/" r)
10007 (concat string (substring r 0 (match-end 0)) f)
10009 rtn))
10010 ((eq flag 'lambda)
10011 ;; exact match?
10012 (assoc string thetable)))
10014 args)))
10016 ;;;; Dynamic blocks
10018 (defun org-find-dblock (name)
10019 "Find the first dynamic block with name NAME in the buffer.
10020 If not found, stay at current position and return nil."
10021 (let (pos)
10022 (save-excursion
10023 (goto-char (point-min))
10024 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10025 nil t)
10026 (match-beginning 0))))
10027 (if pos (goto-char pos))
10028 pos))
10030 (defconst org-dblock-start-re
10031 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10032 "Matches the start line of a dynamic block, with parameters.")
10034 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10035 "Matches the end of a dynamic block.")
10037 (defun org-create-dblock (plist)
10038 "Create a dynamic block section, with parameters taken from PLIST.
10039 PLIST must contain a :name entry which is used as name of the block."
10040 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10041 (end-of-line 1)
10042 (newline))
10043 (let ((col (current-column))
10044 (name (plist-get plist :name)))
10045 (insert "#+BEGIN: " name)
10046 (while plist
10047 (if (eq (car plist) :name)
10048 (setq plist (cddr plist))
10049 (insert " " (prin1-to-string (pop plist)))))
10050 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10051 (beginning-of-line -2)))
10053 (defun org-prepare-dblock ()
10054 "Prepare dynamic block for refresh.
10055 This empties the block, puts the cursor at the insert position and returns
10056 the property list including an extra property :name with the block name."
10057 (unless (looking-at org-dblock-start-re)
10058 (error "Not at a dynamic block"))
10059 (let* ((begdel (1+ (match-end 0)))
10060 (name (org-no-properties (match-string 1)))
10061 (params (append (list :name name)
10062 (read (concat "(" (match-string 3) ")")))))
10063 (save-excursion
10064 (beginning-of-line 1)
10065 (skip-chars-forward " \t")
10066 (setq params (plist-put params :indentation-column (current-column))))
10067 (unless (re-search-forward org-dblock-end-re nil t)
10068 (error "Dynamic block not terminated"))
10069 (setq params
10070 (append params
10071 (list :content (buffer-substring
10072 begdel (match-beginning 0)))))
10073 (delete-region begdel (match-beginning 0))
10074 (goto-char begdel)
10075 (open-line 1)
10076 params))
10078 (defun org-map-dblocks (&optional command)
10079 "Apply COMMAND to all dynamic blocks in the current buffer.
10080 If COMMAND is not given, use `org-update-dblock'."
10081 (let ((cmd (or command 'org-update-dblock)))
10082 (save-excursion
10083 (goto-char (point-min))
10084 (while (re-search-forward org-dblock-start-re nil t)
10085 (goto-char (match-beginning 0))
10086 (save-excursion
10087 (condition-case nil
10088 (funcall cmd)
10089 (error (message "Error during update of dynamic block"))))
10090 (unless (re-search-forward org-dblock-end-re nil t)
10091 (error "Dynamic block not terminated"))))))
10093 (defun org-dblock-update (&optional arg)
10094 "User command for updating dynamic blocks.
10095 Update the dynamic block at point. With prefix ARG, update all dynamic
10096 blocks in the buffer."
10097 (interactive "P")
10098 (if arg
10099 (org-update-all-dblocks)
10100 (or (looking-at org-dblock-start-re)
10101 (org-beginning-of-dblock))
10102 (org-update-dblock)))
10104 (defun org-update-dblock ()
10105 "Update the dynamic block at point
10106 This means to empty the block, parse for parameters and then call
10107 the correct writing function."
10108 (save-window-excursion
10109 (let* ((pos (point))
10110 (line (org-current-line))
10111 (params (org-prepare-dblock))
10112 (name (plist-get params :name))
10113 (indent (plist-get params :indentation-column))
10114 (cmd (intern (concat "org-dblock-write:" name))))
10115 (message "Updating dynamic block `%s' at line %d..." name line)
10116 (funcall cmd params)
10117 (message "Updating dynamic block `%s' at line %d...done" name line)
10118 (goto-char pos)
10119 (when (and indent (> indent 0))
10120 (setq indent (make-string indent ?\ ))
10121 (save-excursion
10122 (org-beginning-of-dblock)
10123 (forward-line 1)
10124 (while (not (looking-at org-dblock-end-re))
10125 (insert indent)
10126 (beginning-of-line 2))
10127 (when (looking-at org-dblock-end-re)
10128 (and (looking-at "[ \t]+")
10129 (replace-match ""))
10130 (insert indent)))))))
10132 (defun org-beginning-of-dblock ()
10133 "Find the beginning of the dynamic block at point.
10134 Error if there is no such block at point."
10135 (let ((pos (point))
10136 beg)
10137 (end-of-line 1)
10138 (if (and (re-search-backward org-dblock-start-re nil t)
10139 (setq beg (match-beginning 0))
10140 (re-search-forward org-dblock-end-re nil t)
10141 (> (match-end 0) pos))
10142 (goto-char beg)
10143 (goto-char pos)
10144 (error "Not in a dynamic block"))))
10146 (defun org-update-all-dblocks ()
10147 "Update all dynamic blocks in the buffer.
10148 This function can be used in a hook."
10149 (when (org-mode-p)
10150 (org-map-dblocks 'org-update-dblock)))
10153 ;;;; Completion
10155 (defconst org-additional-option-like-keywords
10156 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10157 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10158 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10159 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10160 "BEGIN:" "END:"
10161 "ORGTBL" "TBLFM:" "TBLNAME:"
10162 "BEGIN_EXAMPLE" "END_EXAMPLE"
10163 "BEGIN_QUOTE" "END_QUOTE"
10164 "BEGIN_VERSE" "END_VERSE"
10165 "BEGIN_CENTER" "END_CENTER"
10166 "BEGIN_SRC" "END_SRC"
10167 "CATEGORY" "COLUMNS"
10168 "CAPTION" "LABEL"
10169 "SETUPFILE"
10170 "BIND"
10171 "MACRO"))
10173 (defcustom org-structure-template-alist
10175 ("s" "#+begin_src ?\n\n#+end_src"
10176 "<src lang=\"?\">\n\n</src>")
10177 ("e" "#+begin_example\n?\n#+end_example"
10178 "<example>\n?\n</example>")
10179 ("q" "#+begin_quote\n?\n#+end_quote"
10180 "<quote>\n?\n</quote>")
10181 ("v" "#+begin_verse\n?\n#+end_verse"
10182 "<verse>\n?\n/verse>")
10183 ("c" "#+begin_center\n?\n#+end_center"
10184 "<center>\n?\n/center>")
10185 ("l" "#+begin_latex\n?\n#+end_latex"
10186 "<literal style=\"latex\">\n?\n</literal>")
10187 ("L" "#+latex: "
10188 "<literal style=\"latex\">?</literal>")
10189 ("h" "#+begin_html\n?\n#+end_html"
10190 "<literal style=\"html\">\n?\n</literal>")
10191 ("H" "#+html: "
10192 "<literal style=\"html\">?</literal>")
10193 ("a" "#+begin_ascii\n?\n#+end_ascii")
10194 ("A" "#+ascii: ")
10195 ("i" "#+include %file ?"
10196 "<include file=%file markup=\"?\">")
10198 "Structure completion elements.
10199 This is a list of abbreviation keys and values. The value gets inserted
10200 if you type `<' followed by the key and then press the completion key,
10201 usually `M-TAB'. %file will be replaced by a file name after prompting
10202 for the file using completion.
10203 There are two templates for each key, the first uses the original Org syntax,
10204 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10205 the default when the /org-mtags.el/ module has been loaded. See also the
10206 variable `org-mtags-prefer-muse-templates'.
10207 This is an experimental feature, it is undecided if it is going to stay in."
10208 :group 'org-completion
10209 :type '(repeat
10210 (string :tag "Key")
10211 (string :tag "Template")
10212 (string :tag "Muse Template")))
10214 (defun org-try-structure-completion ()
10215 "Try to complete a structure template before point.
10216 This looks for strings like \"<e\" on an otherwise empty line and
10217 expands them."
10218 (let ((l (buffer-substring (point-at-bol) (point)))
10220 (when (and (looking-at "[ \t]*$")
10221 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10222 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10223 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10224 (match-beginning 1)) a)
10225 t)))
10227 (defun org-complete-expand-structure-template (start cell)
10228 "Expand a structure template."
10229 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10230 (rpl (nth (if musep 2 1) cell))
10231 (ind ""))
10232 (delete-region start (point))
10233 (when (string-match "\\`#\\+" rpl)
10234 (cond
10235 ((bolp))
10236 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10237 (setq ind (buffer-substring (point-at-bol) (point))))
10238 (t (newline))))
10239 (setq start (point))
10240 (if (string-match "%file" rpl)
10241 (setq rpl (replace-match
10242 (concat
10243 "\""
10244 (save-match-data
10245 (abbreviate-file-name (read-file-name "Include file: ")))
10246 "\"")
10247 t t rpl)))
10248 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10249 (concat "\n" ind)))
10250 (insert rpl)
10251 (if (re-search-backward "\\?" start t) (delete-char 1))))
10254 (defun org-complete (&optional arg)
10255 "Perform completion on word at point.
10256 At the beginning of a headline, this completes TODO keywords as given in
10257 `org-todo-keywords'.
10258 If the current word is preceded by a backslash, completes the TeX symbols
10259 that are supported for HTML support.
10260 If the current word is preceded by \"#+\", completes special words for
10261 setting file options.
10262 In the line after \"#+STARTUP:, complete valid keywords.\"
10263 At all other locations, this simply calls the value of
10264 `org-completion-fallback-command'."
10265 (interactive "P")
10266 (org-without-partial-completion
10267 (catch 'exit
10268 (let* ((a nil)
10269 (end (point))
10270 (beg1 (save-excursion
10271 (skip-chars-backward (org-re "[:alnum:]_@"))
10272 (point)))
10273 (beg (save-excursion
10274 (skip-chars-backward "a-zA-Z0-9_:$")
10275 (point)))
10276 (confirm (lambda (x) (stringp (car x))))
10277 (searchhead (equal (char-before beg) ?*))
10278 (struct
10279 (when (and (member (char-before beg1) '(?. ?<))
10280 (setq a (assoc (buffer-substring beg1 (point))
10281 org-structure-template-alist)))
10282 (org-complete-expand-structure-template (1- beg1) a)
10283 (throw 'exit t)))
10284 (tag (and (equal (char-before beg1) ?:)
10285 (equal (char-after (point-at-bol)) ?*)))
10286 (prop (and (equal (char-before beg1) ?:)
10287 (not (equal (char-after (point-at-bol)) ?*))))
10288 (texp (equal (char-before beg) ?\\))
10289 (link (equal (char-before beg) ?\[))
10290 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10291 beg)
10292 "#+"))
10293 (startup (string-match "^#\\+STARTUP:.*"
10294 (buffer-substring (point-at-bol) (point))))
10295 (completion-ignore-case opt)
10296 (type nil)
10297 (tbl nil)
10298 (table (cond
10299 (opt
10300 (setq type :opt)
10301 (require 'org-exp)
10302 (append
10303 (delq nil
10304 (mapcar
10305 (lambda (x)
10306 (if (string-match
10307 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10308 (cons (match-string 2 x)
10309 (match-string 1 x))))
10310 (org-split-string (org-get-current-options) "\n")))
10311 (mapcar 'list org-additional-option-like-keywords)))
10312 (startup
10313 (setq type :startup)
10314 org-startup-options)
10315 (link (append org-link-abbrev-alist-local
10316 org-link-abbrev-alist))
10317 (texp
10318 (setq type :tex)
10319 (append org-entities-user org-entities))
10320 ((string-match "\\`\\*+[ \t]+\\'"
10321 (buffer-substring (point-at-bol) beg))
10322 (setq type :todo)
10323 (mapcar 'list org-todo-keywords-1))
10324 (searchhead
10325 (setq type :searchhead)
10326 (save-excursion
10327 (goto-char (point-min))
10328 (while (re-search-forward org-todo-line-regexp nil t)
10329 (push (list
10330 (org-make-org-heading-search-string
10331 (match-string 3) t))
10332 tbl)))
10333 tbl)
10334 (tag (setq type :tag beg beg1)
10335 (or org-tag-alist (org-get-buffer-tags)))
10336 (prop (setq type :prop beg beg1)
10337 (mapcar 'list (org-buffer-property-keys nil t t)))
10338 (t (progn
10339 (call-interactively org-completion-fallback-command)
10340 (throw 'exit nil)))))
10341 (pattern (buffer-substring-no-properties beg end))
10342 (completion (try-completion pattern table confirm)))
10343 (cond ((eq completion t)
10344 (if (not (assoc (upcase pattern) table))
10345 (message "Already complete")
10346 (if (and (equal type :opt)
10347 (not (member (car (assoc (upcase pattern) table))
10348 org-additional-option-like-keywords)))
10349 (insert (substring (cdr (assoc (upcase pattern) table))
10350 (length pattern)))
10351 (if (memq type '(:tag :prop)) (insert ":")))))
10352 ((null completion)
10353 (message "Can't find completion for \"%s\"" pattern)
10354 (ding))
10355 ((not (string= pattern completion))
10356 (delete-region beg end)
10357 (if (string-match " +$" completion)
10358 (setq completion (replace-match "" t t completion)))
10359 (insert completion)
10360 (if (get-buffer-window "*Completions*")
10361 (delete-window (get-buffer-window "*Completions*")))
10362 (if (assoc completion table)
10363 (if (eq type :todo) (insert " ")
10364 (if (memq type '(:tag :prop)) (insert ":"))))
10365 (if (and (equal type :opt) (assoc completion table))
10366 (message "%s" (substitute-command-keys
10367 "Press \\[org-complete] again to insert example settings"))))
10369 (message "Making completion list...")
10370 (let ((list (sort (all-completions pattern table confirm)
10371 'string<)))
10372 (with-output-to-temp-buffer "*Completions*"
10373 (condition-case nil
10374 ;; Protection needed for XEmacs and emacs 21
10375 (display-completion-list list pattern)
10376 (error (display-completion-list list)))))
10377 (message "Making completion list...%s" "done")))))))
10379 ;;;; TODO, DEADLINE, Comments
10381 (defun org-toggle-comment ()
10382 "Change the COMMENT state of an entry."
10383 (interactive)
10384 (save-excursion
10385 (org-back-to-heading)
10386 (let (case-fold-search)
10387 (if (looking-at (concat outline-regexp
10388 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10389 (replace-match "" t t nil 1)
10390 (if (looking-at outline-regexp)
10391 (progn
10392 (goto-char (match-end 0))
10393 (insert org-comment-string " ")))))))
10395 (defvar org-last-todo-state-is-todo nil
10396 "This is non-nil when the last TODO state change led to a TODO state.
10397 If the last change removed the TODO tag or switched to DONE, then
10398 this is nil.")
10400 (defvar org-setting-tags nil) ; dynamically skipped
10402 (defun org-parse-local-options (string var)
10403 "Parse STRING for startup setting relevant for variable VAR."
10404 (let ((rtn (symbol-value var))
10405 e opts)
10406 (save-match-data
10407 (if (or (not string) (not (string-match "\\S-" string)))
10409 (setq opts (delq nil (mapcar (lambda (x)
10410 (setq e (assoc x org-startup-options))
10411 (if (eq (nth 1 e) var) e nil))
10412 (org-split-string string "[ \t]+"))))
10413 (if (not opts)
10415 (setq rtn nil)
10416 (while (setq e (pop opts))
10417 (if (not (nth 3 e))
10418 (setq rtn (nth 2 e))
10419 (if (not (listp rtn)) (setq rtn nil))
10420 (push (nth 2 e) rtn)))
10421 rtn)))))
10423 (defvar org-todo-setup-filter-hook nil
10424 "Hook for functions that pre-filter todo specs.
10426 Each function takes a todo spec and returns either `nil' or the spec
10427 transformed into canonical form." )
10429 (defvar org-todo-get-default-hook nil
10430 "Hook for functions that get a default item for todo.
10432 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10433 `nil' or a string to be used for the todo mark." )
10435 (defvar org-agenda-headline-snapshot-before-repeat)
10437 (defun org-todo (&optional arg)
10438 "Change the TODO state of an item.
10439 The state of an item is given by a keyword at the start of the heading,
10440 like
10441 *** TODO Write paper
10442 *** DONE Call mom
10444 The different keywords are specified in the variable `org-todo-keywords'.
10445 By default the available states are \"TODO\" and \"DONE\".
10446 So for this example: when the item starts with TODO, it is changed to DONE.
10447 When it starts with DONE, the DONE is removed. And when neither TODO nor
10448 DONE are present, add TODO at the beginning of the heading.
10450 With C-u prefix arg, use completion to determine the new state.
10451 With numeric prefix arg, switch to that state.
10452 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10453 With a triple C-u prefix, circumvent any state blocking.
10455 For calling through lisp, arg is also interpreted in the following way:
10456 'none -> empty state
10457 \"\"(empty string) -> switch to empty state
10458 'done -> switch to DONE
10459 'nextset -> switch to the next set of keywords
10460 'previousset -> switch to the previous set of keywords
10461 \"WAITING\" -> switch to the specified keyword, but only if it
10462 really is a member of `org-todo-keywords'."
10463 (interactive "P")
10464 (if (equal arg '(16)) (setq arg 'nextset))
10465 (let ((org-blocker-hook org-blocker-hook)
10466 (case-fold-search nil))
10467 (when (equal arg '(64))
10468 (setq arg nil org-blocker-hook nil))
10469 (when (and org-blocker-hook
10470 (or org-inhibit-blocking
10471 (org-entry-get nil "NOBLOCKING")))
10472 (setq org-blocker-hook nil))
10473 (save-excursion
10474 (catch 'exit
10475 (org-back-to-heading t)
10476 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10477 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10478 (looking-at " *"))
10479 (let* ((match-data (match-data))
10480 (startpos (point-at-bol))
10481 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10482 (org-log-done org-log-done)
10483 (org-log-repeat org-log-repeat)
10484 (org-todo-log-states org-todo-log-states)
10485 (this (match-string 1))
10486 (hl-pos (match-beginning 0))
10487 (head (org-get-todo-sequence-head this))
10488 (ass (assoc head org-todo-kwd-alist))
10489 (interpret (nth 1 ass))
10490 (done-word (nth 3 ass))
10491 (final-done-word (nth 4 ass))
10492 (last-state (or this ""))
10493 (completion-ignore-case t)
10494 (member (member this org-todo-keywords-1))
10495 (tail (cdr member))
10496 (state (cond
10497 ((and org-todo-key-trigger
10498 (or (and (equal arg '(4))
10499 (eq org-use-fast-todo-selection 'prefix))
10500 (and (not arg) org-use-fast-todo-selection
10501 (not (eq org-use-fast-todo-selection
10502 'prefix)))))
10503 ;; Use fast selection
10504 (org-fast-todo-selection))
10505 ((and (equal arg '(4))
10506 (or (not org-use-fast-todo-selection)
10507 (not org-todo-key-trigger)))
10508 ;; Read a state with completion
10509 (org-icompleting-read
10510 "State: " (mapcar (lambda(x) (list x))
10511 org-todo-keywords-1)
10512 nil t))
10513 ((eq arg 'right)
10514 (if this
10515 (if tail (car tail) nil)
10516 (car org-todo-keywords-1)))
10517 ((eq arg 'left)
10518 (if (equal member org-todo-keywords-1)
10520 (if this
10521 (nth (- (length org-todo-keywords-1)
10522 (length tail) 2)
10523 org-todo-keywords-1)
10524 (org-last org-todo-keywords-1))))
10525 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10526 (setq arg nil))) ; hack to fall back to cycling
10527 (arg
10528 ;; user or caller requests a specific state
10529 (cond
10530 ((equal arg "") nil)
10531 ((eq arg 'none) nil)
10532 ((eq arg 'done) (or done-word (car org-done-keywords)))
10533 ((eq arg 'nextset)
10534 (or (car (cdr (member head org-todo-heads)))
10535 (car org-todo-heads)))
10536 ((eq arg 'previousset)
10537 (let ((org-todo-heads (reverse org-todo-heads)))
10538 (or (car (cdr (member head org-todo-heads)))
10539 (car org-todo-heads))))
10540 ((car (member arg org-todo-keywords-1)))
10541 ((stringp arg)
10542 (error "State `%s' not valid in this file" arg))
10543 ((nth (1- (prefix-numeric-value arg))
10544 org-todo-keywords-1))))
10545 ((null member) (or head (car org-todo-keywords-1)))
10546 ((equal this final-done-word) nil) ;; -> make empty
10547 ((null tail) nil) ;; -> first entry
10548 ((memq interpret '(type priority))
10549 (if (eq this-command last-command)
10550 (car tail)
10551 (if (> (length tail) 0)
10552 (or done-word (car org-done-keywords))
10553 nil)))
10555 (car tail))))
10556 (state (or
10557 (run-hook-with-args-until-success
10558 'org-todo-get-default-hook state last-state)
10559 state))
10560 (next (if state (concat " " state " ") " "))
10561 (change-plist (list :type 'todo-state-change :from this :to state
10562 :position startpos))
10563 dolog now-done-p)
10564 (when org-blocker-hook
10565 (setq org-last-todo-state-is-todo
10566 (not (member this org-done-keywords)))
10567 (unless (save-excursion
10568 (save-match-data
10569 (run-hook-with-args-until-failure
10570 'org-blocker-hook change-plist)))
10571 (if (interactive-p)
10572 (error "TODO state change from %s to %s blocked" this state)
10573 ;; fail silently
10574 (message "TODO state change from %s to %s blocked" this state)
10575 (throw 'exit nil))))
10576 (store-match-data match-data)
10577 (replace-match next t t)
10578 (unless (pos-visible-in-window-p hl-pos)
10579 (message "TODO state changed to %s" (org-trim next)))
10580 (unless head
10581 (setq head (org-get-todo-sequence-head state)
10582 ass (assoc head org-todo-kwd-alist)
10583 interpret (nth 1 ass)
10584 done-word (nth 3 ass)
10585 final-done-word (nth 4 ass)))
10586 (when (memq arg '(nextset previousset))
10587 (message "Keyword-Set %d/%d: %s"
10588 (- (length org-todo-sets) -1
10589 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10590 (length org-todo-sets)
10591 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10592 (setq org-last-todo-state-is-todo
10593 (not (member state org-done-keywords)))
10594 (setq now-done-p (and (member state org-done-keywords)
10595 (not (member this org-done-keywords))))
10596 (and logging (org-local-logging logging))
10597 (when (and (or org-todo-log-states org-log-done)
10598 (not (eq org-inhibit-logging t))
10599 (not (memq arg '(nextset previousset))))
10600 ;; we need to look at recording a time and note
10601 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10602 (nth 2 (assoc this org-todo-log-states))))
10603 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10604 (setq dolog 'time))
10605 (when (and state
10606 (member state org-not-done-keywords)
10607 (not (member this org-not-done-keywords)))
10608 ;; This is now a todo state and was not one before
10609 ;; If there was a CLOSED time stamp, get rid of it.
10610 (org-add-planning-info nil nil 'closed))
10611 (when (and now-done-p org-log-done)
10612 ;; It is now done, and it was not done before
10613 (org-add-planning-info 'closed (org-current-time))
10614 (if (and (not dolog) (eq 'note org-log-done))
10615 (org-add-log-setup 'done state this 'findpos 'note)))
10616 (when (and state dolog)
10617 ;; This is a non-nil state, and we need to log it
10618 (org-add-log-setup 'state state this 'findpos dolog)))
10619 ;; Fixup tag positioning
10620 (org-todo-trigger-tag-changes state)
10621 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10622 (when org-provide-todo-statistics
10623 (org-update-parent-todo-statistics))
10624 (run-hooks 'org-after-todo-state-change-hook)
10625 (if (and arg (not (member state org-done-keywords)))
10626 (setq head (org-get-todo-sequence-head state)))
10627 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10628 ;; Do we need to trigger a repeat?
10629 (when now-done-p
10630 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10631 ;; This is for the agenda, take a snapshot of the headline.
10632 (save-match-data
10633 (setq org-agenda-headline-snapshot-before-repeat
10634 (org-get-heading))))
10635 (org-auto-repeat-maybe state))
10636 ;; Fixup cursor location if close to the keyword
10637 (if (and (outline-on-heading-p)
10638 (not (bolp))
10639 (save-excursion (beginning-of-line 1)
10640 (looking-at org-todo-line-regexp))
10641 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10642 (progn
10643 (goto-char (or (match-end 2) (match-end 1)))
10644 (and (looking-at " ") (just-one-space))))
10645 (when org-trigger-hook
10646 (save-excursion
10647 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10649 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10650 "Block turning an entry into a TODO, using the hierarchy.
10651 This checks whether the current task should be blocked from state
10652 changes. Such blocking occurs when:
10654 1. The task has children which are not all in a completed state.
10656 2. A task has a parent with the property :ORDERED:, and there
10657 are siblings prior to the current task with incomplete
10658 status.
10660 3. The parent of the task is blocked because it has siblings that should
10661 be done first, or is child of a block grandparent TODO entry."
10663 (if (not org-enforce-todo-dependencies)
10664 t ; if locally turned off don't block
10665 (catch 'dont-block
10666 ;; If this is not a todo state change, or if this entry is already DONE,
10667 ;; do not block
10668 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10669 (member (plist-get change-plist :from)
10670 (cons 'done org-done-keywords))
10671 (member (plist-get change-plist :to)
10672 (cons 'todo org-not-done-keywords))
10673 (not (plist-get change-plist :to)))
10674 (throw 'dont-block t))
10675 ;; If this task has children, and any are undone, it's blocked
10676 (save-excursion
10677 (org-back-to-heading t)
10678 (let ((this-level (funcall outline-level)))
10679 (outline-next-heading)
10680 (let ((child-level (funcall outline-level)))
10681 (while (and (not (eobp))
10682 (> child-level this-level))
10683 ;; this todo has children, check whether they are all
10684 ;; completed
10685 (if (and (not (org-entry-is-done-p))
10686 (org-entry-is-todo-p))
10687 (throw 'dont-block nil))
10688 (outline-next-heading)
10689 (setq child-level (funcall outline-level))))))
10690 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10691 ;; any previous siblings are undone, it's blocked
10692 (save-excursion
10693 (org-back-to-heading t)
10694 (let* ((pos (point))
10695 (parent-pos (and (org-up-heading-safe) (point))))
10696 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10697 (when (and (org-entry-get (point) "ORDERED")
10698 (forward-line 1)
10699 (re-search-forward org-not-done-heading-regexp pos t))
10700 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10701 ;; Search further up the hierarchy, to see if an anchestor is blocked
10702 (while t
10703 (goto-char parent-pos)
10704 (if (not (looking-at org-not-done-heading-regexp))
10705 (throw 'dont-block t)) ; do not block, parent is not a TODO
10706 (setq pos (point))
10707 (setq parent-pos (and (org-up-heading-safe) (point)))
10708 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10709 (when (and (org-entry-get (point) "ORDERED")
10710 (forward-line 1)
10711 (re-search-forward org-not-done-heading-regexp pos t))
10712 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10714 (defcustom org-track-ordered-property-with-tag nil
10715 "Should the ORDERED property also be shown as a tag?
10716 The ORDERED property decides if an entry should require subtasks to be
10717 completed in sequence. Since a property is not very visible, setting
10718 this option means that toggling the ORDERED property with the command
10719 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10720 not relevant for the behavior, but it makes things more visible.
10722 Note that toggling the tag with tags commands will not change the property
10723 and therefore not influence behavior!
10725 This can be t, meaning the tag ORDERED should be used, It can also be a
10726 string to select a different tag for this task."
10727 :group 'org-todo
10728 :type '(choice
10729 (const :tag "No tracking" nil)
10730 (const :tag "Track with ORDERED tag" t)
10731 (string :tag "Use other tag")))
10733 (defun org-toggle-ordered-property ()
10734 "Toggle the ORDERED property of the current entry.
10735 For better visibility, you can track the value of this property with a tag.
10736 See variable `org-track-ordered-property-with-tag'."
10737 (interactive)
10738 (let* ((t1 org-track-ordered-property-with-tag)
10739 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10740 (save-excursion
10741 (org-back-to-heading)
10742 (if (org-entry-get nil "ORDERED")
10743 (progn
10744 (org-delete-property "ORDERED")
10745 (and tag (org-toggle-tag tag 'off))
10746 (message "Subtasks can be completed in arbitrary order"))
10747 (org-entry-put nil "ORDERED" "t")
10748 (and tag (org-toggle-tag tag 'on))
10749 (message "Subtasks must be completed in sequence")))))
10751 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10752 (defun org-block-todo-from-checkboxes (change-plist)
10753 "Block turning an entry into a TODO, using checkboxes.
10754 This checks whether the current task should be blocked from state
10755 changes because there are unchecked boxes in this entry."
10756 (if (not org-enforce-todo-checkbox-dependencies)
10757 t ; if locally turned off don't block
10758 (catch 'dont-block
10759 ;; If this is not a todo state change, or if this entry is already DONE,
10760 ;; do not block
10761 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10762 (member (plist-get change-plist :from)
10763 (cons 'done org-done-keywords))
10764 (member (plist-get change-plist :to)
10765 (cons 'todo org-not-done-keywords))
10766 (not (plist-get change-plist :to)))
10767 (throw 'dont-block t))
10768 ;; If this task has checkboxes that are not checked, it's blocked
10769 (save-excursion
10770 (org-back-to-heading t)
10771 (let ((beg (point)) end)
10772 (outline-next-heading)
10773 (setq end (point))
10774 (goto-char beg)
10775 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10776 end t)
10777 (progn
10778 (if (boundp 'org-blocked-by-checkboxes)
10779 (setq org-blocked-by-checkboxes t))
10780 (throw 'dont-block nil)))))
10781 t))) ; do not block
10783 (defun org-entry-blocked-p ()
10784 "Is the current entry blocked?"
10785 (if (org-entry-get nil "NOBLOCKING")
10786 nil ;; Never block this entry
10787 (not
10788 (run-hook-with-args-until-failure
10789 'org-blocker-hook
10790 (list :type 'todo-state-change
10791 :position (point)
10792 :from 'todo
10793 :to 'done)))))
10795 (defun org-update-statistics-cookies (all)
10796 "Update the statistics cookie, either from TODO or from checkboxes.
10797 This should be called with the cursor in a line with a statistics cookie."
10798 (interactive "P")
10799 (if all
10800 (progn
10801 (org-update-checkbox-count 'all)
10802 (org-map-entries 'org-update-parent-todo-statistics))
10803 (if (not (org-on-heading-p))
10804 (org-update-checkbox-count)
10805 (let ((pos (move-marker (make-marker) (point)))
10806 end l1 l2)
10807 (ignore-errors (org-back-to-heading t))
10808 (if (not (org-on-heading-p))
10809 (org-update-checkbox-count)
10810 (setq l1 (org-outline-level))
10811 (setq end (save-excursion
10812 (outline-next-heading)
10813 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10814 (point)))
10815 (if (and (save-excursion
10816 (re-search-forward
10817 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10818 (not (save-excursion (re-search-forward
10819 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10820 (org-update-checkbox-count)
10821 (if (and l2 (> l2 l1))
10822 (progn
10823 (goto-char end)
10824 (org-update-parent-todo-statistics))
10825 (goto-char pos)
10826 (beginning-of-line 1)
10827 (while (re-search-forward
10828 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10829 (point-at-eol) t)
10830 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10831 (goto-char pos)
10832 (move-marker pos nil)))))
10834 (defvar org-entry-property-inherited-from) ;; defined below
10835 (defun org-update-parent-todo-statistics ()
10836 "Update any statistics cookie in the parent of the current headline.
10837 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10838 the entire subtree and this will travel up the hierarchy and update
10839 statistics everywhere."
10840 (interactive)
10841 (let* ((lim 0) prop
10842 (recursive (or (not org-hierarchical-todo-statistics)
10843 (string-match
10844 "\\<recursive\\>"
10845 (or (setq prop (org-entry-get
10846 nil "COOKIE_DATA" 'inherit)) ""))))
10847 (lim (or (and prop (marker-position
10848 org-entry-property-inherited-from))
10849 lim))
10850 (first t)
10851 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10852 level ltoggle l1 new ndel
10853 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10854 (catch 'exit
10855 (save-excursion
10856 (beginning-of-line 1)
10857 (if (org-at-heading-p)
10858 (setq ltoggle (funcall outline-level))
10859 (error "This should not happen"))
10860 (while (and (setq level (org-up-heading-safe))
10861 (or recursive first)
10862 (>= (point) lim))
10863 (setq first nil cookie-present nil)
10864 (unless (and level
10865 (not (string-match
10866 "\\<checkbox\\>"
10867 (downcase
10868 (or (org-entry-get
10869 nil "COOKIE_DATA")
10870 "")))))
10871 (throw 'exit nil))
10872 (while (re-search-forward box-re (point-at-eol) t)
10873 (setq cnt-all 0 cnt-done 0 cookie-present t)
10874 (setq is-percent (match-end 2))
10875 (save-match-data
10876 (unless (outline-next-heading) (throw 'exit nil))
10877 (while (and (looking-at org-complex-heading-regexp)
10878 (> (setq l1 (length (match-string 1))) level))
10879 (setq kwd (and (or recursive (= l1 ltoggle))
10880 (match-string 2)))
10881 (if (or (eq org-provide-todo-statistics 'all-headlines)
10882 (and (listp org-provide-todo-statistics)
10883 (or (member kwd org-provide-todo-statistics)
10884 (member kwd org-done-keywords))))
10885 (setq cnt-all (1+ cnt-all))
10886 (if (eq org-provide-todo-statistics t)
10887 (and kwd (setq cnt-all (1+ cnt-all)))))
10888 (and (member kwd org-done-keywords)
10889 (setq cnt-done (1+ cnt-done)))
10890 (outline-next-heading)))
10891 (setq new
10892 (if is-percent
10893 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10894 (format "[%d/%d]" cnt-done cnt-all))
10895 ndel (- (match-end 0) (match-beginning 0)))
10896 (goto-char (match-beginning 0))
10897 (insert new)
10898 (delete-region (point) (+ (point) ndel)))
10899 (when cookie-present
10900 (run-hook-with-args 'org-after-todo-statistics-hook
10901 cnt-done (- cnt-all cnt-done))))))
10902 (run-hooks 'org-todo-statistics-hook)))
10904 (defvar org-after-todo-statistics-hook nil
10905 "Hook that is called after a TODO statistics cookie has been updated.
10906 Each function is called with two arguments: the number of not-done entries
10907 and the number of done entries.
10909 For example, the following function, when added to this hook, will switch
10910 an entry to DONE when all children are done, and back to TODO when new
10911 entries are set to a TODO status. Note that this hook is only called
10912 when there is a statistics cookie in the headline!
10914 (defun org-summary-todo (n-done n-not-done)
10915 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10916 (let (org-log-done org-log-states) ; turn off logging
10917 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10920 (defvar org-todo-statistics-hook nil
10921 "Hook that is run whenever Org thinks TODO statistics should be updated.
10922 This hook runs even if there is no statistics cookie present, in which case
10923 `org-after-todo-statistics-hook' would not run.")
10925 (defun org-todo-trigger-tag-changes (state)
10926 "Apply the changes defined in `org-todo-state-tags-triggers'."
10927 (let ((l org-todo-state-tags-triggers)
10928 changes)
10929 (when (or (not state) (equal state ""))
10930 (setq changes (append changes (cdr (assoc "" l)))))
10931 (when (and (stringp state) (> (length state) 0))
10932 (setq changes (append changes (cdr (assoc state l)))))
10933 (when (member state org-not-done-keywords)
10934 (setq changes (append changes (cdr (assoc 'todo l)))))
10935 (when (member state org-done-keywords)
10936 (setq changes (append changes (cdr (assoc 'done l)))))
10937 (dolist (c changes)
10938 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10940 (defun org-local-logging (value)
10941 "Get logging settings from a property VALUE."
10942 (let* (words w a)
10943 ;; directly set the variables, they are already local.
10944 (setq org-log-done nil
10945 org-log-repeat nil
10946 org-todo-log-states nil)
10947 (setq words (org-split-string value))
10948 (while (setq w (pop words))
10949 (cond
10950 ((setq a (assoc w org-startup-options))
10951 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10952 (set (nth 1 a) (nth 2 a))))
10953 ((setq a (org-extract-log-state-settings w))
10954 (and (member (car a) org-todo-keywords-1)
10955 (push a org-todo-log-states)))))))
10957 (defun org-get-todo-sequence-head (kwd)
10958 "Return the head of the TODO sequence to which KWD belongs.
10959 If KWD is not set, check if there is a text property remembering the
10960 right sequence."
10961 (let (p)
10962 (cond
10963 ((not kwd)
10964 (or (get-text-property (point-at-bol) 'org-todo-head)
10965 (progn
10966 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10967 nil (point-at-eol)))
10968 (get-text-property p 'org-todo-head))))
10969 ((not (member kwd org-todo-keywords-1))
10970 (car org-todo-keywords-1))
10971 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10973 (defun org-fast-todo-selection ()
10974 "Fast TODO keyword selection with single keys.
10975 Returns the new TODO keyword, or nil if no state change should occur."
10976 (let* ((fulltable org-todo-key-alist)
10977 (done-keywords org-done-keywords) ;; needed for the faces.
10978 (maxlen (apply 'max (mapcar
10979 (lambda (x)
10980 (if (stringp (car x)) (string-width (car x)) 0))
10981 fulltable)))
10982 (expert nil)
10983 (fwidth (+ maxlen 3 1 3))
10984 (ncol (/ (- (window-width) 4) fwidth))
10985 tg cnt e c tbl
10986 groups ingroup)
10987 (save-excursion
10988 (save-window-excursion
10989 (if expert
10990 (set-buffer (get-buffer-create " *Org todo*"))
10991 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10992 (erase-buffer)
10993 (org-set-local 'org-done-keywords done-keywords)
10994 (setq tbl fulltable cnt 0)
10995 (while (setq e (pop tbl))
10996 (cond
10997 ((equal e '(:startgroup))
10998 (push '() groups) (setq ingroup t)
10999 (when (not (= cnt 0))
11000 (setq cnt 0)
11001 (insert "\n"))
11002 (insert "{ "))
11003 ((equal e '(:endgroup))
11004 (setq ingroup nil cnt 0)
11005 (insert "}\n"))
11006 ((equal e '(:newline))
11007 (when (not (= cnt 0))
11008 (setq cnt 0)
11009 (insert "\n")
11010 (setq e (car tbl))
11011 (while (equal (car tbl) '(:newline))
11012 (insert "\n")
11013 (setq tbl (cdr tbl)))))
11015 (setq tg (car e) c (cdr e))
11016 (if ingroup (push tg (car groups)))
11017 (setq tg (org-add-props tg nil 'face
11018 (org-get-todo-face tg)))
11019 (if (and (= cnt 0) (not ingroup)) (insert " "))
11020 (insert "[" c "] " tg (make-string
11021 (- fwidth 4 (length tg)) ?\ ))
11022 (when (= (setq cnt (1+ cnt)) ncol)
11023 (insert "\n")
11024 (if ingroup (insert " "))
11025 (setq cnt 0)))))
11026 (insert "\n")
11027 (goto-char (point-min))
11028 (if (not expert) (org-fit-window-to-buffer))
11029 (message "[a-z..]:Set [SPC]:clear")
11030 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11031 (cond
11032 ((or (= c ?\C-g)
11033 (and (= c ?q) (not (rassoc c fulltable))))
11034 (setq quit-flag t))
11035 ((= c ?\ ) nil)
11036 ((setq e (rassoc c fulltable) tg (car e))
11038 (t (setq quit-flag t)))))))
11040 (defun org-entry-is-todo-p ()
11041 (member (org-get-todo-state) org-not-done-keywords))
11043 (defun org-entry-is-done-p ()
11044 (member (org-get-todo-state) org-done-keywords))
11046 (defun org-get-todo-state ()
11047 (save-excursion
11048 (org-back-to-heading t)
11049 (and (looking-at org-todo-line-regexp)
11050 (match-end 2)
11051 (match-string 2))))
11053 (defun org-at-date-range-p (&optional inactive-ok)
11054 "Is the cursor inside a date range?"
11055 (interactive)
11056 (save-excursion
11057 (catch 'exit
11058 (let ((pos (point)))
11059 (skip-chars-backward "^[<\r\n")
11060 (skip-chars-backward "<[")
11061 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11062 (>= (match-end 0) pos)
11063 (throw 'exit t))
11064 (skip-chars-backward "^<[\r\n")
11065 (skip-chars-backward "<[")
11066 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11067 (>= (match-end 0) pos)
11068 (throw 'exit t)))
11069 nil)))
11071 (defun org-get-repeat (&optional tagline)
11072 "Check if there is a deadline/schedule with repeater in this entry."
11073 (save-match-data
11074 (save-excursion
11075 (org-back-to-heading t)
11076 (and (re-search-forward (if tagline
11077 (concat tagline "\\s-*" org-repeat-re)
11078 org-repeat-re)
11079 (org-entry-end-position) t)
11080 (match-string-no-properties 1)))))
11082 (defvar org-last-changed-timestamp)
11083 (defvar org-last-inserted-timestamp)
11084 (defvar org-log-post-message)
11085 (defvar org-log-note-purpose)
11086 (defvar org-log-note-how)
11087 (defvar org-log-note-extra)
11088 (defun org-auto-repeat-maybe (done-word)
11089 "Check if the current headline contains a repeated deadline/schedule.
11090 If yes, set TODO state back to what it was and change the base date
11091 of repeating deadline/scheduled time stamps to new date.
11092 This function is run automatically after each state change to a DONE state."
11093 ;; last-state is dynamically scoped into this function
11094 (let* ((repeat (org-get-repeat))
11095 (aa (assoc last-state org-todo-kwd-alist))
11096 (interpret (nth 1 aa))
11097 (head (nth 2 aa))
11098 (whata '(("d" . day) ("m" . month) ("y" . year)))
11099 (msg "Entry repeats: ")
11100 (org-log-done nil)
11101 (org-todo-log-states nil)
11102 (nshiftmax 10) (nshift 0)
11103 re type n what ts time to-state)
11104 (when repeat
11105 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11106 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11107 org-todo-repeat-to-state))
11108 (unless (and to-state (member to-state org-todo-keywords-1))
11109 (setq to-state (if (eq interpret 'type) last-state head)))
11110 (org-todo to-state)
11111 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11112 (org-entry-put nil "LAST_REPEAT" (format-time-string
11113 (org-time-stamp-format t t))))
11114 (when org-log-repeat
11115 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11116 (memq 'org-add-log-note post-command-hook))
11117 ;; OK, we are already setup for some record
11118 (if (eq org-log-repeat 'note)
11119 ;; make sure we take a note, not only a time stamp
11120 (setq org-log-note-how 'note))
11121 ;; Set up for taking a record
11122 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11123 last-state
11124 'findpos org-log-repeat)))
11125 (org-back-to-heading t)
11126 (org-add-planning-info nil nil 'closed)
11127 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11128 org-deadline-time-regexp "\\)\\|\\("
11129 org-ts-regexp "\\)"))
11130 (while (re-search-forward
11131 re (save-excursion (outline-next-heading) (point)) t)
11132 (setq type (if (match-end 1) org-scheduled-string
11133 (if (match-end 3) org-deadline-string "Plain:"))
11134 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11135 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11136 (setq n (string-to-number (match-string 2 ts))
11137 what (match-string 3 ts))
11138 (if (equal what "w") (setq n (* n 7) what "d"))
11139 ;; Preparation, see if we need to modify the start date for the change
11140 (when (match-end 1)
11141 (setq time (save-match-data (org-time-string-to-time ts)))
11142 (cond
11143 ((equal (match-string 1 ts) ".")
11144 ;; Shift starting date to today
11145 (org-timestamp-change
11146 (- (time-to-days (current-time)) (time-to-days time))
11147 'day))
11148 ((equal (match-string 1 ts) "+")
11149 (while (or (= nshift 0)
11150 (<= (time-to-days time) (time-to-days (current-time))))
11151 (when (= (incf nshift) nshiftmax)
11152 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11153 (error "Abort")))
11154 (org-timestamp-change n (cdr (assoc what whata)))
11155 (org-at-timestamp-p t)
11156 (setq ts (match-string 1))
11157 (setq time (save-match-data (org-time-string-to-time ts))))
11158 (org-timestamp-change (- n) (cdr (assoc what whata)))
11159 ;; rematch, so that we have everything in place for the real shift
11160 (org-at-timestamp-p t)
11161 (setq ts (match-string 1))
11162 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11163 (org-timestamp-change n (cdr (assoc what whata)))
11164 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11165 (setq org-log-post-message msg)
11166 (message "%s" msg))))
11168 (defun org-show-todo-tree (arg)
11169 "Make a compact tree which shows all headlines marked with TODO.
11170 The tree will show the lines where the regexp matches, and all higher
11171 headlines above the match.
11172 With a \\[universal-argument] prefix, prompt for a regexp to match.
11173 With a numeric prefix N, construct a sparse tree for the Nth element
11174 of `org-todo-keywords-1'."
11175 (interactive "P")
11176 (let ((case-fold-search nil)
11177 (kwd-re
11178 (cond ((null arg) org-not-done-regexp)
11179 ((equal arg '(4))
11180 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11181 (mapcar 'list org-todo-keywords-1))))
11182 (concat "\\("
11183 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11184 "\\)\\>")))
11185 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11186 (regexp-quote (nth (1- (prefix-numeric-value arg))
11187 org-todo-keywords-1)))
11188 (t (error "Invalid prefix argument: %s" arg)))))
11189 (message "%d TODO entries found"
11190 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11192 (defun org-deadline (&optional remove time)
11193 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11194 With argument REMOVE, remove any deadline from the item.
11195 When TIME is set, it should be an internal time specification, and the
11196 scheduling will use the corresponding date."
11197 (interactive "P")
11198 (let* ((old-date (org-entry-get nil "DEADLINE"))
11199 (repeater (and old-date
11200 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11201 (match-string 1 old-date))))
11202 (if remove
11203 (progn
11204 (when (and old-date org-log-redeadline)
11205 (org-add-log-setup 'deldeadline nil old-date 'findpos
11206 org-log-redeadline))
11207 (org-remove-timestamp-with-keyword org-deadline-string)
11208 (message "Item no longer has a deadline."))
11209 (org-add-planning-info 'deadline time 'closed)
11210 (when (and old-date org-log-redeadline
11211 (not (equal old-date
11212 (substring org-last-inserted-timestamp 1 -1))))
11213 (org-add-log-setup 'redeadline nil old-date 'findpos
11214 org-log-redeadline))
11215 (when repeater
11216 (save-excursion
11217 (org-back-to-heading t)
11218 (when (re-search-forward (concat org-deadline-string " "
11219 org-last-inserted-timestamp)
11220 (save-excursion
11221 (outline-next-heading) (point)) t)
11222 (goto-char (1- (match-end 0)))
11223 (insert " " repeater)
11224 (setq org-last-inserted-timestamp
11225 (concat (substring org-last-inserted-timestamp 0 -1)
11226 " " repeater
11227 (substring org-last-inserted-timestamp -1))))))
11228 (message "Deadline on %s" org-last-inserted-timestamp))))
11230 (defun org-schedule (&optional remove time)
11231 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11232 With argument REMOVE, remove any scheduling date from the item.
11233 When TIME is set, it should be an internal time specification, and the
11234 scheduling will use the corresponding date."
11235 (interactive "P")
11236 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11237 (repeater (and old-date
11238 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11239 (match-string 1 old-date))))
11240 (if remove
11241 (progn
11242 (when (and old-date org-log-reschedule)
11243 (org-add-log-setup 'delschedule nil old-date 'findpos
11244 org-log-reschedule))
11245 (org-remove-timestamp-with-keyword org-scheduled-string)
11246 (message "Item is no longer scheduled."))
11247 (org-add-planning-info 'scheduled time 'closed)
11248 (when (and old-date org-log-reschedule
11249 (not (equal old-date
11250 (substring org-last-inserted-timestamp 1 -1))))
11251 (org-add-log-setup 'reschedule nil old-date 'findpos
11252 org-log-reschedule))
11253 (when repeater
11254 (save-excursion
11255 (org-back-to-heading t)
11256 (when (re-search-forward (concat org-scheduled-string " "
11257 org-last-inserted-timestamp)
11258 (save-excursion
11259 (outline-next-heading) (point)) t)
11260 (goto-char (1- (match-end 0)))
11261 (insert " " repeater)
11262 (setq org-last-inserted-timestamp
11263 (concat (substring org-last-inserted-timestamp 0 -1)
11264 " " repeater
11265 (substring org-last-inserted-timestamp -1))))))
11266 (message "Scheduled to %s" org-last-inserted-timestamp))))
11268 (defun org-get-scheduled-time (pom &optional inherit)
11269 "Get the scheduled time as a time tuple, of a format suitable
11270 for calling org-schedule with, or if there is no scheduling,
11271 returns nil."
11272 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11273 (when time
11274 (apply 'encode-time (org-parse-time-string time)))))
11276 (defun org-get-deadline-time (pom &optional inherit)
11277 "Get the deadine as a time tuple, of a format suitable for
11278 calling org-deadline with, or if there is no scheduling, returns
11279 nil."
11280 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11281 (when time
11282 (apply 'encode-time (org-parse-time-string time)))))
11284 (defun org-remove-timestamp-with-keyword (keyword)
11285 "Remove all time stamps with KEYWORD in the current entry."
11286 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11287 beg)
11288 (save-excursion
11289 (org-back-to-heading t)
11290 (setq beg (point))
11291 (outline-next-heading)
11292 (while (re-search-backward re beg t)
11293 (replace-match "")
11294 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11295 (equal (char-before) ?\ ))
11296 (backward-delete-char 1)
11297 (if (string-match "^[ \t]*$" (buffer-substring
11298 (point-at-bol) (point-at-eol)))
11299 (delete-region (point-at-bol)
11300 (min (point-max) (1+ (point-at-eol))))))))))
11302 (defun org-add-planning-info (what &optional time &rest remove)
11303 "Insert new timestamp with keyword in the line directly after the headline.
11304 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11305 If non is given, the user is prompted for a date.
11306 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11307 be removed."
11308 (interactive)
11309 (let (org-time-was-given org-end-time-was-given ts
11310 end default-time default-input)
11312 (catch 'exit
11313 (when (and (not time) (memq what '(scheduled deadline)))
11314 ;; Try to get a default date/time from existing timestamp
11315 (save-excursion
11316 (org-back-to-heading t)
11317 (setq end (save-excursion (outline-next-heading) (point)))
11318 (when (re-search-forward (if (eq what 'scheduled)
11319 org-scheduled-time-regexp
11320 org-deadline-time-regexp)
11321 end t)
11322 (setq ts (match-string 1)
11323 default-time
11324 (apply 'encode-time (org-parse-time-string ts))
11325 default-input (and ts (org-get-compact-tod ts))))))
11326 (when what
11327 ;; If necessary, get the time from the user
11328 (setq time (or time (org-read-date nil 'to-time nil nil
11329 default-time default-input))))
11331 (when (and org-insert-labeled-timestamps-at-point
11332 (member what '(scheduled deadline)))
11333 (insert
11334 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11335 (org-insert-time-stamp time org-time-was-given
11336 nil nil nil (list org-end-time-was-given))
11337 (setq what nil))
11338 (save-excursion
11339 (save-restriction
11340 (let (col list elt ts buffer-invisibility-spec)
11341 (org-back-to-heading t)
11342 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11343 (goto-char (match-end 1))
11344 (setq col (current-column))
11345 (goto-char (match-end 0))
11346 (if (eobp) (insert "\n") (forward-char 1))
11347 (when (and (not what)
11348 (not (looking-at
11349 (concat "[ \t]*"
11350 org-keyword-time-not-clock-regexp))))
11351 ;; Nothing to add, nothing to remove...... :-)
11352 (throw 'exit nil))
11353 (if (and (not (looking-at outline-regexp))
11354 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11355 "[^\r\n]*"))
11356 (not (equal (match-string 1) org-clock-string)))
11357 (narrow-to-region (match-beginning 0) (match-end 0))
11358 (insert-before-markers "\n")
11359 (backward-char 1)
11360 (narrow-to-region (point) (point))
11361 (and org-adapt-indentation (org-indent-to-column col)))
11362 ;; Check if we have to remove something.
11363 (setq list (cons what remove))
11364 (while list
11365 (setq elt (pop list))
11366 (goto-char (point-min))
11367 (when (or (and (eq elt 'scheduled)
11368 (re-search-forward org-scheduled-time-regexp nil t))
11369 (and (eq elt 'deadline)
11370 (re-search-forward org-deadline-time-regexp nil t))
11371 (and (eq elt 'closed)
11372 (re-search-forward org-closed-time-regexp nil t)))
11373 (replace-match "")
11374 (if (looking-at "--+<[^>]+>") (replace-match ""))
11375 (skip-chars-backward " ")
11376 (if (looking-at " +") (replace-match ""))))
11377 (goto-char (point-max))
11378 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11379 (when what
11380 (insert
11381 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11382 (cond ((eq what 'scheduled) org-scheduled-string)
11383 ((eq what 'deadline) org-deadline-string)
11384 ((eq what 'closed) org-closed-string))
11385 " ")
11386 (setq ts (org-insert-time-stamp
11387 time
11388 (or org-time-was-given
11389 (and (eq what 'closed) org-log-done-with-time))
11390 (eq what 'closed)
11391 nil nil (list org-end-time-was-given)))
11392 (end-of-line 1))
11393 (goto-char (point-min))
11394 (widen)
11395 (if (and (looking-at "[ \t]*\n")
11396 (equal (char-before) ?\n))
11397 (delete-region (1- (point)) (point-at-eol)))
11398 ts))))))
11400 (defvar org-log-note-marker (make-marker))
11401 (defvar org-log-note-purpose nil)
11402 (defvar org-log-note-state nil)
11403 (defvar org-log-note-previous-state nil)
11404 (defvar org-log-note-how nil)
11405 (defvar org-log-note-extra nil)
11406 (defvar org-log-note-window-configuration nil)
11407 (defvar org-log-note-return-to (make-marker))
11408 (defvar org-log-post-message nil
11409 "Message to be displayed after a log note has been stored.
11410 The auto-repeater uses this.")
11412 (defun org-add-note ()
11413 "Add a note to the current entry.
11414 This is done in the same way as adding a state change note."
11415 (interactive)
11416 (org-add-log-setup 'note nil nil 'findpos nil))
11418 (defvar org-property-end-re)
11419 (defun org-add-log-setup (&optional purpose state prev-state
11420 findpos how &optional extra)
11421 "Set up the post command hook to take a note.
11422 If this is about to TODO state change, the new state is expected in STATE.
11423 When FINDPOS is non-nil, find the correct position for the note in
11424 the current entry. If not, assume that it can be inserted at point.
11425 HOW is an indicator what kind of note should be created.
11426 EXTRA is additional text that will be inserted into the notes buffer."
11427 (let* ((org-log-into-drawer (org-log-into-drawer))
11428 (drawer (cond ((stringp org-log-into-drawer)
11429 org-log-into-drawer)
11430 (org-log-into-drawer "LOGBOOK")
11431 (t nil))))
11432 (save-restriction
11433 (save-excursion
11434 (when findpos
11435 (org-back-to-heading t)
11436 (narrow-to-region (point) (save-excursion
11437 (outline-next-heading) (point)))
11438 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11439 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11440 "[^\r\n]*\\)?"))
11441 (goto-char (match-end 0))
11442 (cond
11443 (drawer
11444 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11445 nil t)
11446 (progn
11447 (goto-char (match-end 0))
11448 (or org-log-states-order-reversed
11449 (and (re-search-forward org-property-end-re nil t)
11450 (goto-char (1- (match-beginning 0))))))
11451 (insert "\n:" drawer ":\n:END:")
11452 (beginning-of-line 0)
11453 (org-indent-line-function)
11454 (beginning-of-line 2)
11455 (org-indent-line-function)
11456 (end-of-line 0)))
11457 ((and org-log-state-notes-insert-after-drawers
11458 (save-excursion
11459 (forward-line) (looking-at org-drawer-regexp)))
11460 (forward-line)
11461 (while (looking-at org-drawer-regexp)
11462 (goto-char (match-end 0))
11463 (re-search-forward org-property-end-re (point-max) t)
11464 (forward-line))
11465 (forward-line -1)))
11466 (unless org-log-states-order-reversed
11467 (and (= (char-after) ?\n) (forward-char 1))
11468 (org-skip-over-state-notes)
11469 (skip-chars-backward " \t\n\r")))
11470 (move-marker org-log-note-marker (point))
11471 (setq org-log-note-purpose purpose
11472 org-log-note-state state
11473 org-log-note-previous-state prev-state
11474 org-log-note-how how
11475 org-log-note-extra extra)
11476 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11478 (defun org-skip-over-state-notes ()
11479 "Skip past the list of State notes in an entry."
11480 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11481 (while (looking-at "[ \t]*- State")
11482 (condition-case nil
11483 (org-next-item)
11484 (error (org-end-of-item)))))
11486 (defun org-add-log-note (&optional purpose)
11487 "Pop up a window for taking a note, and add this note later at point."
11488 (remove-hook 'post-command-hook 'org-add-log-note)
11489 (setq org-log-note-window-configuration (current-window-configuration))
11490 (delete-other-windows)
11491 (move-marker org-log-note-return-to (point))
11492 (switch-to-buffer (marker-buffer org-log-note-marker))
11493 (goto-char org-log-note-marker)
11494 (org-switch-to-buffer-other-window "*Org Note*")
11495 (erase-buffer)
11496 (if (memq org-log-note-how '(time state))
11497 (let (current-prefix-arg) (org-store-log-note))
11498 (let ((org-inhibit-startup t)) (org-mode))
11499 (insert (format "# Insert note for %s.
11500 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11501 (cond
11502 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11503 ((eq org-log-note-purpose 'done) "closed todo item")
11504 ((eq org-log-note-purpose 'state)
11505 (format "state change from \"%s\" to \"%s\""
11506 (or org-log-note-previous-state "")
11507 (or org-log-note-state "")))
11508 ((eq org-log-note-purpose 'reschedule)
11509 "rescheduling")
11510 ((eq org-log-note-purpose 'delschedule)
11511 "no longer scheduled")
11512 ((eq org-log-note-purpose 'redeadline)
11513 "changing deadline")
11514 ((eq org-log-note-purpose 'deldeadline)
11515 "removing deadline")
11516 ((eq org-log-note-purpose 'refile)
11517 "refiling")
11518 ((eq org-log-note-purpose 'note)
11519 "this entry")
11520 (t (error "This should not happen")))))
11521 (if org-log-note-extra (insert org-log-note-extra))
11522 (org-set-local 'org-finish-function 'org-store-log-note)))
11524 (defvar org-note-abort nil) ; dynamically scoped
11525 (defun org-store-log-note ()
11526 "Finish taking a log note, and insert it to where it belongs."
11527 (let ((txt (buffer-string))
11528 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11529 lines ind)
11530 (kill-buffer (current-buffer))
11531 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11532 (setq txt (replace-match "" t t txt)))
11533 (if (string-match "\\s-+\\'" txt)
11534 (setq txt (replace-match "" t t txt)))
11535 (setq lines (org-split-string txt "\n"))
11536 (when (and note (string-match "\\S-" note))
11537 (setq note
11538 (org-replace-escapes
11539 note
11540 (list (cons "%u" (user-login-name))
11541 (cons "%U" user-full-name)
11542 (cons "%t" (format-time-string
11543 (org-time-stamp-format 'long 'inactive)
11544 (current-time)))
11545 (cons "%T" (format-time-string
11546 (org-time-stamp-format 'long nil)
11547 (current-time)))
11548 (cons "%s" (if org-log-note-state
11549 (concat "\"" org-log-note-state "\"")
11550 ""))
11551 (cons "%S" (if org-log-note-previous-state
11552 (concat "\"" org-log-note-previous-state "\"")
11553 "\"\"")))))
11554 (if lines (setq note (concat note " \\\\")))
11555 (push note lines))
11556 (when (or current-prefix-arg org-note-abort)
11557 (when org-log-into-drawer
11558 (org-remove-empty-drawer-at
11559 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11560 org-log-note-marker))
11561 (setq lines nil))
11562 (when lines
11563 (with-current-buffer (marker-buffer org-log-note-marker)
11564 (save-excursion
11565 (goto-char org-log-note-marker)
11566 (move-marker org-log-note-marker nil)
11567 (end-of-line 1)
11568 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11569 (insert "- " (pop lines))
11570 (org-indent-line-function)
11571 (beginning-of-line 1)
11572 (looking-at "[ \t]*")
11573 (setq ind (concat (match-string 0) " "))
11574 (end-of-line 1)
11575 (while lines (insert "\n" ind (pop lines)))
11576 (message "Note stored")
11577 (org-back-to-heading t)
11578 (org-cycle-hide-drawers 'children)))))
11579 (set-window-configuration org-log-note-window-configuration)
11580 (with-current-buffer (marker-buffer org-log-note-return-to)
11581 (goto-char org-log-note-return-to))
11582 (move-marker org-log-note-return-to nil)
11583 (and org-log-post-message (message "%s" org-log-post-message)))
11585 (defun org-remove-empty-drawer-at (drawer pos)
11586 "Remove an empty drawer DRAWER at position POS.
11587 POS may also be a marker."
11588 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11589 (save-excursion
11590 (save-restriction
11591 (widen)
11592 (goto-char pos)
11593 (if (org-in-regexp
11594 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11595 (replace-match ""))))))
11597 (defun org-sparse-tree (&optional arg)
11598 "Create a sparse tree, prompt for the details.
11599 This command can create sparse trees. You first need to select the type
11600 of match used to create the tree:
11602 t Show all TODO entries.
11603 T Show entries with a specific TODO keyword.
11604 m Show entries selected by a tags/property match.
11605 p Enter a property name and its value (both with completion on existing
11606 names/values) and show entries with that property.
11607 / Show entries matching a regular expression (`r' can be used as well)
11608 d Show deadlines due within `org-deadline-warning-days'.
11609 b Show deadlines and scheduled items before a date.
11610 a Show deadlines and scheduled items after a date."
11611 (interactive "P")
11612 (let (ans kwd value)
11613 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11614 (setq ans (read-char-exclusive))
11615 (cond
11616 ((equal ans ?d)
11617 (call-interactively 'org-check-deadlines))
11618 ((equal ans ?b)
11619 (call-interactively 'org-check-before-date))
11620 ((equal ans ?a)
11621 (call-interactively 'org-check-after-date))
11622 ((equal ans ?t)
11623 (org-show-todo-tree nil))
11624 ((equal ans ?T)
11625 (org-show-todo-tree '(4)))
11626 ((member ans '(?T ?m))
11627 (call-interactively 'org-match-sparse-tree))
11628 ((member ans '(?p ?P))
11629 (setq kwd (org-icompleting-read "Property: "
11630 (mapcar 'list (org-buffer-property-keys))))
11631 (setq value (org-icompleting-read "Value: "
11632 (mapcar 'list (org-property-values kwd))))
11633 (unless (string-match "\\`{.*}\\'" value)
11634 (setq value (concat "\"" value "\"")))
11635 (org-match-sparse-tree arg (concat kwd "=" value)))
11636 ((member ans '(?r ?R ?/))
11637 (call-interactively 'org-occur))
11638 (t (error "No such sparse tree command \"%c\"" ans)))))
11640 (defvar org-occur-highlights nil
11641 "List of overlays used for occur matches.")
11642 (make-variable-buffer-local 'org-occur-highlights)
11643 (defvar org-occur-parameters nil
11644 "Parameters of the active org-occur calls.
11645 This is a list, each call to org-occur pushes as cons cell,
11646 containing the regular expression and the callback, onto the list.
11647 The list can contain several entries if `org-occur' has been called
11648 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11649 will only contain one set of parameters. When the highlights are
11650 removed (for example with `C-c C-c', or with the next edit (depending
11651 on `org-remove-highlights-with-change'), this variable is emptied
11652 as well.")
11653 (make-variable-buffer-local 'org-occur-parameters)
11655 (defun org-occur (regexp &optional keep-previous callback)
11656 "Make a compact tree which shows all matches of REGEXP.
11657 The tree will show the lines where the regexp matches, and all higher
11658 headlines above the match. It will also show the heading after the match,
11659 to make sure editing the matching entry is easy.
11660 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11661 call to `org-occur' will be kept, to allow stacking of calls to this
11662 command.
11663 If CALLBACK is non-nil, it is a function which is called to confirm
11664 that the match should indeed be shown."
11665 (interactive "sRegexp: \nP")
11666 (when (equal regexp "")
11667 (error "Regexp cannot be empty"))
11668 (unless keep-previous
11669 (org-remove-occur-highlights nil nil t))
11670 (push (cons regexp callback) org-occur-parameters)
11671 (let ((cnt 0))
11672 (save-excursion
11673 (goto-char (point-min))
11674 (if (or (not keep-previous) ; do not want to keep
11675 (not org-occur-highlights)) ; no previous matches
11676 ;; hide everything
11677 (org-overview))
11678 (while (re-search-forward regexp nil t)
11679 (when (or (not callback)
11680 (save-match-data (funcall callback)))
11681 (setq cnt (1+ cnt))
11682 (when org-highlight-sparse-tree-matches
11683 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11684 (org-show-context 'occur-tree))))
11685 (when org-remove-highlights-with-change
11686 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11687 nil 'local))
11688 (unless org-sparse-tree-open-archived-trees
11689 (org-hide-archived-subtrees (point-min) (point-max)))
11690 (run-hooks 'org-occur-hook)
11691 (if (interactive-p)
11692 (message "%d match(es) for regexp %s" cnt regexp))
11693 cnt))
11695 (defun org-show-context (&optional key)
11696 "Make sure point and context and visible.
11697 How much context is shown depends upon the variables
11698 `org-show-hierarchy-above', `org-show-following-heading'. and
11699 `org-show-siblings'."
11700 (let ((heading-p (org-on-heading-p t))
11701 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11702 (following-p (org-get-alist-option org-show-following-heading key))
11703 (entry-p (org-get-alist-option org-show-entry-below key))
11704 (siblings-p (org-get-alist-option org-show-siblings key)))
11705 (catch 'exit
11706 ;; Show heading or entry text
11707 (if (and heading-p (not entry-p))
11708 (org-flag-heading nil) ; only show the heading
11709 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11710 (org-show-hidden-entry))) ; show entire entry
11711 (when following-p
11712 ;; Show next sibling, or heading below text
11713 (save-excursion
11714 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11715 (org-flag-heading nil))))
11716 (when siblings-p (org-show-siblings))
11717 (when hierarchy-p
11718 ;; show all higher headings, possibly with siblings
11719 (save-excursion
11720 (while (and (condition-case nil
11721 (progn (org-up-heading-all 1) t)
11722 (error nil))
11723 (not (bobp)))
11724 (org-flag-heading nil)
11725 (when siblings-p (org-show-siblings))))))))
11727 (defvar org-reveal-start-hook nil
11728 "Hook run before revealing a location.")
11730 (defun org-reveal (&optional siblings)
11731 "Show current entry, hierarchy above it, and the following headline.
11732 This can be used to show a consistent set of context around locations
11733 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11734 not t for the search context.
11736 With optional argument SIBLINGS, on each level of the hierarchy all
11737 siblings are shown. This repairs the tree structure to what it would
11738 look like when opened with hierarchical calls to `org-cycle'.
11739 With double optional argument `C-u C-u', go to the parent and show the
11740 entire tree."
11741 (interactive "P")
11742 (run-hooks 'org-reveal-start-hook)
11743 (let ((org-show-hierarchy-above t)
11744 (org-show-following-heading t)
11745 (org-show-siblings (if siblings t org-show-siblings)))
11746 (org-show-context nil))
11747 (when (equal siblings '(16))
11748 (save-excursion
11749 (when (org-up-heading-safe)
11750 (org-show-subtree)
11751 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11753 (defun org-highlight-new-match (beg end)
11754 "Highlight from BEG to END and mark the highlight is an occur headline."
11755 (let ((ov (make-overlay beg end)))
11756 (overlay-put ov 'face 'secondary-selection)
11757 (push ov org-occur-highlights)))
11759 (defun org-remove-occur-highlights (&optional beg end noremove)
11760 "Remove the occur highlights from the buffer.
11761 BEG and END are ignored. If NOREMOVE is nil, remove this function
11762 from the `before-change-functions' in the current buffer."
11763 (interactive)
11764 (unless org-inhibit-highlight-removal
11765 (mapc 'delete-overlay org-occur-highlights)
11766 (setq org-occur-highlights nil)
11767 (setq org-occur-parameters nil)
11768 (unless noremove
11769 (remove-hook 'before-change-functions
11770 'org-remove-occur-highlights 'local))))
11772 ;;;; Priorities
11774 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11775 "Regular expression matching the priority indicator.")
11777 (defvar org-remove-priority-next-time nil)
11779 (defun org-priority-up ()
11780 "Increase the priority of the current item."
11781 (interactive)
11782 (org-priority 'up))
11784 (defun org-priority-down ()
11785 "Decrease the priority of the current item."
11786 (interactive)
11787 (org-priority 'down))
11789 (defun org-priority (&optional action)
11790 "Change the priority of an item by ARG.
11791 ACTION can be `set', `up', `down', or a character."
11792 (interactive)
11793 (unless org-enable-priority-commands
11794 (error "Priority commands are disabled"))
11795 (setq action (or action 'set))
11796 (let (current new news have remove)
11797 (save-excursion
11798 (org-back-to-heading t)
11799 (if (looking-at org-priority-regexp)
11800 (setq current (string-to-char (match-string 2))
11801 have t)
11802 (setq current org-default-priority))
11803 (cond
11804 ((eq action 'remove)
11805 (setq remove t new ?\ ))
11806 ((or (eq action 'set)
11807 (if (featurep 'xemacs) (characterp action) (integerp action)))
11808 (if (not (eq action 'set))
11809 (setq new action)
11810 (message "Priority %c-%c, SPC to remove: "
11811 org-highest-priority org-lowest-priority)
11812 (setq new (read-char-exclusive)))
11813 (if (and (= (upcase org-highest-priority) org-highest-priority)
11814 (= (upcase org-lowest-priority) org-lowest-priority))
11815 (setq new (upcase new)))
11816 (cond ((equal new ?\ ) (setq remove t))
11817 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11818 (error "Priority must be between `%c' and `%c'"
11819 org-highest-priority org-lowest-priority))))
11820 ((eq action 'up)
11821 (if (and (not have) (eq last-command this-command))
11822 (setq new org-lowest-priority)
11823 (setq new (if (and org-priority-start-cycle-with-default (not have))
11824 org-default-priority (1- current)))))
11825 ((eq action 'down)
11826 (if (and (not have) (eq last-command this-command))
11827 (setq new org-highest-priority)
11828 (setq new (if (and org-priority-start-cycle-with-default (not have))
11829 org-default-priority (1+ current)))))
11830 (t (error "Invalid action")))
11831 (if (or (< (upcase new) org-highest-priority)
11832 (> (upcase new) org-lowest-priority))
11833 (setq remove t))
11834 (setq news (format "%c" new))
11835 (if have
11836 (if remove
11837 (replace-match "" t t nil 1)
11838 (replace-match news t t nil 2))
11839 (if remove
11840 (error "No priority cookie found in line")
11841 (let ((case-fold-search nil))
11842 (looking-at org-todo-line-regexp))
11843 (if (match-end 2)
11844 (progn
11845 (goto-char (match-end 2))
11846 (insert " [#" news "]"))
11847 (goto-char (match-beginning 3))
11848 (insert "[#" news "] "))))
11849 (org-preserve-lc (org-set-tags nil 'align)))
11850 (if remove
11851 (message "Priority removed")
11852 (message "Priority of current item set to %s" news))))
11854 (defun org-get-priority (s)
11855 "Find priority cookie and return priority."
11856 (save-match-data
11857 (if (not (string-match org-priority-regexp s))
11858 (* 1000 (- org-lowest-priority org-default-priority))
11859 (* 1000 (- org-lowest-priority
11860 (string-to-char (match-string 2 s)))))))
11862 ;;;; Tags
11864 (defvar org-agenda-archives-mode)
11865 (defvar org-map-continue-from nil
11866 "Position from where mapping should continue.
11867 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11869 (defvar org-scanner-tags nil
11870 "The current tag list while the tags scanner is running.")
11871 (defvar org-trust-scanner-tags nil
11872 "Should `org-get-tags-at' use the tags fro the scanner.
11873 This is for internal dynamical scoping only.
11874 When this is non-nil, the function `org-get-tags-at' will return the value
11875 of `org-scanner-tags' instead of building the list by itself. This
11876 can lead to large speed-ups when the tags scanner is used in a file with
11877 many entries, and when the list of tags is retrieved, for example to
11878 obtain a list of properties. Building the tags list for each entry in such
11879 a file becomes an N^2 operation - but with this variable set, it scales
11880 as N.")
11882 (defun org-scan-tags (action matcher &optional todo-only)
11883 "Scan headline tags with inheritance and produce output ACTION.
11885 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11886 or `agenda' to produce an entry list for an agenda view. It can also be
11887 a Lisp form or a function that should be called at each matched headline, in
11888 this case the return value is a list of all return values from these calls.
11890 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11891 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11892 only lines with a TODO keyword are included in the output."
11893 (require 'org-agenda)
11894 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11895 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11896 (org-re
11897 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11898 (props (list 'face 'default
11899 'done-face 'org-agenda-done
11900 'undone-face 'default
11901 'mouse-face 'highlight
11902 'org-not-done-regexp org-not-done-regexp
11903 'org-todo-regexp org-todo-regexp
11904 'help-echo
11905 (format "mouse-2 or RET jump to org file %s"
11906 (abbreviate-file-name
11907 (or (buffer-file-name (buffer-base-buffer))
11908 (buffer-name (buffer-base-buffer)))))))
11909 (case-fold-search nil)
11910 (org-map-continue-from nil)
11911 lspos tags tags-list
11912 (tags-alist (list (cons 0 org-file-tags)))
11913 (llast 0) rtn rtn1 level category i txt
11914 todo marker entry priority)
11915 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11916 (setq action (list 'lambda nil action)))
11917 (save-excursion
11918 (goto-char (point-min))
11919 (when (eq action 'sparse-tree)
11920 (org-overview)
11921 (org-remove-occur-highlights))
11922 (while (re-search-forward re nil t)
11923 (catch :skip
11924 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11925 tags (if (match-end 4) (org-match-string-no-properties 4)))
11926 (goto-char (setq lspos (match-beginning 0)))
11927 (setq level (org-reduced-level (funcall outline-level))
11928 category (org-get-category))
11929 (setq i llast llast level)
11930 ;; remove tag lists from same and sublevels
11931 (while (>= i level)
11932 (when (setq entry (assoc i tags-alist))
11933 (setq tags-alist (delete entry tags-alist)))
11934 (setq i (1- i)))
11935 ;; add the next tags
11936 (when tags
11937 (setq tags (org-split-string tags ":")
11938 tags-alist
11939 (cons (cons level tags) tags-alist)))
11940 ;; compile tags for current headline
11941 (setq tags-list
11942 (if org-use-tag-inheritance
11943 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11944 tags)
11945 org-scanner-tags tags-list)
11946 (when org-use-tag-inheritance
11947 (setcdr (car tags-alist)
11948 (mapcar (lambda (x)
11949 (setq x (copy-sequence x))
11950 (org-add-prop-inherited x))
11951 (cdar tags-alist))))
11952 (when (and tags org-use-tag-inheritance
11953 (or (not (eq t org-use-tag-inheritance))
11954 org-tags-exclude-from-inheritance))
11955 ;; selective inheritance, remove uninherited ones
11956 (setcdr (car tags-alist)
11957 (org-remove-uniherited-tags (cdar tags-alist))))
11958 (when (and (or (not todo-only)
11959 (and (member todo org-not-done-keywords)
11960 (or (not org-agenda-tags-todo-honor-ignore-options)
11961 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11962 (let ((case-fold-search t)) (eval matcher))
11964 (not (member org-archive-tag tags-list))
11965 ;; we have an archive tag, should we use this anyway?
11966 (or (not org-agenda-skip-archived-trees)
11967 (and (eq action 'agenda) org-agenda-archives-mode))))
11968 (unless (eq action 'sparse-tree) (org-agenda-skip))
11970 ;; select this headline
11972 (cond
11973 ((eq action 'sparse-tree)
11974 (and org-highlight-sparse-tree-matches
11975 (org-get-heading) (match-end 0)
11976 (org-highlight-new-match
11977 (match-beginning 0) (match-beginning 1)))
11978 (org-show-context 'tags-tree))
11979 ((eq action 'agenda)
11980 (setq txt (org-format-agenda-item
11982 (concat
11983 (if (eq org-tags-match-list-sublevels 'indented)
11984 (make-string (1- level) ?.) "")
11985 (org-get-heading))
11986 category
11987 tags-list
11989 priority (org-get-priority txt))
11990 (goto-char lspos)
11991 (setq marker (org-agenda-new-marker))
11992 (org-add-props txt props
11993 'org-marker marker 'org-hd-marker marker 'org-category category
11994 'todo-state todo
11995 'priority priority 'type "tagsmatch")
11996 (push txt rtn))
11997 ((functionp action)
11998 (setq org-map-continue-from nil)
11999 (save-excursion
12000 (setq rtn1 (funcall action))
12001 (push rtn1 rtn)))
12002 (t (error "Invalid action")))
12004 ;; if we are to skip sublevels, jump to end of subtree
12005 (unless org-tags-match-list-sublevels
12006 (org-end-of-subtree t)
12007 (backward-char 1))))
12008 ;; Get the correct position from where to continue
12009 (if org-map-continue-from
12010 (goto-char org-map-continue-from)
12011 (and (= (point) lspos) (end-of-line 1)))))
12012 (when (and (eq action 'sparse-tree)
12013 (not org-sparse-tree-open-archived-trees))
12014 (org-hide-archived-subtrees (point-min) (point-max)))
12015 (nreverse rtn)))
12017 (defun org-remove-uniherited-tags (tags)
12018 "Remove all tags that are not inherited from the list TAGS."
12019 (cond
12020 ((eq org-use-tag-inheritance t)
12021 (if org-tags-exclude-from-inheritance
12022 (org-delete-all org-tags-exclude-from-inheritance tags)
12023 tags))
12024 ((not org-use-tag-inheritance) nil)
12025 ((stringp org-use-tag-inheritance)
12026 (delq nil (mapcar
12027 (lambda (x)
12028 (if (and (string-match org-use-tag-inheritance x)
12029 (not (member x org-tags-exclude-from-inheritance)))
12030 x nil))
12031 tags)))
12032 ((listp org-use-tag-inheritance)
12033 (delq nil (mapcar
12034 (lambda (x)
12035 (if (member x org-use-tag-inheritance) x nil))
12036 tags)))))
12038 (defvar todo-only) ;; dynamically scoped
12040 (defun org-match-sparse-tree (&optional todo-only match)
12041 "Create a sparse tree according to tags string MATCH.
12042 MATCH can contain positive and negative selection of tags, like
12043 \"+WORK+URGENT-WITHBOSS\".
12044 If optional argument TODO-ONLY is non-nil, only select lines that are
12045 also TODO lines."
12046 (interactive "P")
12047 (org-prepare-agenda-buffers (list (current-buffer)))
12048 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12050 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12052 (defvar org-cached-props nil)
12053 (defun org-cached-entry-get (pom property)
12054 (if (or (eq t org-use-property-inheritance)
12055 (and (stringp org-use-property-inheritance)
12056 (string-match org-use-property-inheritance property))
12057 (and (listp org-use-property-inheritance)
12058 (member property org-use-property-inheritance)))
12059 ;; Caching is not possible, check it directly
12060 (org-entry-get pom property 'inherit)
12061 ;; Get all properties, so that we can do complicated checks easily
12062 (cdr (assoc property (or org-cached-props
12063 (setq org-cached-props
12064 (org-entry-properties pom)))))))
12066 (defun org-global-tags-completion-table (&optional files)
12067 "Return the list of all tags in all agenda buffer/files."
12068 (save-excursion
12069 (org-uniquify
12070 (delq nil
12071 (apply 'append
12072 (mapcar
12073 (lambda (file)
12074 (set-buffer (find-file-noselect file))
12075 (append (org-get-buffer-tags)
12076 (mapcar (lambda (x) (if (stringp (car-safe x))
12077 (list (car-safe x)) nil))
12078 org-tag-alist)))
12079 (if (and files (car files))
12080 files
12081 (org-agenda-files))))))))
12083 (defun org-make-tags-matcher (match)
12084 "Create the TAGS//TODO matcher form for the selection string MATCH."
12085 ;; todo-only is scoped dynamically into this function, and the function
12086 ;; may change it if the matcher asks for it.
12087 (unless match
12088 ;; Get a new match request, with completion
12089 (let ((org-last-tags-completion-table
12090 (org-global-tags-completion-table)))
12091 (setq match (org-completing-read-no-i
12092 "Match: " 'org-tags-completion-function nil nil nil
12093 'org-tags-history))))
12095 ;; Parse the string and create a lisp form
12096 (let ((match0 match)
12097 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12098 minus tag mm
12099 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12100 orterms term orlist re-p str-p level-p level-op time-p
12101 prop-p pn pv po cat-p gv rest)
12102 (if (string-match "/+" match)
12103 ;; match contains also a todo-matching request
12104 (progn
12105 (setq tagsmatch (substring match 0 (match-beginning 0))
12106 todomatch (substring match (match-end 0)))
12107 (if (string-match "^!" todomatch)
12108 (setq todo-only t todomatch (substring todomatch 1)))
12109 (if (string-match "^\\s-*$" todomatch)
12110 (setq todomatch nil)))
12111 ;; only matching tags
12112 (setq tagsmatch match todomatch nil))
12114 ;; Make the tags matcher
12115 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12116 (setq tagsmatcher t)
12117 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12118 (while (setq term (pop orterms))
12119 (while (and (equal (substring term -1) "\\") orterms)
12120 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12121 (while (string-match re term)
12122 (setq rest (substring term (match-end 0))
12123 minus (and (match-end 1)
12124 (equal (match-string 1 term) "-"))
12125 tag (match-string 2 term)
12126 re-p (equal (string-to-char tag) ?{)
12127 level-p (match-end 4)
12128 prop-p (match-end 5)
12129 mm (cond
12130 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12131 (level-p
12132 (setq level-op (org-op-to-function (match-string 3 term)))
12133 `(,level-op level ,(string-to-number
12134 (match-string 4 term))))
12135 (prop-p
12136 (setq pn (match-string 5 term)
12137 po (match-string 6 term)
12138 pv (match-string 7 term)
12139 cat-p (equal pn "CATEGORY")
12140 re-p (equal (string-to-char pv) ?{)
12141 str-p (equal (string-to-char pv) ?\")
12142 time-p (save-match-data
12143 (string-match "^\"[[<].*[]>]\"$" pv))
12144 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12145 (if time-p (setq pv (org-matcher-time pv)))
12146 (setq po (org-op-to-function po (if time-p 'time str-p)))
12147 (cond
12148 ((equal pn "CATEGORY")
12149 (setq gv '(get-text-property (point) 'org-category)))
12150 ((equal pn "TODO")
12151 (setq gv 'todo))
12153 (setq gv `(org-cached-entry-get nil ,pn))))
12154 (if re-p
12155 (if (eq po 'org<>)
12156 `(not (string-match ,pv (or ,gv "")))
12157 `(string-match ,pv (or ,gv "")))
12158 (if str-p
12159 `(,po (or ,gv "") ,pv)
12160 `(,po (string-to-number (or ,gv ""))
12161 ,(string-to-number pv) ))))
12162 (t `(member ,tag tags-list)))
12163 mm (if minus (list 'not mm) mm)
12164 term rest)
12165 (push mm tagsmatcher))
12166 (push (if (> (length tagsmatcher) 1)
12167 (cons 'and tagsmatcher)
12168 (car tagsmatcher))
12169 orlist)
12170 (setq tagsmatcher nil))
12171 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12172 (setq tagsmatcher
12173 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12174 ;; Make the todo matcher
12175 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12176 (setq todomatcher t)
12177 (setq orterms (org-split-string todomatch "|") orlist nil)
12178 (while (setq term (pop orterms))
12179 (while (string-match re term)
12180 (setq minus (and (match-end 1)
12181 (equal (match-string 1 term) "-"))
12182 kwd (match-string 2 term)
12183 re-p (equal (string-to-char kwd) ?{)
12184 term (substring term (match-end 0))
12185 mm (if re-p
12186 `(string-match ,(substring kwd 1 -1) todo)
12187 (list 'equal 'todo kwd))
12188 mm (if minus (list 'not mm) mm))
12189 (push mm todomatcher))
12190 (push (if (> (length todomatcher) 1)
12191 (cons 'and todomatcher)
12192 (car todomatcher))
12193 orlist)
12194 (setq todomatcher nil))
12195 (setq todomatcher (if (> (length orlist) 1)
12196 (cons 'or orlist) (car orlist))))
12198 ;; Return the string and lisp forms of the matcher
12199 (setq matcher (if todomatcher
12200 (list 'and tagsmatcher todomatcher)
12201 tagsmatcher))
12202 (cons match0 matcher)))
12204 (defun org-op-to-function (op &optional stringp)
12205 "Turn an operator into the appropriate function."
12206 (setq op
12207 (cond
12208 ((equal op "<" ) '(< string< org-time<))
12209 ((equal op ">" ) '(> org-string> org-time>))
12210 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12211 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12212 ((member op '("=" "==")) '(= string= org-time=))
12213 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12214 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12216 (defun org<> (a b) (not (= a b)))
12217 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12218 (defun org-string>= (a b) (not (string< a b)))
12219 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12220 (defun org-string<> (a b) (not (string= a b)))
12221 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12222 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12223 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12224 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12225 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12226 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12227 (defun org-2ft (s)
12228 "Convert S to a floating point time.
12229 If S is already a number, just return it. If it is a string, parse
12230 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12231 (cond
12232 ((numberp s) s)
12233 ((stringp s)
12234 (condition-case nil
12235 (float-time (apply 'encode-time (org-parse-time-string s)))
12236 (error 0.)))
12237 (t 0.)))
12239 (defun org-time-today ()
12240 "Time in seconds today at 0:00.
12241 Returns the float number of seconds since the beginning of the
12242 epoch to the beginning of today (00:00)."
12243 (float-time (apply 'encode-time
12244 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12246 (defun org-matcher-time (s)
12247 "Interpret a time comparison value."
12248 (save-match-data
12249 (cond
12250 ((string= s "<now>") (float-time))
12251 ((string= s "<today>") (org-time-today))
12252 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12253 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12254 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12255 (+ (org-time-today)
12256 (* (string-to-number (match-string 1 s))
12257 (cdr (assoc (match-string 2 s)
12258 '(("d" . 86400.0) ("w" . 604800.0)
12259 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12260 (t (org-2ft s)))))
12262 (defun org-match-any-p (re list)
12263 "Does re match any element of list?"
12264 (setq list (mapcar (lambda (x) (string-match re x)) list))
12265 (delq nil list))
12267 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12268 (defvar org-tags-overlay (make-overlay 1 1))
12269 (org-detach-overlay org-tags-overlay)
12271 (defun org-get-local-tags-at (&optional pos)
12272 "Get a list of tags defined in the current headline."
12273 (org-get-tags-at pos 'local))
12275 (defun org-get-local-tags ()
12276 "Get a list of tags defined in the current headline."
12277 (org-get-tags-at nil 'local))
12279 (defun org-get-tags-at (&optional pos local)
12280 "Get a list of all headline tags applicable at POS.
12281 POS defaults to point. If tags are inherited, the list contains
12282 the targets in the same sequence as the headlines appear, i.e.
12283 the tags of the current headline come last.
12284 When LOCAL is non-nil, only return tags from the current headline,
12285 ignore inherited ones."
12286 (interactive)
12287 (if (and org-trust-scanner-tags
12288 (or (not pos) (equal pos (point)))
12289 (not local))
12290 org-scanner-tags
12291 (let (tags ltags lastpos parent)
12292 (save-excursion
12293 (save-restriction
12294 (widen)
12295 (goto-char (or pos (point)))
12296 (save-match-data
12297 (catch 'done
12298 (condition-case nil
12299 (progn
12300 (org-back-to-heading t)
12301 (while (not (equal lastpos (point)))
12302 (setq lastpos (point))
12303 (when (looking-at
12304 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12305 (setq ltags (org-split-string
12306 (org-match-string-no-properties 1) ":"))
12307 (when parent
12308 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12309 (setq tags (append
12310 (if parent
12311 (org-remove-uniherited-tags ltags)
12312 ltags)
12313 tags)))
12314 (or org-use-tag-inheritance (throw 'done t))
12315 (if local (throw 'done t))
12316 (or (org-up-heading-safe) (error nil))
12317 (setq parent t)))
12318 (error nil)))))
12319 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12321 (defun org-add-prop-inherited (s)
12322 (add-text-properties 0 (length s) '(inherited t) s)
12325 (defun org-toggle-tag (tag &optional onoff)
12326 "Toggle the tag TAG for the current line.
12327 If ONOFF is `on' or `off', don't toggle but set to this state."
12328 (let (res current)
12329 (save-excursion
12330 (org-back-to-heading t)
12331 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12332 (point-at-eol) t)
12333 (progn
12334 (setq current (match-string 1))
12335 (replace-match ""))
12336 (setq current ""))
12337 (setq current (nreverse (org-split-string current ":")))
12338 (cond
12339 ((eq onoff 'on)
12340 (setq res t)
12341 (or (member tag current) (push tag current)))
12342 ((eq onoff 'off)
12343 (or (not (member tag current)) (setq current (delete tag current))))
12344 (t (if (member tag current)
12345 (setq current (delete tag current))
12346 (setq res t)
12347 (push tag current))))
12348 (end-of-line 1)
12349 (if current
12350 (progn
12351 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12352 (org-set-tags nil t))
12353 (delete-horizontal-space))
12354 (run-hooks 'org-after-tags-change-hook))
12355 res))
12357 (defun org-align-tags-here (to-col)
12358 ;; Assumes that this is a headline
12359 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12360 (beginning-of-line 1)
12361 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12362 (< pos (match-beginning 2)))
12363 (progn
12364 (setq tags-l (- (match-end 2) (match-beginning 2)))
12365 (goto-char (match-beginning 1))
12366 (insert " ")
12367 (delete-region (point) (1+ (match-beginning 2)))
12368 (setq ncol (max (1+ (current-column))
12369 (1+ col)
12370 (if (> to-col 0)
12371 to-col
12372 (- (abs to-col) tags-l))))
12373 (setq p (point))
12374 (insert (make-string (- ncol (current-column)) ?\ ))
12375 (setq ncol (current-column))
12376 (when indent-tabs-mode (tabify p (point-at-eol)))
12377 (org-move-to-column (min ncol col) t))
12378 (goto-char pos))))
12380 (defun org-set-tags-command (&optional arg just-align)
12381 "Call the set-tags command for the current entry."
12382 (interactive "P")
12383 (if (org-on-heading-p)
12384 (org-set-tags arg just-align)
12385 (save-excursion
12386 (org-back-to-heading t)
12387 (org-set-tags arg just-align))))
12389 (defun org-set-tags-to (data)
12390 "Set the tags of the current entry to DATA, replacing the current tags.
12391 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12392 If DATA is nil or the empty string, any tags will be removed."
12393 (interactive "sTags: ")
12394 (setq data
12395 (cond
12396 ((eq data nil) "")
12397 ((equal data "") "")
12398 ((stringp data)
12399 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12400 ":"))
12401 ((listp data)
12402 (concat ":" (mapconcat 'identity data ":") ":"))
12403 (t nil)))
12404 (when data
12405 (save-excursion
12406 (org-back-to-heading t)
12407 (when (looking-at org-complex-heading-regexp)
12408 (if (match-end 5)
12409 (progn
12410 (goto-char (match-beginning 5))
12411 (insert data)
12412 (delete-region (point) (point-at-eol))
12413 (org-set-tags nil 'align))
12414 (goto-char (point-at-eol))
12415 (insert " " data)
12416 (org-set-tags nil 'align)))
12417 (beginning-of-line 1)
12418 (if (looking-at ".*?\\([ \t]+\\)$")
12419 (delete-region (match-beginning 1) (match-end 1))))))
12421 (defun org-align-all-tags ()
12422 "Align the tags i all headings."
12423 (interactive)
12424 (save-excursion
12425 (or (ignore-errors (org-back-to-heading t))
12426 (outline-next-heading))
12427 (if (org-on-heading-p)
12428 (org-set-tags t)
12429 (message "No headings"))))
12431 (defun org-set-tags (&optional arg just-align)
12432 "Set the tags for the current headline.
12433 With prefix ARG, realign all tags in headings in the current buffer."
12434 (interactive "P")
12435 (let* ((re (concat "^" outline-regexp))
12436 (current (org-get-tags-string))
12437 (col (current-column))
12438 (org-setting-tags t)
12439 table current-tags inherited-tags ; computed below when needed
12440 tags p0 c0 c1 rpl)
12441 (if arg
12442 (save-excursion
12443 (goto-char (point-min))
12444 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12445 (while (re-search-forward re nil t)
12446 (org-set-tags nil t)
12447 (end-of-line 1)))
12448 (message "All tags realigned to column %d" org-tags-column))
12449 (if just-align
12450 (setq tags current)
12451 ;; Get a new set of tags from the user
12452 (save-excursion
12453 (setq table (append org-tag-persistent-alist
12454 (or org-tag-alist (org-get-buffer-tags))
12455 (and org-complete-tags-always-offer-all-agenda-tags
12456 (org-global-tags-completion-table (org-agenda-files))))
12457 org-last-tags-completion-table table
12458 current-tags (org-split-string current ":")
12459 inherited-tags (nreverse
12460 (nthcdr (length current-tags)
12461 (nreverse (org-get-tags-at))))
12462 tags
12463 (if (or (eq t org-use-fast-tag-selection)
12464 (and org-use-fast-tag-selection
12465 (delq nil (mapcar 'cdr table))))
12466 (org-fast-tag-selection
12467 current-tags inherited-tags table
12468 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12469 (let ((org-add-colon-after-tag-completion t))
12470 (org-trim
12471 (org-without-partial-completion
12472 (org-icompleting-read "Tags: " 'org-tags-completion-function
12473 nil nil current 'org-tags-history)))))))
12474 (while (string-match "[-+&]+" tags)
12475 ;; No boolean logic, just a list
12476 (setq tags (replace-match ":" t t tags))))
12478 (if org-tags-sort-function
12479 (setq tags (mapconcat 'identity
12480 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12481 org-tags-sort-function) ":")))
12483 (if (string-match "\\`[\t ]*\\'" tags)
12484 (setq tags "")
12485 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12486 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12488 ;; Insert new tags at the correct column
12489 (beginning-of-line 1)
12490 (cond
12491 ((and (equal current "") (equal tags "")))
12492 ((re-search-forward
12493 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12494 (point-at-eol) t)
12495 (if (equal tags "")
12496 (setq rpl "")
12497 (goto-char (match-beginning 0))
12498 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12499 (1+ (point)) (point))
12500 c1 (max (1+ c0) (if (> org-tags-column 0)
12501 org-tags-column
12502 (- (- org-tags-column) (length tags))))
12503 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12504 (replace-match rpl t t)
12505 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12506 tags)
12507 (t (error "Tags alignment failed")))
12508 (org-move-to-column col)
12509 (unless just-align
12510 (run-hooks 'org-after-tags-change-hook)))))
12512 (defun org-change-tag-in-region (beg end tag off)
12513 "Add or remove TAG for each entry in the region.
12514 This works in the agenda, and also in an org-mode buffer."
12515 (interactive
12516 (list (region-beginning) (region-end)
12517 (let ((org-last-tags-completion-table
12518 (if (org-mode-p)
12519 (org-get-buffer-tags)
12520 (org-global-tags-completion-table))))
12521 (org-icompleting-read
12522 "Tag: " 'org-tags-completion-function nil nil nil
12523 'org-tags-history))
12524 (progn
12525 (message "[s]et or [r]emove? ")
12526 (equal (read-char-exclusive) ?r))))
12527 (if (fboundp 'deactivate-mark) (deactivate-mark))
12528 (let ((agendap (equal major-mode 'org-agenda-mode))
12529 l1 l2 m buf pos newhead (cnt 0))
12530 (goto-char end)
12531 (setq l2 (1- (org-current-line)))
12532 (goto-char beg)
12533 (setq l1 (org-current-line))
12534 (loop for l from l1 to l2 do
12535 (org-goto-line l)
12536 (setq m (get-text-property (point) 'org-hd-marker))
12537 (when (or (and (org-mode-p) (org-on-heading-p))
12538 (and agendap m))
12539 (setq buf (if agendap (marker-buffer m) (current-buffer))
12540 pos (if agendap m (point)))
12541 (with-current-buffer buf
12542 (save-excursion
12543 (save-restriction
12544 (goto-char pos)
12545 (setq cnt (1+ cnt))
12546 (org-toggle-tag tag (if off 'off 'on))
12547 (setq newhead (org-get-heading)))))
12548 (and agendap (org-agenda-change-all-lines newhead m))))
12549 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12551 (defun org-tags-completion-function (string predicate &optional flag)
12552 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12553 (confirm (lambda (x) (stringp (car x)))))
12554 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12555 (setq s1 (match-string 1 string)
12556 s2 (match-string 2 string))
12557 (setq s1 "" s2 string))
12558 (cond
12559 ((eq flag nil)
12560 ;; try completion
12561 (setq rtn (try-completion s2 ctable confirm))
12562 (if (stringp rtn)
12563 (setq rtn
12564 (concat s1 s2 (substring rtn (length s2))
12565 (if (and org-add-colon-after-tag-completion
12566 (assoc rtn ctable))
12567 ":" ""))))
12568 rtn)
12569 ((eq flag t)
12570 ;; all-completions
12571 (all-completions s2 ctable confirm)
12573 ((eq flag 'lambda)
12574 ;; exact match?
12575 (assoc s2 ctable)))
12578 (defun org-fast-tag-insert (kwd tags face &optional end)
12579 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12580 (insert (format "%-12s" (concat kwd ":"))
12581 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12582 (or end "")))
12584 (defun org-fast-tag-show-exit (flag)
12585 (save-excursion
12586 (org-goto-line 3)
12587 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12588 (replace-match ""))
12589 (when flag
12590 (end-of-line 1)
12591 (org-move-to-column (- (window-width) 19) t)
12592 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12594 (defun org-set-current-tags-overlay (current prefix)
12595 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12596 (if (featurep 'xemacs)
12597 (org-overlay-display org-tags-overlay (concat prefix s)
12598 'secondary-selection)
12599 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12600 (org-overlay-display org-tags-overlay (concat prefix s)))))
12602 (defvar org-last-tag-selection-key nil)
12603 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12604 "Fast tag selection with single keys.
12605 CURRENT is the current list of tags in the headline, INHERITED is the
12606 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12607 possibly with grouping information. TODO-TABLE is a similar table with
12608 TODO keywords, should these have keys assigned to them.
12609 If the keys are nil, a-z are automatically assigned.
12610 Returns the new tags string, or nil to not change the current settings."
12611 (let* ((fulltable (append table todo-table))
12612 (maxlen (apply 'max (mapcar
12613 (lambda (x)
12614 (if (stringp (car x)) (string-width (car x)) 0))
12615 fulltable)))
12616 (buf (current-buffer))
12617 (expert (eq org-fast-tag-selection-single-key 'expert))
12618 (buffer-tags nil)
12619 (fwidth (+ maxlen 3 1 3))
12620 (ncol (/ (- (window-width) 4) fwidth))
12621 (i-face 'org-done)
12622 (c-face 'org-todo)
12623 tg cnt e c char c1 c2 ntable tbl rtn
12624 ov-start ov-end ov-prefix
12625 (exit-after-next org-fast-tag-selection-single-key)
12626 (done-keywords org-done-keywords)
12627 groups ingroup)
12628 (save-excursion
12629 (beginning-of-line 1)
12630 (if (looking-at
12631 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12632 (setq ov-start (match-beginning 1)
12633 ov-end (match-end 1)
12634 ov-prefix "")
12635 (setq ov-start (1- (point-at-eol))
12636 ov-end (1+ ov-start))
12637 (skip-chars-forward "^\n\r")
12638 (setq ov-prefix
12639 (concat
12640 (buffer-substring (1- (point)) (point))
12641 (if (> (current-column) org-tags-column)
12643 (make-string (- org-tags-column (current-column)) ?\ ))))))
12644 (move-overlay org-tags-overlay ov-start ov-end)
12645 (save-window-excursion
12646 (if expert
12647 (set-buffer (get-buffer-create " *Org tags*"))
12648 (delete-other-windows)
12649 (split-window-vertically)
12650 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12651 (erase-buffer)
12652 (org-set-local 'org-done-keywords done-keywords)
12653 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12654 (org-fast-tag-insert "Current" current c-face "\n\n")
12655 (org-fast-tag-show-exit exit-after-next)
12656 (org-set-current-tags-overlay current ov-prefix)
12657 (setq tbl fulltable char ?a cnt 0)
12658 (while (setq e (pop tbl))
12659 (cond
12660 ((equal (car e) :startgroup)
12661 (push '() groups) (setq ingroup t)
12662 (when (not (= cnt 0))
12663 (setq cnt 0)
12664 (insert "\n"))
12665 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12666 ((equal (car e) :endgroup)
12667 (setq ingroup nil cnt 0)
12668 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12669 ((equal e '(:newline))
12670 (when (not (= cnt 0))
12671 (setq cnt 0)
12672 (insert "\n")
12673 (setq e (car tbl))
12674 (while (equal (car tbl) '(:newline))
12675 (insert "\n")
12676 (setq tbl (cdr tbl)))))
12678 (setq tg (copy-sequence (car e)) c2 nil)
12679 (if (cdr e)
12680 (setq c (cdr e))
12681 ;; automatically assign a character.
12682 (setq c1 (string-to-char
12683 (downcase (substring
12684 tg (if (= (string-to-char tg) ?@) 1 0)))))
12685 (if (or (rassoc c1 ntable) (rassoc c1 table))
12686 (while (or (rassoc char ntable) (rassoc char table))
12687 (setq char (1+ char)))
12688 (setq c2 c1))
12689 (setq c (or c2 char)))
12690 (if ingroup (push tg (car groups)))
12691 (setq tg (org-add-props tg nil 'face
12692 (cond
12693 ((not (assoc tg table))
12694 (org-get-todo-face tg))
12695 ((member tg current) c-face)
12696 ((member tg inherited) i-face)
12697 (t nil))))
12698 (if (and (= cnt 0) (not ingroup)) (insert " "))
12699 (insert "[" c "] " tg (make-string
12700 (- fwidth 4 (length tg)) ?\ ))
12701 (push (cons tg c) ntable)
12702 (when (= (setq cnt (1+ cnt)) ncol)
12703 (insert "\n")
12704 (if ingroup (insert " "))
12705 (setq cnt 0)))))
12706 (setq ntable (nreverse ntable))
12707 (insert "\n")
12708 (goto-char (point-min))
12709 (if (not expert) (org-fit-window-to-buffer))
12710 (setq rtn
12711 (catch 'exit
12712 (while t
12713 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12714 (if (not groups) "no " "")
12715 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12716 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12717 (setq org-last-tag-selection-key c)
12718 (cond
12719 ((= c ?\r) (throw 'exit t))
12720 ((= c ?!)
12721 (setq groups (not groups))
12722 (goto-char (point-min))
12723 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12724 ((= c ?\C-c)
12725 (if (not expert)
12726 (org-fast-tag-show-exit
12727 (setq exit-after-next (not exit-after-next)))
12728 (setq expert nil)
12729 (delete-other-windows)
12730 (split-window-vertically)
12731 (org-switch-to-buffer-other-window " *Org tags*")
12732 (org-fit-window-to-buffer)))
12733 ((or (= c ?\C-g)
12734 (and (= c ?q) (not (rassoc c ntable))))
12735 (org-detach-overlay org-tags-overlay)
12736 (setq quit-flag t))
12737 ((= c ?\ )
12738 (setq current nil)
12739 (if exit-after-next (setq exit-after-next 'now)))
12740 ((= c ?\t)
12741 (condition-case nil
12742 (setq tg (org-icompleting-read
12743 "Tag: "
12744 (or buffer-tags
12745 (with-current-buffer buf
12746 (org-get-buffer-tags)))))
12747 (quit (setq tg "")))
12748 (when (string-match "\\S-" tg)
12749 (add-to-list 'buffer-tags (list tg))
12750 (if (member tg current)
12751 (setq current (delete tg current))
12752 (push tg current)))
12753 (if exit-after-next (setq exit-after-next 'now)))
12754 ((setq e (rassoc c todo-table) tg (car e))
12755 (with-current-buffer buf
12756 (save-excursion (org-todo tg)))
12757 (if exit-after-next (setq exit-after-next 'now)))
12758 ((setq e (rassoc c ntable) tg (car e))
12759 (if (member tg current)
12760 (setq current (delete tg current))
12761 (loop for g in groups do
12762 (if (member tg g)
12763 (mapc (lambda (x)
12764 (setq current (delete x current)))
12765 g)))
12766 (push tg current))
12767 (if exit-after-next (setq exit-after-next 'now))))
12769 ;; Create a sorted list
12770 (setq current
12771 (sort current
12772 (lambda (a b)
12773 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12774 (if (eq exit-after-next 'now) (throw 'exit t))
12775 (goto-char (point-min))
12776 (beginning-of-line 2)
12777 (delete-region (point) (point-at-eol))
12778 (org-fast-tag-insert "Current" current c-face)
12779 (org-set-current-tags-overlay current ov-prefix)
12780 (while (re-search-forward
12781 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12782 (setq tg (match-string 1))
12783 (add-text-properties
12784 (match-beginning 1) (match-end 1)
12785 (list 'face
12786 (cond
12787 ((member tg current) c-face)
12788 ((member tg inherited) i-face)
12789 (t (get-text-property (match-beginning 1) 'face))))))
12790 (goto-char (point-min)))))
12791 (org-detach-overlay org-tags-overlay)
12792 (if rtn
12793 (mapconcat 'identity current ":")
12794 nil))))
12796 (defun org-get-tags-string ()
12797 "Get the TAGS string in the current headline."
12798 (unless (org-on-heading-p t)
12799 (error "Not on a heading"))
12800 (save-excursion
12801 (beginning-of-line 1)
12802 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12803 (org-match-string-no-properties 1)
12804 "")))
12806 (defun org-get-tags ()
12807 "Get the list of tags specified in the current headline."
12808 (org-split-string (org-get-tags-string) ":"))
12810 (defun org-get-buffer-tags ()
12811 "Get a table of all tags used in the buffer, for completion."
12812 (let (tags)
12813 (save-excursion
12814 (goto-char (point-min))
12815 (while (re-search-forward
12816 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12817 (when (equal (char-after (point-at-bol 0)) ?*)
12818 (mapc (lambda (x) (add-to-list 'tags x))
12819 (org-split-string (org-match-string-no-properties 1) ":")))))
12820 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12821 (mapcar 'list tags)))
12823 ;;;; The mapping API
12825 ;;;###autoload
12826 (defun org-map-entries (func &optional match scope &rest skip)
12827 "Call FUNC at each headline selected by MATCH in SCOPE.
12829 FUNC is a function or a lisp form. The function will be called without
12830 arguments, with the cursor positioned at the beginning of the headline.
12831 The return values of all calls to the function will be collected and
12832 returned as a list.
12834 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12835 does not need to preserve point. After evaluation, the cursor will be
12836 moved to the end of the line (presumably of the headline of the
12837 processed entry) and search continues from there. Under some
12838 circumstances, this may not produce the wanted results. For example,
12839 if you have removed (e.g. archived) the current (sub)tree it could
12840 mean that the next entry will be skipped entirely. In such cases, you
12841 can specify the position from where search should continue by making
12842 FUNC set the variable `org-map-continue-from' to the desired buffer
12843 position.
12845 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12846 Only headlines that are matched by this query will be considered during
12847 the iteration. When MATCH is nil or t, all headlines will be
12848 visited by the iteration.
12850 SCOPE determines the scope of this command. It can be any of:
12852 nil The current buffer, respecting the restriction if any
12853 tree The subtree started with the entry at point
12854 file The current buffer, without restriction
12855 file-with-archives
12856 The current buffer, and any archives associated with it
12857 agenda All agenda files
12858 agenda-with-archives
12859 All agenda files with any archive files associated with them
12860 \(file1 file2 ...)
12861 If this is a list, all files in the list will be scanned
12863 The remaining args are treated as settings for the skipping facilities of
12864 the scanner. The following items can be given here:
12866 archive skip trees with the archive tag.
12867 comment skip trees with the COMMENT keyword
12868 function or Emacs Lisp form:
12869 will be used as value for `org-agenda-skip-function', so whenever
12870 the function returns t, FUNC will not be called for that
12871 entry and search will continue from the point where the
12872 function leaves it.
12874 If your function needs to retrieve the tags including inherited tags
12875 at the *current* entry, you can use the value of the variable
12876 `org-scanner-tags' which will be much faster than getting the value
12877 with `org-get-tags-at'. If your function gets properties with
12878 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12879 to t around the call to `org-entry-properties' to get the same speedup.
12880 Note that if your function moves around to retrieve tags and properties at
12881 a *different* entry, you cannot use these techniques."
12882 (let* ((org-agenda-archives-mode nil) ; just to make sure
12883 (org-agenda-skip-archived-trees (memq 'archive skip))
12884 (org-agenda-skip-comment-trees (memq 'comment skip))
12885 (org-agenda-skip-function
12886 (car (org-delete-all '(comment archive) skip)))
12887 (org-tags-match-list-sublevels t)
12888 matcher file res
12889 org-todo-keywords-for-agenda
12890 org-done-keywords-for-agenda
12891 org-todo-keyword-alist-for-agenda
12892 org-drawers-for-agenda
12893 org-tag-alist-for-agenda)
12895 (cond
12896 ((eq match t) (setq matcher t))
12897 ((eq match nil) (setq matcher t))
12898 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12900 (save-excursion
12901 (save-restriction
12902 (when (eq scope 'tree)
12903 (org-back-to-heading t)
12904 (org-narrow-to-subtree)
12905 (setq scope nil))
12907 (if (not scope)
12908 (progn
12909 (org-prepare-agenda-buffers
12910 (list (buffer-file-name (current-buffer))))
12911 (setq res (org-scan-tags func matcher)))
12912 ;; Get the right scope
12913 (cond
12914 ((and scope (listp scope) (symbolp (car scope)))
12915 (setq scope (eval scope)))
12916 ((eq scope 'agenda)
12917 (setq scope (org-agenda-files t)))
12918 ((eq scope 'agenda-with-archives)
12919 (setq scope (org-agenda-files t))
12920 (setq scope (org-add-archive-files scope)))
12921 ((eq scope 'file)
12922 (setq scope (list (buffer-file-name))))
12923 ((eq scope 'file-with-archives)
12924 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12925 (org-prepare-agenda-buffers scope)
12926 (while (setq file (pop scope))
12927 (with-current-buffer (org-find-base-buffer-visiting file)
12928 (save-excursion
12929 (save-restriction
12930 (widen)
12931 (goto-char (point-min))
12932 (setq res (append res (org-scan-tags func matcher))))))))))
12933 res))
12935 ;;;; Properties
12937 ;;; Setting and retrieving properties
12939 (defconst org-special-properties
12940 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12941 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12942 "The special properties valid in Org-mode.
12944 These are properties that are not defined in the property drawer,
12945 but in some other way.")
12947 (defconst org-default-properties
12948 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12949 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12950 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12951 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12952 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
12953 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12954 "Some properties that are used by Org-mode for various purposes.
12955 Being in this list makes sure that they are offered for completion.")
12957 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12958 "Regular expression matching the first line of a property drawer.")
12960 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12961 "Regular expression matching the last line of a property drawer.")
12963 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12964 "Regular expression matching the first line of a property drawer.")
12966 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12967 "Regular expression matching the first line of a property drawer.")
12969 (defconst org-property-drawer-re
12970 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12971 org-property-end-re "\\)\n?")
12972 "Matches an entire property drawer.")
12974 (defconst org-clock-drawer-re
12975 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12976 org-property-end-re "\\)\n?")
12977 "Matches an entire clock drawer.")
12979 (defun org-property-action ()
12980 "Do an action on properties."
12981 (interactive)
12982 (let (c)
12983 (org-at-property-p)
12984 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12985 (setq c (read-char-exclusive))
12986 (cond
12987 ((equal c ?s)
12988 (call-interactively 'org-set-property))
12989 ((equal c ?d)
12990 (call-interactively 'org-delete-property))
12991 ((equal c ?D)
12992 (call-interactively 'org-delete-property-globally))
12993 ((equal c ?c)
12994 (call-interactively 'org-compute-property-at-point))
12995 (t (error "No such property action %c" c)))))
12997 (defun org-set-effort (&optional value)
12998 "Set the effort property of the current entry.
12999 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13000 allowed value."
13001 (interactive "P")
13002 (if (equal value 0) (setq value 10))
13003 (let* ((completion-ignore-case t)
13004 (prop org-effort-property)
13005 (cur (org-entry-get nil prop))
13006 (allowed (org-property-get-allowed-values nil prop 'table))
13007 (existing (mapcar 'list (org-property-values prop)))
13009 (val (cond
13010 ((stringp value) value)
13011 ((and allowed (integerp value))
13012 (or (car (nth (1- value) allowed))
13013 (car (org-last allowed))))
13014 (allowed
13015 (message "Select 1-9,0, [RET%s]: %s"
13016 (if cur (concat "=" cur) "")
13017 (mapconcat 'car allowed " "))
13018 (setq rpl (read-char-exclusive))
13019 (if (equal rpl ?\r)
13021 (setq rpl (- rpl ?0))
13022 (if (equal rpl 0) (setq rpl 10))
13023 (if (and (> rpl 0) (<= rpl (length allowed)))
13024 (car (nth (1- rpl) allowed))
13025 (org-completing-read "Effort: " allowed nil))))
13027 (let (org-completion-use-ido org-completion-use-iswitchb)
13028 (org-completing-read
13029 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13030 (concat "[" cur "]") "")
13031 ": ")
13032 existing nil nil "" nil cur))))))
13033 (unless (equal (org-entry-get nil prop) val)
13034 (org-entry-put nil prop val))
13035 (message "%s is now %s" prop val)))
13037 (defun org-at-property-p ()
13038 "Is cursor inside a property drawer?"
13039 (save-excursion
13040 (beginning-of-line 1)
13041 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13042 (let ((match (match-data)) ;; Keep match-data for use by calling
13043 (p (point)) ;; procedures.
13044 (range (unless (org-before-first-heading-p)
13045 (org-get-property-block))))
13046 (prog1 (and range (<= (car range) p) (< p (cdr range)))
13047 (set-match-data match))))))
13049 (defun org-get-property-block (&optional beg end force)
13050 "Return the (beg . end) range of the body of the property drawer.
13051 BEG and END can be beginning and end of subtree, if not given
13052 they will be found.
13053 If the drawer does not exist and FORCE is non-nil, create the drawer."
13054 (catch 'exit
13055 (save-excursion
13056 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13057 (end (or end (progn (outline-next-heading) (point)))))
13058 (goto-char beg)
13059 (if (re-search-forward org-property-start-re end t)
13060 (setq beg (1+ (match-end 0)))
13061 (if force
13062 (save-excursion
13063 (org-insert-property-drawer)
13064 (setq end (progn (outline-next-heading) (point))))
13065 (throw 'exit nil))
13066 (goto-char beg)
13067 (if (re-search-forward org-property-start-re end t)
13068 (setq beg (1+ (match-end 0)))))
13069 (if (re-search-forward org-property-end-re end t)
13070 (setq end (match-beginning 0))
13071 (or force (throw 'exit nil))
13072 (goto-char beg)
13073 (setq end beg)
13074 (org-indent-line-function)
13075 (insert ":END:\n"))
13076 (cons beg end)))))
13078 (defun org-entry-properties (&optional pom which specific)
13079 "Get all properties of the entry at point-or-marker POM.
13080 This includes the TODO keyword, the tags, time strings for deadline,
13081 scheduled, and clocking, and any additional properties defined in the
13082 entry. The return value is an alist, keys may occur multiple times
13083 if the property key was used several times.
13084 POM may also be nil, in which case the current entry is used.
13085 If WHICH is nil or `all', get all properties. If WHICH is
13086 `special' or `standard', only get that subclass. If WHICH
13087 is a string only get exactly this property. Specific can be a string, the
13088 specific property we are interested in. Specifying it can speed
13089 things up because then unnecessary parsing is avoided."
13090 (setq which (or which 'all))
13091 (org-with-point-at pom
13092 (let ((clockstr (substring org-clock-string 0 -1))
13093 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13094 (case-fold-search nil)
13095 beg end range props sum-props key value string clocksum)
13096 (save-excursion
13097 (when (condition-case nil
13098 (and (org-mode-p) (org-back-to-heading t))
13099 (error nil))
13100 (setq beg (point))
13101 (setq sum-props (get-text-property (point) 'org-summaries))
13102 (setq clocksum (get-text-property (point) :org-clock-minutes))
13103 (outline-next-heading)
13104 (setq end (point))
13105 (when (memq which '(all special))
13106 ;; Get the special properties, like TODO and tags
13107 (goto-char beg)
13108 (when (and (or (not specific) (string= specific "TODO"))
13109 (looking-at org-todo-line-regexp) (match-end 2))
13110 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13111 (when (and (or (not specific) (string= specific "PRIORITY"))
13112 (looking-at org-priority-regexp))
13113 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13114 (when (and (or (not specific) (string= specific "TAGS"))
13115 (setq value (org-get-tags-string))
13116 (string-match "\\S-" value))
13117 (push (cons "TAGS" value) props))
13118 (when (and (or (not specific) (string= specific "ALLTAGS"))
13119 (setq value (org-get-tags-at)))
13120 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13121 ":"))
13122 props))
13123 (when (or (not specific) (string= specific "BLOCKED"))
13124 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13125 (when (or (not specific)
13126 (member specific org-all-time-keywords)
13127 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
13128 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13129 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
13130 string (if (equal key clockstr)
13131 (org-no-properties
13132 (org-trim
13133 (buffer-substring
13134 (match-beginning 3) (goto-char (point-at-eol)))))
13135 (substring (org-match-string-no-properties 3) 1 -1)))
13136 (unless key
13137 (if (= (char-after (match-beginning 3)) ?\[)
13138 (setq key "TIMESTAMP_IA")
13139 (setq key "TIMESTAMP")))
13140 (when (or (equal key clockstr) (not (assoc key props)))
13141 (push (cons key string) props))))
13145 (when (memq which '(all standard))
13146 ;; Get the standard properties, like :PROP: ...
13147 (setq range (org-get-property-block beg end))
13148 (when range
13149 (goto-char (car range))
13150 (while (re-search-forward
13151 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13152 (cdr range) t)
13153 (setq key (org-match-string-no-properties 1)
13154 value (org-trim (or (org-match-string-no-properties 2) "")))
13155 (unless (member key excluded)
13156 (push (cons key (or value "")) props)))))
13157 (if clocksum
13158 (push (cons "CLOCKSUM"
13159 (org-columns-number-to-string (/ (float clocksum) 60.)
13160 'add_times))
13161 props))
13162 (unless (assoc "CATEGORY" props)
13163 (setq value (or (org-get-category)
13164 (progn (org-refresh-category-properties)
13165 (org-get-category))))
13166 (push (cons "CATEGORY" value) props))
13167 (append sum-props (nreverse props)))))))
13169 (defun org-entry-get (pom property &optional inherit)
13170 "Get value of PROPERTY for entry at point-or-marker POM.
13171 If INHERIT is non-nil and the entry does not have the property,
13172 then also check higher levels of the hierarchy.
13173 If INHERIT is the symbol `selective', use inheritance only if the setting
13174 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13175 If the property is present but empty, the return value is the empty string.
13176 If the property is not present at all, nil is returned."
13177 (org-with-point-at pom
13178 (if (and inherit (if (eq inherit 'selective)
13179 (org-property-inherit-p property)
13181 (org-entry-get-with-inheritance property)
13182 (if (member property org-special-properties)
13183 ;; We need a special property. Use `org-entry-properties' to
13184 ;; retrieve it, but specify the wanted property
13185 (cdr (assoc property (org-entry-properties nil 'special property)))
13186 (let ((range (org-get-property-block)))
13187 (if (and range
13188 (goto-char (car range))
13189 (re-search-forward
13190 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13191 (cdr range) t))
13192 ;; Found the property, return it.
13193 (if (match-end 1)
13194 (org-match-string-no-properties 1)
13195 "")))))))
13197 (defun org-property-or-variable-value (var &optional inherit)
13198 "Check if there is a property fixing the value of VAR.
13199 If yes, return this value. If not, return the current value of the variable."
13200 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13201 (if (and prop (stringp prop) (string-match "\\S-" prop))
13202 (read prop)
13203 (symbol-value var))))
13205 (defun org-entry-delete (pom property)
13206 "Delete the property PROPERTY from entry at point-or-marker POM."
13207 (org-with-point-at pom
13208 (if (member property org-special-properties)
13209 nil ; cannot delete these properties.
13210 (let ((range (org-get-property-block)))
13211 (if (and range
13212 (goto-char (car range))
13213 (re-search-forward
13214 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13215 (cdr range) t))
13216 (progn
13217 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13219 nil)))))
13221 ;; Multi-values properties are properties that contain multiple values
13222 ;; These values are assumed to be single words, separated by whitespace.
13223 (defun org-entry-add-to-multivalued-property (pom property value)
13224 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13225 (let* ((old (org-entry-get pom property))
13226 (values (and old (org-split-string old "[ \t]"))))
13227 (setq value (org-entry-protect-space value))
13228 (unless (member value values)
13229 (setq values (cons value values))
13230 (org-entry-put pom property
13231 (mapconcat 'identity values " ")))))
13233 (defun org-entry-remove-from-multivalued-property (pom property value)
13234 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13235 (let* ((old (org-entry-get pom property))
13236 (values (and old (org-split-string old "[ \t]"))))
13237 (setq value (org-entry-protect-space value))
13238 (when (member value values)
13239 (setq values (delete value values))
13240 (org-entry-put pom property
13241 (mapconcat 'identity values " ")))))
13243 (defun org-entry-member-in-multivalued-property (pom property value)
13244 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13245 (let* ((old (org-entry-get pom property))
13246 (values (and old (org-split-string old "[ \t]"))))
13247 (setq value (org-entry-protect-space value))
13248 (member value values)))
13250 (defun org-entry-get-multivalued-property (pom property)
13251 "Return a list of values in a multivalued property."
13252 (let* ((value (org-entry-get pom property))
13253 (values (and value (org-split-string value "[ \t]"))))
13254 (mapcar 'org-entry-restore-space values)))
13256 (defun org-entry-put-multivalued-property (pom property &rest values)
13257 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13258 VALUES should be a list of strings. Spaces will be protected."
13259 (org-entry-put pom property
13260 (mapconcat 'org-entry-protect-space values " "))
13261 (let* ((value (org-entry-get pom property))
13262 (values (and value (org-split-string value "[ \t]"))))
13263 (mapcar 'org-entry-restore-space values)))
13265 (defun org-entry-protect-space (s)
13266 "Protect spaces and newline in string S."
13267 (while (string-match " " s)
13268 (setq s (replace-match "%20" t t s)))
13269 (while (string-match "\n" s)
13270 (setq s (replace-match "%0A" t t s)))
13273 (defun org-entry-restore-space (s)
13274 "Restore spaces and newline in string S."
13275 (while (string-match "%20" s)
13276 (setq s (replace-match " " t t s)))
13277 (while (string-match "%0A" s)
13278 (setq s (replace-match "\n" t t s)))
13281 (defvar org-entry-property-inherited-from (make-marker)
13282 "Marker pointing to the entry from where a property was inherited.
13283 Each call to `org-entry-get-with-inheritance' will set this marker to the
13284 location of the entry where the inheritance search matched. If there was
13285 no match, the marker will point nowhere.
13286 Note that also `org-entry-get' calls this function, if the INHERIT flag
13287 is set.")
13289 (defun org-entry-get-with-inheritance (property)
13290 "Get entry property, and search higher levels if not present."
13291 (move-marker org-entry-property-inherited-from nil)
13292 (let (tmp)
13293 (save-excursion
13294 (save-restriction
13295 (widen)
13296 (catch 'ex
13297 (while t
13298 (when (setq tmp (org-entry-get nil property))
13299 (org-back-to-heading t)
13300 (move-marker org-entry-property-inherited-from (point))
13301 (throw 'ex tmp))
13302 (or (org-up-heading-safe) (throw 'ex nil)))))
13303 (or tmp
13304 (cdr (assoc property org-file-properties))
13305 (cdr (assoc property org-global-properties))
13306 (cdr (assoc property org-global-properties-fixed))))))
13308 (defvar org-property-changed-functions nil
13309 "Hook called when the value of a property has changed.
13310 Each hook function should accept two arguments, the name of the property
13311 and the new value.")
13313 (defun org-entry-put (pom property value)
13314 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13315 (org-with-point-at pom
13316 (org-back-to-heading t)
13317 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13318 range)
13319 (cond
13320 ((equal property "TODO")
13321 (when (and (stringp value) (string-match "\\S-" value)
13322 (not (member value org-todo-keywords-1)))
13323 (error "\"%s\" is not a valid TODO state" value))
13324 (if (or (not value)
13325 (not (string-match "\\S-" value)))
13326 (setq value 'none))
13327 (org-todo value)
13328 (org-set-tags nil 'align))
13329 ((equal property "PRIORITY")
13330 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13331 (string-to-char value) ?\ ))
13332 (org-set-tags nil 'align))
13333 ((equal property "SCHEDULED")
13334 (if (re-search-forward org-scheduled-time-regexp end t)
13335 (cond
13336 ((eq value 'earlier) (org-timestamp-change -1 'day))
13337 ((eq value 'later) (org-timestamp-change 1 'day))
13338 (t (call-interactively 'org-schedule)))
13339 (call-interactively 'org-schedule)))
13340 ((equal property "DEADLINE")
13341 (if (re-search-forward org-deadline-time-regexp end t)
13342 (cond
13343 ((eq value 'earlier) (org-timestamp-change -1 'day))
13344 ((eq value 'later) (org-timestamp-change 1 'day))
13345 (t (call-interactively 'org-deadline)))
13346 (call-interactively 'org-deadline)))
13347 ((member property org-special-properties)
13348 (error "The %s property can not yet be set with `org-entry-put'"
13349 property))
13350 (t ; a non-special property
13351 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13352 (setq range (org-get-property-block beg end 'force))
13353 (goto-char (car range))
13354 (if (re-search-forward
13355 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13356 (progn
13357 (delete-region (match-beginning 1) (match-end 1))
13358 (goto-char (match-beginning 1)))
13359 (goto-char (cdr range))
13360 (insert "\n")
13361 (backward-char 1)
13362 (org-indent-line-function)
13363 (insert ":" property ":"))
13364 (and value (insert " " value))
13365 (org-indent-line-function)))))
13366 (run-hook-with-args 'org-property-changed-functions property value)))
13368 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13369 "Get all property keys in the current buffer.
13370 With INCLUDE-SPECIALS, also list the special properties that reflect things
13371 like tags and TODO state.
13372 With INCLUDE-DEFAULTS, also include properties that has special meaning
13373 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13374 With INCLUDE-COLUMNS, also include property names given in COLUMN
13375 formats in the current buffer."
13376 (let (rtn range cfmt s p)
13377 (save-excursion
13378 (save-restriction
13379 (widen)
13380 (goto-char (point-min))
13381 (while (re-search-forward org-property-start-re nil t)
13382 (setq range (org-get-property-block))
13383 (goto-char (car range))
13384 (while (re-search-forward
13385 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13386 (cdr range) t)
13387 (add-to-list 'rtn (org-match-string-no-properties 1)))
13388 (outline-next-heading))))
13390 (when include-specials
13391 (setq rtn (append org-special-properties rtn)))
13393 (when include-defaults
13394 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13395 (add-to-list 'rtn org-effort-property))
13397 (when include-columns
13398 (save-excursion
13399 (save-restriction
13400 (widen)
13401 (goto-char (point-min))
13402 (while (re-search-forward
13403 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13404 nil t)
13405 (setq cfmt (match-string 2) s 0)
13406 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13407 cfmt s)
13408 (setq s (match-end 0)
13409 p (match-string 1 cfmt))
13410 (unless (or (equal p "ITEM")
13411 (member p org-special-properties))
13412 (add-to-list 'rtn (match-string 1 cfmt))))))))
13414 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13416 (defun org-property-values (key)
13417 "Return a list of all values of property KEY."
13418 (save-excursion
13419 (save-restriction
13420 (widen)
13421 (goto-char (point-min))
13422 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13423 values)
13424 (while (re-search-forward re nil t)
13425 (add-to-list 'values (org-trim (match-string 1))))
13426 (delete "" values)))))
13428 (defun org-insert-property-drawer ()
13429 "Insert a property drawer into the current entry."
13430 (interactive)
13431 (org-back-to-heading t)
13432 (looking-at outline-regexp)
13433 (let ((indent (if org-adapt-indentation
13434 (- (match-end 0)(match-beginning 0))
13436 (beg (point))
13437 (re (concat "^[ \t]*" org-keyword-time-regexp))
13438 end hiddenp)
13439 (outline-next-heading)
13440 (setq end (point))
13441 (goto-char beg)
13442 (while (re-search-forward re end t))
13443 (setq hiddenp (org-invisible-p))
13444 (end-of-line 1)
13445 (and (equal (char-after) ?\n) (forward-char 1))
13446 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13447 (if (member (match-string 1) '("CLOCK:" ":END:"))
13448 ;; just skip this line
13449 (beginning-of-line 2)
13450 ;; Drawer start, find the end
13451 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13452 (beginning-of-line 1)))
13453 (org-skip-over-state-notes)
13454 (skip-chars-backward " \t\n\r")
13455 (if (eq (char-before) ?*) (forward-char 1))
13456 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13457 (beginning-of-line 0)
13458 (org-indent-to-column indent)
13459 (beginning-of-line 2)
13460 (org-indent-to-column indent)
13461 (beginning-of-line 0)
13462 (if hiddenp
13463 (save-excursion
13464 (org-back-to-heading t)
13465 (hide-entry))
13466 (org-flag-drawer t))))
13468 (defun org-set-property (property value)
13469 "In the current entry, set PROPERTY to VALUE.
13470 When called interactively, this will prompt for a property name, offering
13471 completion on existing and default properties. And then it will prompt
13472 for a value, offering completion either on allowed values (via an inherited
13473 xxx_ALL property) or on existing values in other instances of this property
13474 in the current file."
13475 (interactive
13476 (let* ((completion-ignore-case t)
13477 (keys (org-buffer-property-keys nil t t))
13478 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13479 (prop (if (member prop0 keys)
13480 prop0
13481 (or (cdr (assoc (downcase prop0)
13482 (mapcar (lambda (x) (cons (downcase x) x))
13483 keys)))
13484 prop0)))
13485 (cur (org-entry-get nil prop))
13486 (prompt (concat prop " value"
13487 (if (and cur (string-match "\\S-" cur))
13488 (concat " [" cur "]") "") ": "))
13489 (allowed (org-property-get-allowed-values nil prop 'table))
13490 (existing (mapcar 'list (org-property-values prop)))
13491 (val (if allowed
13492 (org-completing-read prompt allowed nil
13493 (not (get-text-property 0 'org-unrestricted
13494 (caar allowed))))
13495 (let (org-completion-use-ido org-completion-use-iswitchb)
13496 (org-completing-read prompt existing nil nil "" nil cur)))))
13497 (list prop (if (equal val "") cur val))))
13498 (unless (equal (org-entry-get nil property) value)
13499 (org-entry-put nil property value)))
13501 (defun org-delete-property (property)
13502 "In the current entry, delete PROPERTY."
13503 (interactive
13504 (let* ((completion-ignore-case t)
13505 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13506 (list prop)))
13507 (message "Property %s %s" property
13508 (if (org-entry-delete nil property)
13509 "deleted"
13510 "was not present in the entry")))
13512 (defun org-delete-property-globally (property)
13513 "Remove PROPERTY globally, from all entries."
13514 (interactive
13515 (let* ((completion-ignore-case t)
13516 (prop (org-icompleting-read
13517 "Globally remove property: "
13518 (mapcar 'list (org-buffer-property-keys)))))
13519 (list prop)))
13520 (save-excursion
13521 (save-restriction
13522 (widen)
13523 (goto-char (point-min))
13524 (let ((cnt 0))
13525 (while (re-search-forward
13526 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13527 nil t)
13528 (setq cnt (1+ cnt))
13529 (replace-match ""))
13530 (message "Property \"%s\" removed from %d entries" property cnt)))))
13532 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13534 (defun org-compute-property-at-point ()
13535 "Compute the property at point.
13536 This looks for an enclosing column format, extracts the operator and
13537 then applies it to the property in the column format's scope."
13538 (interactive)
13539 (unless (org-at-property-p)
13540 (error "Not at a property"))
13541 (let ((prop (org-match-string-no-properties 2)))
13542 (org-columns-get-format-and-top-level)
13543 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13544 (error "No operator defined for property %s" prop))
13545 (org-columns-compute prop)))
13547 (defvar org-property-allowed-value-functions nil
13548 "Hook for functions supplying allowed values for a specific property.
13549 The functions must take a single argument, the name of the property, and
13550 return a flat list of allowed values. If \":ETC\" is one of
13551 the values, this means that these values are intended as defaults for
13552 completion, but that other values should be allowed too.
13553 The functions must return nil if they are not responsible for this
13554 property.")
13556 (defun org-property-get-allowed-values (pom property &optional table)
13557 "Get allowed values for the property PROPERTY.
13558 When TABLE is non-nil, return an alist that can directly be used for
13559 completion."
13560 (let (vals)
13561 (cond
13562 ((equal property "TODO")
13563 (setq vals (org-with-point-at pom
13564 (append org-todo-keywords-1 '("")))))
13565 ((equal property "PRIORITY")
13566 (let ((n org-lowest-priority))
13567 (while (>= n org-highest-priority)
13568 (push (char-to-string n) vals)
13569 (setq n (1- n)))))
13570 ((member property org-special-properties))
13571 ((setq vals (run-hook-with-args-until-success
13572 'org-property-allowed-value-functions property)))
13574 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13575 (when (and vals (string-match "\\S-" vals))
13576 (setq vals (car (read-from-string (concat "(" vals ")"))))
13577 (setq vals (mapcar (lambda (x)
13578 (cond ((stringp x) x)
13579 ((numberp x) (number-to-string x))
13580 ((symbolp x) (symbol-name x))
13581 (t "???")))
13582 vals)))))
13583 (when (member ":ETC" vals)
13584 (setq vals (remove ":ETC" vals))
13585 (org-add-props (car vals) '(org-unrestricted t)))
13586 (if table (mapcar 'list vals) vals)))
13588 (defun org-property-previous-allowed-value (&optional previous)
13589 "Switch to the next allowed value for this property."
13590 (interactive)
13591 (org-property-next-allowed-value t))
13593 (defun org-property-next-allowed-value (&optional previous)
13594 "Switch to the next allowed value for this property."
13595 (interactive)
13596 (unless (org-at-property-p)
13597 (error "Not at a property"))
13598 (let* ((key (match-string 2))
13599 (value (match-string 3))
13600 (allowed (or (org-property-get-allowed-values (point) key)
13601 (and (member value '("[ ]" "[-]" "[X]"))
13602 '("[ ]" "[X]"))))
13603 nval)
13604 (unless allowed
13605 (error "Allowed values for this property have not been defined"))
13606 (if previous (setq allowed (reverse allowed)))
13607 (if (member value allowed)
13608 (setq nval (car (cdr (member value allowed)))))
13609 (setq nval (or nval (car allowed)))
13610 (if (equal nval value)
13611 (error "Only one allowed value for this property"))
13612 (org-at-property-p)
13613 (replace-match (concat " :" key ": " nval) t t)
13614 (org-indent-line-function)
13615 (beginning-of-line 1)
13616 (skip-chars-forward " \t")
13617 (run-hook-with-args 'org-property-changed-functions key nval)))
13619 (defun org-find-entry-with-id (ident)
13620 "Locate the entry that contains the ID property with exact value IDENT.
13621 IDENT can be a string, a symbol or a number, this function will search for
13622 the string representation of it.
13623 Return the position where this entry starts, or nil if there is no such entry."
13624 (interactive "sID: ")
13625 (let ((id (cond
13626 ((stringp ident) ident)
13627 ((symbol-name ident) (symbol-name ident))
13628 ((numberp ident) (number-to-string ident))
13629 (t (error "IDENT %s must be a string, symbol or number" ident))))
13630 (case-fold-search nil))
13631 (save-excursion
13632 (save-restriction
13633 (widen)
13634 (goto-char (point-min))
13635 (when (re-search-forward
13636 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13637 nil t)
13638 (org-back-to-heading t)
13639 (point))))))
13641 ;;;; Timestamps
13643 (defvar org-last-changed-timestamp nil)
13644 (defvar org-last-inserted-timestamp nil
13645 "The last time stamp inserted with `org-insert-time-stamp'.")
13646 (defvar org-time-was-given) ; dynamically scoped parameter
13647 (defvar org-end-time-was-given) ; dynamically scoped parameter
13648 (defvar org-ts-what) ; dynamically scoped parameter
13650 (defun org-time-stamp (arg &optional inactive)
13651 "Prompt for a date/time and insert a time stamp.
13652 If the user specifies a time like HH:MM, or if this command is called
13653 with a prefix argument, the time stamp will contain date and time.
13654 Otherwise, only the date will be included. All parts of a date not
13655 specified by the user will be filled in from the current date/time.
13656 So if you press just return without typing anything, the time stamp
13657 will represent the current date/time. If there is already a timestamp
13658 at the cursor, it will be modified."
13659 (interactive "P")
13660 (let* ((ts nil)
13661 (default-time
13662 ;; Default time is either today, or, when entering a range,
13663 ;; the range start.
13664 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13665 (save-excursion
13666 (re-search-backward
13667 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13668 (- (point) 20) t)))
13669 (apply 'encode-time (org-parse-time-string (match-string 1)))
13670 (current-time)))
13671 (default-input (and ts (org-get-compact-tod ts)))
13672 org-time-was-given org-end-time-was-given time)
13673 (cond
13674 ((and (org-at-timestamp-p t)
13675 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13676 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13677 (insert "--")
13678 (setq time (let ((this-command this-command))
13679 (org-read-date arg 'totime nil nil
13680 default-time default-input)))
13681 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13682 ((org-at-timestamp-p t)
13683 (setq time (let ((this-command this-command))
13684 (org-read-date arg 'totime nil nil default-time default-input)))
13685 (when (org-at-timestamp-p t) ; just to get the match data
13686 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13687 (replace-match "")
13688 (setq org-last-changed-timestamp
13689 (org-insert-time-stamp
13690 time (or org-time-was-given arg)
13691 inactive nil nil (list org-end-time-was-given))))
13692 (message "Timestamp updated"))
13694 (setq time (let ((this-command this-command))
13695 (org-read-date arg 'totime nil nil default-time default-input)))
13696 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13697 nil nil (list org-end-time-was-given))))))
13699 ;; FIXME: can we use this for something else, like computing time differences?
13700 (defun org-get-compact-tod (s)
13701 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13702 (let* ((t1 (match-string 1 s))
13703 (h1 (string-to-number (match-string 2 s)))
13704 (m1 (string-to-number (match-string 3 s)))
13705 (t2 (and (match-end 4) (match-string 5 s)))
13706 (h2 (and t2 (string-to-number (match-string 6 s))))
13707 (m2 (and t2 (string-to-number (match-string 7 s))))
13708 dh dm)
13709 (if (not t2)
13711 (setq dh (- h2 h1) dm (- m2 m1))
13712 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13713 (concat t1 "+" (number-to-string dh)
13714 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13716 (defun org-time-stamp-inactive (&optional arg)
13717 "Insert an inactive time stamp.
13718 An inactive time stamp is enclosed in square brackets instead of angle
13719 brackets. It is inactive in the sense that it does not trigger agenda entries,
13720 does not link to the calendar and cannot be changed with the S-cursor keys.
13721 So these are more for recording a certain time/date."
13722 (interactive "P")
13723 (org-time-stamp arg 'inactive))
13725 (defvar org-date-ovl (make-overlay 1 1))
13726 (overlay-put org-date-ovl 'face 'org-warning)
13727 (org-detach-overlay org-date-ovl)
13729 (defvar org-ans1) ; dynamically scoped parameter
13730 (defvar org-ans2) ; dynamically scoped parameter
13732 (defvar org-plain-time-of-day-regexp) ; defined below
13734 (defvar org-overriding-default-time nil) ; dynamically scoped
13735 (defvar org-read-date-overlay nil)
13736 (defvar org-dcst nil) ; dynamically scoped
13737 (defvar org-read-date-history nil)
13738 (defvar org-read-date-final-answer nil)
13740 (defun org-read-date (&optional with-time to-time from-string prompt
13741 default-time default-input)
13742 "Read a date, possibly a time, and make things smooth for the user.
13743 The prompt will suggest to enter an ISO date, but you can also enter anything
13744 which will at least partially be understood by `parse-time-string'.
13745 Unrecognized parts of the date will default to the current day, month, year,
13746 hour and minute. If this command is called to replace a timestamp at point,
13747 of to enter the second timestamp of a range, the default time is taken from the
13748 existing stamp. For example,
13749 3-2-5 --> 2003-02-05
13750 feb 15 --> currentyear-02-15
13751 sep 12 9 --> 2009-09-12
13752 12:45 --> today 12:45
13753 22 sept 0:34 --> currentyear-09-22 0:34
13754 12 --> currentyear-currentmonth-12
13755 Fri --> nearest Friday (today or later)
13756 etc.
13758 Furthermore you can specify a relative date by giving, as the *first* thing
13759 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13760 change in days weeks, months, years.
13761 With a single plus or minus, the date is relative to today. With a double
13762 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13763 +4d --> four days from today
13764 +4 --> same as above
13765 +2w --> two weeks from today
13766 ++5 --> five days from default date
13768 The function understands only English month and weekday abbreviations,
13769 but this can be configured with the variables `parse-time-months' and
13770 `parse-time-weekdays'.
13772 While prompting, a calendar is popped up - you can also select the
13773 date with the mouse (button 1). The calendar shows a period of three
13774 months. To scroll it to other months, use the keys `>' and `<'.
13775 If you don't like the calendar, turn it off with
13776 \(setq org-read-date-popup-calendar nil)
13778 With optional argument TO-TIME, the date will immediately be converted
13779 to an internal time.
13780 With an optional argument WITH-TIME, the prompt will suggest to also
13781 insert a time. Note that when WITH-TIME is not set, you can still
13782 enter a time, and this function will inform the calling routine about
13783 this change. The calling routine may then choose to change the format
13784 used to insert the time stamp into the buffer to include the time.
13785 With optional argument FROM-STRING, read from this string instead from
13786 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13787 the time/date that is used for everything that is not specified by the
13788 user."
13789 (require 'parse-time)
13790 (let* ((org-time-stamp-rounding-minutes
13791 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13792 (org-dcst org-display-custom-times)
13793 (ct (org-current-time))
13794 (def (or org-overriding-default-time default-time ct))
13795 (defdecode (decode-time def))
13796 (dummy (progn
13797 (when (< (nth 2 defdecode) org-extend-today-until)
13798 (setcar (nthcdr 2 defdecode) -1)
13799 (setcar (nthcdr 1 defdecode) 59)
13800 (setq def (apply 'encode-time defdecode)
13801 defdecode (decode-time def)))))
13802 (calendar-frame-setup nil)
13803 (calendar-move-hook nil)
13804 (calendar-view-diary-initially-flag nil)
13805 (calendar-view-holidays-initially-flag nil)
13806 (timestr (format-time-string
13807 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13808 (prompt (concat (if prompt (concat prompt " ") "")
13809 (format "Date+time [%s]: " timestr)))
13810 ans (org-ans0 "") org-ans1 org-ans2 final)
13812 (cond
13813 (from-string (setq ans from-string))
13814 (org-read-date-popup-calendar
13815 (save-excursion
13816 (save-window-excursion
13817 (calendar)
13818 (calendar-forward-day (- (time-to-days def)
13819 (calendar-absolute-from-gregorian
13820 (calendar-current-date))))
13821 (org-eval-in-calendar nil t)
13822 (let* ((old-map (current-local-map))
13823 (map (copy-keymap calendar-mode-map))
13824 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13825 (org-defkey map (kbd "RET") 'org-calendar-select)
13826 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
13827 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
13828 (org-defkey minibuffer-local-map [(meta shift left)]
13829 (lambda () (interactive)
13830 (org-eval-in-calendar '(calendar-backward-month 1))))
13831 (org-defkey minibuffer-local-map [(meta shift right)]
13832 (lambda () (interactive)
13833 (org-eval-in-calendar '(calendar-forward-month 1))))
13834 (org-defkey minibuffer-local-map [(meta shift up)]
13835 (lambda () (interactive)
13836 (org-eval-in-calendar '(calendar-backward-year 1))))
13837 (org-defkey minibuffer-local-map [(meta shift down)]
13838 (lambda () (interactive)
13839 (org-eval-in-calendar '(calendar-forward-year 1))))
13840 (org-defkey minibuffer-local-map [?\e (shift left)]
13841 (lambda () (interactive)
13842 (org-eval-in-calendar '(calendar-backward-month 1))))
13843 (org-defkey minibuffer-local-map [?\e (shift right)]
13844 (lambda () (interactive)
13845 (org-eval-in-calendar '(calendar-forward-month 1))))
13846 (org-defkey minibuffer-local-map [?\e (shift up)]
13847 (lambda () (interactive)
13848 (org-eval-in-calendar '(calendar-backward-year 1))))
13849 (org-defkey minibuffer-local-map [?\e (shift down)]
13850 (lambda () (interactive)
13851 (org-eval-in-calendar '(calendar-forward-year 1))))
13852 (org-defkey minibuffer-local-map [(shift up)]
13853 (lambda () (interactive)
13854 (org-eval-in-calendar '(calendar-backward-week 1))))
13855 (org-defkey minibuffer-local-map [(shift down)]
13856 (lambda () (interactive)
13857 (org-eval-in-calendar '(calendar-forward-week 1))))
13858 (org-defkey minibuffer-local-map [(shift left)]
13859 (lambda () (interactive)
13860 (org-eval-in-calendar '(calendar-backward-day 1))))
13861 (org-defkey minibuffer-local-map [(shift right)]
13862 (lambda () (interactive)
13863 (org-eval-in-calendar '(calendar-forward-day 1))))
13864 (org-defkey minibuffer-local-map ">"
13865 (lambda () (interactive)
13866 (org-eval-in-calendar '(scroll-calendar-left 1))))
13867 (org-defkey minibuffer-local-map "<"
13868 (lambda () (interactive)
13869 (org-eval-in-calendar '(scroll-calendar-right 1))))
13870 (org-defkey minibuffer-local-map "\C-v"
13871 (lambda () (interactive)
13872 (org-eval-in-calendar
13873 '(calendar-scroll-left-three-months 1))))
13874 (org-defkey minibuffer-local-map "\M-v"
13875 (lambda () (interactive)
13876 (org-eval-in-calendar
13877 '(calendar-scroll-right-three-months 1))))
13878 (run-hooks 'org-read-date-minibuffer-setup-hook)
13879 (unwind-protect
13880 (progn
13881 (use-local-map map)
13882 (add-hook 'post-command-hook 'org-read-date-display)
13883 (setq org-ans0 (read-string prompt default-input
13884 'org-read-date-history nil))
13885 ;; org-ans0: from prompt
13886 ;; org-ans1: from mouse click
13887 ;; org-ans2: from calendar motion
13888 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13889 (remove-hook 'post-command-hook 'org-read-date-display)
13890 (use-local-map old-map)
13891 (when org-read-date-overlay
13892 (delete-overlay org-read-date-overlay)
13893 (setq org-read-date-overlay nil)))))))
13895 (t ; Naked prompt only
13896 (unwind-protect
13897 (setq ans (read-string prompt default-input
13898 'org-read-date-history timestr))
13899 (when org-read-date-overlay
13900 (delete-overlay org-read-date-overlay)
13901 (setq org-read-date-overlay nil)))))
13903 (setq final (org-read-date-analyze ans def defdecode))
13904 (setq org-read-date-final-answer ans)
13906 (if to-time
13907 (apply 'encode-time final)
13908 (if (and (boundp 'org-time-was-given) org-time-was-given)
13909 (format "%04d-%02d-%02d %02d:%02d"
13910 (nth 5 final) (nth 4 final) (nth 3 final)
13911 (nth 2 final) (nth 1 final))
13912 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13914 (defvar def)
13915 (defvar defdecode)
13916 (defvar with-time)
13917 (defvar org-read-date-analyze-futurep nil)
13918 (defun org-read-date-display ()
13919 "Display the current date prompt interpretation in the minibuffer."
13920 (when org-read-date-display-live
13921 (when org-read-date-overlay
13922 (delete-overlay org-read-date-overlay))
13923 (let ((p (point)))
13924 (end-of-line 1)
13925 (while (not (equal (buffer-substring
13926 (max (point-min) (- (point) 4)) (point))
13927 " "))
13928 (insert " "))
13929 (goto-char p))
13930 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13931 " " (or org-ans1 org-ans2)))
13932 (org-end-time-was-given nil)
13933 (f (org-read-date-analyze ans def defdecode))
13934 (fmts (if org-dcst
13935 org-time-stamp-custom-formats
13936 org-time-stamp-formats))
13937 (fmt (if (or with-time
13938 (and (boundp 'org-time-was-given) org-time-was-given))
13939 (cdr fmts)
13940 (car fmts)))
13941 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13942 (when (and org-end-time-was-given
13943 (string-match org-plain-time-of-day-regexp txt))
13944 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13945 org-end-time-was-given
13946 (substring txt (match-end 0)))))
13947 (when org-read-date-analyze-futurep
13948 (setq txt (concat txt " (=>F)")))
13949 (setq org-read-date-overlay
13950 (make-overlay (1- (point-at-eol)) (point-at-eol)))
13951 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13953 (defun org-read-date-analyze (ans def defdecode)
13954 "Analyse the combined answer of the date prompt."
13955 ;; FIXME: cleanup and comment
13956 (let ((nowdecode (decode-time (current-time)))
13957 delta deltan deltaw deltadef year month day
13958 hour minute second wday pm h2 m2 tl wday1
13959 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13960 (setq org-read-date-analyze-futurep nil)
13961 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13962 (setq ans "+0"))
13964 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13965 (setq ans (replace-match "" t t ans)
13966 deltan (car delta)
13967 deltaw (nth 1 delta)
13968 deltadef (nth 2 delta)))
13970 ;; Check if there is an iso week date in there
13971 ;; If yes, store the info and postpone interpreting it until the rest
13972 ;; of the parsing is done
13973 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13974 (setq iso-year (if (match-end 1)
13975 (org-small-year-to-year
13976 (string-to-number (match-string 1 ans))))
13977 iso-weekday (if (match-end 3)
13978 (string-to-number (match-string 3 ans)))
13979 iso-week (string-to-number (match-string 2 ans)))
13980 (setq ans (replace-match "" t t ans)))
13982 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13983 (when (string-match
13984 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13985 (setq year (if (match-end 2)
13986 (string-to-number (match-string 2 ans))
13987 (progn (setq kill-year t)
13988 (string-to-number (format-time-string "%Y"))))
13989 month (string-to-number (match-string 3 ans))
13990 day (string-to-number (match-string 4 ans)))
13991 (if (< year 100) (setq year (+ 2000 year)))
13992 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13993 t nil ans)))
13994 ;; Help matching american dates, like 5/30 or 5/30/7
13995 (when (string-match
13996 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13997 (setq year (if (match-end 4)
13998 (string-to-number (match-string 4 ans))
13999 (progn (setq kill-year t)
14000 (string-to-number (format-time-string "%Y"))))
14001 month (string-to-number (match-string 1 ans))
14002 day (string-to-number (match-string 2 ans)))
14003 (if (< year 100) (setq year (+ 2000 year)))
14004 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14005 t nil ans)))
14006 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14007 ;; If there is a time with am/pm, and *no* time without it, we convert
14008 ;; so that matching will be successful.
14009 (loop for i from 1 to 2 do ; twice, for end time as well
14010 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14011 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14012 (setq hour (string-to-number (match-string 1 ans))
14013 minute (if (match-end 3)
14014 (string-to-number (match-string 3 ans))
14016 pm (equal ?p
14017 (string-to-char (downcase (match-string 4 ans)))))
14018 (if (and (= hour 12) (not pm))
14019 (setq hour 0)
14020 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14021 (setq ans (replace-match (format "%02d:%02d" hour minute)
14022 t t ans))))
14024 ;; Check if a time range is given as a duration
14025 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14026 (setq hour (string-to-number (match-string 1 ans))
14027 h2 (+ hour (string-to-number (match-string 3 ans)))
14028 minute (string-to-number (match-string 2 ans))
14029 m2 (+ minute (if (match-end 5) (string-to-number
14030 (match-string 5 ans))0)))
14031 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14032 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14033 t t ans)))
14035 ;; Check if there is a time range
14036 (when (boundp 'org-end-time-was-given)
14037 (setq org-time-was-given nil)
14038 (when (and (string-match org-plain-time-of-day-regexp ans)
14039 (match-end 8))
14040 (setq org-end-time-was-given (match-string 8 ans))
14041 (setq ans (concat (substring ans 0 (match-beginning 7))
14042 (substring ans (match-end 7))))))
14044 (setq tl (parse-time-string ans)
14045 day (or (nth 3 tl) (nth 3 defdecode))
14046 month (or (nth 4 tl)
14047 (if (and org-read-date-prefer-future
14048 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14049 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14050 (nth 4 defdecode)))
14051 year (or (and (not kill-year) (nth 5 tl))
14052 (if (and org-read-date-prefer-future
14053 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14054 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14055 (nth 5 defdecode)))
14056 hour (or (nth 2 tl) (nth 2 defdecode))
14057 minute (or (nth 1 tl) (nth 1 defdecode))
14058 second (or (nth 0 tl) 0)
14059 wday (nth 6 tl))
14061 (when (and (eq org-read-date-prefer-future 'time)
14062 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14063 (equal day (nth 3 nowdecode))
14064 (equal month (nth 4 nowdecode))
14065 (equal year (nth 5 nowdecode))
14066 (nth 2 tl)
14067 (or (< (nth 2 tl) (nth 2 nowdecode))
14068 (and (= (nth 2 tl) (nth 2 nowdecode))
14069 (nth 1 tl)
14070 (< (nth 1 tl) (nth 1 nowdecode)))))
14071 (setq day (1+ day)
14072 futurep t))
14074 ;; Special date definitions below
14075 (cond
14076 (iso-week
14077 ;; There was an iso week
14078 (require 'cal-iso)
14079 (setq futurep nil)
14080 (setq year (or iso-year year)
14081 day (or iso-weekday wday 1)
14082 wday nil ; to make sure that the trigger below does not match
14083 iso-date (calendar-gregorian-from-absolute
14084 (calendar-absolute-from-iso
14085 (list iso-week day year))))
14086 ; FIXME: Should we also push ISO weeks into the future?
14087 ; (when (and org-read-date-prefer-future
14088 ; (not iso-year)
14089 ; (< (calendar-absolute-from-gregorian iso-date)
14090 ; (time-to-days (current-time))))
14091 ; (setq year (1+ year)
14092 ; iso-date (calendar-gregorian-from-absolute
14093 ; (calendar-absolute-from-iso
14094 ; (list iso-week day year)))))
14095 (setq month (car iso-date)
14096 year (nth 2 iso-date)
14097 day (nth 1 iso-date)))
14098 (deltan
14099 (setq futurep nil)
14100 (unless deltadef
14101 (let ((now (decode-time (current-time))))
14102 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14103 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14104 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14105 ((equal deltaw "m") (setq month (+ month deltan)))
14106 ((equal deltaw "y") (setq year (+ year deltan)))))
14107 ((and wday (not (nth 3 tl)))
14108 (setq futurep nil)
14109 ;; Weekday was given, but no day, so pick that day in the week
14110 ;; on or after the derived date.
14111 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14112 (unless (equal wday wday1)
14113 (setq day (+ day (% (- wday wday1 -7) 7))))))
14114 (if (and (boundp 'org-time-was-given)
14115 (nth 2 tl))
14116 (setq org-time-was-given t))
14117 (if (< year 100) (setq year (+ 2000 year)))
14118 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14119 (setq org-read-date-analyze-futurep futurep)
14120 (list second minute hour day month year)))
14122 (defvar parse-time-weekdays)
14124 (defun org-read-date-get-relative (s today default)
14125 "Check string S for special relative date string.
14126 TODAY and DEFAULT are internal times, for today and for a default.
14127 Return shift list (N what def-flag)
14128 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14129 N is the number of WHATs to shift.
14130 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14131 the DEFAULT date rather than TODAY."
14132 (when (and
14133 (string-match
14134 (concat
14135 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14136 "\\([0-9]+\\)?"
14137 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14138 "\\([ \t]\\|$\\)") s)
14139 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14140 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14141 (string-to-char (substring (match-string 1 s) -1))
14142 ?+))
14143 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14144 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14145 (what (if (match-end 3) (match-string 3 s) "d"))
14146 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14147 (date (if rel default today))
14148 (wday (nth 6 (decode-time date)))
14149 delta)
14150 (if wday1
14151 (progn
14152 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14153 (if (= dir ?-) (setq delta (- delta 7)))
14154 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14155 (list delta "d" rel))
14156 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14158 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14159 "Turn a user-specified date into the internal representation.
14160 The internal representation needed by the calendar is (month day year).
14161 This is a wrapper to handle the brain-dead convention in calendar that
14162 user function argument order change dependent on argument order."
14163 (if (boundp 'calendar-date-style)
14164 (cond
14165 ((eq calendar-date-style 'american)
14166 (list arg1 arg2 arg3))
14167 ((eq calendar-date-style 'european)
14168 (list arg2 arg1 arg3))
14169 ((eq calendar-date-style 'iso)
14170 (list arg2 arg3 arg1)))
14171 (if (org-bound-and-true-p european-calendar-style)
14172 (list arg2 arg1 arg3)
14173 (list arg1 arg2 arg3))))
14175 (defun org-eval-in-calendar (form &optional keepdate)
14176 "Eval FORM in the calendar window and return to current window.
14177 Also, store the cursor date in variable org-ans2."
14178 (let ((sf (selected-frame))
14179 (sw (selected-window)))
14180 (select-window (get-buffer-window "*Calendar*" t))
14181 (eval form)
14182 (when (and (not keepdate) (calendar-cursor-to-date))
14183 (let* ((date (calendar-cursor-to-date))
14184 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14185 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14186 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14187 (select-window sw)
14188 (org-select-frame-set-input-focus sf)))
14190 (defun org-calendar-select ()
14191 "Return to `org-read-date' with the date currently selected.
14192 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14193 (interactive)
14194 (when (calendar-cursor-to-date)
14195 (let* ((date (calendar-cursor-to-date))
14196 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14197 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14198 (if (active-minibuffer-window) (exit-minibuffer))))
14200 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14201 "Insert a date stamp for the date given by the internal TIME.
14202 WITH-HM means use the stamp format that includes the time of the day.
14203 INACTIVE means use square brackets instead of angular ones, so that the
14204 stamp will not contribute to the agenda.
14205 PRE and POST are optional strings to be inserted before and after the
14206 stamp.
14207 The command returns the inserted time stamp."
14208 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14209 stamp)
14210 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14211 (insert-before-markers (or pre ""))
14212 (insert-before-markers (setq stamp (format-time-string fmt time)))
14213 (when (listp extra)
14214 (setq extra (car extra))
14215 (if (and (stringp extra)
14216 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14217 (setq extra (format "-%02d:%02d"
14218 (string-to-number (match-string 1 extra))
14219 (string-to-number (match-string 2 extra))))
14220 (setq extra nil)))
14221 (when extra
14222 (backward-char 1)
14223 (insert-before-markers extra)
14224 (forward-char 1))
14225 (insert-before-markers (or post ""))
14226 (setq org-last-inserted-timestamp stamp)))
14228 (defun org-toggle-time-stamp-overlays ()
14229 "Toggle the use of custom time stamp formats."
14230 (interactive)
14231 (setq org-display-custom-times (not org-display-custom-times))
14232 (unless org-display-custom-times
14233 (let ((p (point-min)) (bmp (buffer-modified-p)))
14234 (while (setq p (next-single-property-change p 'display))
14235 (if (and (get-text-property p 'display)
14236 (eq (get-text-property p 'face) 'org-date))
14237 (remove-text-properties
14238 p (setq p (next-single-property-change p 'display))
14239 '(display t))))
14240 (set-buffer-modified-p bmp)))
14241 (if (featurep 'xemacs)
14242 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14243 (org-restart-font-lock)
14244 (setq org-table-may-need-update t)
14245 (if org-display-custom-times
14246 (message "Time stamps are overlayed with custom format")
14247 (message "Time stamp overlays removed")))
14249 (defun org-display-custom-time (beg end)
14250 "Overlay modified time stamp format over timestamp between BEG and END."
14251 (let* ((ts (buffer-substring beg end))
14252 t1 w1 with-hm tf time str w2 (off 0))
14253 (save-match-data
14254 (setq t1 (org-parse-time-string ts t))
14255 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14256 (setq off (- (match-end 0) (match-beginning 0)))))
14257 (setq end (- end off))
14258 (setq w1 (- end beg)
14259 with-hm (and (nth 1 t1) (nth 2 t1))
14260 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14261 time (org-fix-decoded-time t1)
14262 str (org-add-props
14263 (format-time-string
14264 (substring tf 1 -1) (apply 'encode-time time))
14265 nil 'mouse-face 'highlight)
14266 w2 (length str))
14267 (if (not (= w2 w1))
14268 (add-text-properties (1+ beg) (+ 2 beg)
14269 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14270 (if (featurep 'xemacs)
14271 (progn
14272 (put-text-property beg end 'invisible t)
14273 (put-text-property beg end 'end-glyph (make-glyph str)))
14274 (put-text-property beg end 'display str))))
14276 (defun org-translate-time (string)
14277 "Translate all timestamps in STRING to custom format.
14278 But do this only if the variable `org-display-custom-times' is set."
14279 (when org-display-custom-times
14280 (save-match-data
14281 (let* ((start 0)
14282 (re org-ts-regexp-both)
14283 t1 with-hm inactive tf time str beg end)
14284 (while (setq start (string-match re string start))
14285 (setq beg (match-beginning 0)
14286 end (match-end 0)
14287 t1 (save-match-data
14288 (org-parse-time-string (substring string beg end) t))
14289 with-hm (and (nth 1 t1) (nth 2 t1))
14290 inactive (equal (substring string beg (1+ beg)) "[")
14291 tf (funcall (if with-hm 'cdr 'car)
14292 org-time-stamp-custom-formats)
14293 time (org-fix-decoded-time t1)
14294 str (format-time-string
14295 (concat
14296 (if inactive "[" "<") (substring tf 1 -1)
14297 (if inactive "]" ">"))
14298 (apply 'encode-time time))
14299 string (replace-match str t t string)
14300 start (+ start (length str)))))))
14301 string)
14303 (defun org-fix-decoded-time (time)
14304 "Set 0 instead of nil for the first 6 elements of time.
14305 Don't touch the rest."
14306 (let ((n 0))
14307 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14309 (defun org-days-to-time (timestamp-string)
14310 "Difference between TIMESTAMP-STRING and now in days."
14311 (- (time-to-days (org-time-string-to-time timestamp-string))
14312 (time-to-days (current-time))))
14314 (defun org-deadline-close (timestamp-string &optional ndays)
14315 "Is the time in TIMESTAMP-STRING close to the current date?"
14316 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14317 (and (< (org-days-to-time timestamp-string) ndays)
14318 (not (org-entry-is-done-p))))
14320 (defun org-get-wdays (ts)
14321 "Get the deadline lead time appropriate for timestring TS."
14322 (cond
14323 ((<= org-deadline-warning-days 0)
14324 ;; 0 or negative, enforce this value no matter what
14325 (- org-deadline-warning-days))
14326 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14327 ;; lead time is specified.
14328 (floor (* (string-to-number (match-string 1 ts))
14329 (cdr (assoc (match-string 2 ts)
14330 '(("d" . 1) ("w" . 7)
14331 ("m" . 30.4) ("y" . 365.25)))))))
14332 ;; go for the default.
14333 (t org-deadline-warning-days)))
14335 (defun org-calendar-select-mouse (ev)
14336 "Return to `org-read-date' with the date currently selected.
14337 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14338 (interactive "e")
14339 (mouse-set-point ev)
14340 (when (calendar-cursor-to-date)
14341 (let* ((date (calendar-cursor-to-date))
14342 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14343 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14344 (if (active-minibuffer-window) (exit-minibuffer))))
14346 (defun org-check-deadlines (ndays)
14347 "Check if there are any deadlines due or past due.
14348 A deadline is considered due if it happens within `org-deadline-warning-days'
14349 days from today's date. If the deadline appears in an entry marked DONE,
14350 it is not shown. The prefix arg NDAYS can be used to test that many
14351 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14352 (interactive "P")
14353 (let* ((org-warn-days
14354 (cond
14355 ((equal ndays '(4)) 100000)
14356 (ndays (prefix-numeric-value ndays))
14357 (t (abs org-deadline-warning-days))))
14358 (case-fold-search nil)
14359 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14360 (callback
14361 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14363 (message "%d deadlines past-due or due within %d days"
14364 (org-occur regexp nil callback)
14365 org-warn-days)))
14367 (defun org-check-before-date (date)
14368 "Check if there are deadlines or scheduled entries before DATE."
14369 (interactive (list (org-read-date)))
14370 (let ((case-fold-search nil)
14371 (regexp (concat "\\<\\(" org-deadline-string
14372 "\\|" org-scheduled-string
14373 "\\) *<\\([^>]+\\)>"))
14374 (callback
14375 (lambda () (time-less-p
14376 (org-time-string-to-time (match-string 2))
14377 (org-time-string-to-time date)))))
14378 (message "%d entries before %s"
14379 (org-occur regexp nil callback) date)))
14381 (defun org-check-after-date (date)
14382 "Check if there are deadlines or scheduled entries after DATE."
14383 (interactive (list (org-read-date)))
14384 (let ((case-fold-search nil)
14385 (regexp (concat "\\<\\(" org-deadline-string
14386 "\\|" org-scheduled-string
14387 "\\) *<\\([^>]+\\)>"))
14388 (callback
14389 (lambda () (not
14390 (time-less-p
14391 (org-time-string-to-time (match-string 2))
14392 (org-time-string-to-time date))))))
14393 (message "%d entries after %s"
14394 (org-occur regexp nil callback) date)))
14396 (defun org-evaluate-time-range (&optional to-buffer)
14397 "Evaluate a time range by computing the difference between start and end.
14398 Normally the result is just printed in the echo area, but with prefix arg
14399 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14400 If the time range is actually in a table, the result is inserted into the
14401 next column.
14402 For time difference computation, a year is assumed to be exactly 365
14403 days in order to avoid rounding problems."
14404 (interactive "P")
14406 (org-clock-update-time-maybe)
14407 (save-excursion
14408 (unless (org-at-date-range-p t)
14409 (goto-char (point-at-bol))
14410 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14411 (if (not (org-at-date-range-p t))
14412 (error "Not at a time-stamp range, and none found in current line")))
14413 (let* ((ts1 (match-string 1))
14414 (ts2 (match-string 2))
14415 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14416 (match-end (match-end 0))
14417 (time1 (org-time-string-to-time ts1))
14418 (time2 (org-time-string-to-time ts2))
14419 (t1 (org-float-time time1))
14420 (t2 (org-float-time time2))
14421 (diff (abs (- t2 t1)))
14422 (negative (< (- t2 t1) 0))
14423 ;; (ys (floor (* 365 24 60 60)))
14424 (ds (* 24 60 60))
14425 (hs (* 60 60))
14426 (fy "%dy %dd %02d:%02d")
14427 (fy1 "%dy %dd")
14428 (fd "%dd %02d:%02d")
14429 (fd1 "%dd")
14430 (fh "%02d:%02d")
14431 y d h m align)
14432 (if havetime
14433 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14435 d (floor (/ diff ds)) diff (mod diff ds)
14436 h (floor (/ diff hs)) diff (mod diff hs)
14437 m (floor (/ diff 60)))
14438 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14440 d (floor (+ (/ diff ds) 0.5))
14441 h 0 m 0))
14442 (if (not to-buffer)
14443 (message "%s" (org-make-tdiff-string y d h m))
14444 (if (org-at-table-p)
14445 (progn
14446 (goto-char match-end)
14447 (setq align t)
14448 (and (looking-at " *|") (goto-char (match-end 0))))
14449 (goto-char match-end))
14450 (if (looking-at
14451 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14452 (replace-match ""))
14453 (if negative (insert " -"))
14454 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14455 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14456 (insert " " (format fh h m))))
14457 (if align (org-table-align))
14458 (message "Time difference inserted")))))
14460 (defun org-make-tdiff-string (y d h m)
14461 (let ((fmt "")
14462 (l nil))
14463 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14464 l (push y l)))
14465 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14466 l (push d l)))
14467 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14468 l (push h l)))
14469 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14470 l (push m l)))
14471 (apply 'format fmt (nreverse l))))
14473 (defun org-time-string-to-time (s)
14474 (apply 'encode-time (org-parse-time-string s)))
14475 (defun org-time-string-to-seconds (s)
14476 (org-float-time (org-time-string-to-time s)))
14478 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14479 "Convert a time stamp to an absolute day number.
14480 If there is a specifyer for a cyclic time stamp, get the closest date to
14481 DAYNR.
14482 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14483 the variable date is bound by the calendar when this is called."
14484 (cond
14485 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14486 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14487 daynr
14488 (+ daynr 1000)))
14489 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14490 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14491 (time-to-days (current-time))) (match-string 0 s)
14492 prefer show-all))
14493 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14495 (defun org-days-to-iso-week (days)
14496 "Return the iso week number."
14497 (require 'cal-iso)
14498 (car (calendar-iso-from-absolute days)))
14500 (defun org-small-year-to-year (year)
14501 "Convert 2-digit years into 4-digit years.
14502 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14503 The year 2000 cannot be abbreviated. Any year larger than 99
14504 is returned unchanged."
14505 (if (< year 38)
14506 (setq year (+ 2000 year))
14507 (if (< year 100)
14508 (setq year (+ 1900 year))))
14509 year)
14511 (defun org-time-from-absolute (d)
14512 "Return the time corresponding to date D.
14513 D may be an absolute day number, or a calendar-type list (month day year)."
14514 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14515 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14517 (defun org-calendar-holiday ()
14518 "List of holidays, for Diary display in Org-mode."
14519 (require 'holidays)
14520 (let ((hl (funcall
14521 (if (fboundp 'calendar-check-holidays)
14522 'calendar-check-holidays 'check-calendar-holidays) date)))
14523 (if hl (mapconcat 'identity hl "; "))))
14525 (defun org-diary-sexp-entry (sexp entry date)
14526 "Process a SEXP diary ENTRY for DATE."
14527 (require 'diary-lib)
14528 (let ((result (if calendar-debug-sexp
14529 (let ((stack-trace-on-error t))
14530 (eval (car (read-from-string sexp))))
14531 (condition-case nil
14532 (eval (car (read-from-string sexp)))
14533 (error
14534 (beep)
14535 (message "Bad sexp at line %d in %s: %s"
14536 (org-current-line)
14537 (buffer-file-name) sexp)
14538 (sleep-for 2))))))
14539 (cond ((stringp result) result)
14540 ((and (consp result)
14541 (stringp (cdr result))) (cdr result))
14542 (result entry)
14543 (t nil))))
14545 (defun org-diary-to-ical-string (frombuf)
14546 "Get iCalendar entries from diary entries in buffer FROMBUF.
14547 This uses the icalendar.el library."
14548 (let* ((tmpdir (if (featurep 'xemacs)
14549 (temp-directory)
14550 temporary-file-directory))
14551 (tmpfile (make-temp-name
14552 (expand-file-name "orgics" tmpdir)))
14553 buf rtn b e)
14554 (with-current-buffer frombuf
14555 (icalendar-export-region (point-min) (point-max) tmpfile)
14556 (setq buf (find-buffer-visiting tmpfile))
14557 (set-buffer buf)
14558 (goto-char (point-min))
14559 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14560 (setq b (match-beginning 0)))
14561 (goto-char (point-max))
14562 (if (re-search-backward "^END:VEVENT" nil t)
14563 (setq e (match-end 0)))
14564 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14565 (kill-buffer buf)
14566 (delete-file tmpfile)
14567 rtn))
14569 (defun org-closest-date (start current change prefer show-all)
14570 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14571 When PREFER is `past' return a date that is either CURRENT or past.
14572 When PREFER is `future', return a date that is either CURRENT or future.
14573 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14574 ;; Make the proper lists from the dates
14575 (catch 'exit
14576 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14577 dn dw sday cday n1 n2 n0
14578 d m y y1 y2 date1 date2 nmonths nm ny m2)
14580 (setq start (org-date-to-gregorian start)
14581 current (org-date-to-gregorian
14582 (if show-all
14583 current
14584 (time-to-days (current-time))))
14585 sday (calendar-absolute-from-gregorian start)
14586 cday (calendar-absolute-from-gregorian current))
14588 (if (<= cday sday) (throw 'exit sday))
14590 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14591 (setq dn (string-to-number (match-string 1 change))
14592 dw (cdr (assoc (match-string 2 change) a1)))
14593 (error "Invalid change specifyer: %s" change))
14594 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14595 (cond
14596 ((eq dw 'day)
14597 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14598 n2 (+ n1 dn)))
14599 ((eq dw 'year)
14600 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14601 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14602 (setq date1 (list m d y1)
14603 n1 (calendar-absolute-from-gregorian date1)
14604 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14605 n2 (calendar-absolute-from-gregorian date2)))
14606 ((eq dw 'month)
14607 ;; approx number of month between the two dates
14608 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14609 ;; How often does dn fit in there?
14610 (setq d (nth 1 start) m (car start) y (nth 2 start)
14611 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14612 m (+ m nm)
14613 ny (floor (/ m 12))
14614 y (+ y ny)
14615 m (- m (* ny 12)))
14616 (while (> m 12) (setq m (- m 12) y (1+ y)))
14617 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14618 (setq m2 (+ m dn) y2 y)
14619 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14620 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14621 (while (<= n2 cday)
14622 (setq n1 n2 m m2 y y2)
14623 (setq m2 (+ m dn) y2 y)
14624 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14625 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14626 ;; Make sure n1 is the earlier date
14627 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14628 (if show-all
14629 (cond
14630 ((eq prefer 'past) (if (= cday n2) n2 n1))
14631 ((eq prefer 'future) (if (= cday n1) n1 n2))
14632 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14633 (cond
14634 ((eq prefer 'past) (if (= cday n2) n2 n1))
14635 ((eq prefer 'future) (if (= cday n1) n1 n2))
14636 (t (if (= cday n1) n1 n2)))))))
14638 (defun org-date-to-gregorian (date)
14639 "Turn any specification of DATE into a gregorian date for the calendar."
14640 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14641 ((and (listp date) (= (length date) 3)) date)
14642 ((stringp date)
14643 (setq date (org-parse-time-string date))
14644 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14645 ((listp date)
14646 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14648 (defun org-parse-time-string (s &optional nodefault)
14649 "Parse the standard Org-mode time string.
14650 This should be a lot faster than the normal `parse-time-string'.
14651 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14652 hour and minute fields will be nil if not given."
14653 (if (string-match org-ts-regexp0 s)
14654 (list 0
14655 (if (or (match-beginning 8) (not nodefault))
14656 (string-to-number (or (match-string 8 s) "0")))
14657 (if (or (match-beginning 7) (not nodefault))
14658 (string-to-number (or (match-string 7 s) "0")))
14659 (string-to-number (match-string 4 s))
14660 (string-to-number (match-string 3 s))
14661 (string-to-number (match-string 2 s))
14662 nil nil nil)
14663 (error "Not a standard Org-mode time string: %s" s)))
14665 (defun org-timestamp-up (&optional arg)
14666 "Increase the date item at the cursor by one.
14667 If the cursor is on the year, change the year. If it is on the month or
14668 the day, change that.
14669 With prefix ARG, change by that many units."
14670 (interactive "p")
14671 (org-timestamp-change (prefix-numeric-value arg)))
14673 (defun org-timestamp-down (&optional arg)
14674 "Decrease the date item at the cursor by one.
14675 If the cursor is on the year, change the year. If it is on the month or
14676 the day, change that.
14677 With prefix ARG, change by that many units."
14678 (interactive "p")
14679 (org-timestamp-change (- (prefix-numeric-value arg))))
14681 (defun org-timestamp-up-day (&optional arg)
14682 "Increase the date in the time stamp by one day.
14683 With prefix ARG, change that many days."
14684 (interactive "p")
14685 (if (and (not (org-at-timestamp-p t))
14686 (org-on-heading-p))
14687 (org-todo 'up)
14688 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14690 (defun org-timestamp-down-day (&optional arg)
14691 "Decrease the date in the time stamp by one day.
14692 With prefix ARG, change that many days."
14693 (interactive "p")
14694 (if (and (not (org-at-timestamp-p t))
14695 (org-on-heading-p))
14696 (org-todo 'down)
14697 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14699 (defun org-at-timestamp-p (&optional inactive-ok)
14700 "Determine if the cursor is in or at a timestamp."
14701 (interactive)
14702 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14703 (pos (point))
14704 (ans (or (looking-at tsr)
14705 (save-excursion
14706 (skip-chars-backward "^[<\n\r\t")
14707 (if (> (point) (point-min)) (backward-char 1))
14708 (and (looking-at tsr)
14709 (> (- (match-end 0) pos) -1))))))
14710 (and ans
14711 (boundp 'org-ts-what)
14712 (setq org-ts-what
14713 (cond
14714 ((= pos (match-beginning 0)) 'bracket)
14715 ((= pos (1- (match-end 0))) 'bracket)
14716 ((org-pos-in-match-range pos 2) 'year)
14717 ((org-pos-in-match-range pos 3) 'month)
14718 ((org-pos-in-match-range pos 7) 'hour)
14719 ((org-pos-in-match-range pos 8) 'minute)
14720 ((or (org-pos-in-match-range pos 4)
14721 (org-pos-in-match-range pos 5)) 'day)
14722 ((and (> pos (or (match-end 8) (match-end 5)))
14723 (< pos (match-end 0)))
14724 (- pos (or (match-end 8) (match-end 5))))
14725 (t 'day))))
14726 ans))
14728 (defun org-toggle-timestamp-type ()
14729 "Toggle the type (<active> or [inactive]) of a time stamp."
14730 (interactive)
14731 (when (org-at-timestamp-p t)
14732 (let ((beg (match-beginning 0)) (end (match-end 0))
14733 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14734 (save-excursion
14735 (goto-char beg)
14736 (while (re-search-forward "[][<>]" end t)
14737 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14738 t t)))
14739 (message "Timestamp is now %sactive"
14740 (if (equal (char-after beg) ?<) "" "in")))))
14742 (defun org-timestamp-change (n &optional what)
14743 "Change the date in the time stamp at point.
14744 The date will be changed by N times WHAT. WHAT can be `day', `month',
14745 `year', `minute', `second'. If WHAT is not given, the cursor position
14746 in the timestamp determines what will be changed."
14747 (let ((pos (point))
14748 with-hm inactive
14749 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14750 org-ts-what
14751 extra rem
14752 ts time time0)
14753 (if (not (org-at-timestamp-p t))
14754 (error "Not at a timestamp"))
14755 (if (and (not what) (eq org-ts-what 'bracket))
14756 (org-toggle-timestamp-type)
14757 (if (and (not what) (not (eq org-ts-what 'day))
14758 org-display-custom-times
14759 (get-text-property (point) 'display)
14760 (not (get-text-property (1- (point)) 'display)))
14761 (setq org-ts-what 'day))
14762 (setq org-ts-what (or what org-ts-what)
14763 inactive (= (char-after (match-beginning 0)) ?\[)
14764 ts (match-string 0))
14765 (replace-match "")
14766 (if (string-match
14767 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14769 (setq extra (match-string 1 ts)))
14770 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14771 (setq with-hm t))
14772 (setq time0 (org-parse-time-string ts))
14773 (when (and (eq org-ts-what 'minute)
14774 (eq current-prefix-arg nil))
14775 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14776 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14777 (setcar (cdr time0) (+ (nth 1 time0)
14778 (if (> n 0) (- rem) (- dm rem))))))
14779 (setq time
14780 (encode-time (or (car time0) 0)
14781 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14782 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14783 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14784 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14785 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14786 (nthcdr 6 time0)))
14787 (when (and (member org-ts-what '(hour minute))
14788 extra
14789 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14790 (setq extra (org-modify-ts-extra
14791 extra
14792 (if (eq org-ts-what 'hour) 2 5)
14793 n dm)))
14794 (when (integerp org-ts-what)
14795 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14796 (if (eq what 'calendar)
14797 (let ((cal-date (org-get-date-from-calendar)))
14798 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14799 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14800 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14801 (setcar time0 (or (car time0) 0))
14802 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14803 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14804 (setq time (apply 'encode-time time0))))
14805 (setq org-last-changed-timestamp
14806 (org-insert-time-stamp time with-hm inactive nil nil extra))
14807 (org-clock-update-time-maybe)
14808 (goto-char pos)
14809 ;; Try to recenter the calendar window, if any
14810 (if (and org-calendar-follow-timestamp-change
14811 (get-buffer-window "*Calendar*" t)
14812 (memq org-ts-what '(day month year)))
14813 (org-recenter-calendar (time-to-days time))))))
14815 (defun org-modify-ts-extra (s pos n dm)
14816 "Change the different parts of the lead-time and repeat fields in timestamp."
14817 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14818 ng h m new rem)
14819 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14820 (cond
14821 ((or (org-pos-in-match-range pos 2)
14822 (org-pos-in-match-range pos 3))
14823 (setq m (string-to-number (match-string 3 s))
14824 h (string-to-number (match-string 2 s)))
14825 (if (org-pos-in-match-range pos 2)
14826 (setq h (+ h n))
14827 (setq n (* dm (org-no-warnings (signum n))))
14828 (when (not (= 0 (setq rem (% m dm))))
14829 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14830 (setq m (+ m n)))
14831 (if (< m 0) (setq m (+ m 60) h (1- h)))
14832 (if (> m 59) (setq m (- m 60) h (1+ h)))
14833 (setq h (min 24 (max 0 h)))
14834 (setq ng 1 new (format "-%02d:%02d" h m)))
14835 ((org-pos-in-match-range pos 6)
14836 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14837 ((org-pos-in-match-range pos 5)
14838 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14840 ((org-pos-in-match-range pos 9)
14841 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14842 ((org-pos-in-match-range pos 8)
14843 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14845 (when ng
14846 (setq s (concat
14847 (substring s 0 (match-beginning ng))
14849 (substring s (match-end ng))))))
14852 (defun org-recenter-calendar (date)
14853 "If the calendar is visible, recenter it to DATE."
14854 (let* ((win (selected-window))
14855 (cwin (get-buffer-window "*Calendar*" t))
14856 (calendar-move-hook nil))
14857 (when cwin
14858 (select-window cwin)
14859 (calendar-goto-date (if (listp date) date
14860 (calendar-gregorian-from-absolute date)))
14861 (select-window win))))
14863 (defun org-goto-calendar (&optional arg)
14864 "Go to the Emacs calendar at the current date.
14865 If there is a time stamp in the current line, go to that date.
14866 A prefix ARG can be used to force the current date."
14867 (interactive "P")
14868 (let ((tsr org-ts-regexp) diff
14869 (calendar-move-hook nil)
14870 (calendar-view-holidays-initially-flag nil)
14871 (calendar-view-diary-initially-flag nil))
14872 (if (or (org-at-timestamp-p)
14873 (save-excursion
14874 (beginning-of-line 1)
14875 (looking-at (concat ".*" tsr))))
14876 (let ((d1 (time-to-days (current-time)))
14877 (d2 (time-to-days
14878 (org-time-string-to-time (match-string 1)))))
14879 (setq diff (- d2 d1))))
14880 (calendar)
14881 (calendar-goto-today)
14882 (if (and diff (not arg)) (calendar-forward-day diff))))
14884 (defun org-get-date-from-calendar ()
14885 "Return a list (month day year) of date at point in calendar."
14886 (with-current-buffer "*Calendar*"
14887 (save-match-data
14888 (calendar-cursor-to-date))))
14890 (defun org-date-from-calendar ()
14891 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14892 If there is already a time stamp at the cursor position, update it."
14893 (interactive)
14894 (if (org-at-timestamp-p t)
14895 (org-timestamp-change 0 'calendar)
14896 (let ((cal-date (org-get-date-from-calendar)))
14897 (org-insert-time-stamp
14898 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14900 (defun org-minutes-to-hh:mm-string (m)
14901 "Compute H:MM from a number of minutes."
14902 (let ((h (/ m 60)))
14903 (setq m (- m (* 60 h)))
14904 (format org-time-clocksum-format h m)))
14906 (defun org-hh:mm-string-to-minutes (s)
14907 "Convert a string H:MM to a number of minutes.
14908 If the string is just a number, interpret it as minutes.
14909 In fact, the first hh:mm or number in the string will be taken,
14910 there can be extra stuff in the string.
14911 If no number is found, the return value is 0."
14912 (cond
14913 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14914 (+ (* (string-to-number (match-string 1 s)) 60)
14915 (string-to-number (match-string 2 s))))
14916 ((string-match "\\([0-9]+\\)" s)
14917 (string-to-number (match-string 1 s)))
14918 (t 0)))
14920 ;;;; Files
14922 (defun org-save-all-org-buffers ()
14923 "Save all Org-mode buffers without user confirmation."
14924 (interactive)
14925 (message "Saving all Org-mode buffers...")
14926 (save-some-buffers t 'org-mode-p)
14927 (when (featurep 'org-id) (org-id-locations-save))
14928 (message "Saving all Org-mode buffers... done"))
14930 (defun org-revert-all-org-buffers ()
14931 "Revert all Org-mode buffers.
14932 Prompt for confirmation when there are unsaved changes.
14933 Be sure you know what you are doing before letting this function
14934 overwrite your changes.
14936 This function is useful in a setup where one tracks org files
14937 with a version control system, to revert on one machine after pulling
14938 changes from another. I believe the procedure must be like this:
14940 1. M-x org-save-all-org-buffers
14941 2. Pull changes from the other machine, resolve conflicts
14942 3. M-x org-revert-all-org-buffers"
14943 (interactive)
14944 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14945 (error "Abort"))
14946 (save-excursion
14947 (save-window-excursion
14948 (mapc
14949 (lambda (b)
14950 (when (and (with-current-buffer b (org-mode-p))
14951 (with-current-buffer b buffer-file-name))
14952 (switch-to-buffer b)
14953 (revert-buffer t 'no-confirm)))
14954 (buffer-list))
14955 (when (and (featurep 'org-id) org-id-track-globally)
14956 (org-id-locations-load)))))
14958 ;;;; Agenda files
14960 ;;;###autoload
14961 (defun org-iswitchb (&optional arg)
14962 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14963 With a prefix argument, restrict available to files.
14964 With two prefix arguments, restrict available buffers to agenda files."
14965 (interactive "P")
14966 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14967 ((equal arg '(16)) (org-buffer-list 'agenda))
14968 (t (org-buffer-list)))))
14969 (switch-to-buffer
14970 (org-icompleting-read "Org buffer: "
14971 (mapcar 'list (mapcar 'buffer-name blist))
14972 nil t))))
14974 ;;;###autoload
14975 (defalias 'org-ido-switchb 'org-iswitchb)
14977 (defun org-buffer-list (&optional predicate exclude-tmp)
14978 "Return a list of Org buffers.
14979 PREDICATE can be `export', `files' or `agenda'.
14981 export restrict the list to Export buffers.
14982 files restrict the list to buffers visiting Org files.
14983 agenda restrict the list to buffers visiting agenda files.
14985 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14986 (let* ((bfn nil)
14987 (agenda-files (and (eq predicate 'agenda)
14988 (mapcar 'file-truename (org-agenda-files t))))
14989 (filter
14990 (cond
14991 ((eq predicate 'files)
14992 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14993 ((eq predicate 'export)
14994 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14995 ((eq predicate 'agenda)
14996 (lambda (b)
14997 (with-current-buffer b
14998 (and (eq major-mode 'org-mode)
14999 (setq bfn (buffer-file-name b))
15000 (member (file-truename bfn) agenda-files)))))
15001 (t (lambda (b) (with-current-buffer b
15002 (or (eq major-mode 'org-mode)
15003 (string-match "\*Org .*Export"
15004 (buffer-name b)))))))))
15005 (delq nil
15006 (mapcar
15007 (lambda(b)
15008 (if (and (funcall filter b)
15009 (or (not exclude-tmp)
15010 (not (string-match "tmp" (buffer-name b)))))
15012 nil))
15013 (buffer-list)))))
15015 (defun org-agenda-files (&optional unrestricted archives)
15016 "Get the list of agenda files.
15017 Optional UNRESTRICTED means return the full list even if a restriction
15018 is currently in place.
15019 When ARCHIVES is t, include all archive files that are really being
15020 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15021 `org-agenda-archives-mode' is t."
15022 (let ((files
15023 (cond
15024 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15025 ((stringp org-agenda-files) (org-read-agenda-file-list))
15026 ((listp org-agenda-files) org-agenda-files)
15027 (t (error "Invalid value of `org-agenda-files'")))))
15028 (setq files (apply 'append
15029 (mapcar (lambda (f)
15030 (if (file-directory-p f)
15031 (directory-files
15032 f t org-agenda-file-regexp)
15033 (list f)))
15034 files)))
15035 (when org-agenda-skip-unavailable-files
15036 (setq files (delq nil
15037 (mapcar (function
15038 (lambda (file)
15039 (and (file-readable-p file) file)))
15040 files))))
15041 (when (or (eq archives t)
15042 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15043 (setq files (org-add-archive-files files)))
15044 files))
15046 (defun org-edit-agenda-file-list ()
15047 "Edit the list of agenda files.
15048 Depending on setup, this either uses customize to edit the variable
15049 `org-agenda-files', or it visits the file that is holding the list. In the
15050 latter case, the buffer is set up in a way that saving it automatically kills
15051 the buffer and restores the previous window configuration."
15052 (interactive)
15053 (if (stringp org-agenda-files)
15054 (let ((cw (current-window-configuration)))
15055 (find-file org-agenda-files)
15056 (org-set-local 'org-window-configuration cw)
15057 (org-add-hook 'after-save-hook
15058 (lambda ()
15059 (set-window-configuration
15060 (prog1 org-window-configuration
15061 (kill-buffer (current-buffer))))
15062 (org-install-agenda-files-menu)
15063 (message "New agenda file list installed"))
15064 nil 'local)
15065 (message "%s" (substitute-command-keys
15066 "Edit list and finish with \\[save-buffer]")))
15067 (customize-variable 'org-agenda-files)))
15069 (defun org-store-new-agenda-file-list (list)
15070 "Set new value for the agenda file list and save it correctly."
15071 (if (stringp org-agenda-files)
15072 (let ((fe (org-read-agenda-file-list t)) b u)
15073 (while (setq b (find-buffer-visiting org-agenda-files))
15074 (kill-buffer b))
15075 (with-temp-file org-agenda-files
15076 (insert
15077 (mapconcat
15078 (lambda (f) ;; Keep un-expanded entries.
15079 (if (setq u (assoc f fe))
15080 (cdr u)
15082 list "\n")
15083 "\n")))
15084 (let ((org-mode-hook nil) (org-inhibit-startup t)
15085 (org-insert-mode-line-in-empty-file nil))
15086 (setq org-agenda-files list)
15087 (customize-save-variable 'org-agenda-files org-agenda-files))))
15089 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15090 "Read the list of agenda files from a file.
15091 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15092 filenames, used by `org-store-new-agenda-file-list' to write back
15093 un-expanded file names."
15094 (when (file-directory-p org-agenda-files)
15095 (error "`org-agenda-files' cannot be a single directory"))
15096 (when (stringp org-agenda-files)
15097 (with-temp-buffer
15098 (insert-file-contents org-agenda-files)
15099 (mapcar
15100 (lambda (f)
15101 (let ((e (expand-file-name (substitute-in-file-name f)
15102 org-directory)))
15103 (if pair-with-expansion
15104 (cons e f)
15105 e)))
15106 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15108 ;;;###autoload
15109 (defun org-cycle-agenda-files ()
15110 "Cycle through the files in `org-agenda-files'.
15111 If the current buffer visits an agenda file, find the next one in the list.
15112 If the current buffer does not, find the first agenda file."
15113 (interactive)
15114 (let* ((fs (org-agenda-files t))
15115 (files (append fs (list (car fs))))
15116 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15117 file)
15118 (unless files (error "No agenda files"))
15119 (catch 'exit
15120 (while (setq file (pop files))
15121 (if (equal (file-truename file) tcf)
15122 (when (car files)
15123 (find-file (car files))
15124 (throw 'exit t))))
15125 (find-file (car fs)))
15126 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15128 (defun org-agenda-file-to-front (&optional to-end)
15129 "Move/add the current file to the top of the agenda file list.
15130 If the file is not present in the list, it is added to the front. If it is
15131 present, it is moved there. With optional argument TO-END, add/move to the
15132 end of the list."
15133 (interactive "P")
15134 (let ((org-agenda-skip-unavailable-files nil)
15135 (file-alist (mapcar (lambda (x)
15136 (cons (file-truename x) x))
15137 (org-agenda-files t)))
15138 (ctf (file-truename buffer-file-name))
15139 x had)
15140 (setq x (assoc ctf file-alist) had x)
15142 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15143 (if to-end
15144 (setq file-alist (append (delq x file-alist) (list x)))
15145 (setq file-alist (cons x (delq x file-alist))))
15146 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15147 (org-install-agenda-files-menu)
15148 (message "File %s to %s of agenda file list"
15149 (if had "moved" "added") (if to-end "end" "front"))))
15151 (defun org-remove-file (&optional file)
15152 "Remove current file from the list of files in variable `org-agenda-files'.
15153 These are the files which are being checked for agenda entries.
15154 Optional argument FILE means use this file instead of the current."
15155 (interactive)
15156 (let* ((org-agenda-skip-unavailable-files nil)
15157 (file (or file buffer-file-name))
15158 (true-file (file-truename file))
15159 (afile (abbreviate-file-name file))
15160 (files (delq nil (mapcar
15161 (lambda (x)
15162 (if (equal true-file
15163 (file-truename x))
15164 nil x))
15165 (org-agenda-files t)))))
15166 (if (not (= (length files) (length (org-agenda-files t))))
15167 (progn
15168 (org-store-new-agenda-file-list files)
15169 (org-install-agenda-files-menu)
15170 (message "Removed file: %s" afile))
15171 (message "File was not in list: %s (not removed)" afile))))
15173 (defun org-file-menu-entry (file)
15174 (vector file (list 'find-file file) t))
15176 (defun org-check-agenda-file (file)
15177 "Make sure FILE exists. If not, ask user what to do."
15178 (when (not (file-exists-p file))
15179 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15180 (abbreviate-file-name file))
15181 (let ((r (downcase (read-char-exclusive))))
15182 (cond
15183 ((equal r ?r)
15184 (org-remove-file file)
15185 (throw 'nextfile t))
15186 (t (error "Abort"))))))
15188 (defun org-get-agenda-file-buffer (file)
15189 "Get a buffer visiting FILE. If the buffer needs to be created, add
15190 it to the list of buffers which might be released later."
15191 (let ((buf (org-find-base-buffer-visiting file)))
15192 (if buf
15193 buf ; just return it
15194 ;; Make a new buffer and remember it
15195 (setq buf (find-file-noselect file))
15196 (if buf (push buf org-agenda-new-buffers))
15197 buf)))
15199 (defun org-release-buffers (blist)
15200 "Release all buffers in list, asking the user for confirmation when needed.
15201 When a buffer is unmodified, it is just killed. When modified, it is saved
15202 \(if the user agrees) and then killed."
15203 (let (buf file)
15204 (while (setq buf (pop blist))
15205 (setq file (buffer-file-name buf))
15206 (when (and (buffer-modified-p buf)
15207 file
15208 (y-or-n-p (format "Save file %s? " file)))
15209 (with-current-buffer buf (save-buffer)))
15210 (kill-buffer buf))))
15212 (defun org-prepare-agenda-buffers (files)
15213 "Create buffers for all agenda files, protect archived trees and comments."
15214 (interactive)
15215 (let ((pa '(:org-archived t))
15216 (pc '(:org-comment t))
15217 (pall '(:org-archived t :org-comment t))
15218 (inhibit-read-only t)
15219 (rea (concat ":" org-archive-tag ":"))
15220 bmp file re)
15221 (save-excursion
15222 (save-restriction
15223 (while (setq file (pop files))
15224 (catch 'nextfile
15225 (if (bufferp file)
15226 (set-buffer file)
15227 (org-check-agenda-file file)
15228 (set-buffer (org-get-agenda-file-buffer file)))
15229 (widen)
15230 (setq bmp (buffer-modified-p))
15231 (org-refresh-category-properties)
15232 (setq org-todo-keywords-for-agenda
15233 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15234 (setq org-done-keywords-for-agenda
15235 (append org-done-keywords-for-agenda org-done-keywords))
15236 (setq org-todo-keyword-alist-for-agenda
15237 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15238 (setq org-drawers-for-agenda
15239 (append org-drawers-for-agenda org-drawers))
15240 (setq org-tag-alist-for-agenda
15241 (append org-tag-alist-for-agenda org-tag-alist))
15243 (save-excursion
15244 (remove-text-properties (point-min) (point-max) pall)
15245 (when org-agenda-skip-archived-trees
15246 (goto-char (point-min))
15247 (while (re-search-forward rea nil t)
15248 (if (org-on-heading-p t)
15249 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15250 (goto-char (point-min))
15251 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15252 (while (re-search-forward re nil t)
15253 (add-text-properties
15254 (match-beginning 0) (org-end-of-subtree t) pc)))
15255 (set-buffer-modified-p bmp)))))
15256 (setq org-todo-keywords-for-agenda
15257 (org-uniquify org-todo-keywords-for-agenda))
15258 (setq org-todo-keyword-alist-for-agenda
15259 (org-uniquify org-todo-keyword-alist-for-agenda)
15260 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15262 ;;;; Embedded LaTeX
15264 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15265 "Keymap for the minor `org-cdlatex-mode'.")
15267 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15268 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15269 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15270 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15271 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15273 (defvar org-cdlatex-texmathp-advice-is-done nil
15274 "Flag remembering if we have applied the advice to texmathp already.")
15276 (define-minor-mode org-cdlatex-mode
15277 "Toggle the minor `org-cdlatex-mode'.
15278 This mode supports entering LaTeX environment and math in LaTeX fragments
15279 in Org-mode.
15280 \\{org-cdlatex-mode-map}"
15281 nil " OCDL" nil
15282 (when org-cdlatex-mode (require 'cdlatex))
15283 (unless org-cdlatex-texmathp-advice-is-done
15284 (setq org-cdlatex-texmathp-advice-is-done t)
15285 (defadvice texmathp (around org-math-always-on activate)
15286 "Always return t in org-mode buffers.
15287 This is because we want to insert math symbols without dollars even outside
15288 the LaTeX math segments. If Orgmode thinks that point is actually inside
15289 an embedded LaTeX fragment, let texmathp do its job.
15290 \\[org-cdlatex-mode-map]"
15291 (interactive)
15292 (let (p)
15293 (cond
15294 ((not (org-mode-p)) ad-do-it)
15295 ((eq this-command 'cdlatex-math-symbol)
15296 (setq ad-return-value t
15297 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15299 (let ((p (org-inside-LaTeX-fragment-p)))
15300 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15301 (setq ad-return-value t
15302 texmathp-why '("Org-mode embedded math" . 0))
15303 (if p ad-do-it)))))))))
15305 (defun turn-on-org-cdlatex ()
15306 "Unconditionally turn on `org-cdlatex-mode'."
15307 (org-cdlatex-mode 1))
15309 (defun org-inside-LaTeX-fragment-p ()
15310 "Test if point is inside a LaTeX fragment.
15311 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15312 sequence appearing also before point.
15313 Even though the matchers for math are configurable, this function assumes
15314 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15315 delimiters are skipped when they have been removed by customization.
15316 The return value is nil, or a cons cell with the delimiter and
15317 and the position of this delimiter.
15319 This function does a reasonably good job, but can locally be fooled by
15320 for example currency specifications. For example it will assume being in
15321 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15322 fragments that are properly closed, but during editing, we have to live
15323 with the uncertainty caused by missing closing delimiters. This function
15324 looks only before point, not after."
15325 (catch 'exit
15326 (let ((pos (point))
15327 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15328 (lim (progn
15329 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15330 (point)))
15331 dd-on str (start 0) m re)
15332 (goto-char pos)
15333 (when dodollar
15334 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15335 re (nth 1 (assoc "$" org-latex-regexps)))
15336 (while (string-match re str start)
15337 (cond
15338 ((= (match-end 0) (length str))
15339 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15340 ((= (match-end 0) (- (length str) 5))
15341 (throw 'exit nil))
15342 (t (setq start (match-end 0))))))
15343 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15344 (goto-char pos)
15345 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15346 (and (match-beginning 2) (throw 'exit nil))
15347 ;; count $$
15348 (while (re-search-backward "\\$\\$" lim t)
15349 (setq dd-on (not dd-on)))
15350 (goto-char pos)
15351 (if dd-on (cons "$$" m))))))
15353 (defun org-inside-latex-macro-p ()
15354 "Is point inside a LaTeX macro or its arguments?"
15355 (save-match-data
15356 (org-in-regexp
15357 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15359 (defun test ()
15360 (interactive)
15361 (message "%s" (org-inside-latex-macro-p)))
15363 (defun org-try-cdlatex-tab ()
15364 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15365 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15366 - inside a LaTeX fragment, or
15367 - after the first word in a line, where an abbreviation expansion could
15368 insert a LaTeX environment."
15369 (when org-cdlatex-mode
15370 (cond
15371 ((save-excursion
15372 (skip-chars-backward "a-zA-Z0-9*")
15373 (skip-chars-backward " \t")
15374 (bolp))
15375 (cdlatex-tab) t)
15376 ((org-inside-LaTeX-fragment-p)
15377 (cdlatex-tab) t)
15378 (t nil))))
15380 (defun org-cdlatex-underscore-caret (&optional arg)
15381 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15382 Revert to the normal definition outside of these fragments."
15383 (interactive "P")
15384 (if (org-inside-LaTeX-fragment-p)
15385 (call-interactively 'cdlatex-sub-superscript)
15386 (let (org-cdlatex-mode)
15387 (call-interactively (key-binding (vector last-input-event))))))
15389 (defun org-cdlatex-math-modify (&optional arg)
15390 "Execute `cdlatex-math-modify' in LaTeX fragments.
15391 Revert to the normal definition outside of these fragments."
15392 (interactive "P")
15393 (if (org-inside-LaTeX-fragment-p)
15394 (call-interactively 'cdlatex-math-modify)
15395 (let (org-cdlatex-mode)
15396 (call-interactively (key-binding (vector last-input-event))))))
15398 (defvar org-latex-fragment-image-overlays nil
15399 "List of overlays carrying the images of latex fragments.")
15400 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15402 (defun org-remove-latex-fragment-image-overlays ()
15403 "Remove all overlays with LaTeX fragment images in current buffer."
15404 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15405 (setq org-latex-fragment-image-overlays nil))
15407 (defun org-preview-latex-fragment (&optional subtree)
15408 "Preview the LaTeX fragment at point, or all locally or globally.
15409 If the cursor is in a LaTeX fragment, create the image and overlay
15410 it over the source code. If there is no fragment at point, display
15411 all fragments in the current text, from one headline to the next. With
15412 prefix SUBTREE, display all fragments in the current subtree. With a
15413 double prefix `C-u C-u', or when the cursor is before the first headline,
15414 display all fragments in the buffer.
15415 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15416 (interactive "P")
15417 (org-remove-latex-fragment-image-overlays)
15418 (save-excursion
15419 (save-restriction
15420 (let (beg end at msg)
15421 (cond
15422 ((or (equal subtree '(16))
15423 (not (save-excursion
15424 (re-search-backward (concat "^" outline-regexp) nil t))))
15425 (setq beg (point-min) end (point-max)
15426 msg "Creating images for buffer...%s"))
15427 ((equal subtree '(4))
15428 (org-back-to-heading)
15429 (setq beg (point) end (org-end-of-subtree t)
15430 msg "Creating images for subtree...%s"))
15432 (if (setq at (org-inside-LaTeX-fragment-p))
15433 (goto-char (max (point-min) (- (cdr at) 2)))
15434 (org-back-to-heading))
15435 (setq beg (point) end (progn (outline-next-heading) (point))
15436 msg (if at "Creating image...%s"
15437 "Creating images for entry...%s"))))
15438 (message msg "")
15439 (narrow-to-region beg end)
15440 (goto-char beg)
15441 (org-format-latex
15442 (concat "ltxpng/" (file-name-sans-extension
15443 (file-name-nondirectory
15444 buffer-file-name)))
15445 default-directory 'overlays msg at 'forbuffer)
15446 (message msg "done. Use `C-c C-c' to remove images.")))))
15448 (defvar org-latex-regexps
15449 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15450 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15451 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15452 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15453 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15454 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15455 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15456 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15457 "Regular expressions for matching embedded LaTeX.")
15459 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15460 "Replace LaTeX fragments with links to an image, and produce images.
15461 Some of the options can be changed using the variable
15462 `org-format-latex-options'."
15463 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15464 (let* ((prefixnodir (file-name-nondirectory prefix))
15465 (absprefix (expand-file-name prefix dir))
15466 (todir (file-name-directory absprefix))
15467 (opt org-format-latex-options)
15468 (matchers (plist-get opt :matchers))
15469 (re-list org-latex-regexps)
15470 (org-format-latex-header-extra
15471 (plist-get (org-infile-export-plist) :latex-header-extra))
15472 (cnt 0) txt hash link beg end re e checkdir
15473 executables-checked
15474 m n block linkfile movefile ov)
15475 ;; Check the different regular expressions
15476 (while (setq e (pop re-list))
15477 (setq m (car e) re (nth 1 e) n (nth 2 e)
15478 block (if (nth 3 e) "\n\n" ""))
15479 (when (member m matchers)
15480 (goto-char (point-min))
15481 (while (re-search-forward re nil t)
15482 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15483 (not (get-text-property (match-beginning n)
15484 'org-protected))
15485 (or (not overlays)
15486 (not (eq (get-char-property (match-beginning n)
15487 'org-overlay-type)
15488 'org-latex-overlay))))
15489 (setq txt (match-string n)
15490 beg (match-beginning n) end (match-end n)
15491 cnt (1+ cnt))
15492 (let (print-length print-level) ; make sure full list is printed
15493 (setq hash (sha1 (prin1-to-string
15494 (list org-format-latex-header
15495 org-format-latex-header-extra
15496 org-export-latex-default-packages-alist
15497 org-export-latex-packages-alist
15498 org-format-latex-options
15499 forbuffer txt)))
15500 linkfile (format "%s_%s.png" prefix hash)
15501 movefile (format "%s_%s.png" absprefix hash)))
15502 (setq link (concat block "[[file:" linkfile "]]" block))
15503 (if msg (message msg cnt))
15504 (goto-char beg)
15505 (unless checkdir ; make sure the directory exists
15506 (setq checkdir t)
15507 (or (file-directory-p todir) (make-directory todir)))
15509 (unless executables-checked
15510 (org-check-external-command
15511 "latex" "needed to convert LaTeX fragments to images")
15512 (org-check-external-command
15513 "dvipng" "needed to convert LaTeX fragments to images")
15514 (setq executables-checked t))
15516 (unless (file-exists-p movefile)
15517 (org-create-formula-image
15518 txt movefile opt forbuffer))
15519 (if overlays
15520 (progn
15521 (mapc (lambda (o)
15522 (if (eq (overlay-get o 'org-overlay-type)
15523 'org-latex-overlay)
15524 (delete-overlay o)))
15525 (overlays-in beg end))
15526 (setq ov (make-overlay beg end))
15527 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15528 (if (featurep 'xemacs)
15529 (progn
15530 (overlay-put ov 'invisible t)
15531 (overlay-put
15532 ov 'end-glyph
15533 (make-glyph (vector 'png :file movefile))))
15534 (overlay-put
15535 ov 'display
15536 (list 'image :type 'png :file movefile :ascent 'center)))
15537 (push ov org-latex-fragment-image-overlays)
15538 (goto-char end))
15539 (delete-region beg end)
15540 (insert (org-add-props link
15541 (list 'org-latex-src
15542 (replace-regexp-in-string "\"" "" txt)))))))))))
15544 ;; This function borrows from Ganesh Swami's latex2png.el
15545 (defun org-create-formula-image (string tofile options buffer)
15546 "This calls dvipng."
15547 (require 'org-latex)
15548 (let* ((tmpdir (if (featurep 'xemacs)
15549 (temp-directory)
15550 temporary-file-directory))
15551 (texfilebase (make-temp-name
15552 (expand-file-name "orgtex" tmpdir)))
15553 (texfile (concat texfilebase ".tex"))
15554 (dvifile (concat texfilebase ".dvi"))
15555 (pngfile (concat texfilebase ".png"))
15556 (fnh (if (featurep 'xemacs)
15557 (font-height (get-face-font 'default))
15558 (face-attribute 'default :height nil)))
15559 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15560 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15561 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15562 "Black"))
15563 (bg (or (plist-get options (if buffer :background :html-background))
15564 "Transparent")))
15565 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15566 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15567 (with-temp-file texfile
15568 (insert (org-splice-latex-header
15569 org-format-latex-header
15570 org-export-latex-default-packages-alist
15571 org-export-latex-packages-alist t
15572 org-format-latex-header-extra))
15573 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15574 (require 'org-latex)
15575 (org-export-latex-fix-inputenc))
15576 (let ((dir default-directory))
15577 (condition-case nil
15578 (progn
15579 (cd tmpdir)
15580 (call-process "latex" nil nil nil texfile))
15581 (error nil))
15582 (cd dir))
15583 (if (not (file-exists-p dvifile))
15584 (progn (message "Failed to create dvi file from %s" texfile) nil)
15585 (condition-case nil
15586 (call-process "dvipng" nil nil nil
15587 "-fg" fg "-bg" bg
15588 "-D" dpi
15589 ;;"-x" scale "-y" scale
15590 "-T" "tight"
15591 "-o" pngfile
15592 dvifile)
15593 (error nil))
15594 (if (not (file-exists-p pngfile))
15595 (if org-format-latex-signal-error
15596 (error "Failed to create png file from %s" texfile)
15597 (message "Failed to create png file from %s" texfile)
15598 nil)
15599 ;; Use the requested file name and clean up
15600 (copy-file pngfile tofile 'replace)
15601 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15602 (delete-file (concat texfilebase e)))
15603 pngfile))))
15605 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15606 "Fill a LaTeX header template TPL.
15607 In the template, the following place holders will be recognized:
15609 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15610 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15611 [PACKAGES] \\usepackage statements for PKG
15612 [NO-PACKAGES] do not include PKG
15613 [EXTRA] the string EXTRA
15614 [NO-EXTRA] do not include EXTRA
15616 For backward compatibility, if both the positive and the negative place
15617 holder is missing, the positive one (without the \"NO-\") will be
15618 assumed to be present at the end of the template.
15619 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15620 EXTRA is a string.
15621 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15622 (let (rpl (end ""))
15623 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15624 (setq rpl (if (or (match-end 1) (not def-pkg))
15625 "" (org-latex-packages-to-string def-pkg snippets-p t))
15626 tpl (replace-match rpl t t tpl))
15627 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15629 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15630 (setq rpl (if (or (match-end 1) (not pkg))
15631 "" (org-latex-packages-to-string pkg snippets-p t))
15632 tpl (replace-match rpl t t tpl))
15633 (if pkg (setq end
15634 (concat end "\n"
15635 (org-latex-packages-to-string pkg snippets-p)))))
15637 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15638 (setq rpl (if (or (match-end 1) (not extra))
15639 "" (concat extra "\n"))
15640 tpl (replace-match rpl t t tpl))
15641 (if (and extra (string-match "\\S-" extra))
15642 (setq end (concat end "\n" extra))))
15644 (if (string-match "\\S-" end)
15645 (concat tpl "\n" end)
15646 tpl)))
15648 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
15649 "Turn an alist of packages into a string with the \\usepackage macros."
15650 (setq pkg (mapconcat (lambda(p)
15651 (cond
15652 ((stringp p) p)
15653 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
15654 (format "%% Package %s omitted" (cadr p)))
15655 ((equal "" (car p))
15656 (format "\\usepackage{%s}" (cadr p)))
15658 (format "\\usepackage[%s]{%s}"
15659 (car p) (cadr p)))))
15661 "\n"))
15662 (if newline (concat pkg "\n") pkg))
15664 (defun org-dvipng-color (attr)
15665 "Return an rgb color specification for dvipng."
15666 (apply 'format "rgb %s %s %s"
15667 (mapcar 'org-normalize-color
15668 (color-values (face-attribute 'default attr nil)))))
15670 (defun org-normalize-color (value)
15671 "Return string to be used as color value for an RGB component."
15672 (format "%g" (/ value 65535.0)))
15674 ;; Image display
15677 (defvar org-inline-image-overlays nil)
15678 (make-variable-buffer-local 'org-inline-image-overlays)
15680 (defun org-toggle-inline-images (&optional include-linked)
15681 "Toggle the display of inline images.
15682 INCLUDE-LINKED is passed to `org-display-inline-images'."
15683 (interactive "P")
15684 (if org-inline-image-overlays
15685 (progn
15686 (org-remove-inline-images)
15687 (message "Inline image display turned off"))
15688 (org-display-inline-images include-linked)
15689 (if org-inline-image-overlays
15690 (message "%d images displayed inline"
15691 (length org-inline-image-overlays))
15692 (message "No images to display inline"))))
15694 (defun org-display-inline-images (&optional include-linked refresh beg end)
15695 "Display inline images.
15696 Normally only links without a description part are inlined, because this
15697 is how it will work for export. When INCLUDE-LINKED is set, also links
15698 with a description part will be inlined. This can be nice for a quick
15699 look at those images, but it does not reflect whatexported files will look
15700 like.
15701 When REFRESH is set, refresh existing images between BEG and END.
15702 This will create new image displays only if necessary.
15703 BEG and END default to the buffer boundaries."
15704 (interactive "P")
15705 (unless refresh
15706 (org-remove-inline-images)
15707 (clear-image-cache))
15708 (save-excursion
15709 (save-restriction
15710 (widen)
15711 (setq beg (or beg (point-min)) end (or end (point-max)))
15712 (goto-char (point-min))
15713 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~./_0-9a-zA-Z]+"
15714 (substring (org-image-file-name-regexp) 0 -2)
15715 "\\)\\]" (if include-linked "" "\\]")))
15716 old file ov img)
15717 (while (re-search-forward re end t)
15718 (setq old (get-char-property-and-overlay (match-beginning 1)
15719 'org-image-overlay))
15720 (setq file (expand-file-name
15721 (concat (or (match-string 3) "") (match-string 4))))
15722 (when (file-exists-p file)
15723 (if (and (car-safe old) refresh)
15724 (image-refresh (overlay-get (cdr old) 'display))
15725 (setq img (create-image file))
15726 (when img
15727 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
15728 (overlay-put ov 'display img)
15729 (overlay-put ov 'face 'default)
15730 (overlay-put ov 'org-image-overlay t)
15731 (push ov org-inline-image-overlays)))))))))
15733 (defun org-remove-inline-images ()
15734 "Remove inline display of images."
15735 (interactive)
15736 (mapc 'delete-overlay org-inline-image-overlays)
15737 (setq org-inline-image-overlays nil))
15739 ;;;; Key bindings
15741 ;; Make `C-c C-x' a prefix key
15742 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15744 ;; TAB key with modifiers
15745 (org-defkey org-mode-map "\C-i" 'org-cycle)
15746 (org-defkey org-mode-map [(tab)] 'org-cycle)
15747 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15748 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15749 (org-defkey org-mode-map "\M-\t" 'org-complete)
15750 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15751 ;; The following line is necessary under Suse GNU/Linux
15752 (unless (featurep 'xemacs)
15753 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15754 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15755 (define-key org-mode-map [backtab] 'org-shifttab)
15757 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15758 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15759 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15761 ;; Cursor keys with modifiers
15762 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15763 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15764 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15765 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15767 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15768 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15769 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15770 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15772 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15773 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15774 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15775 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15777 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15778 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15780 ;;; Extra keys for tty access.
15781 ;; We only set them when really needed because otherwise the
15782 ;; menus don't show the simple keys
15784 (when (or org-use-extra-keys
15785 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15786 (not window-system))
15787 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15788 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15789 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15790 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15791 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15792 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15793 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15794 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15795 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15796 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15797 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15798 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15799 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15800 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15801 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15802 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15803 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15804 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15805 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15806 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15807 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15808 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15809 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15810 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15811 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15812 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15813 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15814 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15816 ;; All the other keys
15818 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15819 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15820 (if (boundp 'narrow-map)
15821 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15822 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15823 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15824 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15825 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15826 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15827 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15828 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15829 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15830 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15831 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15832 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15833 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15834 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15835 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15836 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15837 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15838 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15839 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15840 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15841 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15842 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15843 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15844 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15845 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15846 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15847 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15848 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15849 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15850 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15851 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15852 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15853 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15854 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15855 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15856 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15857 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15858 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15859 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15860 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15861 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15862 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15863 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15864 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15865 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15866 (org-defkey org-mode-map "\C-c^" 'org-sort)
15867 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15868 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15869 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15870 (org-defkey org-mode-map "\C-m" 'org-return)
15871 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15872 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15873 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15874 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15875 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15876 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15877 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15878 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15879 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15880 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15881 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15882 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15883 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15884 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15885 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15886 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15887 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15888 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15889 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15890 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15891 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15893 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15894 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15895 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15896 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15898 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15899 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15900 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15901 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15902 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15903 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15904 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15905 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15906 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15907 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
15908 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
15909 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15910 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15911 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15912 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15913 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15914 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15916 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15917 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15918 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15919 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15921 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15923 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15925 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15926 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15928 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15931 (when (featurep 'xemacs)
15932 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15935 (defconst org-speed-commands-default
15937 ("Outline Navigation")
15938 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15939 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15940 ("f" . (org-speed-move-safe 'org-forward-same-level))
15941 ("b" . (org-speed-move-safe 'org-backward-same-level))
15942 ("u" . (org-speed-move-safe 'outline-up-heading))
15943 ("j" . org-goto)
15944 ("g" . (org-refile t))
15945 ("Outline Visibility")
15946 ("c" . org-cycle)
15947 ("C" . org-shifttab)
15948 (" " . org-display-outline-path)
15949 ("Outline Structure Editing")
15950 ("U" . org-shiftmetaup)
15951 ("D" . org-shiftmetadown)
15952 ("r" . org-metaright)
15953 ("l" . org-metaleft)
15954 ("R" . org-shiftmetaright)
15955 ("L" . org-shiftmetaleft)
15956 ("i" . (progn (forward-char 1) (call-interactively
15957 'org-insert-heading-respect-content)))
15958 ("^" . org-sort)
15959 ("w" . org-refile)
15960 ("a" . org-archive-subtree-default-with-confirmation)
15961 ("." . outline-mark-subtree)
15962 ("Clock Commands")
15963 ("I" . org-clock-in)
15964 ("O" . org-clock-out)
15965 ("Meta Data Editing")
15966 ("t" . org-todo)
15967 ("0" . (org-priority ?\ ))
15968 ("1" . (org-priority ?A))
15969 ("2" . (org-priority ?B))
15970 ("3" . (org-priority ?C))
15971 (";" . org-set-tags-command)
15972 ("e" . org-set-effort)
15973 ("Agenda Views etc")
15974 ("v" . org-agenda)
15975 ("/" . org-sparse-tree)
15976 ("Misc")
15977 ("o" . org-open-at-point)
15978 ("?" . org-speed-command-help)
15980 "The default speed commands.")
15982 (defun org-print-speed-command (e)
15983 (if (> (length (car e)) 1)
15984 (progn
15985 (princ "\n")
15986 (princ (car e))
15987 (princ "\n")
15988 (princ (make-string (length (car e)) ?-))
15989 (princ "\n"))
15990 (princ (car e))
15991 (princ " ")
15992 (if (symbolp (cdr e))
15993 (princ (symbol-name (cdr e)))
15994 (prin1 (cdr e)))
15995 (princ "\n")))
15997 (defun org-speed-command-help ()
15998 "Show the available speed commands."
15999 (interactive)
16000 (if (not org-use-speed-commands)
16001 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
16002 (with-output-to-temp-buffer "*Help*"
16003 (princ "User-defined Speed commands\n===========================\n")
16004 (mapc 'org-print-speed-command org-speed-commands-user)
16005 (princ "\n")
16006 (princ "Built-in Speed commands\n=======================\n")
16007 (mapc 'org-print-speed-command org-speed-commands-default))
16008 (with-current-buffer "*Help*"
16009 (setq truncate-lines t))))
16011 (defun org-speed-move-safe (cmd)
16012 "Execute CMD, but make sure that the cursor always ends up in a headline.
16013 If not, return to the original position and throw an error."
16014 (interactive)
16015 (let ((pos (point)))
16016 (call-interactively cmd)
16017 (unless (and (bolp) (org-on-heading-p))
16018 (goto-char pos)
16019 (error "Boundary reached while executing %s" cmd))))
16021 (defvar org-self-insert-command-undo-counter 0)
16023 (defvar org-table-auto-blank-field) ; defined in org-table.el
16024 (defvar org-speed-command nil)
16025 (defun org-self-insert-command (N)
16026 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16027 If the cursor is in a table looking at whitespace, the whitespace is
16028 overwritten, and the table is not marked as requiring realignment."
16029 (interactive "p")
16030 (cond
16031 ((and org-use-speed-commands
16032 (or (and (bolp) (looking-at outline-regexp))
16033 (and (functionp org-use-speed-commands)
16034 (funcall org-use-speed-commands)))
16035 (setq
16036 org-speed-command
16037 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16038 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16039 (cond
16040 ((commandp org-speed-command)
16041 (setq this-command org-speed-command)
16042 (call-interactively org-speed-command))
16043 ((functionp org-speed-command)
16044 (funcall org-speed-command))
16045 ((and org-speed-command (listp org-speed-command))
16046 (eval org-speed-command))
16047 (t (let (org-use-speed-commands)
16048 (call-interactively 'org-self-insert-command)))))
16049 ((and
16050 (org-table-p)
16051 (progn
16052 ;; check if we blank the field, and if that triggers align
16053 (and (featurep 'org-table) org-table-auto-blank-field
16054 (member last-command
16055 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16056 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16057 ;; got extra space, this field does not determine column width
16058 (let (org-table-may-need-update) (org-table-blank-field))
16059 ;; no extra space, this field may determine column width
16060 (org-table-blank-field)))
16062 (eq N 1)
16063 (looking-at "[^|\n]* |"))
16064 (let (org-table-may-need-update)
16065 (goto-char (1- (match-end 0)))
16066 (delete-backward-char 1)
16067 (goto-char (match-beginning 0))
16068 (self-insert-command N)))
16070 (setq org-table-may-need-update t)
16071 (self-insert-command N)
16072 (org-fix-tags-on-the-fly)
16073 (if org-self-insert-cluster-for-undo
16074 (if (not (eq last-command 'org-self-insert-command))
16075 (setq org-self-insert-command-undo-counter 1)
16076 (if (>= org-self-insert-command-undo-counter 20)
16077 (setq org-self-insert-command-undo-counter 1)
16078 (and (> org-self-insert-command-undo-counter 0)
16079 buffer-undo-list
16080 (not (cadr buffer-undo-list)) ; remove nil entry
16081 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16082 (setq org-self-insert-command-undo-counter
16083 (1+ org-self-insert-command-undo-counter))))))))
16085 (defun org-fix-tags-on-the-fly ()
16086 (when (and (equal (char-after (point-at-bol)) ?*)
16087 (org-on-heading-p))
16088 (org-align-tags-here org-tags-column)))
16090 (defun org-delete-backward-char (N)
16091 "Like `delete-backward-char', insert whitespace at field end in tables.
16092 When deleting backwards, in tables this function will insert whitespace in
16093 front of the next \"|\" separator, to keep the table aligned. The table will
16094 still be marked for re-alignment if the field did fill the entire column,
16095 because, in this case the deletion might narrow the column."
16096 (interactive "p")
16097 (if (and (org-table-p)
16098 (eq N 1)
16099 (string-match "|" (buffer-substring (point-at-bol) (point)))
16100 (looking-at ".*?|"))
16101 (let ((pos (point))
16102 (noalign (looking-at "[^|\n\r]* |"))
16103 (c org-table-may-need-update))
16104 (backward-delete-char N)
16105 (skip-chars-forward "^|")
16106 (insert " ")
16107 (goto-char (1- pos))
16108 ;; noalign: if there were two spaces at the end, this field
16109 ;; does not determine the width of the column.
16110 (if noalign (setq org-table-may-need-update c)))
16111 (backward-delete-char N)
16112 (org-fix-tags-on-the-fly)))
16114 (defun org-delete-char (N)
16115 "Like `delete-char', but insert whitespace at field end in tables.
16116 When deleting characters, in tables this function will insert whitespace in
16117 front of the next \"|\" separator, to keep the table aligned. The table will
16118 still be marked for re-alignment if the field did fill the entire column,
16119 because, in this case the deletion might narrow the column."
16120 (interactive "p")
16121 (if (and (org-table-p)
16122 (not (bolp))
16123 (not (= (char-after) ?|))
16124 (eq N 1))
16125 (if (looking-at ".*?|")
16126 (let ((pos (point))
16127 (noalign (looking-at "[^|\n\r]* |"))
16128 (c org-table-may-need-update))
16129 (replace-match (concat
16130 (substring (match-string 0) 1 -1)
16131 " |"))
16132 (goto-char pos)
16133 ;; noalign: if there were two spaces at the end, this field
16134 ;; does not determine the width of the column.
16135 (if noalign (setq org-table-may-need-update c)))
16136 (delete-char N))
16137 (delete-char N)
16138 (org-fix-tags-on-the-fly)))
16140 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16141 (put 'org-self-insert-command 'delete-selection t)
16142 (put 'orgtbl-self-insert-command 'delete-selection t)
16143 (put 'org-delete-char 'delete-selection 'supersede)
16144 (put 'org-delete-backward-char 'delete-selection 'supersede)
16145 (put 'org-yank 'delete-selection 'yank)
16147 ;; Make `flyspell-mode' delay after some commands
16148 (put 'org-self-insert-command 'flyspell-delayed t)
16149 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16150 (put 'org-delete-char 'flyspell-delayed t)
16151 (put 'org-delete-backward-char 'flyspell-delayed t)
16153 ;; Make pabbrev-mode expand after org-mode commands
16154 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16155 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16157 ;; How to do this: Measure non-white length of current string
16158 ;; If equal to column width, we should realign.
16160 (defun org-remap (map &rest commands)
16161 "In MAP, remap the functions given in COMMANDS.
16162 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16163 (let (new old)
16164 (while commands
16165 (setq old (pop commands) new (pop commands))
16166 (if (fboundp 'command-remapping)
16167 (org-defkey map (vector 'remap old) new)
16168 (substitute-key-definition old new map global-map)))))
16170 (when (eq org-enable-table-editor 'optimized)
16171 ;; If the user wants maximum table support, we need to hijack
16172 ;; some standard editing functions
16173 (org-remap org-mode-map
16174 'self-insert-command 'org-self-insert-command
16175 'delete-char 'org-delete-char
16176 'delete-backward-char 'org-delete-backward-char)
16177 (org-defkey org-mode-map "|" 'org-force-self-insert))
16179 (defvar org-ctrl-c-ctrl-c-hook nil
16180 "Hook for functions attaching themselves to `C-c C-c'.
16181 This can be used to add additional functionality to the C-c C-c key which
16182 executes context-dependent commands.
16183 Each function will be called with no arguments. The function must check
16184 if the context is appropriate for it to act. If yes, it should do its
16185 thing and then return a non-nil value. If the context is wrong,
16186 just do nothing and return nil.")
16188 (defvar org-tab-first-hook nil
16189 "Hook for functions to attach themselves to TAB.
16190 See `org-ctrl-c-ctrl-c-hook' for more information.
16191 This hook runs as the first action when TAB is pressed, even before
16192 `org-cycle' messes around with the `outline-regexp' to cater for
16193 inline tasks and plain list item folding.
16194 If any function in this hook returns t, any other actions that
16195 would have been caused by TAB (such as table field motion or visibility
16196 cycling) will not occur.")
16198 (defvar org-tab-after-check-for-table-hook nil
16199 "Hook for functions to attach themselves to TAB.
16200 See `org-ctrl-c-ctrl-c-hook' for more information.
16201 This hook runs after it has been established that the cursor is not in a
16202 table, but before checking if the cursor is in a headline or if global cycling
16203 should be done.
16204 If any function in this hook returns t, not other actions like visibility
16205 cycling will be done.")
16207 (defvar org-tab-after-check-for-cycling-hook nil
16208 "Hook for functions to attach themselves to TAB.
16209 See `org-ctrl-c-ctrl-c-hook' for more information.
16210 This hook runs after it has been established that not table field motion and
16211 not visibility should be done because of current context. This is probably
16212 the place where a package like yasnippets can hook in.")
16214 (defvar org-tab-before-tab-emulation-hook nil
16215 "Hook for functions to attach themselves to TAB.
16216 See `org-ctrl-c-ctrl-c-hook' for more information.
16217 This hook runs after every other options for TAB have been exhausted, but
16218 before indentation and \t insertion takes place.")
16220 (defvar org-metaleft-hook nil
16221 "Hook for functions attaching themselves to `M-left'.
16222 See `org-ctrl-c-ctrl-c-hook' for more information.")
16223 (defvar org-metaright-hook nil
16224 "Hook for functions attaching themselves to `M-right'.
16225 See `org-ctrl-c-ctrl-c-hook' for more information.")
16226 (defvar org-metaup-hook nil
16227 "Hook for functions attaching themselves to `M-up'.
16228 See `org-ctrl-c-ctrl-c-hook' for more information.")
16229 (defvar org-metadown-hook nil
16230 "Hook for functions attaching themselves to `M-down'.
16231 See `org-ctrl-c-ctrl-c-hook' for more information.")
16232 (defvar org-shiftmetaleft-hook nil
16233 "Hook for functions attaching themselves to `M-S-left'.
16234 See `org-ctrl-c-ctrl-c-hook' for more information.")
16235 (defvar org-shiftmetaright-hook nil
16236 "Hook for functions attaching themselves to `M-S-right'.
16237 See `org-ctrl-c-ctrl-c-hook' for more information.")
16238 (defvar org-shiftmetaup-hook nil
16239 "Hook for functions attaching themselves to `M-S-up'.
16240 See `org-ctrl-c-ctrl-c-hook' for more information.")
16241 (defvar org-shiftmetadown-hook nil
16242 "Hook for functions attaching themselves to `M-S-down'.
16243 See `org-ctrl-c-ctrl-c-hook' for more information.")
16244 (defvar org-metareturn-hook nil
16245 "Hook for functions attaching themselves to `M-RET'.
16246 See `org-ctrl-c-ctrl-c-hook' for more information.")
16247 (defvar org-shiftup-hook nil
16248 "Hook for functions attaching themselves to `S-up'.
16249 See `org-ctrl-c-ctrl-c-hook' for more information.")
16250 (defvar org-shiftup-final-hook nil
16251 "Hook for functions attaching themselves to `S-up'.
16252 This one runs after all other options except shift-select have been excluded.
16253 See `org-ctrl-c-ctrl-c-hook' for more information.")
16254 (defvar org-shiftdown-hook nil
16255 "Hook for functions attaching themselves to `S-down'.
16256 See `org-ctrl-c-ctrl-c-hook' for more information.")
16257 (defvar org-shiftdown-final-hook nil
16258 "Hook for functions attaching themselves to `S-down'.
16259 This one runs after all other options except shift-select have been excluded.
16260 See `org-ctrl-c-ctrl-c-hook' for more information.")
16261 (defvar org-shiftleft-hook nil
16262 "Hook for functions attaching themselves to `S-left'.
16263 See `org-ctrl-c-ctrl-c-hook' for more information.")
16264 (defvar org-shiftleft-final-hook nil
16265 "Hook for functions attaching themselves to `S-left'.
16266 This one runs after all other options except shift-select have been excluded.
16267 See `org-ctrl-c-ctrl-c-hook' for more information.")
16268 (defvar org-shiftright-hook nil
16269 "Hook for functions attaching themselves to `S-right'.
16270 See `org-ctrl-c-ctrl-c-hook' for more information.")
16271 (defvar org-shiftright-final-hook nil
16272 "Hook for functions attaching themselves to `S-right'.
16273 This one runs after all other options except shift-select have been excluded.
16274 See `org-ctrl-c-ctrl-c-hook' for more information.")
16276 (defun org-modifier-cursor-error ()
16277 "Throw an error, a modified cursor command was applied in wrong context."
16278 (error "This command is active in special context like tables, headlines or items"))
16280 (defun org-shiftselect-error ()
16281 "Throw an error because Shift-Cursor command was applied in wrong context."
16282 (if (and (boundp 'shift-select-mode) shift-select-mode)
16283 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16284 (error "This command works only in special context like headlines or timestamps")))
16286 (defun org-call-for-shift-select (cmd)
16287 (let ((this-command-keys-shift-translated t))
16288 (call-interactively cmd)))
16290 (defun org-shifttab (&optional arg)
16291 "Global visibility cycling or move to previous table field.
16292 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16293 on context.
16294 See the individual commands for more information."
16295 (interactive "P")
16296 (cond
16297 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16298 ((integerp arg)
16299 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16300 (message "Content view to level: %d" arg)
16301 (org-content (prefix-numeric-value arg2))
16302 (setq org-cycle-global-status 'overview)))
16303 (t (call-interactively 'org-global-cycle))))
16305 (defun org-shiftmetaleft ()
16306 "Promote subtree or delete table column.
16307 Calls `org-promote-subtree', `org-outdent-item',
16308 or `org-table-delete-column', depending on context.
16309 See the individual commands for more information."
16310 (interactive)
16311 (cond
16312 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16313 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16314 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16315 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16316 (t (org-modifier-cursor-error))))
16318 (defun org-shiftmetaright ()
16319 "Demote subtree or insert table column.
16320 Calls `org-demote-subtree', `org-indent-item',
16321 or `org-table-insert-column', depending on context.
16322 See the individual commands for more information."
16323 (interactive)
16324 (cond
16325 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16326 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16327 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16328 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16329 (t (org-modifier-cursor-error))))
16331 (defun org-shiftmetaup (&optional arg)
16332 "Move subtree up or kill table row.
16333 Calls `org-move-subtree-up' or `org-table-kill-row' or
16334 `org-move-item-up' depending on context. See the individual commands
16335 for more information."
16336 (interactive "P")
16337 (cond
16338 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16339 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16340 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16341 ((org-at-item-p) (call-interactively 'org-move-item-up))
16342 (t (org-modifier-cursor-error))))
16344 (defun org-shiftmetadown (&optional arg)
16345 "Move subtree down or insert table row.
16346 Calls `org-move-subtree-down' or `org-table-insert-row' or
16347 `org-move-item-down', depending on context. See the individual
16348 commands for more information."
16349 (interactive "P")
16350 (cond
16351 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16352 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16353 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16354 ((org-at-item-p) (call-interactively 'org-move-item-down))
16355 (t (org-modifier-cursor-error))))
16357 (defsubst org-hidden-tree-error ()
16358 (error
16359 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16361 (defun org-metaleft (&optional arg)
16362 "Promote heading or move table column to left.
16363 Calls `org-do-promote' or `org-table-move-column', depending on context.
16364 With no specific context, calls the Emacs default `backward-word'.
16365 See the individual commands for more information."
16366 (interactive "P")
16367 (cond
16368 ((run-hook-with-args-until-success 'org-metaleft-hook))
16369 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16370 ((or (org-on-heading-p)
16371 (and (org-region-active-p)
16372 (save-excursion
16373 (goto-char (region-beginning))
16374 (org-on-heading-p))))
16375 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16376 (call-interactively 'org-do-promote))
16377 ((or (org-at-item-p)
16378 (and (org-region-active-p)
16379 (save-excursion
16380 (goto-char (region-beginning))
16381 (org-at-item-p))))
16382 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16383 (call-interactively 'org-outdent-item))
16384 (t (call-interactively 'backward-word))))
16386 (defun org-metaright (&optional arg)
16387 "Demote subtree or move table column to right.
16388 Calls `org-do-demote' or `org-table-move-column', depending on context.
16389 With no specific context, calls the Emacs default `forward-word'.
16390 See the individual commands for more information."
16391 (interactive "P")
16392 (cond
16393 ((run-hook-with-args-until-success 'org-metaright-hook))
16394 ((org-at-table-p) (call-interactively 'org-table-move-column))
16395 ((or (org-on-heading-p)
16396 (and (org-region-active-p)
16397 (save-excursion
16398 (goto-char (region-beginning))
16399 (org-on-heading-p))))
16400 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16401 (call-interactively 'org-do-demote))
16402 ((or (org-at-item-p)
16403 (and (org-region-active-p)
16404 (save-excursion
16405 (goto-char (region-beginning))
16406 (org-at-item-p))))
16407 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16408 (call-interactively 'org-indent-item))
16409 (t (call-interactively 'forward-word))))
16411 (defun org-check-for-hidden (what)
16412 "Check if there are hidden headlines/items in the current visual line.
16413 WHAT can be either `headlines' or `items'. If the current line is
16414 an outline or item heading and it has a folded subtree below it,
16415 this fucntion returns t, nil otherwise."
16416 (let ((re (cond
16417 ((eq what 'headlines) (concat "^" org-outline-regexp))
16418 ((eq what 'items) (concat "^" (org-item-re t)))
16419 (t (error "This should not happen"))))
16420 beg end)
16421 (save-excursion
16422 (catch 'exit
16423 (unless (org-region-active-p)
16424 (setq beg (point-at-bol))
16425 (beginning-of-line 2)
16426 (while (and (not (eobp)) ;; this is like `next-line'
16427 (get-char-property (1- (point)) 'invisible))
16428 (beginning-of-line 2))
16429 (setq end (point))
16430 (goto-char beg)
16431 (goto-char (point-at-eol))
16432 (setq end (max end (point)))
16433 (while (re-search-forward re end t)
16434 (if (get-char-property (match-beginning 0) 'invisible)
16435 (throw 'exit t))))
16436 nil))))
16438 (defun org-metaup (&optional arg)
16439 "Move subtree up or move table row up.
16440 Calls `org-move-subtree-up' or `org-table-move-row' or
16441 `org-move-item-up', depending on context. See the individual commands
16442 for more information."
16443 (interactive "P")
16444 (cond
16445 ((run-hook-with-args-until-success 'org-metaup-hook))
16446 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16447 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16448 ((org-at-item-p) (call-interactively 'org-move-item-up))
16449 (t (transpose-lines 1) (beginning-of-line -1))))
16451 (defun org-metadown (&optional arg)
16452 "Move subtree down or move table row down.
16453 Calls `org-move-subtree-down' or `org-table-move-row' or
16454 `org-move-item-down', depending on context. See the individual
16455 commands for more information."
16456 (interactive "P")
16457 (cond
16458 ((run-hook-with-args-until-success 'org-metadown-hook))
16459 ((org-at-table-p) (call-interactively 'org-table-move-row))
16460 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16461 ((org-at-item-p) (call-interactively 'org-move-item-down))
16462 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16464 (defun org-shiftup (&optional arg)
16465 "Increase item in timestamp or increase priority of current headline.
16466 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16467 depending on context. See the individual commands for more information."
16468 (interactive "P")
16469 (cond
16470 ((run-hook-with-args-until-success 'org-shiftup-hook))
16471 ((and org-support-shift-select (org-region-active-p))
16472 (org-call-for-shift-select 'previous-line))
16473 ((org-at-timestamp-p t)
16474 (call-interactively (if org-edit-timestamp-down-means-later
16475 'org-timestamp-down 'org-timestamp-up)))
16476 ((and (not (eq org-support-shift-select 'always))
16477 org-enable-priority-commands
16478 (org-on-heading-p))
16479 (call-interactively 'org-priority-up))
16480 ((and (not org-support-shift-select) (org-at-item-p))
16481 (call-interactively 'org-previous-item))
16482 ((org-clocktable-try-shift 'up arg))
16483 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16484 (org-support-shift-select
16485 (org-call-for-shift-select 'previous-line))
16486 (t (org-shiftselect-error))))
16488 (defun org-shiftdown (&optional arg)
16489 "Decrease item in timestamp or decrease priority of current headline.
16490 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16491 depending on context. See the individual commands for more information."
16492 (interactive "P")
16493 (cond
16494 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16495 ((and org-support-shift-select (org-region-active-p))
16496 (org-call-for-shift-select 'next-line))
16497 ((org-at-timestamp-p t)
16498 (call-interactively (if org-edit-timestamp-down-means-later
16499 'org-timestamp-up 'org-timestamp-down)))
16500 ((and (not (eq org-support-shift-select 'always))
16501 org-enable-priority-commands
16502 (org-on-heading-p))
16503 (call-interactively 'org-priority-down))
16504 ((and (not org-support-shift-select) (org-at-item-p))
16505 (call-interactively 'org-next-item))
16506 ((org-clocktable-try-shift 'down arg))
16507 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16508 (org-support-shift-select
16509 (org-call-for-shift-select 'next-line))
16510 (t (org-shiftselect-error))))
16512 (defun org-shiftright (&optional arg)
16513 "Cycle the thing at point or in the current line, depending on context.
16514 Depending on context, this does one of the following:
16516 - switch a timestamp at point one day into the future
16517 - on a headline, switch to the next TODO keyword.
16518 - on an item, switch entire list to the next bullet type
16519 - on a property line, switch to the next allowed value
16520 - on a clocktable definition line, move time block into the future"
16521 (interactive "P")
16522 (cond
16523 ((run-hook-with-args-until-success 'org-shiftright-hook))
16524 ((and org-support-shift-select (org-region-active-p))
16525 (org-call-for-shift-select 'forward-char))
16526 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16527 ((and (not (eq org-support-shift-select 'always))
16528 (org-on-heading-p))
16529 (let ((org-inhibit-logging
16530 (not org-treat-S-cursor-todo-selection-as-state-change))
16531 (org-inhibit-blocking
16532 (not org-treat-S-cursor-todo-selection-as-state-change)))
16533 (org-call-with-arg 'org-todo 'right)))
16534 ((or (and org-support-shift-select
16535 (not (eq org-support-shift-select 'always))
16536 (org-at-item-bullet-p))
16537 (and (not org-support-shift-select) (org-at-item-p)))
16538 (org-call-with-arg 'org-cycle-list-bullet nil))
16539 ((and (not (eq org-support-shift-select 'always))
16540 (org-at-property-p))
16541 (call-interactively 'org-property-next-allowed-value))
16542 ((org-clocktable-try-shift 'right arg))
16543 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16544 (org-support-shift-select
16545 (org-call-for-shift-select 'forward-char))
16546 (t (org-shiftselect-error))))
16548 (defun org-shiftleft (&optional arg)
16549 "Cycle the thing at point or in the current line, depending on context.
16550 Depending on context, this does one of the following:
16552 - switch a timestamp at point one day into the past
16553 - on a headline, switch to the previous TODO keyword.
16554 - on an item, switch entire list to the previous bullet type
16555 - on a property line, switch to the previous allowed value
16556 - on a clocktable definition line, move time block into the past"
16557 (interactive "P")
16558 (cond
16559 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16560 ((and org-support-shift-select (org-region-active-p))
16561 (org-call-for-shift-select 'backward-char))
16562 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16563 ((and (not (eq org-support-shift-select 'always))
16564 (org-on-heading-p))
16565 (let ((org-inhibit-logging
16566 (not org-treat-S-cursor-todo-selection-as-state-change))
16567 (org-inhibit-blocking
16568 (not org-treat-S-cursor-todo-selection-as-state-change)))
16569 (org-call-with-arg 'org-todo 'left)))
16570 ((or (and org-support-shift-select
16571 (not (eq org-support-shift-select 'always))
16572 (org-at-item-bullet-p))
16573 (and (not org-support-shift-select) (org-at-item-p)))
16574 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16575 ((and (not (eq org-support-shift-select 'always))
16576 (org-at-property-p))
16577 (call-interactively 'org-property-previous-allowed-value))
16578 ((org-clocktable-try-shift 'left arg))
16579 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16580 (org-support-shift-select
16581 (org-call-for-shift-select 'backward-char))
16582 (t (org-shiftselect-error))))
16584 (defun org-shiftcontrolright ()
16585 "Switch to next TODO set."
16586 (interactive)
16587 (cond
16588 ((and org-support-shift-select (org-region-active-p))
16589 (org-call-for-shift-select 'forward-word))
16590 ((and (not (eq org-support-shift-select 'always))
16591 (org-on-heading-p))
16592 (org-call-with-arg 'org-todo 'nextset))
16593 (org-support-shift-select
16594 (org-call-for-shift-select 'forward-word))
16595 (t (org-shiftselect-error))))
16597 (defun org-shiftcontrolleft ()
16598 "Switch to previous TODO set."
16599 (interactive)
16600 (cond
16601 ((and org-support-shift-select (org-region-active-p))
16602 (org-call-for-shift-select 'backward-word))
16603 ((and (not (eq org-support-shift-select 'always))
16604 (org-on-heading-p))
16605 (org-call-with-arg 'org-todo 'previousset))
16606 (org-support-shift-select
16607 (org-call-for-shift-select 'backward-word))
16608 (t (org-shiftselect-error))))
16610 (defun org-ctrl-c-ret ()
16611 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16612 (interactive)
16613 (cond
16614 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16615 (t (call-interactively 'org-insert-heading))))
16617 (defun org-copy-special ()
16618 "Copy region in table or copy current subtree.
16619 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16620 See the individual commands for more information."
16621 (interactive)
16622 (call-interactively
16623 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16625 (defun org-cut-special ()
16626 "Cut region in table or cut current subtree.
16627 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16628 See the individual commands for more information."
16629 (interactive)
16630 (call-interactively
16631 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16633 (defun org-paste-special (arg)
16634 "Paste rectangular region into table, or past subtree relative to level.
16635 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16636 See the individual commands for more information."
16637 (interactive "P")
16638 (if (org-at-table-p)
16639 (org-table-paste-rectangle)
16640 (org-paste-subtree arg)))
16642 (defun org-edit-special ()
16643 "Call a special editor for the stuff at point.
16644 When at a table, call the formula editor with `org-table-edit-formulas'.
16645 When at the first line of an src example, call `org-edit-src-code'.
16646 When in an #+include line, visit the include file. Otherwise call
16647 `ffap' to visit the file at point."
16648 (interactive)
16649 (cond
16650 ((org-at-table.el-p)
16651 (org-edit-src-code))
16652 ((org-at-table-p)
16653 (call-interactively 'org-table-edit-formulas))
16654 ((save-excursion
16655 (beginning-of-line 1)
16656 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16657 (find-file (org-trim (match-string 1))))
16658 ((org-edit-src-code))
16659 ((org-edit-fixed-width-region))
16660 (t (call-interactively 'ffap))))
16663 (defun org-ctrl-c-ctrl-c (&optional arg)
16664 "Set tags in headline, or update according to changed information at point.
16666 This command does many different things, depending on context:
16668 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16669 this is what we do.
16671 - If the cursor is on a statistics cookie, update it.
16673 - If the cursor is in a headline, prompt for tags and insert them
16674 into the current line, aligned to `org-tags-column'. When called
16675 with prefix arg, realign all tags in the current buffer.
16677 - If the cursor is in one of the special #+KEYWORD lines, this
16678 triggers scanning the buffer for these lines and updating the
16679 information.
16681 - If the cursor is inside a table, realign the table. This command
16682 works even if the automatic table editor has been turned off.
16684 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16685 the entire table.
16687 - If the cursor is at a footnote reference or definition, jump to
16688 the corresponding definition or references, respectively.
16690 - If the cursor is a the beginning of a dynamic block, update it.
16692 - If the current buffer is a remember buffer, close note and file
16693 it. A prefix argument of 1 files to the default location
16694 without further interaction. A prefix argument of 2 files to
16695 the currently clocking task.
16697 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16698 links in this buffer.
16700 - If the cursor is on a numbered item in a plain list, renumber the
16701 ordered list.
16703 - If the cursor is on a checkbox, toggle it."
16704 (interactive "P")
16705 (let ((org-enable-table-editor t))
16706 (cond
16707 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16708 org-occur-highlights
16709 org-latex-fragment-image-overlays)
16710 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16711 (org-remove-occur-highlights)
16712 (org-remove-latex-fragment-image-overlays)
16713 (message "Temporary highlights/overlays removed from current buffer"))
16714 ((and (local-variable-p 'org-finish-function (current-buffer))
16715 (fboundp org-finish-function))
16716 (funcall org-finish-function))
16717 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16718 ((or (looking-at org-property-start-re)
16719 (org-at-property-p))
16720 (call-interactively 'org-property-action))
16721 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16722 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16723 (or (org-on-heading-p) (org-at-item-p)))
16724 (call-interactively 'org-update-statistics-cookies))
16725 ((org-on-heading-p) (call-interactively 'org-set-tags))
16726 ((org-at-table.el-p)
16727 (message "Use C-c ' to edit table.el tables"))
16728 ((org-at-table-p)
16729 (org-table-maybe-eval-formula)
16730 (if arg
16731 (call-interactively 'org-table-recalculate)
16732 (org-table-maybe-recalculate-line))
16733 (call-interactively 'org-table-align))
16734 ((or (org-footnote-at-reference-p)
16735 (org-footnote-at-definition-p))
16736 (call-interactively 'org-footnote-action))
16737 ((org-at-item-checkbox-p)
16738 (call-interactively 'org-toggle-checkbox))
16739 ((org-at-item-p)
16740 (if arg
16741 (call-interactively 'org-toggle-checkbox)
16742 (call-interactively 'org-maybe-renumber-ordered-list)))
16743 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16744 ;; Dynamic block
16745 (beginning-of-line 1)
16746 (save-excursion (org-update-dblock)))
16747 ((save-excursion
16748 (beginning-of-line 1)
16749 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16750 (cond
16751 ((equal (match-string 1) "TBLFM")
16752 ;; Recalculate the table before this line
16753 (save-excursion
16754 (beginning-of-line 1)
16755 (skip-chars-backward " \r\n\t")
16756 (if (org-at-table-p)
16757 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16759 (let ((org-inhibit-startup-visibility-stuff t)
16760 (org-startup-align-all-tables nil))
16761 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16762 (message "Local setup has been refreshed"))))
16763 ((org-clock-update-time-maybe))
16764 (t (error "C-c C-c can do nothing useful at this location")))))
16766 (defun org-mode-restart ()
16767 "Restart Org-mode, to scan again for special lines.
16768 Also updates the keyword regular expressions."
16769 (interactive)
16770 (org-mode)
16771 (message "Org-mode restarted"))
16773 (defun org-kill-note-or-show-branches ()
16774 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16775 (interactive)
16776 (if (not org-finish-function)
16777 (progn
16778 (hide-subtree)
16779 (call-interactively 'show-branches))
16780 (let ((org-note-abort t))
16781 (funcall org-finish-function))))
16783 (defun org-return (&optional indent)
16784 "Goto next table row or insert a newline.
16785 Calls `org-table-next-row' or `newline', depending on context.
16786 See the individual commands for more information."
16787 (interactive)
16788 (cond
16789 ((bobp) (if indent (newline-and-indent) (newline)))
16790 ((org-at-table-p)
16791 (org-table-justify-field-maybe)
16792 (call-interactively 'org-table-next-row))
16793 ((and org-return-follows-link
16794 (eq (get-text-property (point) 'face) 'org-link))
16795 (call-interactively 'org-open-at-point))
16796 ((and (org-at-heading-p)
16797 (looking-at
16798 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16799 (org-show-entry)
16800 (end-of-line 1)
16801 (newline))
16802 (t (if indent (newline-and-indent) (newline)))))
16804 (defun org-return-indent ()
16805 "Goto next table row or insert a newline and indent.
16806 Calls `org-table-next-row' or `newline-and-indent', depending on
16807 context. See the individual commands for more information."
16808 (interactive)
16809 (org-return t))
16811 (defun org-ctrl-c-star ()
16812 "Compute table, or change heading status of lines.
16813 Calls `org-table-recalculate' or `org-toggle-heading',
16814 depending on context."
16815 (interactive)
16816 (cond
16817 ((org-at-table-p)
16818 (call-interactively 'org-table-recalculate))
16820 ;; Convert all lines in region to list items
16821 (call-interactively 'org-toggle-heading))))
16823 (defun org-ctrl-c-minus ()
16824 "Insert separator line in table or modify bullet status of line.
16825 Also turns a plain line or a region of lines into list items.
16826 Calls `org-table-insert-hline', `org-toggle-item', or
16827 `org-cycle-list-bullet', depending on context."
16828 (interactive)
16829 (cond
16830 ((org-at-table-p)
16831 (call-interactively 'org-table-insert-hline))
16832 ((org-region-active-p)
16833 (call-interactively 'org-toggle-item))
16834 ((org-in-item-p)
16835 (call-interactively 'org-cycle-list-bullet))
16837 (call-interactively 'org-toggle-item))))
16839 (defun org-toggle-item ()
16840 "Convert headings or normal lines to items, items to normal lines.
16841 If there is no active region, only the current line is considered.
16843 If the first line in the region is a headline, convert all headlines to items.
16845 If the first line in the region is an item, convert all items to normal lines.
16847 If the first line is normal text, add an item bullet to each line."
16848 (interactive)
16849 (let (l2 l beg end)
16850 (if (org-region-active-p)
16851 (setq beg (region-beginning) end (region-end))
16852 (setq beg (point-at-bol)
16853 end (min (1+ (point-at-eol)) (point-max))))
16854 (save-excursion
16855 (goto-char end)
16856 (setq l2 (org-current-line))
16857 (goto-char beg)
16858 (beginning-of-line 1)
16859 (setq l (1- (org-current-line)))
16860 (if (org-at-item-p)
16861 ;; We already have items, de-itemize
16862 (while (< (setq l (1+ l)) l2)
16863 (when (org-at-item-p)
16864 (goto-char (match-beginning 2))
16865 (delete-region (match-beginning 2) (match-end 2))
16866 (and (looking-at "[ \t]+") (replace-match "")))
16867 (beginning-of-line 2))
16868 (if (org-on-heading-p)
16869 ;; Headings, convert to items
16870 (while (< (setq l (1+ l)) l2)
16871 (if (looking-at org-outline-regexp)
16872 (replace-match "- " t t))
16873 (beginning-of-line 2))
16874 ;; normal lines, turn them into items
16875 (while (< (setq l (1+ l)) l2)
16876 (unless (org-at-item-p)
16877 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16878 (replace-match "\\1- \\2")))
16879 (beginning-of-line 2)))))))
16881 (defun org-toggle-heading (&optional nstars)
16882 "Convert headings to normal text, or items or text to headings.
16883 If there is no active region, only the current line is considered.
16885 If the first line is a heading, remove the stars from all headlines
16886 in the region.
16888 If the first line is a plain list item, turn all plain list items
16889 into headings.
16891 If the first line is a normal line, turn each and every line in the
16892 region into a heading.
16894 When converting a line into a heading, the number of stars is chosen
16895 such that the lines become children of the current entry. However,
16896 when a prefix argument is given, its value determines the number of
16897 stars to add."
16898 (interactive "P")
16899 (let (l2 l itemp beg end)
16900 (if (org-region-active-p)
16901 (setq beg (region-beginning) end (region-end))
16902 (setq beg (point-at-bol)
16903 end (min (1+ (point-at-eol)) (point-max))))
16904 (save-excursion
16905 (goto-char end)
16906 (setq l2 (org-current-line))
16907 (goto-char beg)
16908 (beginning-of-line 1)
16909 (setq l (1- (org-current-line)))
16910 (if (org-on-heading-p)
16911 ;; We already have headlines, de-star them
16912 (while (< (setq l (1+ l)) l2)
16913 (when (org-on-heading-p t)
16914 (and (looking-at outline-regexp) (replace-match "")))
16915 (beginning-of-line 2))
16916 (setq itemp (org-at-item-p))
16917 (let* ((stars
16918 (if nstars
16919 (make-string (prefix-numeric-value current-prefix-arg)
16921 (save-excursion
16922 (if (re-search-backward org-complex-heading-regexp nil t)
16923 (match-string 1) ""))))
16924 (add-stars (cond (nstars "")
16925 ((equal stars "") "*")
16926 (org-odd-levels-only "**")
16927 (t "*")))
16928 (rpl (concat stars add-stars " ")))
16929 (while (< (setq l (1+ l)) l2)
16930 (if itemp
16931 (and (org-at-item-p) (replace-match rpl t t))
16932 (unless (org-on-heading-p)
16933 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16934 (replace-match (concat rpl (match-string 2))))))
16935 (beginning-of-line 2)))))))
16937 (defun org-meta-return (&optional arg)
16938 "Insert a new heading or wrap a region in a table.
16939 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16940 See the individual commands for more information."
16941 (interactive "P")
16942 (cond
16943 ((run-hook-with-args-until-success 'org-metareturn-hook))
16944 ((org-at-table-p)
16945 (call-interactively 'org-table-wrap-region))
16946 (t (call-interactively 'org-insert-heading))))
16948 ;;; Menu entries
16950 ;; Define the Org-mode menus
16951 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16952 '("Tbl"
16953 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16954 ["Next Field" org-cycle (org-at-table-p)]
16955 ["Previous Field" org-shifttab (org-at-table-p)]
16956 ["Next Row" org-return (org-at-table-p)]
16957 "--"
16958 ["Blank Field" org-table-blank-field (org-at-table-p)]
16959 ["Edit Field" org-table-edit-field (org-at-table-p)]
16960 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16961 "--"
16962 ("Column"
16963 ["Move Column Left" org-metaleft (org-at-table-p)]
16964 ["Move Column Right" org-metaright (org-at-table-p)]
16965 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16966 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16967 ("Row"
16968 ["Move Row Up" org-metaup (org-at-table-p)]
16969 ["Move Row Down" org-metadown (org-at-table-p)]
16970 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16971 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16972 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16973 "--"
16974 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16975 ("Rectangle"
16976 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16977 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16978 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16979 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16980 "--"
16981 ("Calculate"
16982 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16983 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16984 ["Edit Formulas" org-edit-special (org-at-table-p)]
16985 "--"
16986 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16987 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16988 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16989 "--"
16990 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16991 "--"
16992 ["Sum Column/Rectangle" org-table-sum
16993 (or (org-at-table-p) (org-region-active-p))]
16994 ["Which Column?" org-table-current-column (org-at-table-p)])
16995 ["Debug Formulas"
16996 org-table-toggle-formula-debugger
16997 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16998 ["Show Col/Row Numbers"
16999 org-table-toggle-coordinate-overlays
17000 :style toggle
17001 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17002 "--"
17003 ["Create" org-table-create (and (not (org-at-table-p))
17004 org-enable-table-editor)]
17005 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17006 ["Import from File" org-table-import (not (org-at-table-p))]
17007 ["Export to File" org-table-export (org-at-table-p)]
17008 "--"
17009 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17011 (easy-menu-define org-org-menu org-mode-map "Org menu"
17012 '("Org"
17013 ("Show/Hide"
17014 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17015 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17016 ["Sparse Tree..." org-sparse-tree t]
17017 ["Reveal Context" org-reveal t]
17018 ["Show All" show-all t]
17019 "--"
17020 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17021 "--"
17022 ["New Heading" org-insert-heading t]
17023 ("Navigate Headings"
17024 ["Up" outline-up-heading t]
17025 ["Next" outline-next-visible-heading t]
17026 ["Previous" outline-previous-visible-heading t]
17027 ["Next Same Level" outline-forward-same-level t]
17028 ["Previous Same Level" outline-backward-same-level t]
17029 "--"
17030 ["Jump" org-goto t])
17031 ("Edit Structure"
17032 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17033 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17034 "--"
17035 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17036 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17037 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17038 "--"
17039 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17040 "--"
17041 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17042 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17043 ["Demote Heading" org-metaright (not (org-at-table-p))]
17044 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17045 "--"
17046 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17047 "--"
17048 ["Convert to odd levels" org-convert-to-odd-levels t]
17049 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17050 ("Editing"
17051 ["Emphasis..." org-emphasize t]
17052 ["Edit Source Example" org-edit-special t]
17053 "--"
17054 ["Footnote new/jump" org-footnote-action t]
17055 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17056 ("Archive"
17057 ["Archive (default method)" org-archive-subtree-default t]
17058 "--"
17059 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17060 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17061 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17063 "--"
17064 ("Hyperlinks"
17065 ["Store Link (Global)" org-store-link t]
17066 ["Find existing link to here" org-occur-link-in-agenda-files t]
17067 ["Insert Link" org-insert-link t]
17068 ["Follow Link" org-open-at-point t]
17069 "--"
17070 ["Next link" org-next-link t]
17071 ["Previous link" org-previous-link t]
17072 "--"
17073 ["Descriptive Links"
17074 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17075 :style radio
17076 :selected (member '(org-link) buffer-invisibility-spec)]
17077 ["Literal Links"
17078 (progn
17079 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17080 :style radio
17081 :selected (not (member '(org-link) buffer-invisibility-spec))])
17082 "--"
17083 ("TODO Lists"
17084 ["TODO/DONE/-" org-todo t]
17085 ("Select keyword"
17086 ["Next keyword" org-shiftright (org-on-heading-p)]
17087 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17088 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17089 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17090 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17091 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17092 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17093 "--"
17094 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17095 :selected org-enforce-todo-dependencies :style toggle :active t]
17096 "Settings for tree at point"
17097 ["Do Children sequentially" org-toggle-ordered-property :style radio
17098 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17099 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17100 ["Do Children parallel" org-toggle-ordered-property :style radio
17101 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17102 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17103 "--"
17104 ["Set Priority" org-priority t]
17105 ["Priority Up" org-shiftup t]
17106 ["Priority Down" org-shiftdown t]
17107 "--"
17108 ["Get news from all feeds" org-feed-update-all t]
17109 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17110 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17111 ("TAGS and Properties"
17112 ["Set Tags" org-set-tags-command t]
17113 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17114 "--"
17115 ["Set property" org-set-property t]
17116 ["Column view of properties" org-columns t]
17117 ["Insert Column View DBlock" org-insert-columns-dblock t])
17118 ("Dates and Scheduling"
17119 ["Timestamp" org-time-stamp t]
17120 ["Timestamp (inactive)" org-time-stamp-inactive t]
17121 ("Change Date"
17122 ["1 Day Later" org-shiftright t]
17123 ["1 Day Earlier" org-shiftleft t]
17124 ["1 ... Later" org-shiftup t]
17125 ["1 ... Earlier" org-shiftdown t])
17126 ["Compute Time Range" org-evaluate-time-range t]
17127 ["Schedule Item" org-schedule t]
17128 ["Deadline" org-deadline t]
17129 "--"
17130 ["Custom time format" org-toggle-time-stamp-overlays
17131 :style radio :selected org-display-custom-times]
17132 "--"
17133 ["Goto Calendar" org-goto-calendar t]
17134 ["Date from Calendar" org-date-from-calendar t]
17135 "--"
17136 ["Start/Restart Timer" org-timer-start t]
17137 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17138 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17139 ["Insert Timer String" org-timer t]
17140 ["Insert Timer Item" org-timer-item t])
17141 ("Logging work"
17142 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17143 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17144 ["Clock out" org-clock-out t]
17145 ["Clock cancel" org-clock-cancel t]
17146 "--"
17147 ["Mark as default task" org-clock-mark-default-task t]
17148 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17149 ["Goto running clock" org-clock-goto t]
17150 "--"
17151 ["Display times" org-clock-display t]
17152 ["Create clock table" org-clock-report t]
17153 "--"
17154 ["Record DONE time"
17155 (progn (setq org-log-done (not org-log-done))
17156 (message "Switching to %s will %s record a timestamp"
17157 (car org-done-keywords)
17158 (if org-log-done "automatically" "not")))
17159 :style toggle :selected org-log-done])
17160 "--"
17161 ["Agenda Command..." org-agenda t]
17162 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17163 ("File List for Agenda")
17164 ("Special views current file"
17165 ["TODO Tree" org-show-todo-tree t]
17166 ["Check Deadlines" org-check-deadlines t]
17167 ["Timeline" org-timeline t]
17168 ["Tags/Property tree" org-match-sparse-tree t])
17169 "--"
17170 ["Export/Publish..." org-export t]
17171 ("LaTeX"
17172 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17173 :selected org-cdlatex-mode]
17174 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17175 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17176 ["Modify math symbol" org-cdlatex-math-modify
17177 (org-inside-LaTeX-fragment-p)]
17178 ["Insert citation" org-reftex-citation t]
17179 "--"
17180 ["Export LaTeX fragments as images"
17181 (if (featurep 'org-exp)
17182 (setq org-export-with-LaTeX-fragments
17183 (not org-export-with-LaTeX-fragments))
17184 (require 'org-exp))
17185 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
17186 org-export-with-LaTeX-fragments)]
17187 "--"
17188 ["Template for BEAMER" org-beamer-settings-template t])
17189 "--"
17190 ("MobileOrg"
17191 ["Push Files and Views" org-mobile-push t]
17192 ["Get Captured and Flagged" org-mobile-pull t]
17193 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17194 "--"
17195 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17196 "--"
17197 ("Documentation"
17198 ["Show Version" org-version t]
17199 ["Info Documentation" org-info t])
17200 ("Customize"
17201 ["Browse Org Group" org-customize t]
17202 "--"
17203 ["Expand This Menu" org-create-customize-menu
17204 (fboundp 'customize-menu-create)])
17205 ["Send bug report" org-submit-bug-report t]
17206 "--"
17207 ("Refresh/Reload"
17208 ["Refresh setup current buffer" org-mode-restart t]
17209 ["Reload Org (after update)" org-reload t]
17210 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17213 (defun org-info (&optional node)
17214 "Read documentation for Org-mode in the info system.
17215 With optional NODE, go directly to that node."
17216 (interactive)
17217 (info (format "(org)%s" (or node ""))))
17219 ;;;###autoload
17220 (defun org-submit-bug-report ()
17221 "Submit a bug report on Org-mode via mail.
17223 Don't hesitate to report any problems or inaccurate documentation.
17225 If you don't have setup sending mail from (X)Emacs, please copy the
17226 output buffer into your mail program, as it gives us important
17227 information about your Org-mode version and configuration."
17228 (interactive)
17229 (require 'reporter)
17230 (org-load-modules-maybe)
17231 (org-require-autoloaded-modules)
17232 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17233 (reporter-submit-bug-report
17234 "emacs-orgmode@gnu.org"
17235 (org-version)
17236 (let (list)
17237 (save-window-excursion
17238 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17239 (delete-other-windows)
17240 (erase-buffer)
17241 (insert "You are about to submit a bug report to the Org-mode mailing list.
17243 We would like to add your full Org-mode and Outline configuration to the
17244 bug report. This greatly simplifies the work of the maintainer and
17245 other experts on the mailing list.
17247 HOWEVER, some variables you have customized may contain private
17248 information. The names of customers, colleagues, or friends, might
17249 appear in the form of file names, tags, todo states, or search strings.
17250 If you answer yes to the prompt, you might want to check and remove
17251 such private information before sending the email.")
17252 (add-text-properties (point-min) (point-max) '(face org-warning))
17253 (when (yes-or-no-p "Include your Org-mode configuration ")
17254 (mapatoms
17255 (lambda (v)
17256 (and (boundp v)
17257 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17258 (or (and (symbol-value v)
17259 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17260 (and
17261 (get v 'custom-type) (get v 'standard-value)
17262 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17263 (push v list)))))
17264 (kill-buffer (get-buffer "*Warn about privacy*"))
17265 list))
17266 nil nil
17267 "Remember to cover the basics, that is, what you expected to happen and
17268 what in fact did happen. You don't know how to make a good report? See
17270 http://orgmode.org/manual/Feedback.html#Feedback
17272 Your bug report will be posted to the Org-mode mailing list.
17273 ------------------------------------------------------------------------")
17274 (save-excursion
17275 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17276 (replace-match "\\1Bug: \\3 [\\2]")))))
17279 (defun org-install-agenda-files-menu ()
17280 (let ((bl (buffer-list)))
17281 (save-excursion
17282 (while bl
17283 (set-buffer (pop bl))
17284 (if (org-mode-p) (setq bl nil)))
17285 (when (org-mode-p)
17286 (easy-menu-change
17287 '("Org") "File List for Agenda"
17288 (append
17289 (list
17290 ["Edit File List" (org-edit-agenda-file-list) t]
17291 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17292 ["Remove Current File from List" org-remove-file t]
17293 ["Cycle through agenda files" org-cycle-agenda-files t]
17294 ["Occur in all agenda files" org-occur-in-agenda-files t]
17295 "--")
17296 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17298 ;;;; Documentation
17300 ;;;###autoload
17301 (defun org-require-autoloaded-modules ()
17302 (interactive)
17303 (mapc 'require
17304 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17305 org-docbook org-exp org-html org-icalendar
17306 org-id org-latex
17307 org-publish org-remember org-table
17308 org-timer org-xoxo)))
17310 ;;;###autoload
17311 (defun org-reload (&optional uncompiled)
17312 "Reload all org lisp files.
17313 With prefix arg UNCOMPILED, load the uncompiled versions."
17314 (interactive "P")
17315 (require 'find-func)
17316 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17317 (dir-org (file-name-directory (org-find-library-name "org")))
17318 (dir-org-contrib (ignore-errors
17319 (file-name-directory
17320 (org-find-library-name "org-contribdir"))))
17321 (files
17322 (append (directory-files dir-org t file-re)
17323 (and dir-org-contrib
17324 (directory-files dir-org-contrib t file-re))))
17325 (remove-re (concat (if (featurep 'xemacs)
17326 "org-colview" "org-colview-xemacs")
17327 "\\'")))
17328 (setq files (mapcar 'file-name-sans-extension files))
17329 (setq files (mapcar
17330 (lambda (x) (if (string-match remove-re x) nil x))
17331 files))
17332 (setq files (delq nil files))
17333 (mapc
17334 (lambda (f)
17335 (when (featurep (intern (file-name-nondirectory f)))
17336 (if (and (not uncompiled)
17337 (file-exists-p (concat f ".elc")))
17338 (load (concat f ".elc") nil nil t)
17339 (load (concat f ".el") nil nil t))))
17340 files))
17341 (org-version))
17343 ;;;###autoload
17344 (defun org-customize ()
17345 "Call the customize function with org as argument."
17346 (interactive)
17347 (org-load-modules-maybe)
17348 (org-require-autoloaded-modules)
17349 (customize-browse 'org))
17351 (defun org-create-customize-menu ()
17352 "Create a full customization menu for Org-mode, insert it into the menu."
17353 (interactive)
17354 (org-load-modules-maybe)
17355 (org-require-autoloaded-modules)
17356 (if (fboundp 'customize-menu-create)
17357 (progn
17358 (easy-menu-change
17359 '("Org") "Customize"
17360 `(["Browse Org group" org-customize t]
17361 "--"
17362 ,(customize-menu-create 'org)
17363 ["Set" Custom-set t]
17364 ["Save" Custom-save t]
17365 ["Reset to Current" Custom-reset-current t]
17366 ["Reset to Saved" Custom-reset-saved t]
17367 ["Reset to Standard Settings" Custom-reset-standard t]))
17368 (message "\"Org\"-menu now contains full customization menu"))
17369 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17371 ;;;; Miscellaneous stuff
17373 ;;; Generally useful functions
17375 (defun org-get-at-bol (property)
17376 "Get text property PROPERTY at beginning of line."
17377 (get-text-property (point-at-bol) property))
17379 (defun org-find-text-property-in-string (prop s)
17380 "Return the first non-nil value of property PROP in string S."
17381 (or (get-text-property 0 prop s)
17382 (get-text-property (or (next-single-property-change 0 prop s) 0)
17383 prop s)))
17385 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17386 "Display the given MESSAGE as a warning."
17387 (if (fboundp 'display-warning)
17388 (display-warning 'org message
17389 (if (featurep 'xemacs) 'warning :warning))
17390 (let ((buf (get-buffer-create "*Org warnings*")))
17391 (with-current-buffer buf
17392 (goto-char (point-max))
17393 (insert "Warning (Org): " message)
17394 (unless (bolp)
17395 (newline)))
17396 (display-buffer buf)
17397 (sit-for 0))))
17399 (defun org-in-commented-line ()
17400 "Is point in a line starting with `#'?"
17401 (equal (char-after (point-at-bol)) ?#))
17403 (defun org-in-indented-comment-line ()
17404 "Is point in a line starting with `#' after some white space?"
17405 (save-excursion
17406 (save-match-data
17407 (goto-char (point-at-bol))
17408 (looking-at "[ \t]*#"))))
17410 (defun org-in-verbatim-emphasis ()
17411 (save-match-data
17412 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17414 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17415 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17416 (if (and marker (marker-buffer marker)
17417 (buffer-live-p (marker-buffer marker)))
17418 (progn
17419 (switch-to-buffer (marker-buffer marker))
17420 (if (or (> marker (point-max)) (< marker (point-min)))
17421 (widen))
17422 (goto-char marker)
17423 (org-show-context 'org-goto))
17424 (if bookmark
17425 (bookmark-jump bookmark)
17426 (error "Cannot find location"))))
17428 (defun org-quote-csv-field (s)
17429 "Quote field for inclusion in CSV material."
17430 (if (string-match "[\",]" s)
17431 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17434 (defun org-plist-delete (plist property)
17435 "Delete PROPERTY from PLIST.
17436 This is in contrast to merely setting it to 0."
17437 (let (p)
17438 (while plist
17439 (if (not (eq property (car plist)))
17440 (setq p (plist-put p (car plist) (nth 1 plist))))
17441 (setq plist (cddr plist)))
17444 (defun org-force-self-insert (N)
17445 "Needed to enforce self-insert under remapping."
17446 (interactive "p")
17447 (self-insert-command N))
17449 (defun org-string-width (s)
17450 "Compute width of string, ignoring invisible characters.
17451 This ignores character with invisibility property `org-link', and also
17452 characters with property `org-cwidth', because these will become invisible
17453 upon the next fontification round."
17454 (let (b l)
17455 (when (or (eq t buffer-invisibility-spec)
17456 (assq 'org-link buffer-invisibility-spec))
17457 (while (setq b (text-property-any 0 (length s)
17458 'invisible 'org-link s))
17459 (setq s (concat (substring s 0 b)
17460 (substring s (or (next-single-property-change
17461 b 'invisible s) (length s)))))))
17462 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17463 (setq s (concat (substring s 0 b)
17464 (substring s (or (next-single-property-change
17465 b 'org-cwidth s) (length s))))))
17466 (setq l (string-width s) b -1)
17467 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17468 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17471 (defun org-get-indentation (&optional line)
17472 "Get the indentation of the current line, interpreting tabs.
17473 When LINE is given, assume it represents a line and compute its indentation."
17474 (if line
17475 (if (string-match "^ *" (org-remove-tabs line))
17476 (match-end 0))
17477 (save-excursion
17478 (beginning-of-line 1)
17479 (skip-chars-forward " \t")
17480 (current-column))))
17482 (defun org-remove-tabs (s &optional width)
17483 "Replace tabulators in S with spaces.
17484 Assumes that s is a single line, starting in column 0."
17485 (setq width (or width tab-width))
17486 (while (string-match "\t" s)
17487 (setq s (replace-match
17488 (make-string
17489 (- (* width (/ (+ (match-beginning 0) width) width))
17490 (match-beginning 0)) ?\ )
17491 t t s)))
17494 (defun org-fix-indentation (line ind)
17495 "Fix indentation in LINE.
17496 IND is a cons cell with target and minimum indentation.
17497 If the current indentation in LINE is smaller than the minimum,
17498 leave it alone. If it is larger than ind, set it to the target."
17499 (let* ((l (org-remove-tabs line))
17500 (i (org-get-indentation l))
17501 (i1 (car ind)) (i2 (cdr ind)))
17502 (if (>= i i2) (setq l (substring line i2)))
17503 (if (> i1 0)
17504 (concat (make-string i1 ?\ ) l)
17505 l)))
17507 (defun org-remove-indentation (code &optional n)
17508 "Remove the maximum common indentation from the lines in CODE.
17509 N may optionally be the number of spaces to remove."
17510 (with-temp-buffer
17511 (insert code)
17512 (org-do-remove-indentation n)
17513 (buffer-string)))
17515 (defun org-do-remove-indentation (&optional n)
17516 "Remove the maximum common indentation from the buffer."
17517 (untabify (point-min) (point-max))
17518 (let ((min 10000) re)
17519 (if n
17520 (setq min n)
17521 (goto-char (point-min))
17522 (while (re-search-forward "^ *[^ \n]" nil t)
17523 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17524 (unless (or (= min 0) (= min 10000))
17525 (setq re (format "^ \\{%d\\}" min))
17526 (goto-char (point-min))
17527 (while (re-search-forward re nil t)
17528 (replace-match "")
17529 (end-of-line 1))
17530 min)))
17532 (defun org-fill-template (template alist)
17533 "Find each %key of ALIST in TEMPLATE and replace it."
17534 (let ((case-fold-search nil)
17535 entry key value)
17536 (setq alist (sort (copy-sequence alist)
17537 (lambda (a b) (< (length (car a)) (length (car b))))))
17538 (while (setq entry (pop alist))
17539 (setq template
17540 (replace-regexp-in-string
17541 (concat "%" (regexp-quote (car entry)))
17542 (cdr entry) template t t)))
17543 template))
17545 (defun org-base-buffer (buffer)
17546 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17547 (if (not buffer)
17548 buffer
17549 (or (buffer-base-buffer buffer)
17550 buffer)))
17552 (defun org-trim (s)
17553 "Remove whitespace at beginning and end of string."
17554 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17555 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17558 (defun org-wrap (string &optional width lines)
17559 "Wrap string to either a number of lines, or a width in characters.
17560 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17561 that costs. If there is a word longer than WIDTH, the text is actually
17562 wrapped to the length of that word.
17563 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17564 many lines, whatever width that takes.
17565 The return value is a list of lines, without newlines at the end."
17566 (let* ((words (org-split-string string "[ \t\n]+"))
17567 (maxword (apply 'max (mapcar 'org-string-width words)))
17568 w ll)
17569 (cond (width
17570 (org-do-wrap words (max maxword width)))
17571 (lines
17572 (setq w maxword)
17573 (setq ll (org-do-wrap words maxword))
17574 (if (<= (length ll) lines)
17576 (setq ll words)
17577 (while (> (length ll) lines)
17578 (setq w (1+ w))
17579 (setq ll (org-do-wrap words w)))
17580 ll))
17581 (t (error "Cannot wrap this")))))
17583 (defun org-do-wrap (words width)
17584 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17585 (let (lines line)
17586 (while words
17587 (setq line (pop words))
17588 (while (and words (< (+ (length line) (length (car words))) width))
17589 (setq line (concat line " " (pop words))))
17590 (setq lines (push line lines)))
17591 (nreverse lines)))
17593 (defun org-split-string (string &optional separators)
17594 "Splits STRING into substrings at SEPARATORS.
17595 No empty strings are returned if there are matches at the beginning
17596 and end of string."
17597 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17598 (start 0)
17599 notfirst
17600 (list nil))
17601 (while (and (string-match rexp string
17602 (if (and notfirst
17603 (= start (match-beginning 0))
17604 (< start (length string)))
17605 (1+ start) start))
17606 (< (match-beginning 0) (length string)))
17607 (setq notfirst t)
17608 (or (eq (match-beginning 0) 0)
17609 (and (eq (match-beginning 0) (match-end 0))
17610 (eq (match-beginning 0) start))
17611 (setq list
17612 (cons (substring string start (match-beginning 0))
17613 list)))
17614 (setq start (match-end 0)))
17615 (or (eq start (length string))
17616 (setq list
17617 (cons (substring string start)
17618 list)))
17619 (nreverse list)))
17621 (defun org-quote-vert (s)
17622 "Replace \"|\" with \"\\vert\"."
17623 (while (string-match "|" s)
17624 (setq s (replace-match "\\vert" t t s)))
17627 (defun org-uuidgen-p (s)
17628 "Is S an ID created by UUIDGEN?"
17629 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17631 (defun org-context ()
17632 "Return a list of contexts of the current cursor position.
17633 If several contexts apply, all are returned.
17634 Each context entry is a list with a symbol naming the context, and
17635 two positions indicating start and end of the context. Possible
17636 contexts are:
17638 :headline anywhere in a headline
17639 :headline-stars on the leading stars in a headline
17640 :todo-keyword on a TODO keyword (including DONE) in a headline
17641 :tags on the TAGS in a headline
17642 :priority on the priority cookie in a headline
17643 :item on the first line of a plain list item
17644 :item-bullet on the bullet/number of a plain list item
17645 :checkbox on the checkbox in a plain list item
17646 :table in an org-mode table
17647 :table-special on a special filed in a table
17648 :table-table in a table.el table
17649 :link on a hyperlink
17650 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17651 :target on a <<target>>
17652 :radio-target on a <<<radio-target>>>
17653 :latex-fragment on a LaTeX fragment
17654 :latex-preview on a LaTeX fragment with overlayed preview image
17656 This function expects the position to be visible because it uses font-lock
17657 faces as a help to recognize the following contexts: :table-special, :link,
17658 and :keyword."
17659 (let* ((f (get-text-property (point) 'face))
17660 (faces (if (listp f) f (list f)))
17661 (p (point)) clist o)
17662 ;; First the large context
17663 (cond
17664 ((org-on-heading-p t)
17665 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17666 (when (progn
17667 (beginning-of-line 1)
17668 (looking-at org-todo-line-tags-regexp))
17669 (push (org-point-in-group p 1 :headline-stars) clist)
17670 (push (org-point-in-group p 2 :todo-keyword) clist)
17671 (push (org-point-in-group p 4 :tags) clist))
17672 (goto-char p)
17673 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17674 (if (looking-at "\\[#[A-Z0-9]\\]")
17675 (push (org-point-in-group p 0 :priority) clist)))
17677 ((org-at-item-p)
17678 (push (org-point-in-group p 2 :item-bullet) clist)
17679 (push (list :item (point-at-bol)
17680 (save-excursion (org-end-of-item) (point)))
17681 clist)
17682 (and (org-at-item-checkbox-p)
17683 (push (org-point-in-group p 0 :checkbox) clist)))
17685 ((org-at-table-p)
17686 (push (list :table (org-table-begin) (org-table-end)) clist)
17687 (if (memq 'org-formula faces)
17688 (push (list :table-special
17689 (previous-single-property-change p 'face)
17690 (next-single-property-change p 'face)) clist)))
17691 ((org-at-table-p 'any)
17692 (push (list :table-table) clist)))
17693 (goto-char p)
17695 ;; Now the small context
17696 (cond
17697 ((org-at-timestamp-p)
17698 (push (org-point-in-group p 0 :timestamp) clist))
17699 ((memq 'org-link faces)
17700 (push (list :link
17701 (previous-single-property-change p 'face)
17702 (next-single-property-change p 'face)) clist))
17703 ((memq 'org-special-keyword faces)
17704 (push (list :keyword
17705 (previous-single-property-change p 'face)
17706 (next-single-property-change p 'face)) clist))
17707 ((org-on-target-p)
17708 (push (org-point-in-group p 0 :target) clist)
17709 (goto-char (1- (match-beginning 0)))
17710 (if (looking-at org-radio-target-regexp)
17711 (push (org-point-in-group p 0 :radio-target) clist))
17712 (goto-char p))
17713 ((setq o (car (delq nil
17714 (mapcar
17715 (lambda (x)
17716 (if (memq x org-latex-fragment-image-overlays) x))
17717 (overlays-at (point))))))
17718 (push (list :latex-fragment
17719 (overlay-start o) (overlay-end o)) clist)
17720 (push (list :latex-preview
17721 (overlay-start o) (overlay-end o)) clist))
17722 ((org-inside-LaTeX-fragment-p)
17723 ;; FIXME: positions wrong.
17724 (push (list :latex-fragment (point) (point)) clist)))
17726 (setq clist (nreverse (delq nil clist)))
17727 clist))
17729 ;; FIXME: Compare with at-regexp-p Do we need both?
17730 (defun org-in-regexp (re &optional nlines visually)
17731 "Check if point is inside a match of regexp.
17732 Normally only the current line is checked, but you can include NLINES extra
17733 lines both before and after point into the search.
17734 If VISUALLY is set, require that the cursor is not after the match but
17735 really on, so that the block visually is on the match."
17736 (catch 'exit
17737 (let ((pos (point))
17738 (eol (point-at-eol (+ 1 (or nlines 0))))
17739 (inc (if visually 1 0)))
17740 (save-excursion
17741 (beginning-of-line (- 1 (or nlines 0)))
17742 (while (re-search-forward re eol t)
17743 (if (and (<= (match-beginning 0) pos)
17744 (>= (+ inc (match-end 0)) pos))
17745 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17747 (defun org-at-regexp-p (regexp)
17748 "Is point inside a match of REGEXP in the current line?"
17749 (catch 'exit
17750 (save-excursion
17751 (let ((pos (point)) (end (point-at-eol)))
17752 (beginning-of-line 1)
17753 (while (re-search-forward regexp end t)
17754 (if (and (<= (match-beginning 0) pos)
17755 (>= (match-end 0) pos))
17756 (throw 'exit t)))
17757 nil))))
17759 (defun org-in-regexps-block-p (start-re end-re)
17760 "Returns t if the current point is between matches of START-RE and END-RE.
17761 This will also return to if point is on one of the two matches."
17762 (interactive)
17763 (let ((p (point)))
17764 (save-excursion
17765 (and (or (org-at-regexp-p start-re)
17766 (re-search-backward start-re nil t))
17767 (re-search-forward end-re nil t)
17768 (>= (point) p)))))
17770 (defun org-occur-in-agenda-files (regexp &optional nlines)
17771 "Call `multi-occur' with buffers for all agenda files."
17772 (interactive "sOrg-files matching: \np")
17773 (let* ((files (org-agenda-files))
17774 (tnames (mapcar 'file-truename files))
17775 (extra org-agenda-text-search-extra-files)
17777 (when (eq (car extra) 'agenda-archives)
17778 (setq extra (cdr extra))
17779 (setq files (org-add-archive-files files)))
17780 (while (setq f (pop extra))
17781 (unless (member (file-truename f) tnames)
17782 (add-to-list 'files f 'append)
17783 (add-to-list 'tnames (file-truename f) 'append)))
17784 (multi-occur
17785 (mapcar (lambda (x)
17786 (with-current-buffer
17787 (or (get-file-buffer x) (find-file-noselect x))
17788 (widen)
17789 (current-buffer)))
17790 files)
17791 regexp)))
17793 (if (boundp 'occur-mode-find-occurrence-hook)
17794 ;; Emacs 23
17795 (add-hook 'occur-mode-find-occurrence-hook
17796 (lambda ()
17797 (when (org-mode-p)
17798 (org-reveal))))
17799 ;; Emacs 22
17800 (defadvice occur-mode-goto-occurrence
17801 (after org-occur-reveal activate)
17802 (and (org-mode-p) (org-reveal)))
17803 (defadvice occur-mode-goto-occurrence-other-window
17804 (after org-occur-reveal activate)
17805 (and (org-mode-p) (org-reveal)))
17806 (defadvice occur-mode-display-occurrence
17807 (after org-occur-reveal activate)
17808 (when (org-mode-p)
17809 (let ((pos (occur-mode-find-occurrence)))
17810 (with-current-buffer (marker-buffer pos)
17811 (save-excursion
17812 (goto-char pos)
17813 (org-reveal)))))))
17815 (defun org-occur-link-in-agenda-files ()
17816 "Create a link and search for it in the agendas.
17817 The link is not stored in `org-stored-links', it is just created
17818 for the search purpose."
17819 (interactive)
17820 (let ((link (condition-case nil
17821 (org-store-link nil)
17822 (error "Unable to create a link to here"))))
17823 (org-occur-in-agenda-files (regexp-quote link))))
17825 (defun org-uniquify (list)
17826 "Remove duplicate elements from LIST."
17827 (let (res)
17828 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17829 res))
17831 (defun org-delete-all (elts list)
17832 "Remove all elements in ELTS from LIST."
17833 (while elts
17834 (setq list (delete (pop elts) list)))
17835 list)
17837 (defun org-remove-if (predicate seq)
17838 "Remove everything from SEQ that fulfills PREDICATE."
17839 (let (res e)
17840 (while seq
17841 (setq e (pop seq))
17842 (if (not (funcall predicate e)) (push e res)))
17843 (nreverse res)))
17845 (defun org-remove-if-not (predicate seq)
17846 "Remove everything from SEQ that does not fulfill PREDICATE."
17847 (let (res e)
17848 (while seq
17849 (setq e (pop seq))
17850 (if (funcall predicate e) (push e res)))
17851 (nreverse res)))
17853 (defun org-back-over-empty-lines ()
17854 "Move backwards over whitespace, to the beginning of the first empty line.
17855 Returns the number of empty lines passed."
17856 (let ((pos (point)))
17857 (skip-chars-backward " \t\n\r")
17858 (beginning-of-line 2)
17859 (goto-char (min (point) pos))
17860 (count-lines (point) pos)))
17862 (defun org-skip-whitespace ()
17863 (skip-chars-forward " \t\n\r"))
17865 (defun org-point-in-group (point group &optional context)
17866 "Check if POINT is in match-group GROUP.
17867 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17868 match. If the match group does ot exist or point is not inside it,
17869 return nil."
17870 (and (match-beginning group)
17871 (>= point (match-beginning group))
17872 (<= point (match-end group))
17873 (if context
17874 (list context (match-beginning group) (match-end group))
17875 t)))
17877 (defun org-switch-to-buffer-other-window (&rest args)
17878 "Switch to buffer in a second window on the current frame.
17879 In particular, do not allow pop-up frames."
17880 (let (pop-up-frames special-display-buffer-names special-display-regexps
17881 special-display-function)
17882 (apply 'switch-to-buffer-other-window args)))
17884 (defun org-combine-plists (&rest plists)
17885 "Create a single property list from all plists in PLISTS.
17886 The process starts by copying the first list, and then setting properties
17887 from the other lists. Settings in the last list are the most significant
17888 ones and overrule settings in the other lists."
17889 (let ((rtn (copy-sequence (pop plists)))
17890 p v ls)
17891 (while plists
17892 (setq ls (pop plists))
17893 (while ls
17894 (setq p (pop ls) v (pop ls))
17895 (setq rtn (plist-put rtn p v))))
17896 rtn))
17898 (defun org-move-line-down (arg)
17899 "Move the current line down. With prefix argument, move it past ARG lines."
17900 (interactive "p")
17901 (let ((col (current-column))
17902 beg end pos)
17903 (beginning-of-line 1) (setq beg (point))
17904 (beginning-of-line 2) (setq end (point))
17905 (beginning-of-line (+ 1 arg))
17906 (setq pos (move-marker (make-marker) (point)))
17907 (insert (delete-and-extract-region beg end))
17908 (goto-char pos)
17909 (org-move-to-column col)))
17911 (defun org-move-line-up (arg)
17912 "Move the current line up. With prefix argument, move it past ARG lines."
17913 (interactive "p")
17914 (let ((col (current-column))
17915 beg end pos)
17916 (beginning-of-line 1) (setq beg (point))
17917 (beginning-of-line 2) (setq end (point))
17918 (beginning-of-line (- arg))
17919 (setq pos (move-marker (make-marker) (point)))
17920 (insert (delete-and-extract-region beg end))
17921 (goto-char pos)
17922 (org-move-to-column col)))
17924 (defun org-replace-escapes (string table)
17925 "Replace %-escapes in STRING with values in TABLE.
17926 TABLE is an association list with keys like \"%a\" and string values.
17927 The sequences in STRING may contain normal field width and padding information,
17928 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17929 so values can contain further %-escapes if they are define later in TABLE."
17930 (let ((tbl (copy-alist table))
17931 (case-fold-search nil)
17932 (pchg 0)
17933 e re rpl)
17934 (while (setq e (pop tbl))
17935 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17936 (when (and (cdr e) (string-match re (cdr e)))
17937 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
17938 (safe "SREF"))
17939 (add-text-properties 0 3 (list 'sref sref) safe)
17940 (setcdr e (replace-match safe t t (cdr e)))))
17941 (while (string-match re string)
17942 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17943 (cdr e)))
17944 (setq string (replace-match rpl t t string))))
17945 (while (setq pchg (next-property-change pchg string))
17946 (let ((sref (get-text-property pchg 'sref string)))
17947 (when (and sref (string-match "SREF" string pchg))
17948 (setq string (replace-match sref t t string)))))
17949 string))
17951 (defun org-sublist (list start end)
17952 "Return a section of LIST, from START to END.
17953 Counting starts at 1."
17954 (let (rtn (c start))
17955 (setq list (nthcdr (1- start) list))
17956 (while (and list (<= c end))
17957 (push (pop list) rtn)
17958 (setq c (1+ c)))
17959 (nreverse rtn)))
17961 (defun org-find-base-buffer-visiting (file)
17962 "Like `find-buffer-visiting' but always return the base buffer and
17963 not an indirect buffer."
17964 (let ((buf (or (get-file-buffer file)
17965 (find-buffer-visiting file))))
17966 (if buf
17967 (or (buffer-base-buffer buf) buf)
17968 nil)))
17970 (defun org-image-file-name-regexp (&optional extensions)
17971 "Return regexp matching the file names of images.
17972 If EXTENSIONS is given, only match these."
17973 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17974 (image-file-name-regexp)
17975 (let ((image-file-name-extensions
17976 (or extensions
17977 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17978 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17979 (concat "\\."
17980 (regexp-opt (nconc (mapcar 'upcase
17981 image-file-name-extensions)
17982 image-file-name-extensions)
17984 "\\'"))))
17986 (defun org-file-image-p (file &optional extensions)
17987 "Return non-nil if FILE is an image."
17988 (save-match-data
17989 (string-match (org-image-file-name-regexp extensions) file)))
17991 (defun org-get-cursor-date ()
17992 "Return the date at cursor in as a time.
17993 This works in the calendar and in the agenda, anywhere else it just
17994 returns the current time."
17995 (let (date day defd)
17996 (cond
17997 ((eq major-mode 'calendar-mode)
17998 (setq date (calendar-cursor-to-date)
17999 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18000 ((eq major-mode 'org-agenda-mode)
18001 (setq day (get-text-property (point) 'day))
18002 (if day
18003 (setq date (calendar-gregorian-from-absolute day)
18004 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18005 (nth 2 date))))))
18006 (or defd (current-time))))
18008 (defvar org-agenda-action-marker (make-marker)
18009 "Marker pointing to the entry for the next agenda action.")
18011 (defun org-mark-entry-for-agenda-action ()
18012 "Mark the current entry as target of an agenda action.
18013 Agenda actions are actions executed from the agenda with the key `k',
18014 which make use of the date at the cursor."
18015 (interactive)
18016 (move-marker org-agenda-action-marker
18017 (save-excursion (org-back-to-heading t) (point))
18018 (current-buffer))
18019 (message
18020 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18022 ;;; Paragraph filling stuff.
18023 ;; We want this to be just right, so use the full arsenal.
18025 (defun org-indent-line-function ()
18026 "Indent line like previous, but further if previous was headline or item."
18027 (interactive)
18028 (let* ((pos (point))
18029 (itemp (org-at-item-p))
18030 (case-fold-search t)
18031 (org-drawer-regexp (or org-drawer-regexp "\000"))
18032 column bpos bcol tpos tcol bullet btype bullet-type)
18033 ;; Find the previous relevant line
18034 (beginning-of-line 1)
18035 (cond
18036 ((looking-at "#") (setq column 0))
18037 ((looking-at "\\*+ ") (setq column 0))
18038 ((and (looking-at "[ \t]*:END:")
18039 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18040 (save-excursion
18041 (goto-char (1- (match-beginning 1)))
18042 (setq column (current-column))))
18043 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18044 (save-excursion
18045 (re-search-backward
18046 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18047 (setq column (org-get-indentation (match-string 0))))
18049 (beginning-of-line 0)
18050 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18051 (not (looking-at "[ \t]*:END:"))
18052 (not (looking-at org-drawer-regexp)))
18053 (beginning-of-line 0))
18054 (cond
18055 ((looking-at "\\*+[ \t]+")
18056 (if (not org-adapt-indentation)
18057 (setq column 0)
18058 (goto-char (match-end 0))
18059 (setq column (current-column))))
18060 ((looking-at org-drawer-regexp)
18061 (goto-char (1- (match-beginning 1)))
18062 (setq column (current-column)))
18063 ((looking-at "\\([ \t]*\\):END:")
18064 (goto-char (match-end 1))
18065 (setq column (current-column)))
18066 ((org-in-item-p)
18067 (org-beginning-of-item)
18068 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18069 (setq bpos (match-beginning 1) tpos (match-end 0)
18070 bcol (progn (goto-char bpos) (current-column))
18071 tcol (progn (goto-char tpos) (current-column))
18072 bullet (match-string 1)
18073 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18074 (if (> tcol (+ bcol org-description-max-indent))
18075 (setq tcol (+ bcol 5)))
18076 (if (not itemp)
18077 (setq column tcol)
18078 (goto-char pos)
18079 (beginning-of-line 1)
18080 (if (looking-at "\\S-")
18081 (progn
18082 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18083 (setq bullet (match-string 1)
18084 btype (if (string-match "[0-9]" bullet) "n" bullet))
18085 (setq column (if (equal btype bullet-type) bcol tcol)))
18086 (setq column (org-get-indentation)))))
18087 (t (setq column (org-get-indentation))))))
18088 (goto-char pos)
18089 (if (<= (current-column) (current-indentation))
18090 (org-indent-line-to column)
18091 (save-excursion (org-indent-line-to column)))
18092 (setq column (current-column))
18093 (beginning-of-line 1)
18094 (if (looking-at
18095 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18096 (replace-match (concat (match-string 1)
18097 (format org-property-format
18098 (match-string 2) (match-string 3)))
18099 t t))
18100 (org-move-to-column column)))
18102 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18103 "Variable to store copy of `adaptive-fill-regexp'.
18104 Since `adaptive-fill-regexp' is set to never match, we need to
18105 store a backup of its value before entering `org-mode' so that
18106 the functionality can be provided as a fall-back.")
18108 (defun org-set-autofill-regexps ()
18109 (interactive)
18110 ;; In the paragraph separator we include headlines, because filling
18111 ;; text in a line directly attached to a headline would otherwise
18112 ;; fill the headline as well.
18113 (org-set-local 'comment-start-skip "^#+[ \t]*")
18114 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18115 ;; The paragraph starter includes hand-formatted lists.
18116 (org-set-local
18117 'paragraph-start
18118 (concat
18119 "\f" "\\|"
18120 "[ ]*$" "\\|"
18121 "\\*+ " "\\|"
18122 "[ \t]*#" "\\|"
18123 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18124 "[ \t]*[:|]" "\\|"
18125 "\\$\\$" "\\|"
18126 "\\\\\\(begin\\|end\\|[][]\\)"))
18127 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18128 ;; But only if the user has not turned off tables or fixed-width regions
18129 (org-set-local
18130 'auto-fill-inhibit-regexp
18131 (concat "\\*+ \\|#\\+"
18132 "\\|[ \t]*" org-keyword-time-regexp
18133 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18134 (concat
18135 "\\|[ \t]*["
18136 (if org-enable-table-editor "|" "")
18137 (if org-enable-fixed-width-editor ":" "")
18138 "]"))))
18139 ;; We use our own fill-paragraph function, to make sure that tables
18140 ;; and fixed-width regions are not wrapped. That function will pass
18141 ;; through to `fill-paragraph' when appropriate.
18142 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18143 ;; Adaptive filling: To get full control, first make sure that
18144 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18145 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18146 (org-set-local 'org-adaptive-fill-regexp-backup
18147 adaptive-fill-regexp))
18148 (org-set-local 'adaptive-fill-regexp "\000")
18149 (org-set-local 'adaptive-fill-function
18150 'org-adaptive-fill-function)
18151 (org-set-local
18152 'align-mode-rules-list
18153 '((org-in-buffer-settings
18154 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18155 (modes . '(org-mode))))))
18157 (defun org-fill-paragraph (&optional justify)
18158 "Re-align a table, pass through to fill-paragraph if no table."
18159 (let ((table-p (org-at-table-p))
18160 (table.el-p (org-at-table.el-p)))
18161 (cond ((and (equal (char-after (point-at-bol)) ?*)
18162 (save-excursion (goto-char (point-at-bol))
18163 (looking-at outline-regexp)))
18164 t) ; skip headlines
18165 (table.el-p t) ; skip table.el tables
18166 (table-p (org-table-align) t) ; align org-mode tables
18167 (t nil)))) ; call paragraph-fill
18169 ;; For reference, this is the default value of adaptive-fill-regexp
18170 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18172 (defun org-adaptive-fill-function ()
18173 "Return a fill prefix for org-mode files.
18174 In particular, this makes sure hanging paragraphs for hand-formatted lists
18175 work correctly."
18176 (cond
18177 ;; Comment line
18178 ((looking-at "#[ \t]+")
18179 (match-string-no-properties 0))
18180 ;; Description list
18181 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18182 (save-excursion
18183 (if (> (match-end 1) (+ (match-beginning 1)
18184 org-description-max-indent))
18185 (goto-char (+ (match-beginning 1) 5))
18186 (goto-char (match-end 0)))
18187 (make-string (current-column) ?\ )))
18188 ;; Ordered or unordered list
18189 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18190 (save-excursion
18191 (goto-char (match-end 0))
18192 (make-string (current-column) ?\ )))
18193 ;; Other text
18194 ((looking-at org-adaptive-fill-regexp-backup)
18195 (match-string-no-properties 0))))
18197 ;;; Other stuff.
18199 (defun org-toggle-fixed-width-section (arg)
18200 "Toggle the fixed-width export.
18201 If there is no active region, the QUOTE keyword at the current headline is
18202 inserted or removed. When present, it causes the text between this headline
18203 and the next to be exported as fixed-width text, and unmodified.
18204 If there is an active region, this command adds or removes a colon as the
18205 first character of this line. If the first character of a line is a colon,
18206 this line is also exported in fixed-width font."
18207 (interactive "P")
18208 (let* ((cc 0)
18209 (regionp (org-region-active-p))
18210 (beg (if regionp (region-beginning) (point)))
18211 (end (if regionp (region-end)))
18212 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18213 (case-fold-search nil)
18214 (re "[ \t]*\\(: \\)")
18215 off)
18216 (if regionp
18217 (save-excursion
18218 (goto-char beg)
18219 (setq cc (current-column))
18220 (beginning-of-line 1)
18221 (setq off (looking-at re))
18222 (while (> nlines 0)
18223 (setq nlines (1- nlines))
18224 (beginning-of-line 1)
18225 (cond
18226 (arg
18227 (org-move-to-column cc t)
18228 (insert ": \n")
18229 (forward-line -1))
18230 ((and off (looking-at re))
18231 (replace-match "" t t nil 1))
18232 ((not off) (org-move-to-column cc t) (insert ": ")))
18233 (forward-line 1)))
18234 (save-excursion
18235 (org-back-to-heading)
18236 (if (looking-at (concat outline-regexp
18237 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18238 (replace-match "" t t nil 1)
18239 (if (looking-at outline-regexp)
18240 (progn
18241 (goto-char (match-end 0))
18242 (insert org-quote-string " "))))))))
18244 (defun org-reftex-citation ()
18245 "Use reftex-citation to insert a citation into the buffer.
18246 This looks for a line like
18248 #+BIBLIOGRAPHY: foo plain option:-d
18250 and derives from it that foo.bib is the bibliography file relevant
18251 for this document. It then installs the necessary environment for RefTeX
18252 to work in this buffer and calls `reftex-citation' to insert a citation
18253 into the buffer.
18255 Export of such citations to both LaTeX and HTML is handled by the contributed
18256 package org-exp-bibtex by Taru Karttunen."
18257 (interactive)
18258 (let ((reftex-docstruct-symbol 'rds)
18259 (reftex-cite-format "\\cite{%l}")
18260 rds bib)
18261 (save-excursion
18262 (save-restriction
18263 (widen)
18264 (let ((case-fold-search t)
18265 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18266 (if (not (save-excursion
18267 (or (re-search-forward re nil t)
18268 (re-search-backward re nil t))))
18269 (error "No bibliography defined in file")
18270 (setq bib (concat (match-string 1) ".bib")
18271 rds (list (list 'bib bib)))))))
18272 (call-interactively 'reftex-citation)))
18274 ;;;; Functions extending outline functionality
18276 (defun org-beginning-of-line (&optional arg)
18277 "Go to the beginning of the current line. If that is invisible, continue
18278 to a visible line beginning. This makes the function of C-a more intuitive.
18279 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18280 first attempt, and only move to after the tags when the cursor is already
18281 beyond the end of the headline."
18282 (interactive "P")
18283 (let ((pos (point))
18284 (special (if (consp org-special-ctrl-a/e)
18285 (car org-special-ctrl-a/e)
18286 org-special-ctrl-a/e))
18287 refpos)
18288 (if (org-bound-and-true-p line-move-visual)
18289 (beginning-of-visual-line 1)
18290 (beginning-of-line 1))
18291 (if (and arg (fboundp 'move-beginning-of-line))
18292 (call-interactively 'move-beginning-of-line)
18293 (if (bobp)
18295 (backward-char 1)
18296 (if (org-invisible-p)
18297 (while (and (not (bobp)) (org-invisible-p))
18298 (backward-char 1)
18299 (beginning-of-line 1))
18300 (forward-char 1))))
18301 (when special
18302 (cond
18303 ((and (looking-at org-complex-heading-regexp)
18304 (= (char-after (match-end 1)) ?\ ))
18305 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18306 (point-at-eol)))
18307 (goto-char
18308 (if (eq special t)
18309 (cond ((> pos refpos) refpos)
18310 ((= pos (point)) refpos)
18311 (t (point)))
18312 (cond ((> pos (point)) (point))
18313 ((not (eq last-command this-command)) (point))
18314 (t refpos)))))
18315 ((org-at-item-p)
18316 (goto-char
18317 (if (eq special t)
18318 (cond ((> pos (match-end 4)) (match-end 4))
18319 ((= pos (point)) (match-end 4))
18320 (t (point)))
18321 (cond ((> pos (point)) (point))
18322 ((not (eq last-command this-command)) (point))
18323 (t (match-end 4))))))))
18324 (org-no-warnings
18325 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18327 (defun org-end-of-line (&optional arg)
18328 "Go to the end of the line.
18329 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18330 first attempt, and only move to after the tags when the cursor is already
18331 beyond the end of the headline."
18332 (interactive "P")
18333 (let ((special (if (consp org-special-ctrl-a/e)
18334 (cdr org-special-ctrl-a/e)
18335 org-special-ctrl-a/e)))
18336 (if (or (not special)
18337 (not (org-on-heading-p))
18338 arg)
18339 (call-interactively
18340 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18341 ((fboundp 'move-end-of-line) 'move-end-of-line)
18342 (t 'end-of-line)))
18343 (let ((pos (point)))
18344 (beginning-of-line 1)
18345 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18346 (if (eq special t)
18347 (if (or (< pos (match-beginning 1))
18348 (= pos (match-end 0)))
18349 (goto-char (match-beginning 1))
18350 (goto-char (match-end 0)))
18351 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18352 (goto-char (match-end 0))
18353 (goto-char (match-beginning 1))))
18354 (call-interactively (if (fboundp 'move-end-of-line)
18355 'move-end-of-line
18356 'end-of-line)))))
18357 (org-no-warnings
18358 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18360 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18361 (define-key org-mode-map "\C-e" 'org-end-of-line)
18362 (define-key org-mode-map [home] 'org-beginning-of-line)
18363 (define-key org-mode-map [end] 'org-end-of-line)
18365 (defun org-backward-sentence (&optional arg)
18366 "Go to beginning of sentence, or beginning of table field.
18367 This will call `backward-sentence' or `org-table-beginning-of-field',
18368 depending on context."
18369 (interactive "P")
18370 (cond
18371 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18372 (t (call-interactively 'backward-sentence))))
18374 (defun org-forward-sentence (&optional arg)
18375 "Go to end of sentence, or end of table field.
18376 This will call `forward-sentence' or `org-table-end-of-field',
18377 depending on context."
18378 (interactive "P")
18379 (cond
18380 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18381 (t (call-interactively 'forward-sentence))))
18383 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18384 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18386 (defun org-kill-line (&optional arg)
18387 "Kill line, to tags or end of line."
18388 (interactive "P")
18389 (cond
18390 ((or (not org-special-ctrl-k)
18391 (bolp)
18392 (not (org-on-heading-p)))
18393 (call-interactively 'kill-line))
18394 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18395 (kill-region (point) (match-beginning 1))
18396 (org-set-tags nil t))
18397 (t (kill-region (point) (point-at-eol)))))
18399 (define-key org-mode-map "\C-k" 'org-kill-line)
18401 (defun org-yank (&optional arg)
18402 "Yank. If the kill is a subtree, treat it specially.
18403 This command will look at the current kill and check if is a single
18404 subtree, or a series of subtrees[1]. If it passes the test, and if the
18405 cursor is at the beginning of a line or after the stars of a currently
18406 empty headline, then the yank is handled specially. How exactly depends
18407 on the value of the following variables, both set by default.
18409 org-yank-folded-subtrees
18410 When set, the subtree(s) will be folded after insertion, but only
18411 if doing so would now swallow text after the yanked text.
18413 org-yank-adjusted-subtrees
18414 When set, the subtree will be promoted or demoted in order to
18415 fit into the local outline tree structure, which means that the level
18416 will be adjusted so that it becomes the smaller one of the two
18417 *visible* surrounding headings.
18419 Any prefix to this command will cause `yank' to be called directly with
18420 no special treatment. In particular, a simple `C-u' prefix will just
18421 plainly yank the text as it is.
18423 \[1] The test checks if the first non-white line is a heading
18424 and if there are no other headings with fewer stars."
18425 (interactive "P")
18426 (org-yank-generic 'yank arg))
18428 (defun org-yank-generic (command arg)
18429 "Perform some yank-like command.
18431 This function implements the behavior described in the `org-yank'
18432 documentation. However, it has been generalized to work for any
18433 interactive command with similar behavior."
18435 ;; pretend to be command COMMAND
18436 (setq this-command command)
18438 (if arg
18439 (call-interactively command)
18441 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18442 (and (org-kill-is-subtree-p)
18443 (or (bolp)
18444 (and (looking-at "[ \t]*$")
18445 (string-match
18446 "\\`\\*+\\'"
18447 (buffer-substring (point-at-bol) (point)))))))
18448 swallowp)
18449 (cond
18450 ((and subtreep org-yank-folded-subtrees)
18451 (let ((beg (point))
18452 end)
18453 (if (and subtreep org-yank-adjusted-subtrees)
18454 (org-paste-subtree nil nil 'for-yank)
18455 (call-interactively command))
18457 (setq end (point))
18458 (goto-char beg)
18459 (when (and (bolp) subtreep
18460 (not (setq swallowp
18461 (org-yank-folding-would-swallow-text beg end))))
18462 (or (looking-at outline-regexp)
18463 (re-search-forward (concat "^" outline-regexp) end t))
18464 (while (and (< (point) end) (looking-at outline-regexp))
18465 (hide-subtree)
18466 (org-cycle-show-empty-lines 'folded)
18467 (condition-case nil
18468 (outline-forward-same-level 1)
18469 (error (goto-char end)))))
18470 (when swallowp
18471 (message
18472 "Inserted text not folded because that would swallow text"))
18474 (goto-char end)
18475 (skip-chars-forward " \t\n\r")
18476 (beginning-of-line 1)
18477 (push-mark beg 'nomsg)))
18478 ((and subtreep org-yank-adjusted-subtrees)
18479 (let ((beg (point-at-bol)))
18480 (org-paste-subtree nil nil 'for-yank)
18481 (push-mark beg 'nomsg)))
18483 (call-interactively command))))))
18485 (defun org-yank-folding-would-swallow-text (beg end)
18486 "Would hide-subtree at BEG swallow any text after END?"
18487 (let (level)
18488 (save-excursion
18489 (goto-char beg)
18490 (when (or (looking-at outline-regexp)
18491 (re-search-forward (concat "^" outline-regexp) end t))
18492 (setq level (org-outline-level)))
18493 (goto-char end)
18494 (skip-chars-forward " \t\r\n\v\f")
18495 (if (or (eobp)
18496 (and (bolp) (looking-at org-outline-regexp)
18497 (<= (org-outline-level) level)))
18498 nil ; Nothing would be swallowed
18499 t)))) ; something would swallow
18501 (define-key org-mode-map "\C-y" 'org-yank)
18503 (defun org-invisible-p ()
18504 "Check if point is at a character currently not visible."
18505 ;; Early versions of noutline don't have `outline-invisible-p'.
18506 (if (fboundp 'outline-invisible-p)
18507 (outline-invisible-p)
18508 (get-char-property (point) 'invisible)))
18510 (defun org-invisible-p2 ()
18511 "Check if point is at a character currently not visible."
18512 (save-excursion
18513 (if (and (eolp) (not (bobp))) (backward-char 1))
18514 ;; Early versions of noutline don't have `outline-invisible-p'.
18515 (if (fboundp 'outline-invisible-p)
18516 (outline-invisible-p)
18517 (get-char-property (point) 'invisible))))
18519 (defun org-back-to-heading (&optional invisible-ok)
18520 "Call `outline-back-to-heading', but provide a better error message."
18521 (condition-case nil
18522 (outline-back-to-heading invisible-ok)
18523 (error (error "Before first headline at position %d in buffer %s"
18524 (point) (current-buffer)))))
18526 (defun org-beginning-of-defun ()
18527 "Go to the beginning of the subtree, i.e. back to the heading."
18528 (org-back-to-heading))
18529 (defun org-end-of-defun ()
18530 "Go to the end of the subtree."
18531 (org-end-of-subtree nil t))
18533 (defun org-before-first-heading-p ()
18534 "Before first heading?"
18535 (save-excursion
18536 (null (re-search-backward "^\\*+ " nil t))))
18538 (defun org-on-heading-p (&optional ignored)
18539 (outline-on-heading-p t))
18540 (defun org-at-heading-p (&optional ignored)
18541 (outline-on-heading-p t))
18543 (defun org-point-at-end-of-empty-headline ()
18544 "If point is at the end of an empty headline, return t, else nil.
18545 If the heading only contains a TODO keyword, it is still still considered
18546 empty."
18547 (and (looking-at "[ \t]*$")
18548 (save-excursion
18549 (beginning-of-line 1)
18550 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18551 "\\)?[ \t]*$")))))
18552 (defun org-at-heading-or-item-p ()
18553 (or (org-on-heading-p) (org-at-item-p)))
18555 (defun org-on-target-p ()
18556 (or (org-in-regexp org-radio-target-regexp)
18557 (org-in-regexp org-target-regexp)))
18559 (defun org-up-heading-all (arg)
18560 "Move to the heading line of which the present line is a subheading.
18561 This function considers both visible and invisible heading lines.
18562 With argument, move up ARG levels."
18563 (if (fboundp 'outline-up-heading-all)
18564 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18565 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18567 (defun org-up-heading-safe ()
18568 "Move to the heading line of which the present line is a subheading.
18569 This version will not throw an error. It will return the level of the
18570 headline found, or nil if no higher level is found.
18572 Also, this function will be a lot faster than `outline-up-heading',
18573 because it relies on stars being the outline starters. This can really
18574 make a significant difference in outlines with very many siblings."
18575 (let (start-level re)
18576 (org-back-to-heading t)
18577 (setq start-level (funcall outline-level))
18578 (if (equal start-level 1)
18580 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18581 (if (re-search-backward re nil t)
18582 (funcall outline-level)))))
18584 (defun org-first-sibling-p ()
18585 "Is this heading the first child of its parents?"
18586 (interactive)
18587 (let ((re (concat "^" outline-regexp))
18588 level l)
18589 (unless (org-at-heading-p t)
18590 (error "Not at a heading"))
18591 (setq level (funcall outline-level))
18592 (save-excursion
18593 (if (not (re-search-backward re nil t))
18595 (setq l (funcall outline-level))
18596 (< l level)))))
18598 (defun org-goto-sibling (&optional previous)
18599 "Goto the next sibling, even if it is invisible.
18600 When PREVIOUS is set, go to the previous sibling instead. Returns t
18601 when a sibling was found. When none is found, return nil and don't
18602 move point."
18603 (let ((fun (if previous 're-search-backward 're-search-forward))
18604 (pos (point))
18605 (re (concat "^" outline-regexp))
18606 level l)
18607 (when (condition-case nil (org-back-to-heading t) (error nil))
18608 (setq level (funcall outline-level))
18609 (catch 'exit
18610 (or previous (forward-char 1))
18611 (while (funcall fun re nil t)
18612 (setq l (funcall outline-level))
18613 (when (< l level) (goto-char pos) (throw 'exit nil))
18614 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18615 (goto-char pos)
18616 nil))))
18618 (defun org-show-siblings ()
18619 "Show all siblings of the current headline."
18620 (save-excursion
18621 (while (org-goto-sibling) (org-flag-heading nil)))
18622 (save-excursion
18623 (while (org-goto-sibling 'previous)
18624 (org-flag-heading nil))))
18626 (defun org-show-hidden-entry ()
18627 "Show an entry where even the heading is hidden."
18628 (save-excursion
18629 (org-show-entry)))
18631 (defun org-flag-heading (flag &optional entry)
18632 "Flag the current heading. FLAG non-nil means make invisible.
18633 When ENTRY is non-nil, show the entire entry."
18634 (save-excursion
18635 (org-back-to-heading t)
18636 ;; Check if we should show the entire entry
18637 (if entry
18638 (progn
18639 (org-show-entry)
18640 (save-excursion
18641 (and (outline-next-heading)
18642 (org-flag-heading nil))))
18643 (outline-flag-region (max (point-min) (1- (point)))
18644 (save-excursion (outline-end-of-heading) (point))
18645 flag))))
18647 (defun org-get-next-sibling ()
18648 "Move to next heading of the same level, and return point.
18649 If there is no such heading, return nil.
18650 This is like outline-next-sibling, but invisible headings are ok."
18651 (let ((level (funcall outline-level)))
18652 (outline-next-heading)
18653 (while (and (not (eobp)) (> (funcall outline-level) level))
18654 (outline-next-heading))
18655 (if (or (eobp) (< (funcall outline-level) level))
18657 (point))))
18659 (defun org-get-last-sibling ()
18660 "Move to previous heading of the same level, and return point.
18661 If there is no such heading, return nil."
18662 (let ((opoint (point))
18663 (level (funcall outline-level)))
18664 (outline-previous-heading)
18665 (when (and (/= (point) opoint) (outline-on-heading-p t))
18666 (while (and (> (funcall outline-level) level)
18667 (not (bobp)))
18668 (outline-previous-heading))
18669 (if (< (funcall outline-level) level)
18671 (point)))))
18673 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18674 ;; This contains an exact copy of the original function, but it uses
18675 ;; `org-back-to-heading', to make it work also in invisible
18676 ;; trees. And is uses an invisible-OK argument.
18677 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18678 ;; Furthermore, when used inside Org, finding the end of a large subtree
18679 ;; with many children and grandchildren etc, this can be much faster
18680 ;; than the outline version.
18681 (org-back-to-heading invisible-OK)
18682 (let ((first t)
18683 (level (funcall outline-level)))
18684 (if (and (org-mode-p) (< level 1000))
18685 ;; A true heading (not a plain list item), in Org-mode
18686 ;; This means we can easily find the end by looking
18687 ;; only for the right number of stars. Using a regexp to do
18688 ;; this is so much faster than using a Lisp loop.
18689 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18690 (forward-char 1)
18691 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18692 ;; something else, do it the slow way
18693 (while (and (not (eobp))
18694 (or first (> (funcall outline-level) level)))
18695 (setq first nil)
18696 (outline-next-heading)))
18697 (unless to-heading
18698 (if (memq (preceding-char) '(?\n ?\^M))
18699 (progn
18700 ;; Go to end of line before heading
18701 (forward-char -1)
18702 (if (memq (preceding-char) '(?\n ?\^M))
18703 ;; leave blank line before heading
18704 (forward-char -1))))))
18705 (point))
18707 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18708 "Use Org version in org-mode, for dramatic speed-up."
18709 (if (eq major-mode 'org-mode)
18710 (progn
18711 (org-end-of-subtree nil t)
18712 (unless (eobp) (backward-char 1)))
18713 ad-do-it))
18715 (defun org-forward-same-level (arg &optional invisible-ok)
18716 "Move forward to the arg'th subheading at same level as this one.
18717 Stop at the first and last subheadings of a superior heading."
18718 (interactive "p")
18719 (org-back-to-heading invisible-ok)
18720 (org-on-heading-p)
18721 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18722 (re (format "^\\*\\{1,%d\\} " level))
18724 (forward-char 1)
18725 (while (> arg 0)
18726 (while (and (re-search-forward re nil 'move)
18727 (setq l (- (match-end 0) (match-beginning 0) 1))
18728 (= l level)
18729 (not invisible-ok)
18730 (progn (backward-char 1) (org-invisible-p)))
18731 (if (< l level) (setq arg 1)))
18732 (setq arg (1- arg)))
18733 (beginning-of-line 1)))
18735 (defun org-backward-same-level (arg &optional invisible-ok)
18736 "Move backward to the arg'th subheading at same level as this one.
18737 Stop at the first and last subheadings of a superior heading."
18738 (interactive "p")
18739 (org-back-to-heading)
18740 (org-on-heading-p)
18741 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18742 (re (format "^\\*\\{1,%d\\} " level))
18744 (while (> arg 0)
18745 (while (and (re-search-backward re nil 'move)
18746 (setq l (- (match-end 0) (match-beginning 0) 1))
18747 (= l level)
18748 (not invisible-ok)
18749 (org-invisible-p))
18750 (if (< l level) (setq arg 1)))
18751 (setq arg (1- arg)))))
18753 (defun org-show-subtree ()
18754 "Show everything after this heading at deeper levels."
18755 (outline-flag-region
18756 (point)
18757 (save-excursion
18758 (org-end-of-subtree t t))
18759 nil))
18761 (defun org-show-entry ()
18762 "Show the body directly following this heading.
18763 Show the heading too, if it is currently invisible."
18764 (interactive)
18765 (save-excursion
18766 (condition-case nil
18767 (progn
18768 (org-back-to-heading t)
18769 (outline-flag-region
18770 (max (point-min) (1- (point)))
18771 (save-excursion
18772 (if (re-search-forward
18773 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18774 (match-beginning 1)
18775 (point-max)))
18776 nil)
18777 (org-cycle-hide-drawers 'children))
18778 (error nil))))
18780 (defun org-make-options-regexp (kwds &optional extra)
18781 "Make a regular expression for keyword lines."
18782 (concat
18784 "#?[ \t]*\\+\\("
18785 (mapconcat 'regexp-quote kwds "\\|")
18786 (if extra (concat "\\|" extra))
18787 "\\):[ \t]*"
18788 "\\(.*\\)"))
18790 ;; Make isearch reveal the necessary context
18791 (defun org-isearch-end ()
18792 "Reveal context after isearch exits."
18793 (when isearch-success ; only if search was successful
18794 (if (featurep 'xemacs)
18795 ;; Under XEmacs, the hook is run in the correct place,
18796 ;; we directly show the context.
18797 (org-show-context 'isearch)
18798 ;; In Emacs the hook runs *before* restoring the overlays.
18799 ;; So we have to use a one-time post-command-hook to do this.
18800 ;; (Emacs 22 has a special variable, see function `org-mode')
18801 (unless (and (boundp 'isearch-mode-end-hook-quit)
18802 isearch-mode-end-hook-quit)
18803 ;; Only when the isearch was not quitted.
18804 (org-add-hook 'post-command-hook 'org-isearch-post-command
18805 'append 'local)))))
18807 (defun org-isearch-post-command ()
18808 "Remove self from hook, and show context."
18809 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18810 (org-show-context 'isearch))
18813 ;;;; Integration with and fixes for other packages
18815 ;;; Imenu support
18817 (defvar org-imenu-markers nil
18818 "All markers currently used by Imenu.")
18819 (make-variable-buffer-local 'org-imenu-markers)
18821 (defun org-imenu-new-marker (&optional pos)
18822 "Return a new marker for use by Imenu, and remember the marker."
18823 (let ((m (make-marker)))
18824 (move-marker m (or pos (point)))
18825 (push m org-imenu-markers)
18828 (defun org-imenu-get-tree ()
18829 "Produce the index for Imenu."
18830 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18831 (setq org-imenu-markers nil)
18832 (let* ((n org-imenu-depth)
18833 (re (concat "^" outline-regexp))
18834 (subs (make-vector (1+ n) nil))
18835 (last-level 0)
18836 m level head)
18837 (save-excursion
18838 (save-restriction
18839 (widen)
18840 (goto-char (point-max))
18841 (while (re-search-backward re nil t)
18842 (setq level (org-reduced-level (funcall outline-level)))
18843 (when (<= level n)
18844 (looking-at org-complex-heading-regexp)
18845 (setq head (org-link-display-format
18846 (org-match-string-no-properties 4))
18847 m (org-imenu-new-marker))
18848 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18849 (if (>= level last-level)
18850 (push (cons head m) (aref subs level))
18851 (push (cons head (aref subs (1+ level))) (aref subs level))
18852 (loop for i from (1+ level) to n do (aset subs i nil)))
18853 (setq last-level level)))))
18854 (aref subs 1)))
18856 (eval-after-load "imenu"
18857 '(progn
18858 (add-hook 'imenu-after-jump-hook
18859 (lambda ()
18860 (if (eq major-mode 'org-mode)
18861 (org-show-context 'org-goto))))))
18863 (defun org-link-display-format (link)
18864 "Replace a link with either the description, or the link target
18865 if no description is present"
18866 (save-match-data
18867 (if (string-match org-bracket-link-analytic-regexp link)
18868 (replace-match (if (match-end 5)
18869 (match-string 5 link)
18870 (concat (match-string 1 link)
18871 (match-string 3 link)))
18872 nil t link)
18873 link)))
18875 ;; Speedbar support
18877 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
18878 "Overlay marking the agenda restriction line in speedbar.")
18879 (overlay-put org-speedbar-restriction-lock-overlay
18880 'face 'org-agenda-restriction-lock)
18881 (overlay-put org-speedbar-restriction-lock-overlay
18882 'help-echo "Agendas are currently limited to this item.")
18883 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18885 (defun org-speedbar-set-agenda-restriction ()
18886 "Restrict future agenda commands to the location at point in speedbar.
18887 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18888 (interactive)
18889 (require 'org-agenda)
18890 (let (p m tp np dir txt)
18891 (cond
18892 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18893 'org-imenu t))
18894 (setq m (get-text-property p 'org-imenu-marker))
18895 (with-current-buffer (marker-buffer m)
18896 (goto-char m)
18897 (org-agenda-set-restriction-lock 'subtree)))
18898 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18899 'speedbar-function 'speedbar-find-file))
18900 (setq tp (previous-single-property-change
18901 (1+ p) 'speedbar-function)
18902 np (next-single-property-change
18903 tp 'speedbar-function)
18904 dir (speedbar-line-directory)
18905 txt (buffer-substring-no-properties (or tp (point-min))
18906 (or np (point-max))))
18907 (with-current-buffer (find-file-noselect
18908 (let ((default-directory dir))
18909 (expand-file-name txt)))
18910 (unless (org-mode-p)
18911 (error "Cannot restrict to non-Org-mode file"))
18912 (org-agenda-set-restriction-lock 'file)))
18913 (t (error "Don't know how to restrict Org-mode's agenda")))
18914 (move-overlay org-speedbar-restriction-lock-overlay
18915 (point-at-bol) (point-at-eol))
18916 (setq current-prefix-arg nil)
18917 (org-agenda-maybe-redo)))
18919 (eval-after-load "speedbar"
18920 '(progn
18921 (speedbar-add-supported-extension ".org")
18922 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18923 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18924 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18925 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18926 (add-hook 'speedbar-visiting-tag-hook
18927 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18929 ;;; Fixes and Hacks for problems with other packages
18931 ;; Make flyspell not check words in links, to not mess up our keymap
18932 (defun org-mode-flyspell-verify ()
18933 "Don't let flyspell put overlays at active buttons."
18934 (and (not (get-text-property (point) 'keymap))
18935 (not (get-text-property (point) 'org-no-flyspell))))
18937 (defun org-remove-flyspell-overlays-in (beg end)
18938 "Remove flyspell overlays in region."
18939 (and (org-bound-and-true-p flyspell-mode)
18940 (fboundp 'flyspell-delete-region-overlays)
18941 (flyspell-delete-region-overlays beg end))
18942 (add-text-properties beg end '(org-no-flyspell t)))
18944 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18945 (eval-after-load "bookmark"
18946 '(if (boundp 'bookmark-after-jump-hook)
18947 ;; We can use the hook
18948 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18949 ;; Hook not available, use advice
18950 (defadvice bookmark-jump (after org-make-visible activate)
18951 "Make the position visible."
18952 (org-bookmark-jump-unhide))))
18954 ;; Make sure saveplace shows the location if it was hidden
18955 (eval-after-load "saveplace"
18956 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18957 "Make the position visible."
18958 (org-bookmark-jump-unhide)))
18960 ;; Make sure ecb shows the location if it was hidden
18961 (eval-after-load "ecb"
18962 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18963 "Make hierarchy visible when jumping into location from ECB tree buffer."
18964 (if (eq major-mode 'org-mode)
18965 (org-show-context))))
18967 (defun org-bookmark-jump-unhide ()
18968 "Unhide the current position, to show the bookmark location."
18969 (and (org-mode-p)
18970 (or (org-invisible-p)
18971 (save-excursion (goto-char (max (point-min) (1- (point))))
18972 (org-invisible-p)))
18973 (org-show-context 'bookmark-jump)))
18975 ;; Make session.el ignore our circular variable
18976 (eval-after-load "session"
18977 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18979 ;;;; Experimental code
18981 (defun org-closed-in-range ()
18982 "Sparse tree of items closed in a certain time range.
18983 Still experimental, may disappear in the future."
18984 (interactive)
18985 ;; Get the time interval from the user.
18986 (let* ((time1 (org-float-time
18987 (org-read-date nil 'to-time nil "Starting date: ")))
18988 (time2 (org-float-time
18989 (org-read-date nil 'to-time nil "End date:")))
18990 ;; callback function
18991 (callback (lambda ()
18992 (let ((time
18993 (org-float-time
18994 (apply 'encode-time
18995 (org-parse-time-string
18996 (match-string 1))))))
18997 ;; check if time in interval
18998 (and (>= time time1) (<= time time2))))))
18999 ;; make tree, check each match with the callback
19000 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19002 ;;;; Finish up
19004 (provide 'org)
19006 (run-hooks 'org-load-hook)
19008 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19010 ;;; org.el ends here