Make M-right/left work on regions again
[org-mode.git] / lisp / org.el
blob463a0eb0d65d8f166825a5a47d5b85374fce45e2
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.35trans
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
109 ;;; Version
111 (defconst org-version "6.35trans"
112 "The version number of the file org.el.")
114 (defun org-version (&optional here)
115 "Show the org-mode version in the echo area.
116 With prefix arg HERE, insert it at point."
117 (interactive "P")
118 (let* ((origin default-directory)
119 (version org-version)
120 (git-version)
121 (dir (concat (file-name-directory (locate-library "org")) "../" )))
122 (when (and (file-exists-p (expand-file-name ".git" dir))
123 (executable-find "git"))
124 (unwind-protect
125 (progn
126 (cd dir)
127 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
128 (with-current-buffer "*Shell Command Output*"
129 (goto-char (point-min))
130 (setq git-version (buffer-substring (point) (point-at-eol))))
131 (subst-char-in-string ?- ?. git-version t)
132 (when (string-match "\\S-"
133 (shell-command-to-string
134 "git diff-index --name-only HEAD --"))
135 (setq git-version (concat git-version ".dirty")))
136 (setq version (concat version " (" git-version ")"))))
137 (cd origin)))
138 (setq version (format "Org-mode version %s" version))
139 (if here (insert version))
140 (message version)))
142 ;;; Compatibility constants
144 ;;; The custom variables
146 (defgroup org nil
147 "Outline-based notes management and organizer."
148 :tag "Org"
149 :group 'outlines
150 :group 'calendar)
152 (defcustom org-mode-hook nil
153 "Mode hook for Org-mode, run after the mode was turned on."
154 :group 'org
155 :type 'hook)
157 (defcustom org-load-hook nil
158 "Hook that is run after org.el has been loaded."
159 :group 'org
160 :type 'hook)
162 (defvar org-modules) ; defined below
163 (defvar org-modules-loaded nil
164 "Have the modules been loaded already?")
166 (defun org-load-modules-maybe (&optional force)
167 "Load all extensions listed in `org-modules'."
168 (when (or force (not org-modules-loaded))
169 (mapc (lambda (ext)
170 (condition-case nil (require ext)
171 (error (message "Problems while trying to load feature `%s'" ext))))
172 org-modules)
173 (setq org-modules-loaded t)))
175 (defun org-set-modules (var value)
176 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
177 (set var value)
178 (when (featurep 'org)
179 (org-load-modules-maybe 'force)))
181 (when (org-bound-and-true-p org-modules)
182 (let ((a (member 'org-infojs org-modules)))
183 (and a (setcar a 'org-jsinfo))))
185 (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)
186 "Modules that should always be loaded together with org.el.
187 If a description starts with <C>, the file is not part of Emacs
188 and loading it will require that you have downloaded and properly installed
189 the org-mode distribution.
191 You can also use this system to load external packages (i.e. neither Org
192 core modules, nor modules from the CONTRIB directory). Just add symbols
193 to the end of the list. If the package is called org-xyz.el, then you need
194 to add the symbol `xyz', and the package must have a call to
196 (provide 'org-xyz)"
197 :group 'org
198 :set 'org-set-modules
199 :type
200 '(set :greedy t
201 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
202 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
203 (const :tag " crypt: Encryption of subtrees" org-crypt)
204 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
205 (const :tag " docview: Links to doc-view buffers" org-docview)
206 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
207 (const :tag " id: Global IDs for identifying entries" org-id)
208 (const :tag " info: Links to Info nodes" org-info)
209 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
210 (const :tag " habit: Track your consistency with habits" org-habit)
211 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
212 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
213 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
214 (const :tag " mew Links to Mew folders/messages" org-mew)
215 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
216 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
217 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
218 (const :tag " vm: Links to VM folders/messages" org-vm)
219 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
220 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
221 (const :tag " mouse: Additional mouse support" org-mouse)
223 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
224 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
225 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
226 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
227 (const :tag "C collector: Collect properties into tables" org-collector)
228 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
229 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
230 (const :tag "C eval: Include command output as text" org-eval)
231 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
232 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
233 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
234 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
235 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
237 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
239 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
240 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
241 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
242 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
243 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
244 (const :tag "C mtags: Support for muse-like tags" org-mtags)
245 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
246 (const :tag "C registry: A registry for Org-mode links" org-registry)
247 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
248 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
249 (const :tag "C secretary: Team management with org-mode" org-secretary)
250 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
251 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
252 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
253 (const :tag "C track: Keep up with Org-mode development" org-track)
254 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
256 (defcustom org-support-shift-select nil
257 "Non-nil means make shift-cursor commands select text when possible.
259 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
260 selecting a region, or enlarge thusly regions started in this way.
261 In Org-mode, in special contexts, these same keys are used for other
262 purposes, important enough to compete with shift selection. Org tries
263 to balance these needs by supporting `shift-select-mode' outside these
264 special contexts, under control of this variable.
266 The default of this variable is nil, to avoid confusing behavior. Shifted
267 cursor keys will then execute Org commands in the following contexts:
268 - on a headline, changing TODO state (left/right) and priority (up/down)
269 - on a time stamp, changing the time
270 - in a plain list item, changing the bullet type
271 - in a property definition line, switching between allowed values
272 - in the BEGIN line of a clock table (changing the time block).
273 Outside these contexts, the commands will throw an error.
275 When this variable is t and the cursor is not in a special context,
276 Org-mode will support shift-selection for making and enlarging regions.
277 To make this more effective, the bullet cycling will no longer happen
278 anywhere in an item line, but only if the cursor is exactly on the bullet.
280 If you set this variable to the symbol `always', then the keys
281 will not be special in headlines, property lines, and item lines, to make
282 shift selection work there as well. If this is what you want, you can
283 use the following alternative commands: `C-c C-t' and `C-c ,' to
284 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
285 TODO sets, `C-c -' to cycle item bullet types, and properties can be
286 edited by hand or in column view.
288 However, when the cursor is on a timestamp, shift-cursor commands
289 will still edit the time stamp - this is just too good to give up.
291 XEmacs user should have this variable set to nil, because shift-select-mode
292 is Emacs 23 only."
293 :group 'org
294 :type '(choice
295 (const :tag "Never" nil)
296 (const :tag "When outside special context" t)
297 (const :tag "Everywhere except timestamps" always)))
299 (defgroup org-startup nil
300 "Options concerning startup of Org-mode."
301 :tag "Org Startup"
302 :group 'org)
304 (defcustom org-startup-folded t
305 "Non-nil means entering Org-mode will switch to OVERVIEW.
306 This can also be configured on a per-file basis by adding one of
307 the following lines anywhere in the buffer:
309 #+STARTUP: fold (or `overview', this is equivalent)
310 #+STARTUP: nofold (or `showall', this is equivalent)
311 #+STARTUP: content
312 #+STARTUP: showeverything"
313 :group 'org-startup
314 :type '(choice
315 (const :tag "nofold: show all" nil)
316 (const :tag "fold: overview" t)
317 (const :tag "content: all headlines" content)
318 (const :tag "show everything, even drawers" showeverything)))
320 (defcustom org-startup-truncated t
321 "Non-nil means entering Org-mode will set `truncate-lines'.
322 This is useful since some lines containing links can be very long and
323 uninteresting. Also tables look terrible when wrapped."
324 :group 'org-startup
325 :type 'boolean)
327 (defcustom org-startup-indented nil
328 "Non-nil means turn on `org-indent-mode' on startup.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
332 #+STARTUP: indent
333 #+STARTUP: noindent"
334 :group 'org-structure
335 :type '(choice
336 (const :tag "Not" nil)
337 (const :tag "Globally (slow on startup in large files)" t)))
339 (defcustom org-startup-with-beamer-mode nil
340 "Non-nil means turn on `org-beamer-mode' on startup.
341 This can also be configured on a per-file basis by adding one of
342 the following lines anywhere in the buffer:
344 #+STARTUP: beamer"
345 :group 'org-startup
346 :type 'boolean)
348 (defcustom org-startup-align-all-tables nil
349 "Non-nil means align all tables when visiting a file.
350 This is useful when the column width in tables is forced with <N> cookies
351 in table fields. Such tables will look correct only after the first re-align.
352 This can also be configured on a per-file basis by adding one of
353 the following lines anywhere in the buffer:
354 #+STARTUP: align
355 #+STARTUP: noalign"
356 :group 'org-startup
357 :type 'boolean)
359 (defcustom org-insert-mode-line-in-empty-file nil
360 "Non-nil means insert the first line setting Org-mode in empty files.
361 When the function `org-mode' is called interactively in an empty file, this
362 normally means that the file name does not automatically trigger Org-mode.
363 To ensure that the file will always be in Org-mode in the future, a
364 line enforcing Org-mode will be inserted into the buffer, if this option
365 has been set."
366 :group 'org-startup
367 :type 'boolean)
369 (defcustom org-replace-disputed-keys nil
370 "Non-nil means use alternative key bindings for some keys.
371 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
372 These keys are also used by other packages like shift-selection-mode'
373 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
374 If you want to use Org-mode together with one of these other modes,
375 or more generally if you would like to move some Org-mode commands to
376 other keys, set this variable and configure the keys with the variable
377 `org-disputed-keys'.
379 This option is only relevant at load-time of Org-mode, and must be set
380 *before* org.el is loaded. Changing it requires a restart of Emacs to
381 become effective."
382 :group 'org-startup
383 :type 'boolean)
385 (defcustom org-use-extra-keys nil
386 "Non-nil means use extra key sequence definitions for certain
387 commands. This happens automatically if you run XEmacs or if
388 window-system is nil. This variable lets you do the same
389 manually. You must set it before loading org.
391 Example: on Carbon Emacs 22 running graphically, with an external
392 keyboard on a Powerbook, the default way of setting M-left might
393 not work for either Alt or ESC. Setting this variable will make
394 it work for ESC."
395 :group 'org-startup
396 :type 'boolean)
398 (if (fboundp 'defvaralias)
399 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
401 (defcustom org-disputed-keys
402 '(([(shift up)] . [(meta p)])
403 ([(shift down)] . [(meta n)])
404 ([(shift left)] . [(meta -)])
405 ([(shift right)] . [(meta +)])
406 ([(control shift right)] . [(meta shift +)])
407 ([(control shift left)] . [(meta shift -)]))
408 "Keys for which Org-mode and other modes compete.
409 This is an alist, cars are the default keys, second element specifies
410 the alternative to use when `org-replace-disputed-keys' is t.
412 Keys can be specified in any syntax supported by `define-key'.
413 The value of this option takes effect only at Org-mode's startup,
414 therefore you'll have to restart Emacs to apply it after changing."
415 :group 'org-startup
416 :type 'alist)
418 (defun org-key (key)
419 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
420 Or return the original if not disputed.
421 Also apply the trnaslations defined in `org-xemacs-key-equivalents'."
422 (when org-replace-disputed-keys
423 (let* ((nkey (key-description key))
424 (x (org-find-if (lambda (x)
425 (equal (key-description (car x)) nkey))
426 org-disputed-keys)))
427 (setq key (if x (cdr x) key))))
428 (when (featurep 'xemacs)
429 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
430 key)
432 (defun org-find-if (predicate seq)
433 (catch 'exit
434 (while seq
435 (if (funcall predicate (car seq))
436 (throw 'exit (car seq))
437 (pop seq)))))
439 (defun org-defkey (keymap key def)
440 "Define a key, possibly translated, as returned by `org-key'."
441 (define-key keymap (org-key key) def))
443 (defcustom org-ellipsis nil
444 "The ellipsis to use in the Org-mode outline.
445 When nil, just use the standard three dots. When a string, use that instead,
446 When a face, use the standard 3 dots, but with the specified face.
447 The change affects only Org-mode (which will then use its own display table).
448 Changing this requires executing `M-x org-mode' in a buffer to become
449 effective."
450 :group 'org-startup
451 :type '(choice (const :tag "Default" nil)
452 (face :tag "Face" :value org-warning)
453 (string :tag "String" :value "...#")))
455 (defvar org-display-table nil
456 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
458 (defgroup org-keywords nil
459 "Keywords in Org-mode."
460 :tag "Org Keywords"
461 :group 'org)
463 (defcustom org-deadline-string "DEADLINE:"
464 "String to mark deadline entries.
465 A deadline is this string, followed by a time stamp. Should be a word,
466 terminated by a colon. You can insert a schedule keyword and
467 a timestamp with \\[org-deadline].
468 Changes become only effective after restarting Emacs."
469 :group 'org-keywords
470 :type 'string)
472 (defcustom org-scheduled-string "SCHEDULED:"
473 "String to mark scheduled TODO entries.
474 A schedule is this string, followed by a time stamp. Should be a word,
475 terminated by a colon. You can insert a schedule keyword and
476 a timestamp with \\[org-schedule].
477 Changes become only effective after restarting Emacs."
478 :group 'org-keywords
479 :type 'string)
481 (defcustom org-closed-string "CLOSED:"
482 "String used as the prefix for timestamps logging closing a TODO entry."
483 :group 'org-keywords
484 :type 'string)
486 (defcustom org-clock-string "CLOCK:"
487 "String used as prefix for timestamps clocking work hours on an item."
488 :group 'org-keywords
489 :type 'string)
491 (defcustom org-comment-string "COMMENT"
492 "Entries starting with this keyword will never be exported.
493 An entry can be toggled between COMMENT and normal with
494 \\[org-toggle-comment].
495 Changes become only effective after restarting Emacs."
496 :group 'org-keywords
497 :type 'string)
499 (defcustom org-quote-string "QUOTE"
500 "Entries starting with this keyword will be exported in fixed-width font.
501 Quoting applies only to the text in the entry following the headline, and does
502 not extend beyond the next headline, even if that is lower level.
503 An entry can be toggled between QUOTE and normal with
504 \\[org-toggle-fixed-width-section]."
505 :group 'org-keywords
506 :type 'string)
508 (defconst org-repeat-re
509 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
510 "Regular expression for specifying repeated events.
511 After a match, group 1 contains the repeat expression.")
513 (defgroup org-structure nil
514 "Options concerning the general structure of Org-mode files."
515 :tag "Org Structure"
516 :group 'org)
518 (defgroup org-reveal-location nil
519 "Options about how to make context of a location visible."
520 :tag "Org Reveal Location"
521 :group 'org-structure)
523 (defconst org-context-choice
524 '(choice
525 (const :tag "Always" t)
526 (const :tag "Never" nil)
527 (repeat :greedy t :tag "Individual contexts"
528 (cons
529 (choice :tag "Context"
530 (const agenda)
531 (const org-goto)
532 (const occur-tree)
533 (const tags-tree)
534 (const link-search)
535 (const mark-goto)
536 (const bookmark-jump)
537 (const isearch)
538 (const default))
539 (boolean))))
540 "Contexts for the reveal options.")
542 (defcustom org-show-hierarchy-above '((default . t))
543 "Non-nil means show full hierarchy when revealing a location.
544 Org-mode often shows locations in an org-mode file which might have
545 been invisible before. When this is set, the hierarchy of headings
546 above the exposed location is shown.
547 Turning this off for example for sparse trees makes them very compact.
548 Instead of t, this can also be an alist specifying this option for different
549 contexts. Valid contexts are
550 agenda when exposing an entry from the agenda
551 org-goto when using the command `org-goto' on key C-c C-j
552 occur-tree when using the command `org-occur' on key C-c /
553 tags-tree when constructing a sparse tree based on tags matches
554 link-search when exposing search matches associated with a link
555 mark-goto when exposing the jump goal of a mark
556 bookmark-jump when exposing a bookmark location
557 isearch when exiting from an incremental search
558 default default for all contexts not set explicitly"
559 :group 'org-reveal-location
560 :type org-context-choice)
562 (defcustom org-show-following-heading '((default . nil))
563 "Non-nil means show following heading when revealing a location.
564 Org-mode often shows locations in an org-mode file which might have
565 been invisible before. When this is set, the heading following the
566 match is shown.
567 Turning this off for example for sparse trees makes them very compact,
568 but makes it harder to edit the location of the match. In such a case,
569 use the command \\[org-reveal] to show more context.
570 Instead of t, this can also be an alist specifying this option for different
571 contexts. See `org-show-hierarchy-above' for valid contexts."
572 :group 'org-reveal-location
573 :type org-context-choice)
575 (defcustom org-show-siblings '((default . nil) (isearch t))
576 "Non-nil means show all sibling heading when revealing a location.
577 Org-mode often shows locations in an org-mode file which might have
578 been invisible before. When this is set, the sibling of the current entry
579 heading are all made visible. If `org-show-hierarchy-above' is t,
580 the same happens on each level of the hierarchy above the current entry.
582 By default this is on for the isearch context, off for all other contexts.
583 Turning this off for example for sparse trees makes them very compact,
584 but makes it harder to edit the location of the match. In such a case,
585 use the command \\[org-reveal] to show more context.
586 Instead of t, this can also be an alist specifying this option for different
587 contexts. See `org-show-hierarchy-above' for valid contexts."
588 :group 'org-reveal-location
589 :type org-context-choice)
591 (defcustom org-show-entry-below '((default . nil))
592 "Non-nil means show the entry below a headline when revealing a location.
593 Org-mode often shows locations in an org-mode file which might have
594 been invisible before. When this is set, the text below the headline that is
595 exposed is also shown.
597 By default this is off for all contexts.
598 Instead of t, this can also be an alist specifying this option for different
599 contexts. See `org-show-hierarchy-above' for valid contexts."
600 :group 'org-reveal-location
601 :type org-context-choice)
603 (defcustom org-indirect-buffer-display 'other-window
604 "How should indirect tree buffers be displayed?
605 This applies to indirect buffers created with the commands
606 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
607 Valid values are:
608 current-window Display in the current window
609 other-window Just display in another window.
610 dedicated-frame Create one new frame, and re-use it each time.
611 new-frame Make a new frame each time. Note that in this case
612 previously-made indirect buffers are kept, and you need to
613 kill these buffers yourself."
614 :group 'org-structure
615 :group 'org-agenda-windows
616 :type '(choice
617 (const :tag "In current window" current-window)
618 (const :tag "In current frame, other window" other-window)
619 (const :tag "Each time a new frame" new-frame)
620 (const :tag "One dedicated frame" dedicated-frame)))
622 (defcustom org-use-speed-commands nil
623 "Non-nil means activate single letter commands at beginning of a headline.
624 This may also be a function to test for appropriate locations where speed
625 commands should be active."
626 :group 'org-structure
627 :type '(choice
628 (const :tag "Never" nil)
629 (const :tag "At beginning of headline stars" t)
630 (function)))
632 (defcustom org-speed-commands-user nil
633 "Alist of additional speed commands.
634 This list will be checked before `org-speed-commands-default'
635 when the variable `org-use-speed-commands' is non-nil
636 and when the cursor is at the beginning of a headline.
637 The car if each entry is a string with a single letter, which must
638 be assigned to `self-insert-command' in the global map.
639 The cdr is either a command to be called interactively, a function
640 to be called, or a form to be evaluated.
641 An entry that is just a list with a single string will be interpreted
642 as a descriptive headline that will be added when listing the speed
643 copmmands in the Help buffer using the `?' speed command."
644 :group 'org-structure
645 :type '(repeat :value ("k" . ignore)
646 (choice :value ("k" . ignore)
647 (list :tag "Descriptive Headline" (string :tag "Headline"))
648 (cons :tag "Letter and Command"
649 (string :tag "Command letter")
650 (choice
651 (function)
652 (sexp))))))
654 (defgroup org-cycle nil
655 "Options concerning visibility cycling in Org-mode."
656 :tag "Org Cycle"
657 :group 'org-structure)
659 (defcustom org-cycle-skip-children-state-if-no-children t
660 "Non-nil means skip CHILDREN state in entries that don't have any."
661 :group 'org-cycle
662 :type 'boolean)
664 (defcustom org-cycle-max-level nil
665 "Maximum level which should still be subject to visibility cycling.
666 Levels higher than this will, for cycling, be treated as text, not a headline.
667 When `org-odd-levels-only' is set, a value of N in this variable actually
668 means 2N-1 stars as the limiting headline.
669 When nil, cycle all levels.
670 Note that the limiting level of cycling is also influenced by
671 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
672 `org-inlinetask-min-level' is, cycling will be limited to levels one less
673 than its value."
674 :group 'org-cycle
675 :type '(choice
676 (const :tag "No limit" nil)
677 (integer :tag "Maximum level")))
679 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
680 "Names of drawers. Drawers are not opened by cycling on the headline above.
681 Drawers only open with a TAB on the drawer line itself. A drawer looks like
682 this:
683 :DRAWERNAME:
684 .....
685 :END:
686 The drawer \"PROPERTIES\" is special for capturing properties through
687 the property API.
689 Drawers can be defined on the per-file basis with a line like:
691 #+DRAWERS: HIDDEN STATE PROPERTIES"
692 :group 'org-structure
693 :group 'org-cycle
694 :type '(repeat (string :tag "Drawer Name")))
696 (defcustom org-hide-block-startup nil
697 "Non-nil means entering Org-mode will fold all blocks.
698 This can also be set in on a per-file basis with
700 #+STARTUP: hideblocks
701 #+STARTUP: showblocks"
702 :group 'org-startup
703 :group 'org-cycle
704 :type 'boolean)
706 (defcustom org-cycle-global-at-bob nil
707 "Cycle globally if cursor is at beginning of buffer and not at a headline.
708 This makes it possible to do global cycling without having to use S-TAB or
709 C-u TAB. For this special case to work, the first line of the buffer
710 must not be a headline - it may be empty or some other text. When used in
711 this way, `org-cycle-hook' is disables temporarily, to make sure the
712 cursor stays at the beginning of the buffer.
713 When this option is nil, don't do anything special at the beginning
714 of the buffer."
715 :group 'org-cycle
716 :type 'boolean)
718 (defcustom org-cycle-level-after-item/entry-creation t
719 "Non-nil means cycle entry level or item indentation in new empty entries.
721 When the cursor is at the end of an empty headline, i.e with only stars
722 and maybe a TODO keyword, TAB will then switch the entry to become a child,
723 and then all possible anchestor states, before returning to the original state.
724 This makes data entry extremely fast: M-RET to create a new headline,
725 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
727 When the cursor is at the end of an empty plain list item, one TAB will
728 make it a subitem, two or more tabs will back up to make this an item
729 higher up in the item hierarchy."
730 :group 'org-cycle
731 :type 'boolean)
733 (defcustom org-cycle-emulate-tab t
734 "Where should `org-cycle' emulate TAB.
735 nil Never
736 white Only in completely white lines
737 whitestart Only at the beginning of lines, before the first non-white char
738 t Everywhere except in headlines
739 exc-hl-bol Everywhere except at the start of a headline
740 If TAB is used in a place where it does not emulate TAB, the current subtree
741 visibility is cycled."
742 :group 'org-cycle
743 :type '(choice (const :tag "Never" nil)
744 (const :tag "Only in completely white lines" white)
745 (const :tag "Before first char in a line" whitestart)
746 (const :tag "Everywhere except in headlines" t)
747 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
750 (defcustom org-cycle-separator-lines 2
751 "Number of empty lines needed to keep an empty line between collapsed trees.
752 If you leave an empty line between the end of a subtree and the following
753 headline, this empty line is hidden when the subtree is folded.
754 Org-mode will leave (exactly) one empty line visible if the number of
755 empty lines is equal or larger to the number given in this variable.
756 So the default 2 means at least 2 empty lines after the end of a subtree
757 are needed to produce free space between a collapsed subtree and the
758 following headline.
760 If the number is negative, and the number of empty lines is at least -N,
761 all empty lines are shown.
763 Special case: when 0, never leave empty lines in collapsed view."
764 :group 'org-cycle
765 :type 'integer)
766 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
768 (defcustom org-pre-cycle-hook nil
769 "Hook that is run before visibility cycling is happening.
770 The function(s) in this hook must accept a single argument which indicates
771 the new state that will be set right after running this hook. The
772 argument is a symbol. Before a global state change, it can have the values
773 `overview', `content', or `all'. Before a local state change, it can have
774 the values `folded', `children', or `subtree'."
775 :group 'org-cycle
776 :type 'hook)
778 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
779 org-cycle-hide-drawers
780 org-cycle-show-empty-lines
781 org-optimize-window-after-visibility-change)
782 "Hook that is run after `org-cycle' has changed the buffer visibility.
783 The function(s) in this hook must accept a single argument which indicates
784 the new state that was set by the most recent `org-cycle' command. The
785 argument is a symbol. After a global state change, it can have the values
786 `overview', `content', or `all'. After a local state change, it can have
787 the values `folded', `children', or `subtree'."
788 :group 'org-cycle
789 :type 'hook)
791 (defgroup org-edit-structure nil
792 "Options concerning structure editing in Org-mode."
793 :tag "Org Edit Structure"
794 :group 'org-structure)
796 (defcustom org-odd-levels-only nil
797 "Non-nil means skip even levels and only use odd levels for the outline.
798 This has the effect that two stars are being added/taken away in
799 promotion/demotion commands. It also influences how levels are
800 handled by the exporters.
801 Changing it requires restart of `font-lock-mode' to become effective
802 for fontification also in regions already fontified.
803 You may also set this on a per-file basis by adding one of the following
804 lines to the buffer:
806 #+STARTUP: odd
807 #+STARTUP: oddeven"
808 :group 'org-edit-structure
809 :group 'org-appearance
810 :type 'boolean)
812 (defcustom org-adapt-indentation t
813 "Non-nil means adapt indentation to outline node level.
815 When this variable is set, Org assumes that you write outlines by
816 indenting text in each node to align with the headline (after the stars).
817 The following issues are influenced by this variable:
819 - When this is set and the *entire* text in an entry is indented, the
820 indentation is increased by one space in a demotion command, and
821 decreased by one in a promotion command. If any line in the entry
822 body starts with text at column 0, indentation is not changed at all.
824 - Property drawers and planning information is inserted indented when
825 this variable s set. When nil, they will not be indented.
827 - TAB indents a line relative to context. The lines below a headline
828 will be indented when this variable is set.
830 Note that this is all about true indentation, by adding and removing
831 space characters. See also `org-indent.el' which does level-dependent
832 indentation in a virtual way, i.e. at display time in Emacs."
833 :group 'org-edit-structure
834 :type 'boolean)
836 (defcustom org-special-ctrl-a/e nil
837 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
839 When t, `C-a' will bring back the cursor to the beginning of the
840 headline text, i.e. after the stars and after a possible TODO keyword.
841 In an item, this will be the position after the bullet.
842 When the cursor is already at that position, another `C-a' will bring
843 it to the beginning of the line.
845 `C-e' will jump to the end of the headline, ignoring the presence of tags
846 in the headline. A second `C-e' will then jump to the true end of the
847 line, after any tags. This also means that, when this variable is
848 non-nil, `C-e' also will never jump beyond the end of the heading of a
849 folded section, i.e. not after the ellipses.
851 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
852 going to the true line boundary first. Only a directly following, identical
853 keypress will bring the cursor to the special positions.
855 This may also be a cons cell where the behavior for `C-a' and `C-e' is
856 set separately."
857 :group 'org-edit-structure
858 :type '(choice
859 (const :tag "off" nil)
860 (const :tag "on: after stars/bullet and before tags first" t)
861 (const :tag "reversed: true line boundary first" reversed)
862 (cons :tag "Set C-a and C-e separately"
863 (choice :tag "Special C-a"
864 (const :tag "off" nil)
865 (const :tag "on: after stars/bullet first" t)
866 (const :tag "reversed: before stars/bullet first" reversed))
867 (choice :tag "Special C-e"
868 (const :tag "off" nil)
869 (const :tag "on: before tags first" t)
870 (const :tag "reversed: after tags first" reversed)))))
871 (if (fboundp 'defvaralias)
872 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
874 (defcustom org-special-ctrl-k nil
875 "Non-nil means `C-k' will behave specially in headlines.
876 When nil, `C-k' will call the default `kill-line' command.
877 When t, the following will happen while the cursor is in the headline:
879 - When the cursor is at the beginning of a headline, kill the entire
880 line and possible the folded subtree below the line.
881 - When in the middle of the headline text, kill the headline up to the tags.
882 - When after the headline text, kill the tags."
883 :group 'org-edit-structure
884 :type 'boolean)
886 (defcustom org-yank-folded-subtrees t
887 "Non-nil means when yanking subtrees, fold them.
888 If the kill is a single subtree, or a sequence of subtrees, i.e. if
889 it starts with a heading and all other headings in it are either children
890 or siblings, then fold all the subtrees. However, do this only if no
891 text after the yank would be swallowed into a folded tree by this action."
892 :group 'org-edit-structure
893 :type 'boolean)
895 (defcustom org-yank-adjusted-subtrees nil
896 "Non-nil means when yanking subtrees, adjust the level.
897 With this setting, `org-paste-subtree' is used to insert the subtree, see
898 this function for details."
899 :group 'org-edit-structure
900 :type 'boolean)
902 (defcustom org-M-RET-may-split-line '((default . t))
903 "Non-nil means M-RET will split the line at the cursor position.
904 When nil, it will go to the end of the line before making a
905 new line.
906 You may also set this option in a different way for different
907 contexts. Valid contexts are:
909 headline when creating a new headline
910 item when creating a new item
911 table in a table field
912 default the value to be used for all contexts not explicitly
913 customized"
914 :group 'org-structure
915 :group 'org-table
916 :type '(choice
917 (const :tag "Always" t)
918 (const :tag "Never" nil)
919 (repeat :greedy t :tag "Individual contexts"
920 (cons
921 (choice :tag "Context"
922 (const headline)
923 (const item)
924 (const table)
925 (const default))
926 (boolean)))))
929 (defcustom org-insert-heading-respect-content nil
930 "Non-nil means insert new headings after the current subtree.
931 When nil, the new heading is created directly after the current line.
932 The commands \\[org-insert-heading-respect-content] and
933 \\[org-insert-todo-heading-respect-content] turn this variable on
934 for the duration of the command."
935 :group 'org-structure
936 :type 'boolean)
938 (defcustom org-blank-before-new-entry '((heading . auto)
939 (plain-list-item . auto))
940 "Should `org-insert-heading' leave a blank line before new heading/item?
941 The value is an alist, with `heading' and `plain-list-item' as car,
942 and a boolean flag as cdr. For plain lists, if the variable
943 `org-empty-line-terminates-plain-lists' is set, the setting here
944 is ignored and no empty line is inserted, to keep the list in tact."
945 :group 'org-edit-structure
946 :type '(list
947 (cons (const heading)
948 (choice (const :tag "Never" nil)
949 (const :tag "Always" t)
950 (const :tag "Auto" auto)))
951 (cons (const plain-list-item)
952 (choice (const :tag "Never" nil)
953 (const :tag "Always" t)
954 (const :tag "Auto" auto)))))
956 (defcustom org-insert-heading-hook nil
957 "Hook being run after inserting a new heading."
958 :group 'org-edit-structure
959 :type 'hook)
961 (defcustom org-enable-fixed-width-editor t
962 "Non-nil means lines starting with \":\" are treated as fixed-width.
963 This currently only means they are never auto-wrapped.
964 When nil, such lines will be treated like ordinary lines.
965 See also the QUOTE keyword."
966 :group 'org-edit-structure
967 :type 'boolean)
970 (defcustom org-goto-auto-isearch t
971 "Non-nil means typing characters in org-goto starts incremental search."
972 :group 'org-edit-structure
973 :type 'boolean)
975 (defgroup org-sparse-trees nil
976 "Options concerning sparse trees in Org-mode."
977 :tag "Org Sparse Trees"
978 :group 'org-structure)
980 (defcustom org-highlight-sparse-tree-matches t
981 "Non-nil means highlight all matches that define a sparse tree.
982 The highlights will automatically disappear the next time the buffer is
983 changed by an edit command."
984 :group 'org-sparse-trees
985 :type 'boolean)
987 (defcustom org-remove-highlights-with-change t
988 "Non-nil means any change to the buffer will remove temporary highlights.
989 Such highlights are created by `org-occur' and `org-clock-display'.
990 When nil, `C-c C-c needs to be used to get rid of the highlights.
991 The highlights created by `org-preview-latex-fragment' always need
992 `C-c C-c' to be removed."
993 :group 'org-sparse-trees
994 :group 'org-time
995 :type 'boolean)
998 (defcustom org-occur-hook '(org-first-headline-recenter)
999 "Hook that is run after `org-occur' has constructed a sparse tree.
1000 This can be used to recenter the window to show as much of the structure
1001 as possible."
1002 :group 'org-sparse-trees
1003 :type 'hook)
1005 (defgroup org-imenu-and-speedbar nil
1006 "Options concerning imenu and speedbar in Org-mode."
1007 :tag "Org Imenu and Speedbar"
1008 :group 'org-structure)
1010 (defcustom org-imenu-depth 2
1011 "The maximum level for Imenu access to Org-mode headlines.
1012 This also applied for speedbar access."
1013 :group 'org-imenu-and-speedbar
1014 :type 'integer)
1016 (defgroup org-table nil
1017 "Options concerning tables in Org-mode."
1018 :tag "Org Table"
1019 :group 'org)
1021 (defcustom org-enable-table-editor 'optimized
1022 "Non-nil means lines starting with \"|\" are handled by the table editor.
1023 When nil, such lines will be treated like ordinary lines.
1025 When equal to the symbol `optimized', the table editor will be optimized to
1026 do the following:
1027 - Automatic overwrite mode in front of whitespace in table fields.
1028 This makes the structure of the table stay in tact as long as the edited
1029 field does not exceed the column width.
1030 - Minimize the number of realigns. Normally, the table is aligned each time
1031 TAB or RET are pressed to move to another field. With optimization this
1032 happens only if changes to a field might have changed the column width.
1033 Optimization requires replacing the functions `self-insert-command',
1034 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1035 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1036 very good at guessing when a re-align will be necessary, but you can always
1037 force one with \\[org-ctrl-c-ctrl-c].
1039 If you would like to use the optimized version in Org-mode, but the
1040 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1042 This variable can be used to turn on and off the table editor during a session,
1043 but in order to toggle optimization, a restart is required.
1045 See also the variable `org-table-auto-blank-field'."
1046 :group 'org-table
1047 :type '(choice
1048 (const :tag "off" nil)
1049 (const :tag "on" t)
1050 (const :tag "on, optimized" optimized)))
1052 (defcustom org-self-insert-cluster-for-undo t
1053 "Non-nil means cluster self-insert commands for undo when possible.
1054 If this is set, then, like in the Emacs command loop, 20 consecutive
1055 characters will be undone together.
1056 This is configurable, because there is some impact on typing performance."
1057 :group 'org-table
1058 :type 'boolean)
1060 (defcustom org-table-tab-recognizes-table.el t
1061 "Non-nil means TAB will automatically notice a table.el table.
1062 When it sees such a table, it moves point into it and - if necessary -
1063 calls `table-recognize-table'."
1064 :group 'org-table-editing
1065 :type 'boolean)
1067 (defgroup org-link nil
1068 "Options concerning links in Org-mode."
1069 :tag "Org Link"
1070 :group 'org)
1072 (defvar org-link-abbrev-alist-local nil
1073 "Buffer-local version of `org-link-abbrev-alist', which see.
1074 The value of this is taken from the #+LINK lines.")
1075 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1077 (defcustom org-link-abbrev-alist nil
1078 "Alist of link abbreviations.
1079 The car of each element is a string, to be replaced at the start of a link.
1080 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1081 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1083 [[linkkey:tag][description]]
1085 The 'linkkey' must be a word word, starting with a letter, followed
1086 by letters, numbers, '-' or '_'.
1088 If REPLACE is a string, the tag will simply be appended to create the link.
1089 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1090 the placeholder \"%h\" will cause a url-encoded version of the tag to
1091 be inserted at that point (see the function `url-hexify-string').
1093 REPLACE may also be a function that will be called with the tag as the
1094 only argument to create the link, which should be returned as a string.
1096 See the manual for examples."
1097 :group 'org-link
1098 :type '(repeat
1099 (cons
1100 (string :tag "Protocol")
1101 (choice
1102 (string :tag "Format")
1103 (function)))))
1105 (defcustom org-descriptive-links t
1106 "Non-nil means hide link part and only show description of bracket links.
1107 Bracket links are like [[link][description]]. This variable sets the initial
1108 state in new org-mode buffers. The setting can then be toggled on a
1109 per-buffer basis from the Org->Hyperlinks menu."
1110 :group 'org-link
1111 :type 'boolean)
1113 (defcustom org-link-file-path-type 'adaptive
1114 "How the path name in file links should be stored.
1115 Valid values are:
1117 relative Relative to the current directory, i.e. the directory of the file
1118 into which the link is being inserted.
1119 absolute Absolute path, if possible with ~ for home directory.
1120 noabbrev Absolute path, no abbreviation of home directory.
1121 adaptive Use relative path for files in the current directory and sub-
1122 directories of it. For other files, use an absolute path."
1123 :group 'org-link
1124 :type '(choice
1125 (const relative)
1126 (const absolute)
1127 (const noabbrev)
1128 (const adaptive)))
1130 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1131 "Types of links that should be activated in Org-mode files.
1132 This is a list of symbols, each leading to the activation of a certain link
1133 type. In principle, it does not hurt to turn on most link types - there may
1134 be a small gain when turning off unused link types. The types are:
1136 bracket The recommended [[link][description]] or [[link]] links with hiding.
1137 angular Links in angular brackets that may contain whitespace like
1138 <bbdb:Carsten Dominik>.
1139 plain Plain links in normal text, no whitespace, like http://google.com.
1140 radio Text that is matched by a radio target, see manual for details.
1141 tag Tag settings in a headline (link to tag search).
1142 date Time stamps (link to calendar).
1143 footnote Footnote labels.
1145 Changing this variable requires a restart of Emacs to become effective."
1146 :group 'org-link
1147 :type '(set :greedy t
1148 (const :tag "Double bracket links (new style)" bracket)
1149 (const :tag "Angular bracket links (old style)" angular)
1150 (const :tag "Plain text links" plain)
1151 (const :tag "Radio target matches" radio)
1152 (const :tag "Tags" tag)
1153 (const :tag "Timestamps" date)
1154 (const :tag "Footnotes" footnote)))
1156 (defcustom org-make-link-description-function nil
1157 "Function to use to generate link descriptions from links. If
1158 nil the link location will be used. This function must take two
1159 parameters; the first is the link and the second the description
1160 org-insert-link has generated, and should return the description
1161 to use."
1162 :group 'org-link
1163 :type 'function)
1165 (defgroup org-link-store nil
1166 "Options concerning storing links in Org-mode."
1167 :tag "Org Store Link"
1168 :group 'org-link)
1170 (defcustom org-email-link-description-format "Email %c: %.30s"
1171 "Format of the description part of a link to an email or usenet message.
1172 The following %-escapes will be replaced by corresponding information:
1174 %F full \"From\" field
1175 %f name, taken from \"From\" field, address if no name
1176 %T full \"To\" field
1177 %t first name in \"To\" field, address if no name
1178 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1179 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1180 %s subject
1181 %m message-id.
1183 You may use normal field width specification between the % and the letter.
1184 This is for example useful to limit the length of the subject.
1186 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1187 :group 'org-link-store
1188 :type 'string)
1190 (defcustom org-from-is-user-regexp
1191 (let (r1 r2)
1192 (when (and user-mail-address (not (string= user-mail-address "")))
1193 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1194 (when (and user-full-name (not (string= user-full-name "")))
1195 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1196 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1197 "Regexp matched against the \"From:\" header of an email or usenet message.
1198 It should match if the message is from the user him/herself."
1199 :group 'org-link-store
1200 :type 'regexp)
1202 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1203 "Non-nil means storing a link to an Org file will use entry IDs.
1205 Note that before this variable is even considered, org-id must be loaded,
1206 so please customize `org-modules' and turn it on.
1208 The variable can have the following values:
1210 t Create an ID if needed to make a link to the current entry.
1212 create-if-interactive
1213 If `org-store-link' is called directly (interactively, as a user
1214 command), do create an ID to support the link. But when doing the
1215 job for remember, only use the ID if it already exists. The
1216 purpose of this setting is to avoid proliferation of unwanted
1217 IDs, just because you happen to be in an Org file when you
1218 call `org-remember' that automatically and preemptively
1219 creates a link. If you do want to get an ID link in a remember
1220 template to an entry not having an ID, create it first by
1221 explicitly creating a link to it, using `C-c C-l' first.
1223 create-if-interactive-and-no-custom-id
1224 Like create-if-interactive, but do not create an ID if there is
1225 a CUSTOM_ID property defined in the entry. This is the default.
1227 use-existing
1228 Use existing ID, do not create one.
1230 nil Never use an ID to make a link, instead link using a text search for
1231 the headline text."
1232 :group 'org-link-store
1233 :type '(choice
1234 (const :tag "Create ID to make link" t)
1235 (const :tag "Create if storing link interactively"
1236 create-if-interactive)
1237 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1238 create-if-interactive-and-no-custom-id)
1239 (const :tag "Only use existing" use-existing)
1240 (const :tag "Do not use ID to create link" nil)))
1242 (defcustom org-context-in-file-links t
1243 "Non-nil means file links from `org-store-link' contain context.
1244 A search string will be added to the file name with :: as separator and
1245 used to find the context when the link is activated by the command
1246 `org-open-at-point'.
1247 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1248 negates this setting for the duration of the command."
1249 :group 'org-link-store
1250 :type 'boolean)
1252 (defcustom org-keep-stored-link-after-insertion nil
1253 "Non-nil means keep link in list for entire session.
1255 The command `org-store-link' adds a link pointing to the current
1256 location to an internal list. These links accumulate during a session.
1257 The command `org-insert-link' can be used to insert links into any
1258 Org-mode file (offering completion for all stored links). When this
1259 option is nil, every link which has been inserted once using \\[org-insert-link]
1260 will be removed from the list, to make completing the unused links
1261 more efficient."
1262 :group 'org-link-store
1263 :type 'boolean)
1265 (defgroup org-link-follow nil
1266 "Options concerning following links in Org-mode."
1267 :tag "Org Follow Link"
1268 :group 'org-link)
1270 (defcustom org-link-translation-function nil
1271 "Function to translate links with different syntax to Org syntax.
1272 This can be used to translate links created for example by the Planner
1273 or emacs-wiki packages to Org syntax.
1274 The function must accept two parameters, a TYPE containing the link
1275 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1276 which is everything after the link protocol. It should return a cons
1277 with possibly modified values of type and path.
1278 Org contains a function for this, so if you set this variable to
1279 `org-translate-link-from-planner', you should be able follow many
1280 links created by planner."
1281 :group 'org-link-follow
1282 :type 'function)
1284 (defcustom org-follow-link-hook nil
1285 "Hook that is run after a link has been followed."
1286 :group 'org-link-follow
1287 :type 'hook)
1289 (defcustom org-tab-follows-link nil
1290 "Non-nil means on links TAB will follow the link.
1291 Needs to be set before org.el is loaded.
1292 This really should not be used, it does not make sense, and the
1293 implementation is bad."
1294 :group 'org-link-follow
1295 :type 'boolean)
1297 (defcustom org-return-follows-link nil
1298 "Non-nil means on links RET will follow the link.
1299 Needs to be set before org.el is loaded."
1300 :group 'org-link-follow
1301 :type 'boolean)
1303 (defcustom org-mouse-1-follows-link
1304 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1305 "Non-nil means mouse-1 on a link will follow the link.
1306 A longer mouse click will still set point. Does not work on XEmacs.
1307 Needs to be set before org.el is loaded."
1308 :group 'org-link-follow
1309 :type 'boolean)
1311 (defcustom org-mark-ring-length 4
1312 "Number of different positions to be recorded in the ring
1313 Changing this requires a restart of Emacs to work correctly."
1314 :group 'org-link-follow
1315 :type 'integer)
1317 (defcustom org-link-frame-setup
1318 '((vm . vm-visit-folder-other-frame)
1319 (gnus . gnus-other-frame)
1320 (file . find-file-other-window))
1321 "Setup the frame configuration for following links.
1322 When following a link with Emacs, it may often be useful to display
1323 this link in another window or frame. This variable can be used to
1324 set this up for the different types of links.
1325 For VM, use any of
1326 `vm-visit-folder'
1327 `vm-visit-folder-other-frame'
1328 For Gnus, use any of
1329 `gnus'
1330 `gnus-other-frame'
1331 `org-gnus-no-new-news'
1332 For FILE, use any of
1333 `find-file'
1334 `find-file-other-window'
1335 `find-file-other-frame'
1336 For the calendar, use the variable `calendar-setup'.
1337 For BBDB, it is currently only possible to display the matches in
1338 another window."
1339 :group 'org-link-follow
1340 :type '(list
1341 (cons (const vm)
1342 (choice
1343 (const vm-visit-folder)
1344 (const vm-visit-folder-other-window)
1345 (const vm-visit-folder-other-frame)))
1346 (cons (const gnus)
1347 (choice
1348 (const gnus)
1349 (const gnus-other-frame)
1350 (const org-gnus-no-new-news)))
1351 (cons (const file)
1352 (choice
1353 (const find-file)
1354 (const find-file-other-window)
1355 (const find-file-other-frame)))))
1357 (defcustom org-display-internal-link-with-indirect-buffer nil
1358 "Non-nil means use indirect buffer to display infile links.
1359 Activating internal links (from one location in a file to another location
1360 in the same file) normally just jumps to the location. When the link is
1361 activated with a C-u prefix (or with mouse-3), the link is displayed in
1362 another window. When this option is set, the other window actually displays
1363 an indirect buffer clone of the current buffer, to avoid any visibility
1364 changes to the current buffer."
1365 :group 'org-link-follow
1366 :type 'boolean)
1368 (defcustom org-open-non-existing-files nil
1369 "Non-nil means `org-open-file' will open non-existing files.
1370 When nil, an error will be generated.
1371 This variable applies only to external applications because they
1372 might choke on non-existing files. If the link is to a file that
1373 will be opened in Emacs, the variable is ignored."
1374 :group 'org-link-follow
1375 :type 'boolean)
1377 (defcustom org-open-directory-means-index-dot-org nil
1378 "Non-nil means a link to a directory really means to index.org.
1379 When nil, following a directory link will run dired or open a finder/explorer
1380 window on that directory."
1381 :group 'org-link-follow
1382 :type 'boolean)
1384 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1385 "Function and arguments to call for following mailto links.
1386 This is a list with the first element being a lisp function, and the
1387 remaining elements being arguments to the function. In string arguments,
1388 %a will be replaced by the address, and %s will be replaced by the subject
1389 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1390 :group 'org-link-follow
1391 :type '(choice
1392 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1393 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1394 (const :tag "message-mail" (message-mail "%a" "%s"))
1395 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1397 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1398 "Non-nil means ask for confirmation before executing shell links.
1399 Shell links can be dangerous: just think about a link
1401 [[shell:rm -rf ~/*][Google Search]]
1403 This link would show up in your Org-mode document as \"Google Search\",
1404 but really it would remove your entire home directory.
1405 Therefore we advise against setting this variable to nil.
1406 Just change it to `y-or-n-p' if you want to confirm with a
1407 single keystroke rather than having to type \"yes\"."
1408 :group 'org-link-follow
1409 :type '(choice
1410 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1411 (const :tag "with y-or-n (faster)" y-or-n-p)
1412 (const :tag "no confirmation (dangerous)" nil)))
1414 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1415 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1416 Elisp links can be dangerous: just think about a link
1418 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1420 This link would show up in your Org-mode document as \"Google Search\",
1421 but really it would remove your entire home directory.
1422 Therefore we advise against setting this variable to nil.
1423 Just change it to `y-or-n-p' if you want to confirm with a
1424 single keystroke rather than having to type \"yes\"."
1425 :group 'org-link-follow
1426 :type '(choice
1427 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1428 (const :tag "with y-or-n (faster)" y-or-n-p)
1429 (const :tag "no confirmation (dangerous)" nil)))
1431 (defconst org-file-apps-defaults-gnu
1432 '((remote . emacs)
1433 (system . mailcap)
1434 (t . mailcap))
1435 "Default file applications on a UNIX or GNU/Linux system.
1436 See `org-file-apps'.")
1438 (defconst org-file-apps-defaults-macosx
1439 '((remote . emacs)
1440 (t . "open %s")
1441 (system . "open %s")
1442 ("ps.gz" . "gv %s")
1443 ("eps.gz" . "gv %s")
1444 ("dvi" . "xdvi %s")
1445 ("fig" . "xfig %s"))
1446 "Default file applications on a MacOS X system.
1447 The system \"open\" is known as a default, but we use X11 applications
1448 for some files for which the OS does not have a good default.
1449 See `org-file-apps'.")
1451 (defconst org-file-apps-defaults-windowsnt
1452 (list
1453 '(remote . emacs)
1454 (cons t
1455 (list (if (featurep 'xemacs)
1456 'mswindows-shell-execute
1457 'w32-shell-execute)
1458 "open" 'file))
1459 (cons 'system
1460 (list (if (featurep 'xemacs)
1461 'mswindows-shell-execute
1462 'w32-shell-execute)
1463 "open" 'file)))
1464 "Default file applications on a Windows NT system.
1465 The system \"open\" is used for most files.
1466 See `org-file-apps'.")
1468 (defcustom org-file-apps
1470 (auto-mode . emacs)
1471 ("\\.mm\\'" . default)
1472 ("\\.x?html?\\'" . default)
1473 ("\\.pdf\\'" . default)
1475 "External applications for opening `file:path' items in a document.
1476 Org-mode uses system defaults for different file types, but
1477 you can use this variable to set the application for a given file
1478 extension. The entries in this list are cons cells where the car identifies
1479 files and the cdr the corresponding command. Possible values for the
1480 file identifier are
1481 \"regex\" Regular expression matched against the file name. For backward
1482 compatibility, this can also be a string with only alphanumeric
1483 characters, which is then interpreted as an extension.
1484 `directory' Matches a directory
1485 `remote' Matches a remote file, accessible through tramp or efs.
1486 Remote files most likely should be visited through Emacs
1487 because external applications cannot handle such paths.
1488 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1489 so all files Emacs knows how to handle. Using this with
1490 command `emacs' will open most files in Emacs. Beware that this
1491 will also open html files inside Emacs, unless you add
1492 (\"html\" . default) to the list as well.
1493 t Default for files not matched by any of the other options.
1494 `system' The system command to open files, like `open' on Windows
1495 and Mac OS X, and mailcap under GNU/Linux. This is the command
1496 that will be selected if you call `C-c C-o' with a double
1497 `C-u C-u' prefix.
1499 Possible values for the command are:
1500 `emacs' The file will be visited by the current Emacs process.
1501 `default' Use the default application for this file type, which is the
1502 association for t in the list, most likely in the system-specific
1503 part.
1504 This can be used to overrule an unwanted setting in the
1505 system-specific variable.
1506 `system' Use the system command for opening files, like \"open\".
1507 This command is specified by the entry whose car is `system'.
1508 Most likely, the system-specific version of this variable
1509 does define this command, but you can overrule/replace it
1510 here.
1511 string A command to be executed by a shell; %s will be replaced
1512 by the path to the file.
1513 sexp A Lisp form which will be evaluated. The file path will
1514 be available in the Lisp variable `file'.
1515 For more examples, see the system specific constants
1516 `org-file-apps-defaults-macosx'
1517 `org-file-apps-defaults-windowsnt'
1518 `org-file-apps-defaults-gnu'."
1519 :group 'org-link-follow
1520 :type '(repeat
1521 (cons (choice :value ""
1522 (string :tag "Extension")
1523 (const :tag "System command to open files" system)
1524 (const :tag "Default for unrecognized files" t)
1525 (const :tag "Remote file" remote)
1526 (const :tag "Links to a directory" directory)
1527 (const :tag "Any files that have Emacs modes"
1528 auto-mode))
1529 (choice :value ""
1530 (const :tag "Visit with Emacs" emacs)
1531 (const :tag "Use default" default)
1532 (const :tag "Use the system command" system)
1533 (string :tag "Command")
1534 (sexp :tag "Lisp form")))))
1538 (defgroup org-refile nil
1539 "Options concerning refiling entries in Org-mode."
1540 :tag "Org Refile"
1541 :group 'org)
1543 (defcustom org-directory "~/org"
1544 "Directory with org files.
1545 This is just a default location to look for Org files. There is no need
1546 at all to put your files into this directory. It is only used in the
1547 following situations:
1549 1. When a remember template specifies a target file that is not an
1550 absolute path. The path will then be interpreted relative to
1551 `org-directory'
1552 2. When a remember note is filed away in an interactive way (when exiting the
1553 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1554 with `org-directory' as the default path."
1555 :group 'org-refile
1556 :group 'org-remember
1557 :type 'directory)
1559 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1560 "Default target for storing notes.
1561 Used by the hooks for remember.el. This can be a string, or nil to mean
1562 the value of `remember-data-file'.
1563 You can set this on a per-template basis with the variable
1564 `org-remember-templates'."
1565 :group 'org-refile
1566 :group 'org-remember
1567 :type '(choice
1568 (const :tag "Default from remember-data-file" nil)
1569 file))
1571 (defcustom org-goto-interface 'outline
1572 "The default interface to be used for `org-goto'.
1573 Allowed values are:
1574 outline The interface shows an outline of the relevant file
1575 and the correct heading is found by moving through
1576 the outline or by searching with incremental search.
1577 outline-path-completion Headlines in the current buffer are offered via
1578 completion. This is the interface also used by
1579 the refile command."
1580 :group 'org-refile
1581 :type '(choice
1582 (const :tag "Outline" outline)
1583 (const :tag "Outline-path-completion" outline-path-completion)))
1585 (defcustom org-goto-max-level 5
1586 "Maximum level to be considered when running org-goto with refile interface."
1587 :group 'org-refile
1588 :type 'integer)
1590 (defcustom org-reverse-note-order nil
1591 "Non-nil means store new notes at the beginning of a file or entry.
1592 When nil, new notes will be filed to the end of a file or entry.
1593 This can also be a list with cons cells of regular expressions that
1594 are matched against file names, and values."
1595 :group 'org-remember
1596 :group 'org-refile
1597 :type '(choice
1598 (const :tag "Reverse always" t)
1599 (const :tag "Reverse never" nil)
1600 (repeat :tag "By file name regexp"
1601 (cons regexp boolean))))
1603 (defcustom org-log-refile nil
1604 "Information to record when a task is refiled.
1606 Possible values are:
1608 nil Don't add anything
1609 time Add a time stamp to the task
1610 note Prompt for a note and add it with template `org-log-note-headings'
1612 This option can also be set with on a per-file-basis with
1614 #+STARTUP: nologrefile
1615 #+STARTUP: logrefile
1616 #+STARTUP: lognoterefile
1618 You can have local logging settings for a subtree by setting the LOGGING
1619 property to one or more of these keywords.
1621 When bulk-refiling from the agenda, the value `note' is forbidden and
1622 will temporarily be changed to `time'."
1623 :group 'org-refile
1624 :group 'org-progress
1625 :type '(choice
1626 (const :tag "No logging" nil)
1627 (const :tag "Record timestamp" time)
1628 (const :tag "Record timestamp with note." note)))
1630 (defcustom org-refile-targets nil
1631 "Targets for refiling entries with \\[org-refile].
1632 This is list of cons cells. Each cell contains:
1633 - a specification of the files to be considered, either a list of files,
1634 or a symbol whose function or variable value will be used to retrieve
1635 a file name or a list of file names. If you use `org-agenda-files' for
1636 that, all agenda files will be scanned for targets. Nil means consider
1637 headings in the current buffer.
1638 - A specification of how to find candidate refile targets. This may be
1639 any of:
1640 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1641 This tag has to be present in all target headlines, inheritance will
1642 not be considered.
1643 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1644 todo keyword.
1645 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1646 headlines that are refiling targets.
1647 - a cons cell (:level . N). Any headline of level N is considered a target.
1648 Note that, when `org-odd-levels-only' is set, level corresponds to
1649 order in hierarchy, not to the number of stars.
1650 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1651 Note that, when `org-odd-levels-only' is set, level corresponds to
1652 order in hierarchy, not to the number of stars.
1654 You can set the variable `org-refile-target-verify-function' to a function
1655 to verify each headline found by the simple critery above.
1657 When this variable is nil, all top-level headlines in the current buffer
1658 are used, equivalent to the value `((nil . (:level . 1))'."
1659 :group 'org-refile
1660 :type '(repeat
1661 (cons
1662 (choice :value org-agenda-files
1663 (const :tag "All agenda files" org-agenda-files)
1664 (const :tag "Current buffer" nil)
1665 (function) (variable) (file))
1666 (choice :tag "Identify target headline by"
1667 (cons :tag "Specific tag" (const :value :tag) (string))
1668 (cons :tag "TODO keyword" (const :value :todo) (string))
1669 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1670 (cons :tag "Level number" (const :value :level) (integer))
1671 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1673 (defcustom org-refile-target-verify-function nil
1674 "Function to verify if the headline at point should be a refile target.
1675 The function will be called without arguments, with point at the
1676 beginning of the headline. It should return t and leave point
1677 where it is if the headline is a valid target for refiling.
1679 If the target should not be selected, the function must return nil.
1680 In addition to this, it may move point to a place from where the search
1681 should be continued. For example, the function may decide that the entire
1682 subtree of the current entry should be excluded and move point to the end
1683 of the subtree."
1684 :group 'org-refile
1685 :type 'function)
1687 (defcustom org-refile-use-outline-path nil
1688 "Non-nil means provide refile targets as paths.
1689 So a level 3 headline will be available as level1/level2/level3.
1691 When the value is `file', also include the file name (without directory)
1692 into the path. In this case, you can also stop the completion after
1693 the file name, to get entries inserted as top level in the file.
1695 When `full-file-path', include the full file path."
1696 :group 'org-refile
1697 :type '(choice
1698 (const :tag "Not" nil)
1699 (const :tag "Yes" t)
1700 (const :tag "Start with file name" file)
1701 (const :tag "Start with full file path" full-file-path)))
1703 (defcustom org-outline-path-complete-in-steps t
1704 "Non-nil means complete the outline path in hierarchical steps.
1705 When Org-mode uses the refile interface to select an outline path
1706 \(see variable `org-refile-use-outline-path'), the completion of
1707 the path can be done is a single go, or if can be done in steps down
1708 the headline hierarchy. Going in steps is probably the best if you
1709 do not use a special completion package like `ido' or `icicles'.
1710 However, when using these packages, going in one step can be very
1711 fast, while still showing the whole path to the entry."
1712 :group 'org-refile
1713 :type 'boolean)
1715 (defcustom org-refile-allow-creating-parent-nodes nil
1716 "Non-nil means allow to create new nodes as refile targets.
1717 New nodes are then created by adding \"/new node name\" to the completion
1718 of an existing node. When the value of this variable is `confirm',
1719 new node creation must be confirmed by the user (recommended)
1720 When nil, the completion must match an existing entry.
1722 Note that, if the new heading is not seen by the criteria
1723 listed in `org-refile-targets', multiple instances of the same
1724 heading would be created by trying again to file under the new
1725 heading."
1726 :group 'org-refile
1727 :type '(choice
1728 (const :tag "Never" nil)
1729 (const :tag "Always" t)
1730 (const :tag "Prompt for confirmation" confirm)))
1732 (defgroup org-todo nil
1733 "Options concerning TODO items in Org-mode."
1734 :tag "Org TODO"
1735 :group 'org)
1737 (defgroup org-progress nil
1738 "Options concerning Progress logging in Org-mode."
1739 :tag "Org Progress"
1740 :group 'org-time)
1742 (defvar org-todo-interpretation-widgets
1744 (:tag "Sequence (cycling hits every state)" sequence)
1745 (:tag "Type (cycling directly to DONE)" type))
1746 "The available interpretation symbols for customizing
1747 `org-todo-keywords'.
1748 Interested libraries should add to this list.")
1750 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1751 "List of TODO entry keyword sequences and their interpretation.
1752 \\<org-mode-map>This is a list of sequences.
1754 Each sequence starts with a symbol, either `sequence' or `type',
1755 indicating if the keywords should be interpreted as a sequence of
1756 action steps, or as different types of TODO items. The first
1757 keywords are states requiring action - these states will select a headline
1758 for inclusion into the global TODO list Org-mode produces. If one of
1759 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1760 signify that no further action is necessary. If \"|\" is not found,
1761 the last keyword is treated as the only DONE state of the sequence.
1763 The command \\[org-todo] cycles an entry through these states, and one
1764 additional state where no keyword is present. For details about this
1765 cycling, see the manual.
1767 TODO keywords and interpretation can also be set on a per-file basis with
1768 the special #+SEQ_TODO and #+TYP_TODO lines.
1770 Each keyword can optionally specify a character for fast state selection
1771 \(in combination with the variable `org-use-fast-todo-selection')
1772 and specifiers for state change logging, using the same syntax
1773 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1774 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1775 indicates to record a time stamp each time this state is selected.
1777 Each keyword may also specify if a timestamp or a note should be
1778 recorded when entering or leaving the state, by adding additional
1779 characters in the parenthesis after the keyword. This looks like this:
1780 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1781 record only the time of the state change. With X and Y being either
1782 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1783 Y when leaving the state if and only if the *target* state does not
1784 define X. You may omit any of the fast-selection key or X or /Y,
1785 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1787 For backward compatibility, this variable may also be just a list
1788 of keywords - in this case the interpretation (sequence or type) will be
1789 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1790 :group 'org-todo
1791 :group 'org-keywords
1792 :type '(choice
1793 (repeat :tag "Old syntax, just keywords"
1794 (string :tag "Keyword"))
1795 (repeat :tag "New syntax"
1796 (cons
1797 (choice
1798 :tag "Interpretation"
1799 ;;Quick and dirty way to see
1800 ;;`org-todo-interpretations'. This takes the
1801 ;;place of item arguments
1802 :convert-widget
1803 (lambda (widget)
1804 (widget-put widget
1805 :args (mapcar
1806 #'(lambda (x)
1807 (widget-convert
1808 (cons 'const x)))
1809 org-todo-interpretation-widgets))
1810 widget))
1811 (repeat
1812 (string :tag "Keyword"))))))
1814 (defvar org-todo-keywords-1 nil
1815 "All TODO and DONE keywords active in a buffer.")
1816 (make-variable-buffer-local 'org-todo-keywords-1)
1817 (defvar org-todo-keywords-for-agenda nil)
1818 (defvar org-done-keywords-for-agenda nil)
1819 (defvar org-drawers-for-agenda nil)
1820 (defvar org-todo-keyword-alist-for-agenda nil)
1821 (defvar org-tag-alist-for-agenda nil)
1822 (defvar org-agenda-contributing-files nil)
1823 (defvar org-not-done-keywords nil)
1824 (make-variable-buffer-local 'org-not-done-keywords)
1825 (defvar org-done-keywords nil)
1826 (make-variable-buffer-local 'org-done-keywords)
1827 (defvar org-todo-heads nil)
1828 (make-variable-buffer-local 'org-todo-heads)
1829 (defvar org-todo-sets nil)
1830 (make-variable-buffer-local 'org-todo-sets)
1831 (defvar org-todo-log-states nil)
1832 (make-variable-buffer-local 'org-todo-log-states)
1833 (defvar org-todo-kwd-alist nil)
1834 (make-variable-buffer-local 'org-todo-kwd-alist)
1835 (defvar org-todo-key-alist nil)
1836 (make-variable-buffer-local 'org-todo-key-alist)
1837 (defvar org-todo-key-trigger nil)
1838 (make-variable-buffer-local 'org-todo-key-trigger)
1840 (defcustom org-todo-interpretation 'sequence
1841 "Controls how TODO keywords are interpreted.
1842 This variable is in principle obsolete and is only used for
1843 backward compatibility, if the interpretation of todo keywords is
1844 not given already in `org-todo-keywords'. See that variable for
1845 more information."
1846 :group 'org-todo
1847 :group 'org-keywords
1848 :type '(choice (const sequence)
1849 (const type)))
1851 (defcustom org-use-fast-todo-selection t
1852 "Non-nil means use the fast todo selection scheme with C-c C-t.
1853 This variable describes if and under what circumstances the cycling
1854 mechanism for TODO keywords will be replaced by a single-key, direct
1855 selection scheme.
1857 When nil, fast selection is never used.
1859 When the symbol `prefix', it will be used when `org-todo' is called with
1860 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1861 in an agenda buffer.
1863 When t, fast selection is used by default. In this case, the prefix
1864 argument forces cycling instead.
1866 In all cases, the special interface is only used if access keys have actually
1867 been assigned by the user, i.e. if keywords in the configuration are followed
1868 by a letter in parenthesis, like TODO(t)."
1869 :group 'org-todo
1870 :type '(choice
1871 (const :tag "Never" nil)
1872 (const :tag "By default" t)
1873 (const :tag "Only with C-u C-c C-t" prefix)))
1875 (defcustom org-provide-todo-statistics t
1876 "Non-nil means update todo statistics after insert and toggle.
1877 ALL-HEADLINES means update todo statistics by including headlines
1878 with no TODO keyword as well, counting them as not done.
1879 A list of TODO keywords means the same, but skip keywords that are
1880 not in this list.
1882 When this is set, todo statistics is updated in the parent of the
1883 current entry each time a todo state is changed."
1884 :group 'org-todo
1885 :type '(choice
1886 (const :tag "Yes, only for TODO entries" t)
1887 (const :tag "Yes, including all entries" 'all-headlines)
1888 (repeat :tag "Yes, for TODOs in this list"
1889 (string :tag "TODO keyword"))
1890 (other :tag "No TODO statistics" nil)))
1892 (defcustom org-hierarchical-todo-statistics t
1893 "Non-nil means TODO statistics covers just direct children.
1894 When nil, all entries in the subtree are considered.
1895 This has only an effect if `org-provide-todo-statistics' is set.
1896 To set this to nil for only a single subtree, use a COOKIE_DATA
1897 property and include the word \"recursive\" into the value."
1898 :group 'org-todo
1899 :type 'boolean)
1901 (defcustom org-after-todo-state-change-hook nil
1902 "Hook which is run after the state of a TODO item was changed.
1903 The new state (a string with a TODO keyword, or nil) is available in the
1904 Lisp variable `state'."
1905 :group 'org-todo
1906 :type 'hook)
1908 (defvar org-blocker-hook nil
1909 "Hook for functions that are allowed to block a state change.
1911 Each function gets as its single argument a property list, see
1912 `org-trigger-hook' for more information about this list.
1914 If any of the functions in this hook returns nil, the state change
1915 is blocked.")
1917 (defvar org-trigger-hook nil
1918 "Hook for functions that are triggered by a state change.
1920 Each function gets as its single argument a property list with at least
1921 the following elements:
1923 (:type type-of-change :position pos-at-entry-start
1924 :from old-state :to new-state)
1926 Depending on the type, more properties may be present.
1928 This mechanism is currently implemented for:
1930 TODO state changes
1931 ------------------
1932 :type todo-state-change
1933 :from previous state (keyword as a string), or nil, or a symbol
1934 'todo' or 'done', to indicate the general type of state.
1935 :to new state, like in :from")
1937 (defcustom org-enforce-todo-dependencies nil
1938 "Non-nil means undone TODO entries will block switching the parent to DONE.
1939 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1940 be blocked if any prior sibling is not yet done.
1941 Finally, if the parent is blocked because of ordered siblings of its own,
1942 the child will also be blocked.
1943 This variable needs to be set before org.el is loaded, and you need to
1944 restart Emacs after a change to make the change effective. The only way
1945 to change is while Emacs is running is through the customize interface."
1946 :set (lambda (var val)
1947 (set var val)
1948 (if val
1949 (add-hook 'org-blocker-hook
1950 'org-block-todo-from-children-or-siblings-or-parent)
1951 (remove-hook 'org-blocker-hook
1952 'org-block-todo-from-children-or-siblings-or-parent)))
1953 :group 'org-todo
1954 :type 'boolean)
1956 (defcustom org-enforce-todo-checkbox-dependencies nil
1957 "Non-nil means unchecked boxes will block switching the parent to DONE.
1958 When this is nil, checkboxes have no influence on switching TODO states.
1959 When non-nil, you first need to check off all check boxes before the TODO
1960 entry can be switched to DONE.
1961 This variable needs to be set before org.el is loaded, and you need to
1962 restart Emacs after a change to make the change effective. The only way
1963 to change is while Emacs is running is through the customize interface."
1964 :set (lambda (var val)
1965 (set var val)
1966 (if val
1967 (add-hook 'org-blocker-hook
1968 'org-block-todo-from-checkboxes)
1969 (remove-hook 'org-blocker-hook
1970 'org-block-todo-from-checkboxes)))
1971 :group 'org-todo
1972 :type 'boolean)
1974 (defcustom org-treat-insert-todo-heading-as-state-change nil
1975 "Non-nil means inserting a TODO heading is treated as state change.
1976 So when the command \\[org-insert-todo-heading] is used, state change
1977 logging will apply if appropriate. When nil, the new TODO item will
1978 be inserted directly, and no logging will take place."
1979 :group 'org-todo
1980 :type 'boolean)
1982 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1983 "Non-nil means switching TODO states with S-cursor counts as state change.
1984 This is the default behavior. However, setting this to nil allows a
1985 convenient way to select a TODO state and bypass any logging associated
1986 with that."
1987 :group 'org-todo
1988 :type 'boolean)
1990 (defcustom org-todo-state-tags-triggers nil
1991 "Tag changes that should be triggered by TODO state changes.
1992 This is a list. Each entry is
1994 (state-change (tag . flag) .......)
1996 State-change can be a string with a state, and empty string to indicate the
1997 state that has no TODO keyword, or it can be one of the symbols `todo'
1998 or `done', meaning any not-done or done state, respectively."
1999 :group 'org-todo
2000 :group 'org-tags
2001 :type '(repeat
2002 (cons (choice :tag "When changing to"
2003 (const :tag "Not-done state" todo)
2004 (const :tag "Done state" done)
2005 (string :tag "State"))
2006 (repeat
2007 (cons :tag "Tag action"
2008 (string :tag "Tag")
2009 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2011 (defcustom org-log-done nil
2012 "Information to record when a task moves to the DONE state.
2014 Possible values are:
2016 nil Don't add anything, just change the keyword
2017 time Add a time stamp to the task
2018 note Prompt for a note and add it with template `org-log-note-headings'
2020 This option can also be set with on a per-file-basis with
2022 #+STARTUP: nologdone
2023 #+STARTUP: logdone
2024 #+STARTUP: lognotedone
2026 You can have local logging settings for a subtree by setting the LOGGING
2027 property to one or more of these keywords."
2028 :group 'org-todo
2029 :group 'org-progress
2030 :type '(choice
2031 (const :tag "No logging" nil)
2032 (const :tag "Record CLOSED timestamp" time)
2033 (const :tag "Record CLOSED timestamp with note." note)))
2035 ;; Normalize old uses of org-log-done.
2036 (cond
2037 ((eq org-log-done t) (setq org-log-done 'time))
2038 ((and (listp org-log-done) (memq 'done org-log-done))
2039 (setq org-log-done 'note)))
2041 (defcustom org-log-reschedule nil
2042 "Information to record when the scheduling date of a tasks is modified.
2044 Possible values are:
2046 nil Don't add anything, just change the date
2047 time Add a time stamp to the task
2048 note Prompt for a note and add it with template `org-log-note-headings'
2050 This option can also be set with on a per-file-basis with
2052 #+STARTUP: nologreschedule
2053 #+STARTUP: logreschedule
2054 #+STARTUP: lognotereschedule"
2055 :group 'org-todo
2056 :group 'org-progress
2057 :type '(choice
2058 (const :tag "No logging" nil)
2059 (const :tag "Record timestamp" time)
2060 (const :tag "Record timestamp with note." note)))
2062 (defcustom org-log-redeadline nil
2063 "Information to record when the deadline date of a tasks is modified.
2065 Possible values are:
2067 nil Don't add anything, just change the date
2068 time Add a time stamp to the task
2069 note Prompt for a note and add it with template `org-log-note-headings'
2071 This option can also be set with on a per-file-basis with
2073 #+STARTUP: nologredeadline
2074 #+STARTUP: logredeadline
2075 #+STARTUP: lognoteredeadline
2077 You can have local logging settings for a subtree by setting the LOGGING
2078 property to one or more of these keywords."
2079 :group 'org-todo
2080 :group 'org-progress
2081 :type '(choice
2082 (const :tag "No logging" nil)
2083 (const :tag "Record timestamp" time)
2084 (const :tag "Record timestamp with note." note)))
2086 (defcustom org-log-note-clock-out nil
2087 "Non-nil means record a note when clocking out of an item.
2088 This can also be configured on a per-file basis by adding one of
2089 the following lines anywhere in the buffer:
2091 #+STARTUP: lognoteclock-out
2092 #+STARTUP: nolognoteclock-out"
2093 :group 'org-todo
2094 :group 'org-progress
2095 :type 'boolean)
2097 (defcustom org-log-done-with-time t
2098 "Non-nil means the CLOSED time stamp will contain date and time.
2099 When nil, only the date will be recorded."
2100 :group 'org-progress
2101 :type 'boolean)
2103 (defcustom org-log-note-headings
2104 '((done . "CLOSING NOTE %t")
2105 (state . "State %-12s from %-12S %t")
2106 (note . "Note taken on %t")
2107 (reschedule . "Rescheduled from %S on %t")
2108 (delschedule . "Not scheduled, was %S on %t")
2109 (redeadline . "New deadline from %S on %t")
2110 (deldeadline . "Removed deadline, was %S on %t")
2111 (refile . "Refiled on %t")
2112 (clock-out . ""))
2113 "Headings for notes added to entries.
2114 The value is an alist, with the car being a symbol indicating the note
2115 context, and the cdr is the heading to be used. The heading may also be the
2116 empty string.
2117 %t in the heading will be replaced by a time stamp.
2118 %s will be replaced by the new TODO state, in double quotes.
2119 %S will be replaced by the old TODO state, in double quotes.
2120 %u will be replaced by the user name.
2121 %U will be replaced by the full user name.
2123 In fact, it is not a good idea to change the `state' entry, because
2124 agenda log mode depends on the format of these entries."
2125 :group 'org-todo
2126 :group 'org-progress
2127 :type '(list :greedy t
2128 (cons (const :tag "Heading when closing an item" done) string)
2129 (cons (const :tag
2130 "Heading when changing todo state (todo sequence only)"
2131 state) string)
2132 (cons (const :tag "Heading when just taking a note" note) string)
2133 (cons (const :tag "Heading when clocking out" clock-out) string)
2134 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2135 (cons (const :tag "Heading when rescheduling" reschedule) string)
2136 (cons (const :tag "Heading when changing deadline" redeadline) string)
2137 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2138 (cons (const :tag "Heading when refiling" refile) string)))
2140 (unless (assq 'note org-log-note-headings)
2141 (push '(note . "%t") org-log-note-headings))
2143 (defcustom org-log-into-drawer nil
2144 "Non-nil means insert state change notes and time stamps into a drawer.
2145 When nil, state changes notes will be inserted after the headline and
2146 any scheduling and clock lines, but not inside a drawer.
2148 The value of this variable should be the name of the drawer to use.
2149 LOGBOOK is proposed at the default drawer for this purpose, you can
2150 also set this to a string to define the drawer of your choice.
2152 A value of t is also allowed, representing \"LOGBOOK\".
2154 If this variable is set, `org-log-state-notes-insert-after-drawers'
2155 will be ignored.
2157 You can set the property LOG_INTO_DRAWER to overrule this setting for
2158 a subtree."
2159 :group 'org-todo
2160 :group 'org-progress
2161 :type '(choice
2162 (const :tag "Not into a drawer" nil)
2163 (const :tag "LOGBOOK" t)
2164 (string :tag "Other")))
2166 (if (fboundp 'defvaralias)
2167 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2169 (defun org-log-into-drawer ()
2170 "Return the value of `org-log-into-drawer', but let properties overrule.
2171 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2172 used instead of the default value."
2173 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2174 (cond
2175 ((or (not p) (equal p "nil")) org-log-into-drawer)
2176 ((equal p "t") "LOGBOOK")
2177 (t p))))
2179 (defcustom org-log-state-notes-insert-after-drawers nil
2180 "Non-nil means insert state change notes after any drawers in entry.
2181 Only the drawers that *immediately* follow the headline and the
2182 deadline/scheduled line are skipped.
2183 When nil, insert notes right after the heading and perhaps the line
2184 with deadline/scheduling if present.
2186 This variable will have no effect if `org-log-into-drawer' is
2187 set."
2188 :group 'org-todo
2189 :group 'org-progress
2190 :type 'boolean)
2192 (defcustom org-log-states-order-reversed t
2193 "Non-nil means the latest state note will be directly after heading.
2194 When nil, the state change notes will be ordered according to time."
2195 :group 'org-todo
2196 :group 'org-progress
2197 :type 'boolean)
2199 (defcustom org-todo-repeat-to-state nil
2200 "The TODO state to which a repeater should return the repeating task.
2201 By default this is the first task in a TODO sequence, or the previous state
2202 in a TODO_TYP set. But you can specify another task here.
2203 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2204 :group 'org-todo
2205 :type '(choice (const :tag "Head of sequence" nil)
2206 (string :tag "Specific state")))
2208 (defcustom org-log-repeat 'time
2209 "Non-nil means record moving through the DONE state when triggering repeat.
2210 An auto-repeating task is immediately switched back to TODO when
2211 marked DONE. If you are not logging state changes (by adding \"@\"
2212 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2213 record a closing note, there will be no record of the task moving
2214 through DONE. This variable forces taking a note anyway.
2216 nil Don't force a record
2217 time Record a time stamp
2218 note Record a note
2220 This option can also be set with on a per-file-basis with
2222 #+STARTUP: logrepeat
2223 #+STARTUP: lognoterepeat
2224 #+STARTUP: nologrepeat
2226 You can have local logging settings for a subtree by setting the LOGGING
2227 property to one or more of these keywords."
2228 :group 'org-todo
2229 :group 'org-progress
2230 :type '(choice
2231 (const :tag "Don't force a record" nil)
2232 (const :tag "Force recording the DONE state" time)
2233 (const :tag "Force recording a note with the DONE state" note)))
2236 (defgroup org-priorities nil
2237 "Priorities in Org-mode."
2238 :tag "Org Priorities"
2239 :group 'org-todo)
2241 (defcustom org-enable-priority-commands t
2242 "Non-nil means priority commands are active.
2243 When nil, these commands will be disabled, so that you never accidentally
2244 set a priority."
2245 :group 'org-priorities
2246 :type 'boolean)
2248 (defcustom org-highest-priority ?A
2249 "The highest priority of TODO items. A character like ?A, ?B etc.
2250 Must have a smaller ASCII number than `org-lowest-priority'."
2251 :group 'org-priorities
2252 :type 'character)
2254 (defcustom org-lowest-priority ?C
2255 "The lowest priority of TODO items. A character like ?A, ?B etc.
2256 Must have a larger ASCII number than `org-highest-priority'."
2257 :group 'org-priorities
2258 :type 'character)
2260 (defcustom org-default-priority ?B
2261 "The default priority of TODO items.
2262 This is the priority an item get if no explicit priority is given."
2263 :group 'org-priorities
2264 :type 'character)
2266 (defcustom org-priority-start-cycle-with-default t
2267 "Non-nil means start with default priority when starting to cycle.
2268 When this is nil, the first step in the cycle will be (depending on the
2269 command used) one higher or lower that the default priority."
2270 :group 'org-priorities
2271 :type 'boolean)
2273 (defgroup org-time nil
2274 "Options concerning time stamps and deadlines in Org-mode."
2275 :tag "Org Time"
2276 :group 'org)
2278 (defcustom org-insert-labeled-timestamps-at-point nil
2279 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2280 When nil, these labeled time stamps are forces into the second line of an
2281 entry, just after the headline. When scheduling from the global TODO list,
2282 the time stamp will always be forced into the second line."
2283 :group 'org-time
2284 :type 'boolean)
2286 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2287 "Formats for `format-time-string' which are used for time stamps.
2288 It is not recommended to change this constant.")
2290 (defcustom org-time-stamp-rounding-minutes '(0 5)
2291 "Number of minutes to round time stamps to.
2292 These are two values, the first applies when first creating a time stamp.
2293 The second applies when changing it with the commands `S-up' and `S-down'.
2294 When changing the time stamp, this means that it will change in steps
2295 of N minutes, as given by the second value.
2297 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2298 numbers should be factors of 60, so for example 5, 10, 15.
2300 When this is larger than 1, you can still force an exact time-stamp by using
2301 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2302 and by using a prefix arg to `S-up/down' to specify the exact number
2303 of minutes to shift."
2304 :group 'org-time
2305 :get '(lambda (var) ; Make sure both elements are there
2306 (if (integerp (default-value var))
2307 (list (default-value var) 5)
2308 (default-value var)))
2309 :type '(list
2310 (integer :tag "when inserting times")
2311 (integer :tag "when modifying times")))
2313 ;; Normalize old customizations of this variable.
2314 (when (integerp org-time-stamp-rounding-minutes)
2315 (setq org-time-stamp-rounding-minutes
2316 (list org-time-stamp-rounding-minutes
2317 org-time-stamp-rounding-minutes)))
2319 (defcustom org-display-custom-times nil
2320 "Non-nil means overlay custom formats over all time stamps.
2321 The formats are defined through the variable `org-time-stamp-custom-formats'.
2322 To turn this on on a per-file basis, insert anywhere in the file:
2323 #+STARTUP: customtime"
2324 :group 'org-time
2325 :set 'set-default
2326 :type 'sexp)
2327 (make-variable-buffer-local 'org-display-custom-times)
2329 (defcustom org-time-stamp-custom-formats
2330 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2331 "Custom formats for time stamps. See `format-time-string' for the syntax.
2332 These are overlayed over the default ISO format if the variable
2333 `org-display-custom-times' is set. Time like %H:%M should be at the
2334 end of the second format. The custom formats are also honored by export
2335 commands, if custom time display is turned on at the time of export."
2336 :group 'org-time
2337 :type 'sexp)
2339 (defun org-time-stamp-format (&optional long inactive)
2340 "Get the right format for a time string."
2341 (let ((f (if long (cdr org-time-stamp-formats)
2342 (car org-time-stamp-formats))))
2343 (if inactive
2344 (concat "[" (substring f 1 -1) "]")
2345 f)))
2347 (defcustom org-time-clocksum-format "%d:%02d"
2348 "The format string used when creating CLOCKSUM lines, or when
2349 org-mode generates a time duration."
2350 :group 'org-time
2351 :type 'string)
2353 (defcustom org-time-clocksum-use-fractional nil
2354 "If non-nil, \\[org-clock-display] uses fractional times.
2355 org-mode generates a time duration."
2356 :group 'org-time
2357 :type 'boolean)
2359 (defcustom org-time-clocksum-fractional-format "%.2f"
2360 "The format string used when creating CLOCKSUM lines, or when
2361 org-mode generates a time duration."
2362 :group 'org-time
2363 :type 'string)
2365 (defcustom org-deadline-warning-days 14
2366 "No. of days before expiration during which a deadline becomes active.
2367 This variable governs the display in sparse trees and in the agenda.
2368 When 0 or negative, it means use this number (the absolute value of it)
2369 even if a deadline has a different individual lead time specified.
2371 Custom commands can set this variable in the options section."
2372 :group 'org-time
2373 :group 'org-agenda-daily/weekly
2374 :type 'integer)
2376 (defcustom org-read-date-prefer-future t
2377 "Non-nil means assume future for incomplete date input from user.
2378 This affects the following situations:
2379 1. The user gives a month but not a year.
2380 For example, if it is april and you enter \"feb 2\", this will be read
2381 as feb 2, *next* year. \"May 5\", however, will be this year.
2382 2. The user gives a day, but no month.
2383 For example, if today is the 15th, and you enter \"3\", Org-mode will
2384 read this as the third of *next* month. However, if you enter \"17\",
2385 it will be considered as *this* month.
2387 If you set this variable to the symbol `time', then also the following
2388 will work:
2390 3. If the user gives a time, but no day. If the time is before now,
2391 to will be interpreted as tomorrow.
2393 Currently none of this works for ISO week specifications.
2395 When this option is nil, the current day, month and year will always be
2396 used as defaults."
2397 :group 'org-time
2398 :type '(choice
2399 (const :tag "Never" nil)
2400 (const :tag "Check month and day" t)
2401 (const :tag "Check month, day, and time" time)))
2403 (defcustom org-read-date-display-live t
2404 "Non-nil means display current interpretation of date prompt live.
2405 This display will be in an overlay, in the minibuffer."
2406 :group 'org-time
2407 :type 'boolean)
2409 (defcustom org-read-date-popup-calendar t
2410 "Non-nil means pop up a calendar when prompting for a date.
2411 In the calendar, the date can be selected with mouse-1. However, the
2412 minibuffer will also be active, and you can simply enter the date as well.
2413 When nil, only the minibuffer will be available."
2414 :group 'org-time
2415 :type 'boolean)
2416 (if (fboundp 'defvaralias)
2417 (defvaralias 'org-popup-calendar-for-date-prompt
2418 'org-read-date-popup-calendar))
2420 (defcustom org-read-date-minibuffer-setup-hook nil
2421 "Hook to be used to set up keys for the date/time interface.
2422 Add key definitions to `minibuffer-local-map', which will be a temporary
2423 copy."
2424 :group 'org-time
2425 :type 'hook)
2427 (defcustom org-extend-today-until 0
2428 "The hour when your day really ends. Must be an integer.
2429 This has influence for the following applications:
2430 - When switching the agenda to \"today\". It it is still earlier than
2431 the time given here, the day recognized as TODAY is actually yesterday.
2432 - When a date is read from the user and it is still before the time given
2433 here, the current date and time will be assumed to be yesterday, 23:59.
2434 Also, timestamps inserted in remember templates follow this rule.
2436 IMPORTANT: This is a feature whose implementation is and likely will
2437 remain incomplete. Really, it is only here because past midnight seems to
2438 be the favorite working time of John Wiegley :-)"
2439 :group 'org-time
2440 :type 'integer)
2442 (defcustom org-edit-timestamp-down-means-later nil
2443 "Non-nil means S-down will increase the time in a time stamp.
2444 When nil, S-up will increase."
2445 :group 'org-time
2446 :type 'boolean)
2448 (defcustom org-calendar-follow-timestamp-change t
2449 "Non-nil means make the calendar window follow timestamp changes.
2450 When a timestamp is modified and the calendar window is visible, it will be
2451 moved to the new date."
2452 :group 'org-time
2453 :type 'boolean)
2455 (defgroup org-tags nil
2456 "Options concerning tags in Org-mode."
2457 :tag "Org Tags"
2458 :group 'org)
2460 (defcustom org-tag-alist nil
2461 "List of tags allowed in Org-mode files.
2462 When this list is nil, Org-mode will base TAG input on what is already in the
2463 buffer.
2464 The value of this variable is an alist, the car of each entry must be a
2465 keyword as a string, the cdr may be a character that is used to select
2466 that tag through the fast-tag-selection interface.
2467 See the manual for details."
2468 :group 'org-tags
2469 :type '(repeat
2470 (choice
2471 (cons (string :tag "Tag name")
2472 (character :tag "Access char"))
2473 (list :tag "Start radio group"
2474 (const :startgroup)
2475 (option (string :tag "Group description")))
2476 (list :tag "End radio group"
2477 (const :endgroup)
2478 (option (string :tag "Group description")))
2479 (const :tag "New line" (:newline)))))
2481 (defcustom org-tag-persistent-alist nil
2482 "List of tags that will always appear in all Org-mode files.
2483 This is in addition to any in buffer settings or customizations
2484 of `org-tag-alist'.
2485 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2486 The value of this variable is an alist, the car of each entry must be a
2487 keyword as a string, the cdr may be a character that is used to select
2488 that tag through the fast-tag-selection interface.
2489 See the manual for details.
2490 To disable these tags on a per-file basis, insert anywhere in the file:
2491 #+STARTUP: noptag"
2492 :group 'org-tags
2493 :type '(repeat
2494 (choice
2495 (cons (string :tag "Tag name")
2496 (character :tag "Access char"))
2497 (const :tag "Start radio group" (:startgroup))
2498 (const :tag "End radio group" (:endgroup))
2499 (const :tag "New line" (:newline)))))
2501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2502 "If non-nil, always offer completion for all tags of all agenda files.
2503 Instead of customizing this variable directly, you might want to
2504 set it locally for remember buffers, because there no list of
2505 tags in that file can be created dynamically (there are none).
2507 (add-hook 'org-remember-mode-hook
2508 (lambda ()
2509 (set (make-local-variable
2510 'org-complete-tags-always-offer-all-agenda-tags)
2511 t)))"
2512 :group 'org-tags
2513 :type 'boolean)
2515 (defvar org-file-tags nil
2516 "List of tags that can be inherited by all entries in the file.
2517 The tags will be inherited if the variable `org-use-tag-inheritance'
2518 says they should be.
2519 This variable is populated from #+FILETAGS lines.")
2521 (defcustom org-use-fast-tag-selection 'auto
2522 "Non-nil means use fast tag selection scheme.
2523 This is a special interface to select and deselect tags with single keys.
2524 When nil, fast selection is never used.
2525 When the symbol `auto', fast selection is used if and only if selection
2526 characters for tags have been configured, either through the variable
2527 `org-tag-alist' or through a #+TAGS line in the buffer.
2528 When t, fast selection is always used and selection keys are assigned
2529 automatically if necessary."
2530 :group 'org-tags
2531 :type '(choice
2532 (const :tag "Always" t)
2533 (const :tag "Never" nil)
2534 (const :tag "When selection characters are configured" 'auto)))
2536 (defcustom org-fast-tag-selection-single-key nil
2537 "Non-nil means fast tag selection exits after first change.
2538 When nil, you have to press RET to exit it.
2539 During fast tag selection, you can toggle this flag with `C-c'.
2540 This variable can also have the value `expert'. In this case, the window
2541 displaying the tags menu is not even shown, until you press C-c again."
2542 :group 'org-tags
2543 :type '(choice
2544 (const :tag "No" nil)
2545 (const :tag "Yes" t)
2546 (const :tag "Expert" expert)))
2548 (defvar org-fast-tag-selection-include-todo nil
2549 "Non-nil means fast tags selection interface will also offer TODO states.
2550 This is an undocumented feature, you should not rely on it.")
2552 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2553 "The column to which tags should be indented in a headline.
2554 If this number is positive, it specifies the column. If it is negative,
2555 it means that the tags should be flushright to that column. For example,
2556 -80 works well for a normal 80 character screen."
2557 :group 'org-tags
2558 :type 'integer)
2560 (defcustom org-auto-align-tags t
2561 "Non-nil means realign tags after pro/demotion of TODO state change.
2562 These operations change the length of a headline and therefore shift
2563 the tags around. With this options turned on, after each such operation
2564 the tags are again aligned to `org-tags-column'."
2565 :group 'org-tags
2566 :type 'boolean)
2568 (defcustom org-use-tag-inheritance t
2569 "Non-nil means tags in levels apply also for sublevels.
2570 When nil, only the tags directly given in a specific line apply there.
2571 This may also be a list of tags that should be inherited, or a regexp that
2572 matches tags that should be inherited. Additional control is possible
2573 with the variable `org-tags-exclude-from-inheritance' which gives an
2574 explicit list of tags to be excluded from inheritance., even if the value of
2575 `org-use-tag-inheritance' would select it for inheritance.
2577 If this option is t, a match early-on in a tree can lead to a large
2578 number of matches in the subtree when constructing the agenda or creating
2579 a sparse tree. If you only want to see the first match in a tree during
2580 a search, check out the variable `org-tags-match-list-sublevels'."
2581 :group 'org-tags
2582 :type '(choice
2583 (const :tag "Not" nil)
2584 (const :tag "Always" t)
2585 (repeat :tag "Specific tags" (string :tag "Tag"))
2586 (regexp :tag "Tags matched by regexp")))
2588 (defcustom org-tags-exclude-from-inheritance nil
2589 "List of tags that should never be inherited.
2590 This is a way to exclude a few tags from inheritance. For way to do
2591 the opposite, to actively allow inheritance for selected tags,
2592 see the variable `org-use-tag-inheritance'."
2593 :group 'org-tags
2594 :type '(repeat (string :tag "Tag")))
2596 (defun org-tag-inherit-p (tag)
2597 "Check if TAG is one that should be inherited."
2598 (cond
2599 ((member tag org-tags-exclude-from-inheritance) nil)
2600 ((eq org-use-tag-inheritance t) t)
2601 ((not org-use-tag-inheritance) nil)
2602 ((stringp org-use-tag-inheritance)
2603 (string-match org-use-tag-inheritance tag))
2604 ((listp org-use-tag-inheritance)
2605 (member tag org-use-tag-inheritance))
2606 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2608 (defcustom org-tags-match-list-sublevels t
2609 "Non-nil means list also sublevels of headlines matching a search.
2610 This variable applies to tags/property searches, and also to stuck
2611 projects because this search is based on a tags match as well.
2613 When set to the symbol `indented', sublevels are indented with
2614 leading dots.
2616 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2617 the sublevels of a headline matching a tag search often also match
2618 the same search. Listing all of them can create very long lists.
2619 Setting this variable to nil causes subtrees of a match to be skipped.
2621 This variable is semi-obsolete and probably should always be true. It
2622 is better to limit inheritance to certain tags using the variables
2623 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2624 :group 'org-tags
2625 :type '(choice
2626 (const :tag "No, don't list them" nil)
2627 (const :tag "Yes, do list them" t)
2628 (const :tag "List them, indented with leading dots" indented)))
2630 (defcustom org-tags-sort-function nil
2631 "When set, tags are sorted using this function as a comparator"
2632 :group 'org-tags
2633 :type '(choice
2634 (const :tag "No sorting" nil)
2635 (const :tag "Alphabetical" string<)
2636 (const :tag "Reverse alphabetical" string>)
2637 (function :tag "Custom function" nil)))
2639 (defvar org-tags-history nil
2640 "History of minibuffer reads for tags.")
2641 (defvar org-last-tags-completion-table nil
2642 "The last used completion table for tags.")
2643 (defvar org-after-tags-change-hook nil
2644 "Hook that is run after the tags in a line have changed.")
2646 (defgroup org-properties nil
2647 "Options concerning properties in Org-mode."
2648 :tag "Org Properties"
2649 :group 'org)
2651 (defcustom org-property-format "%-10s %s"
2652 "How property key/value pairs should be formatted by `indent-line'.
2653 When `indent-line' hits a property definition, it will format the line
2654 according to this format, mainly to make sure that the values are
2655 lined-up with respect to each other."
2656 :group 'org-properties
2657 :type 'string)
2659 (defcustom org-use-property-inheritance nil
2660 "Non-nil means properties apply also for sublevels.
2662 This setting is chiefly used during property searches. Turning it on can
2663 cause significant overhead when doing a search, which is why it is not
2664 on by default.
2666 When nil, only the properties directly given in the current entry count.
2667 When t, every property is inherited. The value may also be a list of
2668 properties that should have inheritance, or a regular expression matching
2669 properties that should be inherited.
2671 However, note that some special properties use inheritance under special
2672 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2673 and the properties ending in \"_ALL\" when they are used as descriptor
2674 for valid values of a property.
2676 Note for programmers:
2677 When querying an entry with `org-entry-get', you can control if inheritance
2678 should be used. By default, `org-entry-get' looks only at the local
2679 properties. You can request inheritance by setting the inherit argument
2680 to t (to force inheritance) or to `selective' (to respect the setting
2681 in this variable)."
2682 :group 'org-properties
2683 :type '(choice
2684 (const :tag "Not" nil)
2685 (const :tag "Always" t)
2686 (repeat :tag "Specific properties" (string :tag "Property"))
2687 (regexp :tag "Properties matched by regexp")))
2689 (defun org-property-inherit-p (property)
2690 "Check if PROPERTY is one that should be inherited."
2691 (cond
2692 ((eq org-use-property-inheritance t) t)
2693 ((not org-use-property-inheritance) nil)
2694 ((stringp org-use-property-inheritance)
2695 (string-match org-use-property-inheritance property))
2696 ((listp org-use-property-inheritance)
2697 (member property org-use-property-inheritance))
2698 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2700 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2701 "The default column format, if no other format has been defined.
2702 This variable can be set on the per-file basis by inserting a line
2704 #+COLUMNS: %25ITEM ....."
2705 :group 'org-properties
2706 :type 'string)
2708 (defcustom org-columns-ellipses ".."
2709 "The ellipses to be used when a field in column view is truncated.
2710 When this is the empty string, as many characters as possible are shown,
2711 but then there will be no visual indication that the field has been truncated.
2712 When this is a string of length N, the last N characters of a truncated
2713 field are replaced by this string. If the column is narrower than the
2714 ellipses string, only part of the ellipses string will be shown."
2715 :group 'org-properties
2716 :type 'string)
2718 (defcustom org-columns-modify-value-for-display-function nil
2719 "Function that modifies values for display in column view.
2720 For example, it can be used to cut out a certain part from a time stamp.
2721 The function must take 2 arguments:
2723 column-title The title of the column (*not* the property name)
2724 value The value that should be modified.
2726 The function should return the value that should be displayed,
2727 or nil if the normal value should be used."
2728 :group 'org-properties
2729 :type 'function)
2731 (defcustom org-effort-property "Effort"
2732 "The property that is being used to keep track of effort estimates.
2733 Effort estimates given in this property need to have the format H:MM."
2734 :group 'org-properties
2735 :group 'org-progress
2736 :type '(string :tag "Property"))
2738 (defconst org-global-properties-fixed
2739 '(("VISIBILITY_ALL" . "folded children content all")
2740 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2741 "List of property/value pairs that can be inherited by any entry.
2743 These are fixed values, for the preset properties. The user variable
2744 that can be used to add to this list is `org-global-properties'.
2746 The entries in this list are cons cells where the car is a property
2747 name and cdr is a string with the value. If the value represents
2748 multiple items like an \"_ALL\" property, separate the items by
2749 spaces.")
2751 (defcustom org-global-properties nil
2752 "List of property/value pairs that can be inherited by any entry.
2754 This list will be combined with the constant `org-global-properties-fixed'.
2756 The entries in this list are cons cells where the car is a property
2757 name and cdr is a string with the value.
2759 You can set buffer-local values for the same purpose in the variable
2760 `org-file-properties' this by adding lines like
2762 #+PROPERTY: NAME VALUE"
2763 :group 'org-properties
2764 :type '(repeat
2765 (cons (string :tag "Property")
2766 (string :tag "Value"))))
2768 (defvar org-file-properties nil
2769 "List of property/value pairs that can be inherited by any entry.
2770 Valid for the current buffer.
2771 This variable is populated from #+PROPERTY lines.")
2772 (make-variable-buffer-local 'org-file-properties)
2774 (defgroup org-agenda nil
2775 "Options concerning agenda views in Org-mode."
2776 :tag "Org Agenda"
2777 :group 'org)
2779 (defvar org-category nil
2780 "Variable used by org files to set a category for agenda display.
2781 Such files should use a file variable to set it, for example
2783 # -*- mode: org; org-category: \"ELisp\"
2785 or contain a special line
2787 #+CATEGORY: ELisp
2789 If the file does not specify a category, then file's base name
2790 is used instead.")
2791 (make-variable-buffer-local 'org-category)
2792 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2794 (defcustom org-agenda-files nil
2795 "The files to be used for agenda display.
2796 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2797 \\[org-remove-file]. You can also use customize to edit the list.
2799 If an entry is a directory, all files in that directory that are matched by
2800 `org-agenda-file-regexp' will be part of the file list.
2802 If the value of the variable is not a list but a single file name, then
2803 the list of agenda files is actually stored and maintained in that file, one
2804 agenda file per line. In this file paths can be given relative to
2805 `org-directory'. Tilde expansion and environment variable substitution
2806 are also made."
2807 :group 'org-agenda
2808 :type '(choice
2809 (repeat :tag "List of files and directories" file)
2810 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2812 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2813 "Regular expression to match files for `org-agenda-files'.
2814 If any element in the list in that variable contains a directory instead
2815 of a normal file, all files in that directory that are matched by this
2816 regular expression will be included."
2817 :group 'org-agenda
2818 :type 'regexp)
2820 (defcustom org-agenda-text-search-extra-files nil
2821 "List of extra files to be searched by text search commands.
2822 These files will be search in addition to the agenda files by the
2823 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2824 Note that these files will only be searched for text search commands,
2825 not for the other agenda views like todo lists, tag searches or the weekly
2826 agenda. This variable is intended to list notes and possibly archive files
2827 that should also be searched by these two commands.
2828 In fact, if the first element in the list is the symbol `agenda-archives',
2829 than all archive files of all agenda files will be added to the search
2830 scope."
2831 :group 'org-agenda
2832 :type '(set :greedy t
2833 (const :tag "Agenda Archives" agenda-archives)
2834 (repeat :inline t (file))))
2836 (if (fboundp 'defvaralias)
2837 (defvaralias 'org-agenda-multi-occur-extra-files
2838 'org-agenda-text-search-extra-files))
2840 (defcustom org-agenda-skip-unavailable-files nil
2841 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2842 A nil value means to remove them, after a query, from the list."
2843 :group 'org-agenda
2844 :type 'boolean)
2846 (defcustom org-calendar-to-agenda-key [?c]
2847 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2848 The command `org-calendar-goto-agenda' will be bound to this key. The
2849 default is the character `c' because then `c' can be used to switch back and
2850 forth between agenda and calendar."
2851 :group 'org-agenda
2852 :type 'sexp)
2854 (defcustom org-calendar-agenda-action-key [?k]
2855 "The key to be installed in `calendar-mode-map' for agenda-action.
2856 The command `org-agenda-action' will be bound to this key. The
2857 default is the character `k' because we use the same key in the agenda."
2858 :group 'org-agenda
2859 :type 'sexp)
2861 (defcustom org-calendar-insert-diary-entry-key [?i]
2862 "The key to be installed in `calendar-mode-map' for adding diary entries.
2863 This option is irrelevant until `org-agenda-diary-file' has been configured
2864 to point to an Org-mode file. When that is the case, the command
2865 `org-agenda-diary-entry' will be bound to the key given here, by default
2866 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2867 if you want to continue doing this, you need to change this to a different
2868 key."
2869 :group 'org-agenda
2870 :type 'sexp)
2872 (defcustom org-agenda-diary-file 'diary-file
2873 "File to which to add new entries with the `i' key in agenda and calendar.
2874 When this is the symbol `diary-file', the functionality in the Emacs
2875 calendar will be used to add entries to the `diary-file'. But when this
2876 points to a file, `org-agenda-diary-entry' will be used instead."
2877 :group 'org-agenda
2878 :type '(choice
2879 (const :tag "The standard Emacs diary file" diary-file)
2880 (file :tag "Special Org file diary entries")))
2882 (eval-after-load "calendar"
2883 '(progn
2884 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2885 'org-calendar-goto-agenda)
2886 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2887 'org-agenda-action)
2888 (add-hook 'calendar-mode-hook
2889 (lambda ()
2890 (unless (eq org-agenda-diary-file 'diary-file)
2891 (define-key calendar-mode-map
2892 org-calendar-insert-diary-entry-key
2893 'org-agenda-diary-entry))))))
2895 (defgroup org-latex nil
2896 "Options for embedding LaTeX code into Org-mode."
2897 :tag "Org LaTeX"
2898 :group 'org)
2900 (defcustom org-format-latex-options
2901 '(:foreground default :background default :scale 1.0
2902 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2903 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2904 "Options for creating images from LaTeX fragments.
2905 This is a property list with the following properties:
2906 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2907 `default' means use the foreground of the default face.
2908 :background the background color, or \"Transparent\".
2909 `default' means use the background of the default face.
2910 :scale a scaling factor for the size of the images.
2911 :html-foreground, :html-background, :html-scale
2912 the same numbers for HTML export.
2913 :matchers a list indicating which matchers should be used to
2914 find LaTeX fragments. Valid members of this list are:
2915 \"begin\" find environments
2916 \"$1\" find single characters surrounded by $.$
2917 \"$\" find math expressions surrounded by $...$
2918 \"$$\" find math expressions surrounded by $$....$$
2919 \"\\(\" find math expressions surrounded by \\(...\\)
2920 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2921 :group 'org-latex
2922 :type 'plist)
2924 (defcustom org-format-latex-signal-error t
2925 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2926 When nil, just push out a message."
2927 :group 'org-latex
2928 :type 'boolean)
2930 (defcustom org-format-latex-header "\\documentclass{article}
2931 \\usepackage[usenames]{color}
2932 \\usepackage{amsmath}
2933 \\usepackage[mathscr]{eucal}
2934 \\pagestyle{empty} % do not remove
2935 \[PACKAGES]
2936 \[DEFAULT-PACKAGES]
2937 % The settings below are copied from fullpage.sty
2938 \\setlength{\\textwidth}{\\paperwidth}
2939 \\addtolength{\\textwidth}{-3cm}
2940 \\setlength{\\oddsidemargin}{1.5cm}
2941 \\addtolength{\\oddsidemargin}{-2.54cm}
2942 \\setlength{\\evensidemargin}{\\oddsidemargin}
2943 \\setlength{\\textheight}{\\paperheight}
2944 \\addtolength{\\textheight}{-\\headheight}
2945 \\addtolength{\\textheight}{-\\headsep}
2946 \\addtolength{\\textheight}{-\\footskip}
2947 \\addtolength{\\textheight}{-3cm}
2948 \\setlength{\\topmargin}{1.5cm}
2949 \\addtolength{\\topmargin}{-2.54cm}"
2950 "The document header used for processing LaTeX fragments.
2951 It is imperative that this header make sure that no page number
2952 appears on the page. The package defined in the variables
2953 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
2954 will either replace the placeholder \"[PACKAGES]\" in this header, or they
2955 will be appended."
2956 :group 'org-latex
2957 :type 'string)
2959 (defvar org-format-latex-header-extra nil)
2961 (defun org-set-packages-alist (var val)
2962 "Set the packages alist and make sure it has 3 elements per entry."
2963 (set var (mapcar (lambda (x)
2964 (if (and (consp x) (= (length x) 2))
2965 (list (car x) (nth 1 x) t)
2967 val)))
2969 (defun org-get-packages-alist (var)
2971 "Get the packages alist and make sure it has 3 elements per entry."
2972 (mapcar (lambda (x)
2973 (if (and (consp x) (= (length x) 2))
2974 (list (car x) (nth 1 x) t)
2976 (default-value var)))
2978 ;; The following variables are defined here because is it also used
2979 ;; when formatting latex fragments. Originally it was part of the
2980 ;; LaTeX exporter, which is why the name includes "export".
2981 (defcustom org-export-latex-default-packages-alist
2982 '(("AUTO" "inputenc" t)
2983 ("T1" "fontenc" t)
2984 ("" "fixltx2e" nil)
2985 ("" "graphicx" t)
2986 ("" "longtable" nil)
2987 ("" "float" nil)
2988 ("" "wrapfig" nil)
2989 ("" "soul" t)
2990 ("" "t1enc" t)
2991 ("" "textcomp" t)
2992 ("" "marvosym" t)
2993 ("" "wasysym" t)
2994 ("" "latexsym" t)
2995 ("" "amssymb" t)
2996 ("" "hyperref" nil)
2997 "\\tolerance=1000"
2999 "Alist of default packages to be inserted in the header.
3000 Change this only if one of the packages here causes an incompatibility
3001 with another package you are using.
3002 The packages in this list are needed by one part or another of Org-mode
3003 to function properly.
3005 - inputenc, fontenc, t1enc: for basic font and character selection
3006 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3007 for interpreting the entities in `org-entities'. You can skip some of these
3008 packages if you don't use any of the symbols in it.
3009 - graphicx: for including images
3010 - float, wrapfig: for figure placement
3011 - longtable: for long tables
3012 - hyperref: for cross references
3014 Therefore you should not modify this variable unless you know what you
3015 are doing. The one reason to change it anyway is that you might be loading
3016 some other package that conflicts with one of the default packages.
3017 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3018 If SNIPPET-FLAG is t, the package also needs to be included when
3019 compiling LaTeX snippets into images for inclusion into HTML."
3020 :group 'org-export-latex
3021 :set 'org-set-packages-alist
3022 :get 'org-get-packages-alist
3023 :type '(repeat
3024 (choice
3025 (list :tag "options/package pair"
3026 (string :tag "options")
3027 (string :tag "package")
3028 (boolean :tag "Snippet"))
3029 (string :tag "A line of LaTeX"))))
3031 (defcustom org-export-latex-packages-alist nil
3032 "Alist of packages to be inserted in every LaTeX header.
3033 These will be inserted after `org-export-latex-default-packages-alist'.
3034 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3035 SNIPPET-FLAG, when t, indicates that this package is also needed when
3036 turning LaTeX snippets into images for inclusion into HTML.
3037 Make sure that you only list packages here which:
3038 - you want in every file
3039 - do not conflict with the default packages in
3040 `org-export-latex-default-packages-alist'
3041 - do not conflict with the setup in `org-format-latex-header'."
3042 :group 'org-export-latex
3043 :set 'org-set-packages-alist
3044 :get 'org-get-packages-alist
3045 :type '(repeat
3046 (choice
3047 (list :tag "options/package pair"
3048 (string :tag "options")
3049 (string :tag "package")
3050 (boolean :tag "Snippet"))
3051 (string :tag "A line of LaTeX"))))
3054 (defgroup org-appearance nil
3055 "Settings for Org-mode appearance."
3056 :tag "Org Appearance"
3057 :group 'org)
3059 (defcustom org-level-color-stars-only nil
3060 "Non-nil means fontify only the stars in each headline.
3061 When nil, the entire headline is fontified.
3062 Changing it requires restart of `font-lock-mode' to become effective
3063 also in regions already fontified."
3064 :group 'org-appearance
3065 :type 'boolean)
3067 (defcustom org-hide-leading-stars nil
3068 "Non-nil means hide the first N-1 stars in a headline.
3069 This works by using the face `org-hide' for these stars. This
3070 face is white for a light background, and black for a dark
3071 background. You may have to customize the face `org-hide' to
3072 make this work.
3073 Changing it requires restart of `font-lock-mode' to become effective
3074 also in regions already fontified.
3075 You may also set this on a per-file basis by adding one of the following
3076 lines to the buffer:
3078 #+STARTUP: hidestars
3079 #+STARTUP: showstars"
3080 :group 'org-appearance
3081 :type 'boolean)
3083 (defcustom org-hidden-keywords nil
3084 "List of keywords that should be hidden when typed in the org buffer.
3085 For example, add #+TITLE to this list in order to make the
3086 document title appear in the buffer without the initial #+TITLE:
3087 keyword."
3088 :group 'org-appearance
3089 :type '(set (const :tag "#+AUTHOR" author)
3090 (const :tag "#+DATE" date)
3091 (const :tag "#+EMAIL" email)
3092 (const :tag "#+TITLE" title)))
3094 (defcustom org-fontify-done-headline nil
3095 "Non-nil means change the face of a headline if it is marked DONE.
3096 Normally, only the TODO/DONE keyword indicates the state of a headline.
3097 When this is non-nil, the headline after the keyword is set to the
3098 `org-headline-done' as an additional indication."
3099 :group 'org-appearance
3100 :type 'boolean)
3102 (defcustom org-fontify-emphasized-text t
3103 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3104 Changing this variable requires a restart of Emacs to take effect."
3105 :group 'org-appearance
3106 :type 'boolean)
3108 (defcustom org-fontify-whole-heading-line nil
3109 "Non-nil means fontify the whole line for headings.
3110 This is useful when setting a background color for the
3111 org-level-* faces."
3112 :group 'org-appearance
3113 :type 'boolean)
3115 (defcustom org-highlight-latex-fragments-and-specials nil
3116 "Non-nil means fontify what is treated specially by the exporters."
3117 :group 'org-appearance
3118 :type 'boolean)
3120 (defcustom org-hide-emphasis-markers nil
3121 "Non-nil mean font-lock should hide the emphasis marker characters."
3122 :group 'org-appearance
3123 :type 'boolean)
3125 (defvar org-emph-re nil
3126 "Regular expression for matching emphasis.")
3127 (defvar org-verbatim-re nil
3128 "Regular expression for matching verbatim text.")
3129 (defvar org-emphasis-regexp-components) ; defined just below
3130 (defvar org-emphasis-alist) ; defined just below
3131 (defun org-set-emph-re (var val)
3132 "Set variable and compute the emphasis regular expression."
3133 (set var val)
3134 (when (and (boundp 'org-emphasis-alist)
3135 (boundp 'org-emphasis-regexp-components)
3136 org-emphasis-alist org-emphasis-regexp-components)
3137 (let* ((e org-emphasis-regexp-components)
3138 (pre (car e))
3139 (post (nth 1 e))
3140 (border (nth 2 e))
3141 (body (nth 3 e))
3142 (nl (nth 4 e))
3143 (body1 (concat body "*?"))
3144 (markers (mapconcat 'car org-emphasis-alist ""))
3145 (vmarkers (mapconcat
3146 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3147 org-emphasis-alist "")))
3148 ;; make sure special characters appear at the right position in the class
3149 (if (string-match "\\^" markers)
3150 (setq markers (concat (replace-match "" t t markers) "^")))
3151 (if (string-match "-" markers)
3152 (setq markers (concat (replace-match "" t t markers) "-")))
3153 (if (string-match "\\^" vmarkers)
3154 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3155 (if (string-match "-" vmarkers)
3156 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3157 (if (> nl 0)
3158 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3159 (int-to-string nl) "\\}")))
3160 ;; Make the regexp
3161 (setq org-emph-re
3162 (concat "\\([" pre "]\\|^\\)"
3163 "\\("
3164 "\\([" markers "]\\)"
3165 "\\("
3166 "[^" border "]\\|"
3167 "[^" border "]"
3168 body1
3169 "[^" border "]"
3170 "\\)"
3171 "\\3\\)"
3172 "\\([" post "]\\|$\\)"))
3173 (setq org-verbatim-re
3174 (concat "\\([" pre "]\\|^\\)"
3175 "\\("
3176 "\\([" vmarkers "]\\)"
3177 "\\("
3178 "[^" border "]\\|"
3179 "[^" border "]"
3180 body1
3181 "[^" border "]"
3182 "\\)"
3183 "\\3\\)"
3184 "\\([" post "]\\|$\\)")))))
3186 (defcustom org-emphasis-regexp-components
3187 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3188 "Components used to build the regular expression for emphasis.
3189 This is a list with 6 entries. Terminology: In an emphasis string
3190 like \" *strong word* \", we call the initial space PREMATCH, the final
3191 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3192 and \"trong wor\" is the body. The different components in this variable
3193 specify what is allowed/forbidden in each part:
3195 pre Chars allowed as prematch. Beginning of line will be allowed too.
3196 post Chars allowed as postmatch. End of line will be allowed too.
3197 border The chars *forbidden* as border characters.
3198 body-regexp A regexp like \".\" to match a body character. Don't use
3199 non-shy groups here, and don't allow newline here.
3200 newline The maximum number of newlines allowed in an emphasis exp.
3202 Use customize to modify this, or restart Emacs after changing it."
3203 :group 'org-appearance
3204 :set 'org-set-emph-re
3205 :type '(list
3206 (sexp :tag "Allowed chars in pre ")
3207 (sexp :tag "Allowed chars in post ")
3208 (sexp :tag "Forbidden chars in border ")
3209 (sexp :tag "Regexp for body ")
3210 (integer :tag "number of newlines allowed")
3211 (option (boolean :tag "Please ignore this button"))))
3213 (defcustom org-emphasis-alist
3214 `(("*" bold "<b>" "</b>")
3215 ("/" italic "<i>" "</i>")
3216 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3217 ("=" org-code "<code>" "</code>" verbatim)
3218 ("~" org-verbatim "<code>" "</code>" verbatim)
3219 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3220 "<del>" "</del>")
3222 "Special syntax for emphasized text.
3223 Text starting and ending with a special character will be emphasized, for
3224 example *bold*, _underlined_ and /italic/. This variable sets the marker
3225 characters, the face to be used by font-lock for highlighting in Org-mode
3226 Emacs buffers, and the HTML tags to be used for this.
3227 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3228 Use customize to modify this, or restart Emacs after changing it."
3229 :group 'org-appearance
3230 :set 'org-set-emph-re
3231 :type '(repeat
3232 (list
3233 (string :tag "Marker character")
3234 (choice
3235 (face :tag "Font-lock-face")
3236 (plist :tag "Face property list"))
3237 (string :tag "HTML start tag")
3238 (string :tag "HTML end tag")
3239 (option (const verbatim)))))
3241 (defvar org-protecting-blocks
3242 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3243 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3244 This is needed for font-lock setup.")
3246 ;;; Miscellaneous options
3248 (defgroup org-completion nil
3249 "Completion in Org-mode."
3250 :tag "Org Completion"
3251 :group 'org)
3253 (defcustom org-completion-use-ido nil
3254 "Non-nil means use ido completion wherever possible.
3255 Note that `ido-mode' must be active for this variable to be relevant.
3256 If you decide to turn this variable on, you might well want to turn off
3257 `org-outline-path-complete-in-steps'.
3258 See also `org-completion-use-iswitchb'."
3259 :group 'org-completion
3260 :type 'boolean)
3262 (defcustom org-completion-use-iswitchb nil
3263 "Non-nil means use iswitchb completion wherever possible.
3264 Note that `iswitchb-mode' must be active for this variable to be relevant.
3265 If you decide to turn this variable on, you might well want to turn off
3266 `org-outline-path-complete-in-steps'.
3267 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3268 :group 'org-completion
3269 :type 'boolean)
3271 (defcustom org-completion-fallback-command 'hippie-expand
3272 "The expansion command called by \\[org-complete] in normal context.
3273 Normal means no org-mode-specific context."
3274 :group 'org-completion
3275 :type 'function)
3277 ;;; Functions and variables from their packages
3278 ;; Declared here to avoid compiler warnings
3280 ;; XEmacs only
3281 (defvar outline-mode-menu-heading)
3282 (defvar outline-mode-menu-show)
3283 (defvar outline-mode-menu-hide)
3284 (defvar zmacs-regions) ; XEmacs regions
3286 ;; Emacs only
3287 (defvar mark-active)
3289 ;; Various packages
3290 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3291 (declare-function calendar-forward-day "cal-move" (arg))
3292 (declare-function calendar-goto-date "cal-move" (date))
3293 (declare-function calendar-goto-today "cal-move" ())
3294 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3295 (defvar calc-embedded-close-formula)
3296 (defvar calc-embedded-open-formula)
3297 (declare-function cdlatex-tab "ext:cdlatex" ())
3298 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3299 (defvar font-lock-unfontify-region-function)
3300 (declare-function iswitchb-read-buffer "iswitchb"
3301 (prompt &optional default require-match start matches-set))
3302 (defvar iswitchb-temp-buflist)
3303 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3304 (defvar org-agenda-tags-todo-honor-ignore-options)
3305 (declare-function org-agenda-skip "org-agenda" ())
3306 (declare-function
3307 org-format-agenda-item "org-agenda"
3308 (extra txt &optional category tags dotime noprefix remove-re habitp))
3309 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3310 (declare-function org-agenda-change-all-lines "org-agenda"
3311 (newhead hdmarker &optional fixface just-this))
3312 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3313 (declare-function org-agenda-maybe-redo "org-agenda" ())
3314 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3315 (beg end))
3316 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3317 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3318 "org-agenda" (&optional end))
3319 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3320 (declare-function org-indent-mode "org-indent" (&optional arg))
3321 (declare-function parse-time-string "parse-time" (string))
3322 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3323 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3324 (defvar remember-data-file)
3325 (defvar texmathp-why)
3326 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3327 (declare-function table--at-cell-p "table" (position &optional object at-column))
3329 (defvar w3m-current-url)
3330 (defvar w3m-current-title)
3332 (defvar org-latex-regexps)
3334 ;;; Autoload and prepare some org modules
3336 ;; Some table stuff that needs to be defined here, because it is used
3337 ;; by the functions setting up org-mode or checking for table context.
3339 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3340 "Detects an org-type or table-type table.")
3341 (defconst org-table-line-regexp "^[ \t]*|"
3342 "Detects an org-type table line.")
3343 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3344 "Detects an org-type table line.")
3345 (defconst org-table-hline-regexp "^[ \t]*|-"
3346 "Detects an org-type table hline.")
3347 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3348 "Detects a table-type table hline.")
3349 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3350 "Searching from within a table (any type) this finds the first line
3351 outside the table.")
3353 ;; Autoload the functions in org-table.el that are needed by functions here.
3355 (eval-and-compile
3356 (org-autoload "org-table"
3357 '(org-table-align org-table-begin org-table-blank-field
3358 org-table-convert org-table-convert-region org-table-copy-down
3359 org-table-copy-region org-table-create
3360 org-table-create-or-convert-from-region
3361 org-table-create-with-table.el org-table-current-dline
3362 org-table-cut-region org-table-delete-column org-table-edit-field
3363 org-table-edit-formulas org-table-end org-table-eval-formula
3364 org-table-export org-table-field-info
3365 org-table-get-stored-formulas org-table-goto-column
3366 org-table-hline-and-move org-table-import org-table-insert-column
3367 org-table-insert-hline org-table-insert-row org-table-iterate
3368 org-table-justify-field-maybe org-table-kill-row
3369 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3370 org-table-move-column org-table-move-column-left
3371 org-table-move-column-right org-table-move-row
3372 org-table-move-row-down org-table-move-row-up
3373 org-table-next-field org-table-next-row org-table-paste-rectangle
3374 org-table-previous-field org-table-recalculate
3375 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3376 org-table-toggle-coordinate-overlays
3377 org-table-toggle-formula-debugger org-table-wrap-region
3378 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3380 (defun org-at-table-p (&optional table-type)
3381 "Return t if the cursor is inside an org-type table.
3382 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3383 (if org-enable-table-editor
3384 (save-excursion
3385 (beginning-of-line 1)
3386 (looking-at (if table-type org-table-any-line-regexp
3387 org-table-line-regexp)))
3388 nil))
3389 (defsubst org-table-p () (org-at-table-p))
3391 (defun org-at-table.el-p ()
3392 "Return t if and only if we are at a table.el table."
3393 (and (org-at-table-p 'any)
3394 (save-excursion
3395 (goto-char (org-table-begin 'any))
3396 (looking-at org-table1-hline-regexp))))
3397 (defun org-table-recognize-table.el ()
3398 "If there is a table.el table nearby, recognize it and move into it."
3399 (if org-table-tab-recognizes-table.el
3400 (if (org-at-table.el-p)
3401 (progn
3402 (beginning-of-line 1)
3403 (if (looking-at org-table-dataline-regexp)
3405 (if (looking-at org-table1-hline-regexp)
3406 (progn
3407 (beginning-of-line 2)
3408 (if (looking-at org-table-any-border-regexp)
3409 (beginning-of-line -1)))))
3410 (if (re-search-forward "|" (org-table-end t) t)
3411 (progn
3412 (require 'table)
3413 (if (table--at-cell-p (point))
3415 (message "recognizing table.el table...")
3416 (table-recognize-table)
3417 (message "recognizing table.el table...done")))
3418 (error "This should not happen..."))
3420 nil)
3421 nil))
3423 (defun org-at-table-hline-p ()
3424 "Return t if the cursor is inside a hline in a table."
3425 (if org-enable-table-editor
3426 (save-excursion
3427 (beginning-of-line 1)
3428 (looking-at org-table-hline-regexp))
3429 nil))
3431 (defvar org-table-clean-did-remove-column nil)
3433 (defun org-table-map-tables (function &optional quietly)
3434 "Apply FUNCTION to the start of all tables in the buffer."
3435 (save-excursion
3436 (save-restriction
3437 (widen)
3438 (goto-char (point-min))
3439 (while (re-search-forward org-table-any-line-regexp nil t)
3440 (unless quietly
3441 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3442 (beginning-of-line 1)
3443 (when (looking-at org-table-line-regexp)
3444 (save-excursion (funcall function))
3445 (or (looking-at org-table-line-regexp)
3446 (forward-char 1)))
3447 (re-search-forward org-table-any-border-regexp nil 1))))
3448 (unless quietly (message "Mapping tables: done")))
3450 ;; Declare and autoload functions from org-exp.el & Co
3452 (declare-function org-default-export-plist "org-exp")
3453 (declare-function org-infile-export-plist "org-exp")
3454 (declare-function org-get-current-options "org-exp")
3455 (eval-and-compile
3456 (org-autoload "org-exp"
3457 '(org-export org-export-visible
3458 org-insert-export-options-template
3459 org-table-clean-before-export))
3460 (org-autoload "org-ascii"
3461 '(org-export-as-ascii org-export-ascii-preprocess
3462 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3463 org-export-region-as-ascii))
3464 (org-autoload "org-latex"
3465 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3466 org-replace-region-by-latex org-export-region-as-latex
3467 org-export-as-latex org-export-as-pdf
3468 org-export-as-pdf-and-open))
3469 (org-autoload "org-html"
3470 '(org-export-as-html-and-open
3471 org-export-as-html-batch org-export-as-html-to-buffer
3472 org-replace-region-by-html org-export-region-as-html
3473 org-export-as-html))
3474 (org-autoload "org-docbook"
3475 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3476 org-replace-region-by-docbook org-export-region-as-docbook
3477 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3478 org-export-as-docbook))
3479 (org-autoload "org-icalendar"
3480 '(org-export-icalendar-this-file
3481 org-export-icalendar-all-agenda-files
3482 org-export-icalendar-combine-agenda-files))
3483 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3484 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3486 ;; Declare and autoload functions from org-agenda.el
3488 (eval-and-compile
3489 (org-autoload "org-agenda"
3490 '(org-agenda org-agenda-list org-search-view
3491 org-todo-list org-tags-view org-agenda-list-stuck-projects
3492 org-diary org-agenda-to-appt
3493 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3495 ;; Autoload org-remember
3497 (eval-and-compile
3498 (org-autoload "org-remember"
3499 '(org-remember-insinuate org-remember-annotation
3500 org-remember-apply-template org-remember org-remember-handler)))
3502 ;; Autoload org-clock.el
3505 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3506 (beg end))
3507 (declare-function org-clock-update-mode-line "org-clock" ())
3508 (declare-function org-resolve-clocks "org-clock"
3509 (&optional also-non-dangling-p prompt last-valid))
3510 (defvar org-clock-start-time)
3511 (defvar org-clock-marker (make-marker)
3512 "Marker recording the last clock-in.")
3513 (defvar org-clock-hd-marker (make-marker)
3514 "Marker recording the last clock-in, but the headline position.")
3515 (defvar org-clock-heading ""
3516 "The heading of the current clock entry.")
3517 (defun org-clock-is-active ()
3518 "Return non-nil if clock is currently running.
3519 The return value is actually the clock marker."
3520 (marker-buffer org-clock-marker))
3522 (eval-and-compile
3523 (org-autoload
3524 "org-clock"
3525 '(org-clock-in org-clock-out org-clock-cancel
3526 org-clock-goto org-clock-sum org-clock-display
3527 org-clock-remove-overlays org-clock-report
3528 org-clocktable-shift org-dblock-write:clocktable
3529 org-get-clocktable org-resolve-clocks)))
3531 (defun org-clock-update-time-maybe ()
3532 "If this is a CLOCK line, update it and return t.
3533 Otherwise, return nil."
3534 (interactive)
3535 (save-excursion
3536 (beginning-of-line 1)
3537 (skip-chars-forward " \t")
3538 (when (looking-at org-clock-string)
3539 (let ((re (concat "[ \t]*" org-clock-string
3540 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3541 "\\([ \t]*=>.*\\)?\\)?"))
3542 ts te h m s neg)
3543 (cond
3544 ((not (looking-at re))
3545 nil)
3546 ((not (match-end 2))
3547 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3548 (> org-clock-marker (point))
3549 (<= org-clock-marker (point-at-eol)))
3550 ;; The clock is running here
3551 (setq org-clock-start-time
3552 (apply 'encode-time
3553 (org-parse-time-string (match-string 1))))
3554 (org-clock-update-mode-line)))
3556 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3557 (end-of-line 1)
3558 (setq ts (match-string 1)
3559 te (match-string 3))
3560 (setq s (- (org-float-time
3561 (apply 'encode-time (org-parse-time-string te)))
3562 (org-float-time
3563 (apply 'encode-time (org-parse-time-string ts))))
3564 neg (< s 0)
3565 s (abs s)
3566 h (floor (/ s 3600))
3567 s (- s (* 3600 h))
3568 m (floor (/ s 60))
3569 s (- s (* 60 s)))
3570 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3571 t))))))
3573 (defun org-check-running-clock ()
3574 "Check if the current buffer contains the running clock.
3575 If yes, offer to stop it and to save the buffer with the changes."
3576 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3577 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3578 (buffer-name))))
3579 (org-clock-out)
3580 (when (y-or-n-p "Save changed buffer?")
3581 (save-buffer))))
3583 (defun org-clocktable-try-shift (dir n)
3584 "Check if this line starts a clock table, if yes, shift the time block."
3585 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3586 (org-clocktable-shift dir n)))
3588 ;; Autoload org-timer.el
3590 (eval-and-compile
3591 (org-autoload
3592 "org-timer"
3593 '(org-timer-start org-timer org-timer-item
3594 org-timer-change-times-in-region
3595 org-timer-set-timer
3596 org-timer-reset-timers
3597 org-timer-show-remaining-time)))
3599 ;; Autoload org-feed.el
3601 (eval-and-compile
3602 (org-autoload
3603 "org-feed"
3604 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3607 ;; Autoload org-indent.el
3609 ;; Define the variable already here, to make sure we have it.
3610 (defvar org-indent-mode nil
3611 "Non-nil if Org-Indent mode is enabled.
3612 Use the command `org-indent-mode' to change this variable.")
3614 (eval-and-compile
3615 (org-autoload
3616 "org-indent"
3617 '(org-indent-mode)))
3619 ;; Autoload org-mobile.el
3621 (eval-and-compile
3622 (org-autoload
3623 "org-mobile"
3624 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3626 ;; Autoload archiving code
3627 ;; The stuff that is needed for cycling and tags has to be defined here.
3629 (defgroup org-archive nil
3630 "Options concerning archiving in Org-mode."
3631 :tag "Org Archive"
3632 :group 'org-structure)
3634 (defcustom org-archive-location "%s_archive::"
3635 "The location where subtrees should be archived.
3637 The value of this variable is a string, consisting of two parts,
3638 separated by a double-colon. The first part is a filename and
3639 the second part is a headline.
3641 When the filename is omitted, archiving happens in the same file.
3642 %s in the filename will be replaced by the current file
3643 name (without the directory part). Archiving to a different file
3644 is useful to keep archived entries from contributing to the
3645 Org-mode Agenda.
3647 The archived entries will be filed as subtrees of the specified
3648 headline. When the headline is omitted, the subtrees are simply
3649 filed away at the end of the file, as top-level entries. Also in
3650 the heading you can use %s to represent the file name, this can be
3651 useful when using the same archive for a number of different files.
3653 Here are a few examples:
3654 \"%s_archive::\"
3655 If the current file is Projects.org, archive in file
3656 Projects.org_archive, as top-level trees. This is the default.
3658 \"::* Archived Tasks\"
3659 Archive in the current file, under the top-level headline
3660 \"* Archived Tasks\".
3662 \"~/org/archive.org::\"
3663 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3665 \"~/org/archive.org::From %s\"
3666 Archive in file ~/org/archive.org (absolute path), under headlines
3667 \"From FILENAME\" where file name is the current file name.
3669 \"basement::** Finished Tasks\"
3670 Archive in file ./basement (relative path), as level 3 trees
3671 below the level 2 heading \"** Finished Tasks\".
3673 You may set this option on a per-file basis by adding to the buffer a
3674 line like
3676 #+ARCHIVE: basement::** Finished Tasks
3678 You may also define it locally for a subtree by setting an ARCHIVE property
3679 in the entry. If such a property is found in an entry, or anywhere up
3680 the hierarchy, it will be used."
3681 :group 'org-archive
3682 :type 'string)
3684 (defcustom org-archive-tag "ARCHIVE"
3685 "The tag that marks a subtree as archived.
3686 An archived subtree does not open during visibility cycling, and does
3687 not contribute to the agenda listings.
3688 After changing this, font-lock must be restarted in the relevant buffers to
3689 get the proper fontification."
3690 :group 'org-archive
3691 :group 'org-keywords
3692 :type 'string)
3694 (defcustom org-agenda-skip-archived-trees t
3695 "Non-nil means the agenda will skip any items located in archived trees.
3696 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3697 variable is no longer recommended, you should leave it at the value t.
3698 Instead, use the key `v' to cycle the archives-mode in the agenda."
3699 :group 'org-archive
3700 :group 'org-agenda-skip
3701 :type 'boolean)
3703 (defcustom org-columns-skip-archived-trees t
3704 "Non-nil means ignore archived trees when creating column view."
3705 :group 'org-archive
3706 :group 'org-properties
3707 :type 'boolean)
3709 (defcustom org-cycle-open-archived-trees nil
3710 "Non-nil means `org-cycle' will open archived trees.
3711 An archived tree is a tree marked with the tag ARCHIVE.
3712 When nil, archived trees will stay folded. You can still open them with
3713 normal outline commands like `show-all', but not with the cycling commands."
3714 :group 'org-archive
3715 :group 'org-cycle
3716 :type 'boolean)
3718 (defcustom org-sparse-tree-open-archived-trees nil
3719 "Non-nil means sparse tree construction shows matches in archived trees.
3720 When nil, matches in these trees are highlighted, but the trees are kept in
3721 collapsed state."
3722 :group 'org-archive
3723 :group 'org-sparse-trees
3724 :type 'boolean)
3726 (defun org-cycle-hide-archived-subtrees (state)
3727 "Re-hide all archived subtrees after a visibility state change."
3728 (when (and (not org-cycle-open-archived-trees)
3729 (not (memq state '(overview folded))))
3730 (save-excursion
3731 (let* ((globalp (memq state '(contents all)))
3732 (beg (if globalp (point-min) (point)))
3733 (end (if globalp (point-max) (org-end-of-subtree t))))
3734 (org-hide-archived-subtrees beg end)
3735 (goto-char beg)
3736 (if (looking-at (concat ".*:" org-archive-tag ":"))
3737 (message "%s" (substitute-command-keys
3738 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3740 (defun org-force-cycle-archived ()
3741 "Cycle subtree even if it is archived."
3742 (interactive)
3743 (setq this-command 'org-cycle)
3744 (let ((org-cycle-open-archived-trees t))
3745 (call-interactively 'org-cycle)))
3747 (defun org-hide-archived-subtrees (beg end)
3748 "Re-hide all archived subtrees after a visibility state change."
3749 (save-excursion
3750 (let* ((re (concat ":" org-archive-tag ":")))
3751 (goto-char beg)
3752 (while (re-search-forward re end t)
3753 (when (org-on-heading-p)
3754 (org-flag-subtree t)
3755 (org-end-of-subtree t))))))
3757 (defun org-flag-subtree (flag)
3758 (save-excursion
3759 (org-back-to-heading t)
3760 (outline-end-of-heading)
3761 (outline-flag-region (point)
3762 (progn (org-end-of-subtree t) (point))
3763 flag)))
3765 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3767 (eval-and-compile
3768 (org-autoload "org-archive"
3769 '(org-add-archive-files org-archive-subtree
3770 org-archive-to-archive-sibling org-toggle-archive-tag
3771 org-archive-subtree-default
3772 org-archive-subtree-default-with-confirmation)))
3774 ;; Autoload Column View Code
3776 (declare-function org-columns-number-to-string "org-colview")
3777 (declare-function org-columns-get-format-and-top-level "org-colview")
3778 (declare-function org-columns-compute "org-colview")
3780 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3781 '(org-columns-number-to-string org-columns-get-format-and-top-level
3782 org-columns-compute org-agenda-columns org-columns-remove-overlays
3783 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3785 ;; Autoload ID code
3787 (declare-function org-id-store-link "org-id")
3788 (declare-function org-id-locations-load "org-id")
3789 (declare-function org-id-locations-save "org-id")
3790 (defvar org-id-track-globally)
3791 (org-autoload "org-id"
3792 '(org-id-get-create org-id-new org-id-copy org-id-get
3793 org-id-get-with-outline-path-completion
3794 org-id-get-with-outline-drilling
3795 org-id-goto org-id-find org-id-store-link))
3797 ;; Autoload Plotting Code
3799 (org-autoload "org-plot"
3800 '(org-plot/gnuplot))
3802 ;;; Variables for pre-computed regular expressions, all buffer local
3804 (defvar org-drawer-regexp nil
3805 "Matches first line of a hidden block.")
3806 (make-variable-buffer-local 'org-drawer-regexp)
3807 (defvar org-todo-regexp nil
3808 "Matches any of the TODO state keywords.")
3809 (make-variable-buffer-local 'org-todo-regexp)
3810 (defvar org-not-done-regexp nil
3811 "Matches any of the TODO state keywords except the last one.")
3812 (make-variable-buffer-local 'org-not-done-regexp)
3813 (defvar org-not-done-heading-regexp nil
3814 "Matches a TODO headline that is not done.")
3815 (make-variable-buffer-local 'org-not-done-regexp)
3816 (defvar org-todo-line-regexp nil
3817 "Matches a headline and puts TODO state into group 2 if present.")
3818 (make-variable-buffer-local 'org-todo-line-regexp)
3819 (defvar org-complex-heading-regexp nil
3820 "Matches a headline and puts everything into groups:
3821 group 1: the stars
3822 group 2: The todo keyword, maybe
3823 group 3: Priority cookie
3824 group 4: True headline
3825 group 5: Tags")
3826 (make-variable-buffer-local 'org-complex-heading-regexp)
3827 (defvar org-complex-heading-regexp-format nil)
3828 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3829 (defvar org-todo-line-tags-regexp nil
3830 "Matches a headline and puts TODO state into group 2 if present.
3831 Also put tags into group 4 if tags are present.")
3832 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3833 (defvar org-nl-done-regexp nil
3834 "Matches newline followed by a headline with the DONE keyword.")
3835 (make-variable-buffer-local 'org-nl-done-regexp)
3836 (defvar org-looking-at-done-regexp nil
3837 "Matches the DONE keyword a point.")
3838 (make-variable-buffer-local 'org-looking-at-done-regexp)
3839 (defvar org-ds-keyword-length 12
3840 "Maximum length of the Deadline and SCHEDULED keywords.")
3841 (make-variable-buffer-local 'org-ds-keyword-length)
3842 (defvar org-deadline-regexp nil
3843 "Matches the DEADLINE keyword.")
3844 (make-variable-buffer-local 'org-deadline-regexp)
3845 (defvar org-deadline-time-regexp nil
3846 "Matches the DEADLINE keyword together with a time stamp.")
3847 (make-variable-buffer-local 'org-deadline-time-regexp)
3848 (defvar org-deadline-line-regexp nil
3849 "Matches the DEADLINE keyword and the rest of the line.")
3850 (make-variable-buffer-local 'org-deadline-line-regexp)
3851 (defvar org-scheduled-regexp nil
3852 "Matches the SCHEDULED keyword.")
3853 (make-variable-buffer-local 'org-scheduled-regexp)
3854 (defvar org-scheduled-time-regexp nil
3855 "Matches the SCHEDULED keyword together with a time stamp.")
3856 (make-variable-buffer-local 'org-scheduled-time-regexp)
3857 (defvar org-closed-time-regexp nil
3858 "Matches the CLOSED keyword together with a time stamp.")
3859 (make-variable-buffer-local 'org-closed-time-regexp)
3861 (defvar org-keyword-time-regexp nil
3862 "Matches any of the 4 keywords, together with the time stamp.")
3863 (make-variable-buffer-local 'org-keyword-time-regexp)
3864 (defvar org-keyword-time-not-clock-regexp nil
3865 "Matches any of the 3 keywords, together with the time stamp.")
3866 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3867 (defvar org-maybe-keyword-time-regexp nil
3868 "Matches a timestamp, possibly preceeded by a keyword.")
3869 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3870 (defvar org-planning-or-clock-line-re nil
3871 "Matches a line with planning or clock info.")
3872 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3873 (defvar org-all-time-keywords nil
3874 "List of time keywords.")
3875 (make-variable-buffer-local 'org-all-time-keywords)
3877 (defconst org-plain-time-of-day-regexp
3878 (concat
3879 "\\(\\<[012]?[0-9]"
3880 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3881 "\\(--?"
3882 "\\(\\<[012]?[0-9]"
3883 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3884 "\\)?")
3885 "Regular expression to match a plain time or time range.
3886 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3887 groups carry important information:
3888 0 the full match
3889 1 the first time, range or not
3890 8 the second time, if it is a range.")
3892 (defconst org-plain-time-extension-regexp
3893 (concat
3894 "\\(\\<[012]?[0-9]"
3895 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3896 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3897 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3898 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3899 groups carry important information:
3900 0 the full match
3901 7 hours of duration
3902 9 minutes of duration")
3904 (defconst org-stamp-time-of-day-regexp
3905 (concat
3906 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3907 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3908 "\\(--?"
3909 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3910 "Regular expression to match a timestamp time or time range.
3911 After a match, the following groups carry important information:
3912 0 the full match
3913 1 date plus weekday, for back referencing to make sure both times are on the same day
3914 2 the first time, range or not
3915 4 the second time, if it is a range.")
3917 (defconst org-startup-options
3918 '(("fold" org-startup-folded t)
3919 ("overview" org-startup-folded t)
3920 ("nofold" org-startup-folded nil)
3921 ("showall" org-startup-folded nil)
3922 ("showeverything" org-startup-folded showeverything)
3923 ("content" org-startup-folded content)
3924 ("indent" org-startup-indented t)
3925 ("noindent" org-startup-indented nil)
3926 ("hidestars" org-hide-leading-stars t)
3927 ("showstars" org-hide-leading-stars nil)
3928 ("odd" org-odd-levels-only t)
3929 ("oddeven" org-odd-levels-only nil)
3930 ("align" org-startup-align-all-tables t)
3931 ("noalign" org-startup-align-all-tables nil)
3932 ("customtime" org-display-custom-times t)
3933 ("logdone" org-log-done time)
3934 ("lognotedone" org-log-done note)
3935 ("nologdone" org-log-done nil)
3936 ("lognoteclock-out" org-log-note-clock-out t)
3937 ("nolognoteclock-out" org-log-note-clock-out nil)
3938 ("logrepeat" org-log-repeat state)
3939 ("lognoterepeat" org-log-repeat note)
3940 ("nologrepeat" org-log-repeat nil)
3941 ("logreschedule" org-log-reschedule time)
3942 ("lognotereschedule" org-log-reschedule note)
3943 ("nologreschedule" org-log-reschedule nil)
3944 ("logredeadline" org-log-redeadline time)
3945 ("lognoteredeadline" org-log-redeadline note)
3946 ("nologredeadline" org-log-redeadline nil)
3947 ("logrefile" org-log-refile time)
3948 ("lognoterefile" org-log-refile note)
3949 ("nologrefile" org-log-refile nil)
3950 ("fninline" org-footnote-define-inline t)
3951 ("nofninline" org-footnote-define-inline nil)
3952 ("fnlocal" org-footnote-section nil)
3953 ("fnauto" org-footnote-auto-label t)
3954 ("fnprompt" org-footnote-auto-label nil)
3955 ("fnconfirm" org-footnote-auto-label confirm)
3956 ("fnplain" org-footnote-auto-label plain)
3957 ("fnadjust" org-footnote-auto-adjust t)
3958 ("nofnadjust" org-footnote-auto-adjust nil)
3959 ("constcgs" constants-unit-system cgs)
3960 ("constSI" constants-unit-system SI)
3961 ("noptag" org-tag-persistent-alist nil)
3962 ("hideblocks" org-hide-block-startup t)
3963 ("nohideblocks" org-hide-block-startup nil)
3964 ("beamer" org-startup-with-beamer-mode t))
3965 "Variable associated with STARTUP options for org-mode.
3966 Each element is a list of three items: The startup options as written
3967 in the #+STARTUP line, the corresponding variable, and the value to
3968 set this variable to if the option is found. An optional forth element PUSH
3969 means to push this value onto the list in the variable.")
3971 (defun org-set-regexps-and-options ()
3972 "Precompute regular expressions for current buffer."
3973 (when (org-mode-p)
3974 (org-set-local 'org-todo-kwd-alist nil)
3975 (org-set-local 'org-todo-key-alist nil)
3976 (org-set-local 'org-todo-key-trigger nil)
3977 (org-set-local 'org-todo-keywords-1 nil)
3978 (org-set-local 'org-done-keywords nil)
3979 (org-set-local 'org-todo-heads nil)
3980 (org-set-local 'org-todo-sets nil)
3981 (org-set-local 'org-todo-log-states nil)
3982 (org-set-local 'org-file-properties nil)
3983 (org-set-local 'org-file-tags nil)
3984 (let ((re (org-make-options-regexp
3985 '("CATEGORY" "TODO" "COLUMNS"
3986 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3987 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3988 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3989 (splitre "[ \t]+")
3990 kwds kws0 kwsa key log value cat arch tags const links hw dws
3991 tail sep kws1 prio props ftags drawers beamer-p
3992 ext-setup-or-nil setup-contents (start 0))
3993 (save-excursion
3994 (save-restriction
3995 (widen)
3996 (goto-char (point-min))
3997 (while (or (and ext-setup-or-nil
3998 (string-match re ext-setup-or-nil start)
3999 (setq start (match-end 0)))
4000 (and (setq ext-setup-or-nil nil start 0)
4001 (re-search-forward re nil t)))
4002 (setq key (upcase (match-string 1 ext-setup-or-nil))
4003 value (org-match-string-no-properties 2 ext-setup-or-nil))
4004 (cond
4005 ((equal key "CATEGORY")
4006 (if (string-match "[ \t]+$" value)
4007 (setq value (replace-match "" t t value)))
4008 (setq cat value))
4009 ((member key '("SEQ_TODO" "TODO"))
4010 (push (cons 'sequence (org-split-string value splitre)) kwds))
4011 ((equal key "TYP_TODO")
4012 (push (cons 'type (org-split-string value splitre)) kwds))
4013 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4014 ;; general TODO-like setup
4015 (push (cons (intern (downcase (match-string 1 key)))
4016 (org-split-string value splitre)) kwds))
4017 ((equal key "TAGS")
4018 (setq tags (append tags (if tags '("\\n") nil)
4019 (org-split-string value splitre))))
4020 ((equal key "COLUMNS")
4021 (org-set-local 'org-columns-default-format value))
4022 ((equal key "LINK")
4023 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4024 (push (cons (match-string 1 value)
4025 (org-trim (match-string 2 value)))
4026 links)))
4027 ((equal key "PRIORITIES")
4028 (setq prio (org-split-string value " +")))
4029 ((equal key "PROPERTY")
4030 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4031 (push (cons (match-string 1 value) (match-string 2 value))
4032 props)))
4033 ((equal key "FILETAGS")
4034 (when (string-match "\\S-" value)
4035 (setq ftags
4036 (append
4037 ftags
4038 (apply 'append
4039 (mapcar (lambda (x) (org-split-string x ":"))
4040 (org-split-string value)))))))
4041 ((equal key "DRAWERS")
4042 (setq drawers (org-split-string value splitre)))
4043 ((equal key "CONSTANTS")
4044 (setq const (append const (org-split-string value splitre))))
4045 ((equal key "STARTUP")
4046 (let ((opts (org-split-string value splitre))
4047 l var val)
4048 (while (setq l (pop opts))
4049 (when (setq l (assoc l org-startup-options))
4050 (setq var (nth 1 l) val (nth 2 l))
4051 (if (not (nth 3 l))
4052 (set (make-local-variable var) val)
4053 (if (not (listp (symbol-value var)))
4054 (set (make-local-variable var) nil))
4055 (set (make-local-variable var) (symbol-value var))
4056 (add-to-list var val))))))
4057 ((equal key "ARCHIVE")
4058 (string-match " *$" value)
4059 (setq arch (replace-match "" t t value))
4060 (remove-text-properties 0 (length arch)
4061 '(face t fontified t) arch))
4062 ((equal key "LATEX_CLASS")
4063 (setq beamer-p (equal value "beamer")))
4064 ((equal key "SETUPFILE")
4065 (setq setup-contents (org-file-contents
4066 (expand-file-name
4067 (org-remove-double-quotes value))
4068 'noerror))
4069 (if (not ext-setup-or-nil)
4070 (setq ext-setup-or-nil setup-contents start 0)
4071 (setq ext-setup-or-nil
4072 (concat (substring ext-setup-or-nil 0 start)
4073 "\n" setup-contents "\n"
4074 (substring ext-setup-or-nil start)))))
4075 ))))
4076 (when cat
4077 (org-set-local 'org-category (intern cat))
4078 (push (cons "CATEGORY" cat) props))
4079 (when prio
4080 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4081 (setq prio (mapcar 'string-to-char prio))
4082 (org-set-local 'org-highest-priority (nth 0 prio))
4083 (org-set-local 'org-lowest-priority (nth 1 prio))
4084 (org-set-local 'org-default-priority (nth 2 prio)))
4085 (and props (org-set-local 'org-file-properties (nreverse props)))
4086 (and ftags (org-set-local 'org-file-tags
4087 (mapcar 'org-add-prop-inherited ftags)))
4088 (and drawers (org-set-local 'org-drawers drawers))
4089 (and arch (org-set-local 'org-archive-location arch))
4090 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4091 ;; Process the TODO keywords
4092 (unless kwds
4093 ;; Use the global values as if they had been given locally.
4094 (setq kwds (default-value 'org-todo-keywords))
4095 (if (stringp (car kwds))
4096 (setq kwds (list (cons org-todo-interpretation
4097 (default-value 'org-todo-keywords)))))
4098 (setq kwds (reverse kwds)))
4099 (setq kwds (nreverse kwds))
4100 (let (inter kws kw)
4101 (while (setq kws (pop kwds))
4102 (let ((kws (or
4103 (run-hook-with-args-until-success
4104 'org-todo-setup-filter-hook kws)
4105 kws)))
4106 (setq inter (pop kws) sep (member "|" kws)
4107 kws0 (delete "|" (copy-sequence kws))
4108 kwsa nil
4109 kws1 (mapcar
4110 (lambda (x)
4111 ;; 1 2
4112 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4113 (progn
4114 (setq kw (match-string 1 x)
4115 key (and (match-end 2) (match-string 2 x))
4116 log (org-extract-log-state-settings x))
4117 (push (cons kw (and key (string-to-char key))) kwsa)
4118 (and log (push log org-todo-log-states))
4120 (error "Invalid TODO keyword %s" x)))
4121 kws0)
4122 kwsa (if kwsa (append '((:startgroup))
4123 (nreverse kwsa)
4124 '((:endgroup))))
4125 hw (car kws1)
4126 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4127 tail (list inter hw (car dws) (org-last dws))))
4128 (add-to-list 'org-todo-heads hw 'append)
4129 (push kws1 org-todo-sets)
4130 (setq org-done-keywords (append org-done-keywords dws nil))
4131 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4132 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4133 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4134 (setq org-todo-sets (nreverse org-todo-sets)
4135 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4136 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4137 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4138 ;; Process the constants
4139 (when const
4140 (let (e cst)
4141 (while (setq e (pop const))
4142 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4143 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4144 (setq org-table-formula-constants-local cst)))
4146 ;; Process the tags.
4147 (when tags
4148 (let (e tgs)
4149 (while (setq e (pop tags))
4150 (cond
4151 ((equal e "{") (push '(:startgroup) tgs))
4152 ((equal e "}") (push '(:endgroup) tgs))
4153 ((equal e "\\n") (push '(:newline) tgs))
4154 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4155 (push (cons (match-string 1 e)
4156 (string-to-char (match-string 2 e)))
4157 tgs))
4158 (t (push (list e) tgs))))
4159 (org-set-local 'org-tag-alist nil)
4160 (while (setq e (pop tgs))
4161 (or (and (stringp (car e))
4162 (assoc (car e) org-tag-alist))
4163 (push e org-tag-alist)))))
4165 ;; Compute the regular expressions and other local variables
4166 (if (not org-done-keywords)
4167 (setq org-done-keywords (and org-todo-keywords-1
4168 (list (org-last org-todo-keywords-1)))))
4169 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4170 (length org-scheduled-string)
4171 (length org-clock-string)
4172 (length org-closed-string)))
4173 org-drawer-regexp
4174 (concat "^[ \t]*:\\("
4175 (mapconcat 'regexp-quote org-drawers "\\|")
4176 "\\):[ \t]*$")
4177 org-not-done-keywords
4178 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4179 org-todo-regexp
4180 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4181 "\\|") "\\)\\>")
4182 org-not-done-regexp
4183 (concat "\\<\\("
4184 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4185 "\\)\\>")
4186 org-not-done-heading-regexp
4187 (concat "^\\(\\*+\\)[ \t]+\\("
4188 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4189 "\\)\\>")
4190 org-todo-line-regexp
4191 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4192 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4193 "\\)\\>\\)?[ \t]*\\(.*\\)")
4194 org-complex-heading-regexp
4195 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4196 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4197 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4198 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4199 org-complex-heading-regexp-format
4200 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4201 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4202 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4203 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4204 org-nl-done-regexp
4205 (concat "\n\\*+[ \t]+"
4206 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4207 "\\)" "\\>")
4208 org-todo-line-tags-regexp
4209 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4210 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4211 (org-re
4212 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4213 org-looking-at-done-regexp
4214 (concat "^" "\\(?:"
4215 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4216 "\\>")
4217 org-deadline-regexp (concat "\\<" org-deadline-string)
4218 org-deadline-time-regexp
4219 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4220 org-deadline-line-regexp
4221 (concat "\\<\\(" org-deadline-string "\\).*")
4222 org-scheduled-regexp
4223 (concat "\\<" org-scheduled-string)
4224 org-scheduled-time-regexp
4225 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4226 org-closed-time-regexp
4227 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4228 org-keyword-time-regexp
4229 (concat "\\<\\(" org-scheduled-string
4230 "\\|" org-deadline-string
4231 "\\|" org-closed-string
4232 "\\|" org-clock-string "\\)"
4233 " *[[<]\\([^]>]+\\)[]>]")
4234 org-keyword-time-not-clock-regexp
4235 (concat "\\<\\(" org-scheduled-string
4236 "\\|" org-deadline-string
4237 "\\|" org-closed-string
4238 "\\)"
4239 " *[[<]\\([^]>]+\\)[]>]")
4240 org-maybe-keyword-time-regexp
4241 (concat "\\(\\<\\(" org-scheduled-string
4242 "\\|" org-deadline-string
4243 "\\|" org-closed-string
4244 "\\|" org-clock-string "\\)\\)?"
4245 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4246 org-planning-or-clock-line-re
4247 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4248 "\\|" org-deadline-string
4249 "\\|" org-closed-string "\\|" org-clock-string
4250 "\\)\\>\\)")
4251 org-all-time-keywords
4252 (mapcar (lambda (w) (substring w 0 -1))
4253 (list org-scheduled-string org-deadline-string
4254 org-clock-string org-closed-string))
4256 (org-compute-latex-and-specials-regexp)
4257 (org-set-font-lock-defaults))))
4259 (defun org-file-contents (file &optional noerror)
4260 "Return the contents of FILE, as a string."
4261 (if (or (not file)
4262 (not (file-readable-p file)))
4263 (if noerror
4264 (progn
4265 (message "Cannot read file %s" file)
4266 (ding) (sit-for 2)
4268 (error "Cannot read file %s" file))
4269 (with-temp-buffer
4270 (insert-file-contents file)
4271 (buffer-string))))
4273 (defun org-extract-log-state-settings (x)
4274 "Extract the log state setting from a TODO keyword string.
4275 This will extract info from a string like \"WAIT(w@/!)\"."
4276 (let (kw key log1 log2)
4277 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4278 (setq kw (match-string 1 x)
4279 key (and (match-end 2) (match-string 2 x))
4280 log1 (and (match-end 3) (match-string 3 x))
4281 log2 (and (match-end 4) (match-string 4 x)))
4282 (and (or log1 log2)
4283 (list kw
4284 (and log1 (if (equal log1 "!") 'time 'note))
4285 (and log2 (if (equal log2 "!") 'time 'note)))))))
4287 (defun org-remove-keyword-keys (list)
4288 "Remove a pair of parenthesis at the end of each string in LIST."
4289 (mapcar (lambda (x)
4290 (if (string-match "(.*)$" x)
4291 (substring x 0 (match-beginning 0))
4293 list))
4295 (defun org-assign-fast-keys (alist)
4296 "Assign fast keys to a keyword-key alist.
4297 Respect keys that are already there."
4298 (let (new e (alt ?0))
4299 (while (setq e (pop alist))
4300 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4301 (cdr e)) ;; Key already assigned.
4302 (push e new)
4303 (let ((clist (string-to-list (downcase (car e))))
4304 (used (append new alist)))
4305 (when (= (car clist) ?@)
4306 (pop clist))
4307 (while (and clist (rassoc (car clist) used))
4308 (pop clist))
4309 (unless clist
4310 (while (rassoc alt used)
4311 (incf alt)))
4312 (push (cons (car e) (or (car clist) alt)) new))))
4313 (nreverse new)))
4315 ;;; Some variables used in various places
4317 (defvar org-window-configuration nil
4318 "Used in various places to store a window configuration.")
4319 (defvar org-selected-window nil
4320 "Used in various places to store a window configuration.")
4321 (defvar org-finish-function nil
4322 "Function to be called when `C-c C-c' is used.
4323 This is for getting out of special buffers like remember.")
4326 ;; FIXME: Occasionally check by commenting these, to make sure
4327 ;; no other functions uses these, forgetting to let-bind them.
4328 (defvar entry)
4329 (defvar last-state)
4330 (defvar date)
4332 ;; Defined somewhere in this file, but used before definition.
4333 (defvar org-entities) ;; defined in org-entities.el
4334 (defvar org-struct-menu)
4335 (defvar org-org-menu)
4336 (defvar org-tbl-menu)
4338 ;;;; Define the Org-mode
4340 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4341 (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."))
4344 ;; We use a before-change function to check if a table might need
4345 ;; an update.
4346 (defvar org-table-may-need-update t
4347 "Indicates that a table might need an update.
4348 This variable is set by `org-before-change-function'.
4349 `org-table-align' sets it back to nil.")
4350 (defun org-before-change-function (beg end)
4351 "Every change indicates that a table might need an update."
4352 (setq org-table-may-need-update t))
4353 (defvar org-mode-map)
4354 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4355 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4356 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4357 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4358 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4359 (defvar org-table-buffer-is-an nil)
4360 (defconst org-outline-regexp "\\*+ ")
4362 ;;;###autoload
4363 (define-derived-mode org-mode outline-mode "Org"
4364 "Outline-based notes management and organizer, alias
4365 \"Carsten's outline-mode for keeping track of everything.\"
4367 Org-mode develops organizational tasks around a NOTES file which
4368 contains information about projects as plain text. Org-mode is
4369 implemented on top of outline-mode, which is ideal to keep the content
4370 of large files well structured. It supports ToDo items, deadlines and
4371 time stamps, which magically appear in the diary listing of the Emacs
4372 calendar. Tables are easily created with a built-in table editor.
4373 Plain text URL-like links connect to websites, emails (VM), Usenet
4374 messages (Gnus), BBDB entries, and any files related to the project.
4375 For printing and sharing of notes, an Org-mode file (or a part of it)
4376 can be exported as a structured ASCII or HTML file.
4378 The following commands are available:
4380 \\{org-mode-map}"
4382 ;; Get rid of Outline menus, they are not needed
4383 ;; Need to do this here because define-derived-mode sets up
4384 ;; the keymap so late. Still, it is a waste to call this each time
4385 ;; we switch another buffer into org-mode.
4386 (if (featurep 'xemacs)
4387 (when (boundp 'outline-mode-menu-heading)
4388 ;; Assume this is Greg's port, it uses easymenu
4389 (easy-menu-remove outline-mode-menu-heading)
4390 (easy-menu-remove outline-mode-menu-show)
4391 (easy-menu-remove outline-mode-menu-hide))
4392 (define-key org-mode-map [menu-bar headings] 'undefined)
4393 (define-key org-mode-map [menu-bar hide] 'undefined)
4394 (define-key org-mode-map [menu-bar show] 'undefined))
4396 (org-load-modules-maybe)
4397 (easy-menu-add org-org-menu)
4398 (easy-menu-add org-tbl-menu)
4399 (org-install-agenda-files-menu)
4400 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4401 (add-to-invisibility-spec '(org-cwidth))
4402 (add-to-invisibility-spec '(org-hide-block . t))
4403 (when (featurep 'xemacs)
4404 (org-set-local 'line-move-ignore-invisible t))
4405 (org-set-local 'outline-regexp org-outline-regexp)
4406 (org-set-local 'outline-level 'org-outline-level)
4407 (when (and org-ellipsis
4408 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4409 (fboundp 'make-glyph-code))
4410 (unless org-display-table
4411 (setq org-display-table (make-display-table)))
4412 (set-display-table-slot
4413 org-display-table 4
4414 (vconcat (mapcar
4415 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4416 org-ellipsis)))
4417 (if (stringp org-ellipsis) org-ellipsis "..."))))
4418 (setq buffer-display-table org-display-table))
4419 (org-set-regexps-and-options)
4420 (when (and org-tag-faces (not org-tags-special-faces-re))
4421 ;; tag faces set outside customize.... force initialization.
4422 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4423 ;; Calc embedded
4424 (org-set-local 'calc-embedded-open-mode "# ")
4425 (modify-syntax-entry ?# "<")
4426 (modify-syntax-entry ?@ "w")
4427 (if org-startup-truncated (setq truncate-lines t))
4428 (org-set-local 'font-lock-unfontify-region-function
4429 'org-unfontify-region)
4430 ;; Activate before-change-function
4431 (org-set-local 'org-table-may-need-update t)
4432 (org-add-hook 'before-change-functions 'org-before-change-function nil
4433 'local)
4434 ;; Check for running clock before killing a buffer
4435 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4436 ;; Paragraphs and auto-filling
4437 (org-set-autofill-regexps)
4438 (setq indent-line-function 'org-indent-line-function)
4439 (org-update-radio-target-regexp)
4440 ;; Make sure dependence stuff works reliably, even for users who set it
4441 ;; too late :-(
4442 (if org-enforce-todo-dependencies
4443 (add-hook 'org-blocker-hook
4444 'org-block-todo-from-children-or-siblings-or-parent)
4445 (remove-hook 'org-blocker-hook
4446 'org-block-todo-from-children-or-siblings-or-parent))
4447 (if org-enforce-todo-checkbox-dependencies
4448 (add-hook 'org-blocker-hook
4449 'org-block-todo-from-checkboxes)
4450 (remove-hook 'org-blocker-hook
4451 'org-block-todo-from-checkboxes))
4453 ;; Comment characters
4454 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4455 (org-set-local 'comment-padding " ")
4457 ;; Align options lines
4458 (org-set-local
4459 'align-mode-rules-list
4460 '((org-in-buffer-settings
4461 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4462 (modes . '(org-mode)))))
4464 ;; Imenu
4465 (org-set-local 'imenu-create-index-function
4466 'org-imenu-get-tree)
4468 ;; Make isearch reveal context
4469 (if (or (featurep 'xemacs)
4470 (not (boundp 'outline-isearch-open-invisible-function)))
4471 ;; Emacs 21 and XEmacs make use of the hook
4472 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4473 ;; Emacs 22 deals with this through a special variable
4474 (org-set-local 'outline-isearch-open-invisible-function
4475 (lambda (&rest ignore) (org-show-context 'isearch))))
4477 ;; Turn on org-beamer-mode?
4478 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4480 ;; If empty file that did not turn on org-mode automatically, make it to.
4481 (if (and org-insert-mode-line-in-empty-file
4482 (interactive-p)
4483 (= (point-min) (point-max)))
4484 (insert "# -*- mode: org -*-\n\n"))
4485 (unless org-inhibit-startup
4486 (when org-startup-align-all-tables
4487 (let ((bmp (buffer-modified-p)))
4488 (org-table-map-tables 'org-table-align 'quietly)
4489 (set-buffer-modified-p bmp)))
4490 (when org-startup-indented
4491 (require 'org-indent)
4492 (org-indent-mode 1))
4493 (unless org-inhibit-startup-visibility-stuff
4494 (org-set-startup-visibility))))
4496 (when (fboundp 'abbrev-table-put)
4497 (abbrev-table-put org-mode-abbrev-table
4498 :parents (list text-mode-abbrev-table)))
4500 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4502 (defun org-current-time ()
4503 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4504 (if (> (car org-time-stamp-rounding-minutes) 1)
4505 (let ((r (car org-time-stamp-rounding-minutes))
4506 (time (decode-time)))
4507 (apply 'encode-time
4508 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4509 (nthcdr 2 time))))
4510 (current-time)))
4512 ;;;; Font-Lock stuff, including the activators
4514 (defvar org-mouse-map (make-sparse-keymap))
4515 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4516 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4517 (when org-mouse-1-follows-link
4518 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4519 (when org-tab-follows-link
4520 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4521 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4523 (require 'font-lock)
4525 (defconst org-non-link-chars "]\t\n\r<>")
4526 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4527 "shell" "elisp" "doi"))
4528 (defvar org-link-types-re nil
4529 "Matches a link that has a url-like prefix like \"http:\"")
4530 (defvar org-link-re-with-space nil
4531 "Matches a link with spaces, optional angular brackets around it.")
4532 (defvar org-link-re-with-space2 nil
4533 "Matches a link with spaces, optional angular brackets around it.")
4534 (defvar org-link-re-with-space3 nil
4535 "Matches a link with spaces, only for internal part in bracket links.")
4536 (defvar org-angle-link-re nil
4537 "Matches link with angular brackets, spaces are allowed.")
4538 (defvar org-plain-link-re nil
4539 "Matches plain link, without spaces.")
4540 (defvar org-bracket-link-regexp nil
4541 "Matches a link in double brackets.")
4542 (defvar org-bracket-link-analytic-regexp nil
4543 "Regular expression used to analyze links.
4544 Here is what the match groups contain after a match:
4545 1: http:
4546 2: http
4547 3: path
4548 4: [desc]
4549 5: desc")
4550 (defvar org-bracket-link-analytic-regexp++ nil
4551 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4552 (defvar org-any-link-re nil
4553 "Regular expression matching any link.")
4555 (defun org-make-link-regexps ()
4556 "Update the link regular expressions.
4557 This should be called after the variable `org-link-types' has changed."
4558 (setq org-link-types-re
4559 (concat
4560 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4561 org-link-re-with-space
4562 (concat
4563 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4564 "\\([^" org-non-link-chars " ]"
4565 "[^" org-non-link-chars "]*"
4566 "[^" org-non-link-chars " ]\\)>?")
4567 org-link-re-with-space2
4568 (concat
4569 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4570 "\\([^" org-non-link-chars " ]"
4571 "[^\t\n\r]*"
4572 "[^" org-non-link-chars " ]\\)>?")
4573 org-link-re-with-space3
4574 (concat
4575 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4576 "\\([^" org-non-link-chars " ]"
4577 "[^\t\n\r]*\\)")
4578 org-angle-link-re
4579 (concat
4580 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4581 "\\([^" org-non-link-chars " ]"
4582 "[^" org-non-link-chars "]*"
4583 "\\)>")
4584 org-plain-link-re
4585 (concat
4586 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4587 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4588 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4589 org-bracket-link-regexp
4590 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4591 org-bracket-link-analytic-regexp
4592 (concat
4593 "\\[\\["
4594 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4595 "\\([^]]+\\)"
4596 "\\]"
4597 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4598 "\\]")
4599 org-bracket-link-analytic-regexp++
4600 (concat
4601 "\\[\\["
4602 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4603 "\\([^]]+\\)"
4604 "\\]"
4605 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4606 "\\]")
4607 org-any-link-re
4608 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4609 org-angle-link-re "\\)\\|\\("
4610 org-plain-link-re "\\)")))
4612 (org-make-link-regexps)
4614 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4615 "Regular expression for fast time stamp matching.")
4616 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4617 "Regular expression for fast time stamp matching.")
4618 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4619 "Regular expression matching time strings for analysis.
4620 This one does not require the space after the date, so it can be used
4621 on a string that terminates immediately after the date.")
4622 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4623 "Regular expression matching time strings for analysis.")
4624 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4625 "Regular expression matching time stamps, with groups.")
4626 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4627 "Regular expression matching time stamps (also [..]), with groups.")
4628 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4629 "Regular expression matching a time stamp range.")
4630 (defconst org-tr-regexp-both
4631 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4632 "Regular expression matching a time stamp range.")
4633 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4634 org-ts-regexp "\\)?")
4635 "Regular expression matching a time stamp or time stamp range.")
4636 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4637 org-ts-regexp-both "\\)?")
4638 "Regular expression matching a time stamp or time stamp range.
4639 The time stamps may be either active or inactive.")
4641 (defvar org-emph-face nil)
4643 (defun org-do-emphasis-faces (limit)
4644 "Run through the buffer and add overlays to links."
4645 (let (rtn a)
4646 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4647 (if (not (= (char-after (match-beginning 3))
4648 (char-after (match-beginning 4))))
4649 (progn
4650 (setq rtn t)
4651 (setq a (assoc (match-string 3) org-emphasis-alist))
4652 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4653 'face
4654 (nth 1 a))
4655 (and (nth 4 a)
4656 (org-remove-flyspell-overlays-in
4657 (match-beginning 0) (match-end 0)))
4658 (add-text-properties (match-beginning 2) (match-end 2)
4659 '(font-lock-multiline t))
4660 (when org-hide-emphasis-markers
4661 (add-text-properties (match-end 4) (match-beginning 5)
4662 '(invisible org-link))
4663 (add-text-properties (match-beginning 3) (match-end 3)
4664 '(invisible org-link)))))
4665 (backward-char 1))
4666 rtn))
4668 (defun org-emphasize (&optional char)
4669 "Insert or change an emphasis, i.e. a font like bold or italic.
4670 If there is an active region, change that region to a new emphasis.
4671 If there is no region, just insert the marker characters and position
4672 the cursor between them.
4673 CHAR should be either the marker character, or the first character of the
4674 HTML tag associated with that emphasis. If CHAR is a space, the means
4675 to remove the emphasis of the selected region.
4676 If char is not given (for example in an interactive call) it
4677 will be prompted for."
4678 (interactive)
4679 (let ((eal org-emphasis-alist) e det
4680 (erc org-emphasis-regexp-components)
4681 (prompt "")
4682 (string "") beg end move tag c s)
4683 (if (org-region-active-p)
4684 (setq beg (region-beginning) end (region-end)
4685 string (buffer-substring beg end))
4686 (setq move t))
4688 (while (setq e (pop eal))
4689 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4690 c (aref tag 0))
4691 (push (cons c (string-to-char (car e))) det)
4692 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4693 (substring tag 1)))))
4694 (setq det (nreverse det))
4695 (unless char
4696 (message "%s" (concat "Emphasis marker or tag:" prompt))
4697 (setq char (read-char-exclusive)))
4698 (setq char (or (cdr (assoc char det)) char))
4699 (if (equal char ?\ )
4700 (setq s "" move nil)
4701 (unless (assoc (char-to-string char) org-emphasis-alist)
4702 (error "No such emphasis marker: \"%c\"" char))
4703 (setq s (char-to-string char)))
4704 (while (and (> (length string) 1)
4705 (equal (substring string 0 1) (substring string -1))
4706 (assoc (substring string 0 1) org-emphasis-alist))
4707 (setq string (substring string 1 -1)))
4708 (setq string (concat s string s))
4709 (if beg (delete-region beg end))
4710 (unless (or (bolp)
4711 (string-match (concat "[" (nth 0 erc) "\n]")
4712 (char-to-string (char-before (point)))))
4713 (insert " "))
4714 (unless (or (eobp)
4715 (string-match (concat "[" (nth 1 erc) "\n]")
4716 (char-to-string (char-after (point)))))
4717 (insert " ") (backward-char 1))
4718 (insert string)
4719 (and move (backward-char 1))))
4721 (defconst org-nonsticky-props
4722 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4724 (defsubst org-rear-nonsticky-at (pos)
4725 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4727 (defun org-activate-plain-links (limit)
4728 "Run through the buffer and add overlays to links."
4729 (catch 'exit
4730 (let (f)
4731 (if (re-search-forward org-plain-link-re limit t)
4732 (progn
4733 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4734 (setq f (get-text-property (match-beginning 0) 'face))
4735 (if (or (eq f 'org-tag)
4736 (and (listp f) (memq 'org-tag f)))
4738 (add-text-properties (match-beginning 0) (match-end 0)
4739 (list 'mouse-face 'highlight
4740 'face 'org-link
4741 'keymap org-mouse-map))
4742 (org-rear-nonsticky-at (match-end 0)))
4743 t)))))
4745 (defun org-activate-code (limit)
4746 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4747 (progn
4748 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4749 (remove-text-properties (match-beginning 0) (match-end 0)
4750 '(display t invisible t intangible t))
4751 t)))
4753 (defun org-fontify-meta-lines-and-blocks (limit)
4754 "Fontify #+ lines and blocks, in the correct ways."
4755 (let ((case-fold-search t))
4756 (if (re-search-forward
4757 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4758 limit t)
4759 (let ((beg (match-beginning 0))
4760 (beg1 (line-beginning-position 2))
4761 (dc1 (downcase (match-string 2)))
4762 (dc3 (downcase (match-string 3)))
4763 end end1 quoting block-type)
4764 (cond
4765 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4766 ;; a single line of backend-specific content
4767 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4768 (remove-text-properties (match-beginning 0) (match-end 0)
4769 '(display t invisible t intangible t))
4770 (add-text-properties (match-beginning 1) (match-end 3)
4771 '(font-lock-fontified t face org-meta-line))
4772 (add-text-properties (match-beginning 6) (match-end 6)
4773 '(font-lock-fontified t face org-block))
4775 ((and (match-end 4) (equal dc3 "begin"))
4776 ;; Truly a block
4777 (setq block-type (downcase (match-string 5))
4778 quoting (member block-type org-protecting-blocks))
4779 (when (re-search-forward
4780 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4781 nil t) ;; on purpose, we look further than LIMIT
4782 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4783 (when quoting
4784 (remove-text-properties beg end
4785 '(display t invisible t intangible t)))
4786 (add-text-properties
4787 beg end
4788 '(font-lock-fontified t font-lock-multiline t))
4789 (add-text-properties beg beg1 '(face org-meta-line))
4790 (add-text-properties end1 end '(face org-meta-line))
4791 (cond
4792 (quoting
4793 (add-text-properties beg1 end1 '(face org-block)))
4794 ((not org-fontify-quote-and-verse-blocks))
4795 ((string= block-type "quote")
4796 (add-text-properties beg1 end1 '(face org-quote)))
4797 ((string= block-type "verse")
4798 (add-text-properties beg1 end1 '(face org-verse))))
4800 ((member dc1 '("title:" "author:" "email:" "date:"))
4801 (add-text-properties
4802 beg (match-end 3)
4803 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4804 '(font-lock-fontified t invisible t)
4805 '(font-lock-fontified t face org-document-info-keyword)))
4806 (add-text-properties
4807 (match-beginning 6) (match-end 6)
4808 (if (string-equal dc1 "title:")
4809 '(font-lock-fontified t face org-document-title)
4810 '(font-lock-fontified t face org-document-info))))
4811 ((not (member (char-after beg) '(?\ ?\t)))
4812 ;; just any other in-buffer setting, but not indented
4813 (add-text-properties
4814 beg (match-end 0)
4815 '(font-lock-fontified t face org-meta-line))
4817 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4818 "orgtbl:" "tblfm:" "tblname:"))
4819 (and (match-end 4) (equal dc3 "attr")))
4820 (add-text-properties
4821 beg (match-end 0)
4822 '(font-lock-fontified t face org-meta-line))
4824 ((member dc3 '(" " ""))
4825 (add-text-properties
4826 beg (match-end 0)
4827 '(font-lock-fontified t face font-lock-comment-face)))
4828 (t nil))))))
4830 (defun org-activate-angle-links (limit)
4831 "Run through the buffer and add overlays to links."
4832 (if (re-search-forward org-angle-link-re limit t)
4833 (progn
4834 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4835 (add-text-properties (match-beginning 0) (match-end 0)
4836 (list 'mouse-face 'highlight
4837 'keymap org-mouse-map))
4838 (org-rear-nonsticky-at (match-end 0))
4839 t)))
4841 (defun org-activate-footnote-links (limit)
4842 "Run through the buffer and add overlays to links."
4843 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4844 limit t)
4845 (progn
4846 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4847 (add-text-properties (match-beginning 2) (match-end 2)
4848 (list 'mouse-face 'highlight
4849 'keymap org-mouse-map
4850 'help-echo
4851 (if (= (point-at-bol) (match-beginning 2))
4852 "Footnote definition"
4853 "Footnote reference")
4855 (org-rear-nonsticky-at (match-end 2))
4856 t)))
4858 (defun org-activate-bracket-links (limit)
4859 "Run through the buffer and add overlays to bracketed links."
4860 (if (re-search-forward org-bracket-link-regexp limit t)
4861 (let* ((help (concat "LINK: "
4862 (org-match-string-no-properties 1)))
4863 ;; FIXME: above we should remove the escapes.
4864 ;; but that requires another match, protecting match data,
4865 ;; a lot of overhead for font-lock.
4866 (ip (org-maybe-intangible
4867 (list 'invisible 'org-link
4868 'keymap org-mouse-map 'mouse-face 'highlight
4869 'font-lock-multiline t 'help-echo help)))
4870 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4871 'font-lock-multiline t 'help-echo help)))
4872 ;; We need to remove the invisible property here. Table narrowing
4873 ;; may have made some of this invisible.
4874 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4875 (remove-text-properties (match-beginning 0) (match-end 0)
4876 '(invisible nil))
4877 (if (match-end 3)
4878 (progn
4879 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4880 (org-rear-nonsticky-at (match-beginning 3))
4881 (add-text-properties (match-beginning 3) (match-end 3) vp)
4882 (org-rear-nonsticky-at (match-end 3))
4883 (add-text-properties (match-end 3) (match-end 0) ip)
4884 (org-rear-nonsticky-at (match-end 0)))
4885 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4886 (org-rear-nonsticky-at (match-beginning 1))
4887 (add-text-properties (match-beginning 1) (match-end 1) vp)
4888 (org-rear-nonsticky-at (match-end 1))
4889 (add-text-properties (match-end 1) (match-end 0) ip)
4890 (org-rear-nonsticky-at (match-end 0)))
4891 t)))
4893 (defun org-activate-dates (limit)
4894 "Run through the buffer and add overlays to dates."
4895 (if (re-search-forward org-tsr-regexp-both limit t)
4896 (progn
4897 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4898 (add-text-properties (match-beginning 0) (match-end 0)
4899 (list 'mouse-face 'highlight
4900 'keymap org-mouse-map))
4901 (org-rear-nonsticky-at (match-end 0))
4902 (when org-display-custom-times
4903 (if (match-end 3)
4904 (org-display-custom-time (match-beginning 3) (match-end 3)))
4905 (org-display-custom-time (match-beginning 1) (match-end 1)))
4906 t)))
4908 (defvar org-target-link-regexp nil
4909 "Regular expression matching radio targets in plain text.")
4910 (make-variable-buffer-local 'org-target-link-regexp)
4911 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4912 "Regular expression matching a link target.")
4913 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4914 "Regular expression matching a radio target.")
4915 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4916 "Regular expression matching any target.")
4918 (defun org-activate-target-links (limit)
4919 "Run through the buffer and add overlays to target matches."
4920 (when org-target-link-regexp
4921 (let ((case-fold-search t))
4922 (if (re-search-forward org-target-link-regexp limit t)
4923 (progn
4924 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4925 (add-text-properties (match-beginning 0) (match-end 0)
4926 (list 'mouse-face 'highlight
4927 'keymap org-mouse-map
4928 'help-echo "Radio target link"
4929 'org-linked-text t))
4930 (org-rear-nonsticky-at (match-end 0))
4931 t)))))
4933 (defun org-update-radio-target-regexp ()
4934 "Find all radio targets in this file and update the regular expression."
4935 (interactive)
4936 (when (memq 'radio org-activate-links)
4937 (setq org-target-link-regexp
4938 (org-make-target-link-regexp (org-all-targets 'radio)))
4939 (org-restart-font-lock)))
4941 (defun org-hide-wide-columns (limit)
4942 (let (s e)
4943 (setq s (text-property-any (point) (or limit (point-max))
4944 'org-cwidth t))
4945 (when s
4946 (setq e (next-single-property-change s 'org-cwidth))
4947 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4948 (goto-char e)
4949 t)))
4951 (defvar org-latex-and-specials-regexp nil
4952 "Regular expression for highlighting export special stuff.")
4953 (defvar org-match-substring-regexp)
4954 (defvar org-match-substring-with-braces-regexp)
4956 ;; This should be with the exporter code, but we also use if for font-locking
4957 (defconst org-export-html-special-string-regexps
4958 '(("\\\\-" . "&shy;")
4959 ("---\\([^-]\\)" . "&mdash;\\1")
4960 ("--\\([^-]\\)" . "&ndash;\\1")
4961 ("\\.\\.\\." . "&hellip;"))
4962 "Regular expressions for special string conversion.")
4965 (defun org-compute-latex-and-specials-regexp ()
4966 "Compute regular expression for stuff treated specially by exporters."
4967 (if (not org-highlight-latex-fragments-and-specials)
4968 (org-set-local 'org-latex-and-specials-regexp nil)
4969 (require 'org-exp)
4970 (let*
4971 ((matchers (plist-get org-format-latex-options :matchers))
4972 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4973 org-latex-regexps)))
4974 (org-export-allow-BIND nil)
4975 (options (org-combine-plists (org-default-export-plist)
4976 (org-infile-export-plist)))
4977 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4978 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4979 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4980 (org-export-html-expand (plist-get options :expand-quoted-html))
4981 (org-export-with-special-strings (plist-get options :special-strings))
4982 (re-sub
4983 (cond
4984 ((equal org-export-with-sub-superscripts '{})
4985 (list org-match-substring-with-braces-regexp))
4986 (org-export-with-sub-superscripts
4987 (list org-match-substring-regexp))
4988 (t nil)))
4989 (re-latex
4990 (if org-export-with-LaTeX-fragments
4991 (mapcar (lambda (x) (nth 1 x)) latexs)))
4992 (re-macros
4993 (if org-export-with-TeX-macros
4994 (list (concat "\\\\"
4995 (regexp-opt
4996 (append (mapcar 'car (append org-entities-user
4997 org-entities))
4998 (if (boundp 'org-latex-entities)
4999 (mapcar (lambda (x)
5000 (or (car-safe x) x))
5001 org-latex-entities)
5002 nil))
5003 'words))) ; FIXME
5005 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5006 (re-special (if org-export-with-special-strings
5007 (mapcar (lambda (x) (car x))
5008 org-export-html-special-string-regexps)))
5009 (re-rest
5010 (delq nil
5011 (list
5012 (if org-export-html-expand "@<[^>\n]+>")
5013 ))))
5014 (org-set-local
5015 'org-latex-and-specials-regexp
5016 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5017 re-rest) "\\|")))))
5019 (defun org-do-latex-and-special-faces (limit)
5020 "Run through the buffer and add overlays to links."
5021 (when org-latex-and-specials-regexp
5022 (let (rtn d)
5023 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5024 limit t))
5025 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5026 'face))
5027 '(org-code org-verbatim underline)))
5028 (progn
5029 (setq rtn t
5030 d (cond ((member (char-after (1+ (match-beginning 0)))
5031 '(?_ ?^)) 1)
5032 (t 0)))
5033 (font-lock-prepend-text-property
5034 (+ d (match-beginning 0)) (match-end 0)
5035 'face 'org-latex-and-export-specials)
5036 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5037 '(font-lock-multiline t)))))
5038 rtn)))
5040 (defun org-restart-font-lock ()
5041 "Restart font-lock-mode, to force refontification."
5042 (when (and (boundp 'font-lock-mode) font-lock-mode)
5043 (font-lock-mode -1)
5044 (font-lock-mode 1)))
5046 (defun org-all-targets (&optional radio)
5047 "Return a list of all targets in this file.
5048 With optional argument RADIO, only find radio targets."
5049 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5050 rtn)
5051 (save-excursion
5052 (goto-char (point-min))
5053 (while (re-search-forward re nil t)
5054 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5055 rtn)))
5057 (defun org-make-target-link-regexp (targets)
5058 "Make regular expression matching all strings in TARGETS.
5059 The regular expression finds the targets also if there is a line break
5060 between words."
5061 (and targets
5062 (concat
5063 "\\<\\("
5064 (mapconcat
5065 (lambda (x)
5066 (while (string-match " +" x)
5067 (setq x (replace-match "\\s-+" t t x)))
5069 targets
5070 "\\|")
5071 "\\)\\>")))
5073 (defun org-activate-tags (limit)
5074 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5075 (progn
5076 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5077 (add-text-properties (match-beginning 1) (match-end 1)
5078 (list 'mouse-face 'highlight
5079 'keymap org-mouse-map))
5080 (org-rear-nonsticky-at (match-end 1))
5081 t)))
5083 (defun org-outline-level ()
5084 "Compute the outline level of the heading at point.
5085 This function assumes that the cursor is at the beginning of a line matched
5086 by outline-regexp. Otherwise it returns garbage.
5087 If this is called at a normal headline, the level is the number of stars.
5088 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5089 For plain list items, if they are matched by `outline-regexp', this returns
5090 1000 plus the line indentation."
5091 (save-excursion
5092 (looking-at outline-regexp)
5093 (if (match-beginning 1)
5094 (+ (org-get-string-indentation (match-string 1)) 1000)
5095 (1- (- (match-end 0) (match-beginning 0))))))
5097 (defvar org-font-lock-keywords nil)
5099 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5100 "Regular expression matching a property line.")
5102 (defvar org-font-lock-hook nil
5103 "Functions to be called for special font lock stuff.")
5105 (defun org-font-lock-hook (limit)
5106 (run-hook-with-args 'org-font-lock-hook limit))
5108 (defun org-set-font-lock-defaults ()
5109 (let* ((em org-fontify-emphasized-text)
5110 (lk org-activate-links)
5111 (org-font-lock-extra-keywords
5112 (list
5113 ;; Call the hook
5114 '(org-font-lock-hook)
5115 ;; Headlines
5116 `(,(if org-fontify-whole-heading-line
5117 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5118 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5119 (1 (org-get-level-face 1))
5120 (2 (org-get-level-face 2))
5121 (3 (org-get-level-face 3)))
5122 ;; Table lines
5123 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5124 (1 'org-table t))
5125 ;; Table internals
5126 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5127 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5128 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5129 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5130 ;; Drawers
5131 (list org-drawer-regexp '(0 'org-special-keyword t))
5132 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5133 ;; Properties
5134 (list org-property-re
5135 '(1 'org-special-keyword t)
5136 '(3 'org-property-value t))
5137 ;; Links
5138 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5139 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5140 (if (memq 'plain lk) '(org-activate-plain-links))
5141 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5142 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5143 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5144 (if (memq 'footnote lk) '(org-activate-footnote-links
5145 (2 'org-footnote t)))
5146 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5147 '(org-hide-wide-columns (0 nil append))
5148 ;; TODO lines
5149 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5150 '(1 (org-get-todo-face 1) t))
5151 ;; DONE
5152 (if org-fontify-done-headline
5153 (list (concat "^[*]+ +\\<\\("
5154 (mapconcat 'regexp-quote org-done-keywords "\\|")
5155 "\\)\\(.*\\)")
5156 '(2 'org-headline-done t))
5157 nil)
5158 ;; Priorities
5159 '(org-font-lock-add-priority-faces)
5160 ;; Tags
5161 '(org-font-lock-add-tag-faces)
5162 ;; Special keywords
5163 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5164 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5165 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5166 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5167 ;; Emphasis
5168 (if em
5169 (if (featurep 'xemacs)
5170 '(org-do-emphasis-faces (0 nil append))
5171 '(org-do-emphasis-faces)))
5172 ;; Checkboxes
5173 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5174 2 'org-checkbox prepend)
5175 (if org-provide-checkbox-statistics
5176 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5177 (0 (org-get-checkbox-statistics-face) t)))
5178 ;; Description list items
5179 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5180 2 'bold prepend)
5181 ;; ARCHIVEd headings
5182 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5183 '(1 'org-archived prepend))
5184 ;; Specials
5185 '(org-do-latex-and-special-faces)
5186 ;; Code
5187 '(org-activate-code (1 'org-code t))
5188 ;; COMMENT
5189 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5190 "\\|" org-quote-string "\\)\\>")
5191 '(1 'org-special-keyword t))
5192 '("^#.*" (0 'font-lock-comment-face t))
5193 ;; Blocks and meta lines
5194 '(org-fontify-meta-lines-and-blocks)
5196 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5197 ;; Now set the full font-lock-keywords
5198 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5199 (org-set-local 'font-lock-defaults
5200 '(org-font-lock-keywords t nil nil backward-paragraph))
5201 (kill-local-variable 'font-lock-keywords) nil))
5203 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5204 "Fontify string S like in Org-mode"
5205 (with-temp-buffer
5206 (insert s)
5207 (let ((org-odd-levels-only odd-levels))
5208 (org-mode)
5209 (font-lock-fontify-buffer)
5210 (buffer-string))))
5212 (defvar org-m nil)
5213 (defvar org-l nil)
5214 (defvar org-f nil)
5215 (defun org-get-level-face (n)
5216 "Get the right face for match N in font-lock matching of headlines."
5217 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5218 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5219 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5220 (cond
5221 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5222 ((eq n 2) org-f)
5223 (t (if org-level-color-stars-only nil org-f))))
5225 (defun org-get-todo-face (kwd)
5226 "Get the right face for a TODO keyword KWD.
5227 If KWD is a number, get the corresponding match group."
5228 (if (numberp kwd) (setq kwd (match-string kwd)))
5229 (or (org-face-from-face-or-color
5230 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5231 (and (member kwd org-done-keywords) 'org-done)
5232 'org-todo))
5234 (defun org-face-from-face-or-color (context inherit face-or-color)
5235 "Create a face list that inherits INHERIT, but sets the foreground color.
5236 When FACE-OR-COLOR is not a string, just return it."
5237 (if (stringp face-or-color)
5238 (list :inherit inherit
5239 (cdr (assoc context org-faces-easy-properties))
5240 face-or-color)
5241 face-or-color))
5243 (defun org-font-lock-add-tag-faces (limit)
5244 "Add the special tag faces."
5245 (when (and org-tag-faces org-tags-special-faces-re)
5246 (while (re-search-forward org-tags-special-faces-re limit t)
5247 (add-text-properties (match-beginning 1) (match-end 1)
5248 (list 'face (org-get-tag-face 1)
5249 'font-lock-fontified t))
5250 (backward-char 1))))
5252 (defun org-font-lock-add-priority-faces (limit)
5253 "Add the special priority faces."
5254 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5255 (add-text-properties
5256 (match-beginning 0) (match-end 0)
5257 (list 'face (or (org-face-from-face-or-color
5258 'priority 'org-special-keyword
5259 (cdr (assoc (char-after (match-beginning 1))
5260 org-priority-faces)))
5261 'org-special-keyword)
5262 'font-lock-fontified t))))
5264 (defun org-get-tag-face (kwd)
5265 "Get the right face for a TODO keyword KWD.
5266 If KWD is a number, get the corresponding match group."
5267 (if (numberp kwd) (setq kwd (match-string kwd)))
5268 (or (org-face-from-face-or-color
5269 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5270 'org-tag))
5272 (defun org-unfontify-region (beg end &optional maybe_loudly)
5273 "Remove fontification and activation overlays from links."
5274 (font-lock-default-unfontify-region beg end)
5275 (let* ((buffer-undo-list t)
5276 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5277 (inhibit-modification-hooks t)
5278 deactivate-mark buffer-file-name buffer-file-truename)
5279 (remove-text-properties
5280 beg end
5281 (if org-indent-mode
5282 ;; also remove line-prefix and wrap-prefix properties
5283 '(mouse-face t keymap t org-linked-text t
5284 invisible t intangible t
5285 line-prefix t wrap-prefix t
5286 org-no-flyspell t)
5287 '(mouse-face t keymap t org-linked-text t
5288 invisible t intangible t
5289 org-no-flyspell t)))))
5291 ;;;; Visibility cycling, including org-goto and indirect buffer
5293 ;;; Cycling
5295 (defvar org-cycle-global-status nil)
5296 (make-variable-buffer-local 'org-cycle-global-status)
5297 (defvar org-cycle-subtree-status nil)
5298 (make-variable-buffer-local 'org-cycle-subtree-status)
5300 ;;;###autoload
5302 (defvar org-inlinetask-min-level)
5304 (defun org-cycle (&optional arg)
5305 "TAB-action and visibility cycling for Org-mode.
5307 This is the command invoked in Org-mode by the TAB key. Its main purpose
5308 is outline visibility cycling, but it also invokes other actions
5309 in special contexts.
5311 - When this function is called with a prefix argument, rotate the entire
5312 buffer through 3 states (global cycling)
5313 1. OVERVIEW: Show only top-level headlines.
5314 2. CONTENTS: Show all headlines of all levels, but no body text.
5315 3. SHOW ALL: Show everything.
5316 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5317 determined by the variable `org-startup-folded', and by any VISIBILITY
5318 properties in the buffer.
5319 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5320 including any drawers.
5322 - When inside a table, re-align the table and move to the next field.
5324 - When point is at the beginning of a headline, rotate the subtree started
5325 by this line through 3 different states (local cycling)
5326 1. FOLDED: Only the main headline is shown.
5327 2. CHILDREN: The main headline and the direct children are shown.
5328 From this state, you can move to one of the children
5329 and zoom in further.
5330 3. SUBTREE: Show the entire subtree, including body text.
5331 If there is no subtree, switch directly from CHILDREN to FOLDED.
5333 - When point is at the beginning of an empty headline and the variable
5334 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5335 of the headline by demoting and promoting it to likely levels. This
5336 speeds up creation document structure by presing TAB once or several
5337 times right after creating a new headline.
5339 - When there is a numeric prefix, go up to a heading with level ARG, do
5340 a `show-subtree' and return to the previous cursor position. If ARG
5341 is negative, go up that many levels.
5343 - When point is not at the beginning of a headline, execute the global
5344 binding for TAB, which is re-indenting the line. See the option
5345 `org-cycle-emulate-tab' for details.
5347 - Special case: if point is at the beginning of the buffer and there is
5348 no headline in line 1, this function will act as if called with prefix arg.
5349 But only if also the variable `org-cycle-global-at-bob' is t."
5350 (interactive "P")
5351 (org-load-modules-maybe)
5352 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5353 (and org-cycle-level-after-item/entry-creation
5354 (or (org-cycle-level)
5355 (org-cycle-item-indentation))))
5356 (let* ((limit-level
5357 (or org-cycle-max-level
5358 (and (boundp 'org-inlinetask-min-level)
5359 org-inlinetask-min-level
5360 (1- org-inlinetask-min-level))))
5361 (nstars (and limit-level
5362 (if org-odd-levels-only
5363 (and limit-level (1- (* limit-level 2)))
5364 limit-level)))
5365 (outline-regexp
5366 (cond
5367 ((not (org-mode-p)) outline-regexp)
5368 ((or (eq org-cycle-include-plain-lists 'integrate)
5369 (and org-cycle-include-plain-lists (org-at-item-p)))
5370 (concat "\\(?:\\*"
5371 (if nstars (format "\\{1,%d\\}" nstars) "+")
5372 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5373 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5374 (bob-special (and org-cycle-global-at-bob (bobp)
5375 (not (looking-at outline-regexp))))
5376 (org-cycle-hook
5377 (if bob-special
5378 (delq 'org-optimize-window-after-visibility-change
5379 (copy-sequence org-cycle-hook))
5380 org-cycle-hook))
5381 (pos (point)))
5383 (if (or bob-special (equal arg '(4)))
5384 ;; special case: use global cycling
5385 (setq arg t))
5387 (cond
5389 ((equal arg '(16))
5390 (org-set-startup-visibility)
5391 (message "Startup visibility, plus VISIBILITY properties"))
5393 ((equal arg '(64))
5394 (show-all)
5395 (message "Entire buffer visible, including drawers"))
5397 ((org-at-table-p 'any)
5398 ;; Enter the table or move to the next field in the table
5399 (if (org-at-table.el-p)
5400 (message "Use C-c ' to edit table.el tables")
5401 (if arg (org-table-edit-field t)
5402 (org-table-justify-field-maybe)
5403 (call-interactively 'org-table-next-field))))
5405 ((run-hook-with-args-until-success
5406 'org-tab-after-check-for-table-hook))
5408 ((eq arg t) ;; Global cycling
5409 (org-cycle-internal-global))
5411 ((and org-drawers org-drawer-regexp
5412 (save-excursion
5413 (beginning-of-line 1)
5414 (looking-at org-drawer-regexp)))
5415 ;; Toggle block visibility
5416 (org-flag-drawer
5417 (not (get-char-property (match-end 0) 'invisible))))
5419 ((integerp arg)
5420 ;; Show-subtree, ARG levels up from here.
5421 (save-excursion
5422 (org-back-to-heading)
5423 (outline-up-heading (if (< arg 0) (- arg)
5424 (- (funcall outline-level) arg)))
5425 (org-show-subtree)))
5427 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5428 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5430 (org-cycle-internal-local))
5432 ;; TAB emulation and template completion
5433 (buffer-read-only (org-back-to-heading))
5435 ((run-hook-with-args-until-success
5436 'org-tab-after-check-for-cycling-hook))
5438 ((org-try-structure-completion))
5440 ((org-try-cdlatex-tab))
5442 ((run-hook-with-args-until-success
5443 'org-tab-before-tab-emulation-hook))
5445 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5446 (or (not (bolp))
5447 (not (looking-at outline-regexp))))
5448 (call-interactively (global-key-binding "\t")))
5450 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5451 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5452 (or (and (eq org-cycle-emulate-tab 'white)
5453 (= (match-end 0) (point-at-eol)))
5454 (and (eq org-cycle-emulate-tab 'whitestart)
5455 (>= (match-end 0) pos))))
5457 (eq org-cycle-emulate-tab t))
5458 (call-interactively (global-key-binding "\t")))
5460 (t (save-excursion
5461 (org-back-to-heading)
5462 (org-cycle)))))))
5464 (defun org-cycle-internal-global ()
5465 "Do the global cycling action."
5466 (cond
5467 ((and (eq last-command this-command)
5468 (eq org-cycle-global-status 'overview))
5469 ;; We just created the overview - now do table of contents
5470 ;; This can be slow in very large buffers, so indicate action
5471 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5472 (message "CONTENTS...")
5473 (org-content)
5474 (message "CONTENTS...done")
5475 (setq org-cycle-global-status 'contents)
5476 (run-hook-with-args 'org-cycle-hook 'contents))
5478 ((and (eq last-command this-command)
5479 (eq org-cycle-global-status 'contents))
5480 ;; We just showed the table of contents - now show everything
5481 (run-hook-with-args 'org-pre-cycle-hook 'all)
5482 (show-all)
5483 (message "SHOW ALL")
5484 (setq org-cycle-global-status 'all)
5485 (run-hook-with-args 'org-cycle-hook 'all))
5488 ;; Default action: go to overview
5489 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5490 (org-overview)
5491 (message "OVERVIEW")
5492 (setq org-cycle-global-status 'overview)
5493 (run-hook-with-args 'org-cycle-hook 'overview))))
5495 (defun org-cycle-internal-local ()
5496 "Do the local cycling action."
5497 (org-back-to-heading)
5498 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5499 ;; First, some boundaries
5500 (save-excursion
5501 (org-back-to-heading)
5502 (setq level (funcall outline-level))
5503 (save-excursion
5504 (beginning-of-line 2)
5505 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5506 ; XEmacs does not have `next-single-char-property-change'
5507 ; I'm not sure about Emacs 21.
5508 (while (and (not (eobp)) ;; this is like `next-line'
5509 (get-char-property (1- (point)) 'invisible))
5510 (beginning-of-line 2))
5511 (while (and (not (eobp)) ;; this is like `next-line'
5512 (get-char-property (1- (point)) 'invisible))
5513 (goto-char (next-single-char-property-change (point) 'invisible))
5514 (and (eolp) (beginning-of-line 2))))
5515 (setq eol (point)))
5516 (outline-end-of-heading) (setq eoh (point))
5517 (save-excursion
5518 (outline-next-heading)
5519 (setq has-children (and (org-at-heading-p t)
5520 (> (funcall outline-level) level))))
5521 (org-end-of-subtree t)
5522 (unless (eobp)
5523 (skip-chars-forward " \t\n")
5524 (beginning-of-line 1) ; in case this is an item
5526 (setq eos (if (eobp) (point) (1- (point)))))
5527 ;; Find out what to do next and set `this-command'
5528 (cond
5529 ((= eos eoh)
5530 ;; Nothing is hidden behind this heading
5531 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5532 (message "EMPTY ENTRY")
5533 (setq org-cycle-subtree-status nil)
5534 (save-excursion
5535 (goto-char eos)
5536 (outline-next-heading)
5537 (if (org-invisible-p) (org-flag-heading nil))))
5538 ((and (or (>= eol eos)
5539 (not (string-match "\\S-" (buffer-substring eol eos))))
5540 (or has-children
5541 (not (setq children-skipped
5542 org-cycle-skip-children-state-if-no-children))))
5543 ;; Entire subtree is hidden in one line: children view
5544 (run-hook-with-args 'org-pre-cycle-hook 'children)
5545 (org-show-entry)
5546 (show-children)
5547 (message "CHILDREN")
5548 (save-excursion
5549 (goto-char eos)
5550 (outline-next-heading)
5551 (if (org-invisible-p) (org-flag-heading nil)))
5552 (setq org-cycle-subtree-status 'children)
5553 (run-hook-with-args 'org-cycle-hook 'children))
5554 ((or children-skipped
5555 (and (eq last-command this-command)
5556 (eq org-cycle-subtree-status 'children)))
5557 ;; We just showed the children, or no children are there,
5558 ;; now show everything.
5559 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5560 (org-show-subtree)
5561 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5562 (setq org-cycle-subtree-status 'subtree)
5563 (run-hook-with-args 'org-cycle-hook 'subtree))
5565 ;; Default action: hide the subtree.
5566 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5567 (hide-subtree)
5568 (message "FOLDED")
5569 (setq org-cycle-subtree-status 'folded)
5570 (run-hook-with-args 'org-cycle-hook 'folded)))))
5572 ;;;###autoload
5573 (defun org-global-cycle (&optional arg)
5574 "Cycle the global visibility. For details see `org-cycle'.
5575 With C-u prefix arg, switch to startup visibility.
5576 With a numeric prefix, show all headlines up to that level."
5577 (interactive "P")
5578 (let ((org-cycle-include-plain-lists
5579 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5580 (cond
5581 ((integerp arg)
5582 (show-all)
5583 (hide-sublevels arg)
5584 (setq org-cycle-global-status 'contents))
5585 ((equal arg '(4))
5586 (org-set-startup-visibility)
5587 (message "Startup visibility, plus VISIBILITY properties."))
5589 (org-cycle '(4))))))
5591 (defun org-set-startup-visibility ()
5592 "Set the visibility required by startup options and properties."
5593 (cond
5594 ((eq org-startup-folded t)
5595 (org-cycle '(4)))
5596 ((eq org-startup-folded 'content)
5597 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5598 (org-cycle '(4)) (org-cycle '(4)))))
5599 (unless (eq org-startup-folded 'showeverything)
5600 (if org-hide-block-startup (org-hide-block-all))
5601 (org-set-visibility-according-to-property 'no-cleanup)
5602 (org-cycle-hide-archived-subtrees 'all)
5603 (org-cycle-hide-drawers 'all)
5604 (org-cycle-show-empty-lines 'all)))
5606 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5607 "Switch subtree visibilities according to :VISIBILITY: property."
5608 (interactive)
5609 (let (org-show-entry-below state)
5610 (save-excursion
5611 (goto-char (point-min))
5612 (while (re-search-forward
5613 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5614 nil t)
5615 (setq state (match-string 1))
5616 (save-excursion
5617 (org-back-to-heading t)
5618 (hide-subtree)
5619 (org-reveal)
5620 (cond
5621 ((equal state '("fold" "folded"))
5622 (hide-subtree))
5623 ((equal state "children")
5624 (org-show-hidden-entry)
5625 (show-children))
5626 ((equal state "content")
5627 (save-excursion
5628 (save-restriction
5629 (org-narrow-to-subtree)
5630 (org-content))))
5631 ((member state '("all" "showall"))
5632 (show-subtree)))))
5633 (unless no-cleanup
5634 (org-cycle-hide-archived-subtrees 'all)
5635 (org-cycle-hide-drawers 'all)
5636 (org-cycle-show-empty-lines 'all)))))
5638 (defun org-overview ()
5639 "Switch to overview mode, showing only top-level headlines.
5640 Really, this shows all headlines with level equal or greater than the level
5641 of the first headline in the buffer. This is important, because if the
5642 first headline is not level one, then (hide-sublevels 1) gives confusing
5643 results."
5644 (interactive)
5645 (let ((level (save-excursion
5646 (goto-char (point-min))
5647 (if (re-search-forward (concat "^" outline-regexp) nil t)
5648 (progn
5649 (goto-char (match-beginning 0))
5650 (funcall outline-level))))))
5651 (and level (hide-sublevels level))))
5653 (defun org-content (&optional arg)
5654 "Show all headlines in the buffer, like a table of contents.
5655 With numerical argument N, show content up to level N."
5656 (interactive "P")
5657 (save-excursion
5658 ;; Visit all headings and show their offspring
5659 (and (integerp arg) (org-overview))
5660 (goto-char (point-max))
5661 (catch 'exit
5662 (while (and (progn (condition-case nil
5663 (outline-previous-visible-heading 1)
5664 (error (goto-char (point-min))))
5666 (looking-at outline-regexp))
5667 (if (integerp arg)
5668 (show-children (1- arg))
5669 (show-branches))
5670 (if (bobp) (throw 'exit nil))))))
5673 (defun org-optimize-window-after-visibility-change (state)
5674 "Adjust the window after a change in outline visibility.
5675 This function is the default value of the hook `org-cycle-hook'."
5676 (when (get-buffer-window (current-buffer))
5677 (cond
5678 ((eq state 'content) nil)
5679 ((eq state 'all) nil)
5680 ((eq state 'folded) nil)
5681 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5682 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5684 (defun org-remove-empty-overlays-at (pos)
5685 "Remove outline overlays that do not contain non-white stuff."
5686 (mapc
5687 (lambda (o)
5688 (and (eq 'outline (overlay-get o 'invisible))
5689 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5690 (overlay-end o))))
5691 (delete-overlay o)))
5692 (overlays-at pos)))
5694 (defun org-clean-visibility-after-subtree-move ()
5695 "Fix visibility issues after moving a subtree."
5696 ;; First, find a reasonable region to look at:
5697 ;; Start two siblings above, end three below
5698 (let* ((beg (save-excursion
5699 (and (org-get-last-sibling)
5700 (org-get-last-sibling))
5701 (point)))
5702 (end (save-excursion
5703 (and (org-get-next-sibling)
5704 (org-get-next-sibling)
5705 (org-get-next-sibling))
5706 (if (org-at-heading-p)
5707 (point-at-eol)
5708 (point))))
5709 (level (looking-at "\\*+"))
5710 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5711 (save-excursion
5712 (save-restriction
5713 (narrow-to-region beg end)
5714 (when re
5715 ;; Properly fold already folded siblings
5716 (goto-char (point-min))
5717 (while (re-search-forward re nil t)
5718 (if (and (not (org-invisible-p))
5719 (save-excursion
5720 (goto-char (point-at-eol)) (org-invisible-p)))
5721 (hide-entry))))
5722 (org-cycle-show-empty-lines 'overview)
5723 (org-cycle-hide-drawers 'overview)))))
5725 (defun org-cycle-show-empty-lines (state)
5726 "Show empty lines above all visible headlines.
5727 The region to be covered depends on STATE when called through
5728 `org-cycle-hook'. Lisp program can use t for STATE to get the
5729 entire buffer covered. Note that an empty line is only shown if there
5730 are at least `org-cycle-separator-lines' empty lines before the headline."
5731 (when (not (= org-cycle-separator-lines 0))
5732 (save-excursion
5733 (let* ((n (abs org-cycle-separator-lines))
5734 (re (cond
5735 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5736 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5737 (t (let ((ns (number-to-string (- n 2))))
5738 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5739 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5740 beg end b e)
5741 (cond
5742 ((memq state '(overview contents t))
5743 (setq beg (point-min) end (point-max)))
5744 ((memq state '(children folded))
5745 (setq beg (point) end (progn (org-end-of-subtree t t)
5746 (beginning-of-line 2)
5747 (point)))))
5748 (when beg
5749 (goto-char beg)
5750 (while (re-search-forward re end t)
5751 (unless (get-char-property (match-end 1) 'invisible)
5752 (setq e (match-end 1))
5753 (if (< org-cycle-separator-lines 0)
5754 (setq b (save-excursion
5755 (goto-char (match-beginning 0))
5756 (org-back-over-empty-lines)
5757 (if (save-excursion
5758 (goto-char (max (point-min) (1- (point))))
5759 (org-on-heading-p))
5760 (1- (point))
5761 (point))))
5762 (setq b (match-beginning 1)))
5763 (outline-flag-region b e nil)))))))
5764 ;; Never hide empty lines at the end of the file.
5765 (save-excursion
5766 (goto-char (point-max))
5767 (outline-previous-heading)
5768 (outline-end-of-heading)
5769 (if (and (looking-at "[ \t\n]+")
5770 (= (match-end 0) (point-max)))
5771 (outline-flag-region (point) (match-end 0) nil))))
5773 (defun org-show-empty-lines-in-parent ()
5774 "Move to the parent and re-show empty lines before visible headlines."
5775 (save-excursion
5776 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5777 (org-cycle-show-empty-lines context))))
5779 (defun org-files-list ()
5780 "Return `org-agenda-files' list, plus all open org-mode files.
5781 This is useful for operations that need to scan all of a user's
5782 open and agenda-wise Org files."
5783 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5784 (dolist (buf (buffer-list))
5785 (with-current-buffer buf
5786 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5787 (let ((file (expand-file-name (buffer-file-name))))
5788 (unless (member file files)
5789 (push file files))))))
5790 files))
5792 (defsubst org-entry-beginning-position ()
5793 "Return the beginning position of the current entry."
5794 (save-excursion (outline-back-to-heading t) (point)))
5796 (defsubst org-entry-end-position ()
5797 "Return the end position of the current entry."
5798 (save-excursion (outline-next-heading) (point)))
5800 (defun org-cycle-hide-drawers (state)
5801 "Re-hide all drawers after a visibility state change."
5802 (when (and (org-mode-p)
5803 (not (memq state '(overview folded contents))))
5804 (save-excursion
5805 (let* ((globalp (memq state '(contents all)))
5806 (beg (if globalp (point-min) (point)))
5807 (end (if globalp (point-max)
5808 (if (eq state 'children)
5809 (save-excursion (outline-next-heading) (point))
5810 (org-end-of-subtree t)))))
5811 (goto-char beg)
5812 (while (re-search-forward org-drawer-regexp end t)
5813 (org-flag-drawer t))))))
5815 (defun org-flag-drawer (flag)
5816 (save-excursion
5817 (beginning-of-line 1)
5818 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5819 (let ((b (match-end 0))
5820 (outline-regexp org-outline-regexp))
5821 (if (re-search-forward
5822 "^[ \t]*:END:"
5823 (save-excursion (outline-next-heading) (point)) t)
5824 (outline-flag-region b (point-at-eol) flag)
5825 (error ":END: line missing at position %s" b))))))
5827 (defun org-subtree-end-visible-p ()
5828 "Is the end of the current subtree visible?"
5829 (pos-visible-in-window-p
5830 (save-excursion (org-end-of-subtree t) (point))))
5832 (defun org-first-headline-recenter (&optional N)
5833 "Move cursor to the first headline and recenter the headline.
5834 Optional argument N means put the headline into the Nth line of the window."
5835 (goto-char (point-min))
5836 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5837 (beginning-of-line)
5838 (recenter (prefix-numeric-value N))))
5840 ;;; Saving and restoring visibility
5842 (defun org-outline-overlay-data (&optional use-markers)
5843 "Return a list of the locations of all outline overlays.
5844 The are overlays with the `invisible' property value `outline'.
5845 The return valus is a list of cons cells, with start and stop
5846 positions for each overlay.
5847 If USE-MARKERS is set, return the positions as markers."
5848 (let (beg end)
5849 (save-excursion
5850 (save-restriction
5851 (widen)
5852 (delq nil
5853 (mapcar (lambda (o)
5854 (when (eq (overlay-get o 'invisible) 'outline)
5855 (setq beg (overlay-start o)
5856 end (overlay-end o))
5857 (and beg end (> end beg)
5858 (if use-markers
5859 (cons (move-marker (make-marker) beg)
5860 (move-marker (make-marker) end))
5861 (cons beg end)))))
5862 (overlays-in (point-min) (point-max))))))))
5864 (defun org-set-outline-overlay-data (data)
5865 "Create visibility overlays for all positions in DATA.
5866 DATA should have been made by `org-outline-overlay-data'."
5867 (let (o)
5868 (save-excursion
5869 (save-restriction
5870 (widen)
5871 (show-all)
5872 (mapc (lambda (c)
5873 (setq o (make-overlay (car c) (cdr c)))
5874 (overlay-put o 'invisible 'outline))
5875 data)))))
5877 (defmacro org-save-outline-visibility (use-markers &rest body)
5878 "Save and restore outline visibility around BODY.
5879 If USE-MARKERS is non-nil, use markers for the positions.
5880 This means that the buffer may change while running BODY,
5881 but it also means that the buffer should stay alive
5882 during the operation, because otherwise all these markers will
5883 point nowhere."
5884 `(let ((data (org-outline-overlay-data ,use-markers)))
5885 (unwind-protect
5886 (progn
5887 ,@body
5888 (org-set-outline-overlay-data data))
5889 (when ,use-markers
5890 (mapc (lambda (c)
5891 (and (markerp (car c)) (move-marker (car c) nil))
5892 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5893 data)))))
5896 ;;; Folding of blocks
5898 (defconst org-block-regexp
5900 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5901 "Regular expression for hiding blocks.")
5903 (defvar org-hide-block-overlays nil
5904 "Overlays hiding blocks.")
5905 (make-variable-buffer-local 'org-hide-block-overlays)
5907 (defun org-block-map (function &optional start end)
5908 "Call func at the head of all source blocks in the current
5909 buffer. Optional arguments START and END can be used to limit
5910 the range."
5911 (let ((start (or start (point-min)))
5912 (end (or end (point-max))))
5913 (save-excursion
5914 (goto-char start)
5915 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5916 (save-excursion
5917 (save-match-data
5918 (goto-char (match-beginning 0))
5919 (funcall function)))))))
5921 (defun org-hide-block-toggle-all ()
5922 "Toggle the visibility of all blocks in the current buffer."
5923 (org-block-map #'org-hide-block-toggle))
5925 (defun org-hide-block-all ()
5926 "Fold all blocks in the current buffer."
5927 (interactive)
5928 (org-show-block-all)
5929 (org-block-map #'org-hide-block-toggle-maybe))
5931 (defun org-show-block-all ()
5932 "Unfold all blocks in the current buffer."
5933 (mapc 'delete-overlay org-hide-block-overlays)
5934 (setq org-hide-block-overlays nil))
5936 (defun org-hide-block-toggle-maybe ()
5937 "Toggle visibility of block at point."
5938 (interactive)
5939 (let ((case-fold-search t))
5940 (if (save-excursion
5941 (beginning-of-line 1)
5942 (looking-at org-block-regexp))
5943 (progn (org-hide-block-toggle)
5944 t) ;; to signal that we took action
5945 nil))) ;; to signal that we did not
5947 (defun org-hide-block-toggle (&optional force)
5948 "Toggle the visibility of the current block."
5949 (interactive)
5950 (save-excursion
5951 (beginning-of-line)
5952 (if (re-search-forward org-block-regexp nil t)
5953 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5954 (end (match-end 0)) ;; end of entire body
5956 (if (memq t (mapcar (lambda (overlay)
5957 (eq (overlay-get overlay 'invisible)
5958 'org-hide-block))
5959 (overlays-at start)))
5960 (if (or (not force) (eq force 'off))
5961 (mapc (lambda (ov)
5962 (when (member ov org-hide-block-overlays)
5963 (setq org-hide-block-overlays
5964 (delq ov org-hide-block-overlays)))
5965 (when (eq (overlay-get ov 'invisible)
5966 'org-hide-block)
5967 (delete-overlay ov)))
5968 (overlays-at start)))
5969 (setq ov (make-overlay start end))
5970 (overlay-put ov 'invisible 'org-hide-block)
5971 ;; make the block accessible to isearch
5972 (overlay-put
5973 ov 'isearch-open-invisible
5974 (lambda (ov)
5975 (when (member ov org-hide-block-overlays)
5976 (setq org-hide-block-overlays
5977 (delq ov org-hide-block-overlays)))
5978 (when (eq (overlay-get ov 'invisible)
5979 'org-hide-block)
5980 (delete-overlay ov))))
5981 (push ov org-hide-block-overlays)))
5982 (error "Not looking at a source block"))))
5984 ;; org-tab-after-check-for-cycling-hook
5985 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5986 ;; Remove overlays when changing major mode
5987 (add-hook 'org-mode-hook
5988 (lambda () (org-add-hook 'change-major-mode-hook
5989 'org-show-block-all 'append 'local)))
5991 ;;; Org-goto
5993 (defvar org-goto-window-configuration nil)
5994 (defvar org-goto-marker nil)
5995 (defvar org-goto-map
5996 (let ((map (make-sparse-keymap)))
5997 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5998 (while (setq cmd (pop cmds))
5999 (substitute-key-definition cmd cmd map global-map)))
6000 (suppress-keymap map)
6001 (org-defkey map "\C-m" 'org-goto-ret)
6002 (org-defkey map [(return)] 'org-goto-ret)
6003 (org-defkey map [(left)] 'org-goto-left)
6004 (org-defkey map [(right)] 'org-goto-right)
6005 (org-defkey map [(control ?g)] 'org-goto-quit)
6006 (org-defkey map "\C-i" 'org-cycle)
6007 (org-defkey map [(tab)] 'org-cycle)
6008 (org-defkey map [(down)] 'outline-next-visible-heading)
6009 (org-defkey map [(up)] 'outline-previous-visible-heading)
6010 (if org-goto-auto-isearch
6011 (if (fboundp 'define-key-after)
6012 (define-key-after map [t] 'org-goto-local-auto-isearch)
6013 nil)
6014 (org-defkey map "q" 'org-goto-quit)
6015 (org-defkey map "n" 'outline-next-visible-heading)
6016 (org-defkey map "p" 'outline-previous-visible-heading)
6017 (org-defkey map "f" 'outline-forward-same-level)
6018 (org-defkey map "b" 'outline-backward-same-level)
6019 (org-defkey map "u" 'outline-up-heading))
6020 (org-defkey map "/" 'org-occur)
6021 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6022 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6023 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6024 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6025 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6026 map))
6028 (defconst org-goto-help
6029 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6030 RET=jump to location [Q]uit and return to previous location
6031 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6033 (defvar org-goto-start-pos) ; dynamically scoped parameter
6035 ;; FIXME: Docstring does not mention both interfaces
6036 (defun org-goto (&optional alternative-interface)
6037 "Look up a different location in the current file, keeping current visibility.
6039 When you want look-up or go to a different location in a document, the
6040 fastest way is often to fold the entire buffer and then dive into the tree.
6041 This method has the disadvantage, that the previous location will be folded,
6042 which may not be what you want.
6044 This command works around this by showing a copy of the current buffer
6045 in an indirect buffer, in overview mode. You can dive into the tree in
6046 that copy, use org-occur and incremental search to find a location.
6047 When pressing RET or `Q', the command returns to the original buffer in
6048 which the visibility is still unchanged. After RET is will also jump to
6049 the location selected in the indirect buffer and expose the
6050 the headline hierarchy above."
6051 (interactive "P")
6052 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6053 (org-refile-use-outline-path t)
6054 (org-refile-target-verify-function nil)
6055 (interface
6056 (if (not alternative-interface)
6057 org-goto-interface
6058 (if (eq org-goto-interface 'outline)
6059 'outline-path-completion
6060 'outline)))
6061 (org-goto-start-pos (point))
6062 (selected-point
6063 (if (eq interface 'outline)
6064 (car (org-get-location (current-buffer) org-goto-help))
6065 (nth 3 (org-refile-get-location "Goto: ")))))
6066 (if selected-point
6067 (progn
6068 (org-mark-ring-push org-goto-start-pos)
6069 (goto-char selected-point)
6070 (if (or (org-invisible-p) (org-invisible-p2))
6071 (org-show-context 'org-goto)))
6072 (message "Quit"))))
6074 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6075 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6076 (defvar org-goto-local-auto-isearch-map) ; defined below
6078 (defun org-get-location (buf help)
6079 "Let the user select a location in the Org-mode buffer BUF.
6080 This function uses a recursive edit. It returns the selected position
6081 or nil."
6082 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6083 (isearch-hide-immediately nil)
6084 (isearch-search-fun-function
6085 (lambda () 'org-goto-local-search-headings))
6086 (org-goto-selected-point org-goto-exit-command)
6087 (pop-up-frames nil)
6088 (special-display-buffer-names nil)
6089 (special-display-regexps nil)
6090 (special-display-function nil))
6091 (save-excursion
6092 (save-window-excursion
6093 (delete-other-windows)
6094 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6095 (switch-to-buffer
6096 (condition-case nil
6097 (make-indirect-buffer (current-buffer) "*org-goto*")
6098 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6099 (with-output-to-temp-buffer "*Help*"
6100 (princ help))
6101 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6102 (setq buffer-read-only nil)
6103 (let ((org-startup-truncated t)
6104 (org-startup-folded nil)
6105 (org-startup-align-all-tables nil))
6106 (org-mode)
6107 (org-overview))
6108 (setq buffer-read-only t)
6109 (if (and (boundp 'org-goto-start-pos)
6110 (integer-or-marker-p org-goto-start-pos))
6111 (let ((org-show-hierarchy-above t)
6112 (org-show-siblings t)
6113 (org-show-following-heading t))
6114 (goto-char org-goto-start-pos)
6115 (and (org-invisible-p) (org-show-context)))
6116 (goto-char (point-min)))
6117 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6118 (message "Select location and press RET")
6119 (use-local-map org-goto-map)
6120 (recursive-edit)
6122 (kill-buffer "*org-goto*")
6123 (cons org-goto-selected-point org-goto-exit-command)))
6125 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6126 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6127 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6128 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6130 (defun org-goto-local-search-headings (string bound noerror)
6131 "Search and make sure that any matches are in headlines."
6132 (catch 'return
6133 (while (if isearch-forward
6134 (search-forward string bound noerror)
6135 (search-backward string bound noerror))
6136 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6137 (and (member :headline context)
6138 (not (member :tags context))))
6139 (throw 'return (point))))))
6141 (defun org-goto-local-auto-isearch ()
6142 "Start isearch."
6143 (interactive)
6144 (goto-char (point-min))
6145 (let ((keys (this-command-keys)))
6146 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6147 (isearch-mode t)
6148 (isearch-process-search-char (string-to-char keys)))))
6150 (defun org-goto-ret (&optional arg)
6151 "Finish `org-goto' by going to the new location."
6152 (interactive "P")
6153 (setq org-goto-selected-point (point)
6154 org-goto-exit-command 'return)
6155 (throw 'exit nil))
6157 (defun org-goto-left ()
6158 "Finish `org-goto' by going to the new location."
6159 (interactive)
6160 (if (org-on-heading-p)
6161 (progn
6162 (beginning-of-line 1)
6163 (setq org-goto-selected-point (point)
6164 org-goto-exit-command 'left)
6165 (throw 'exit nil))
6166 (error "Not on a heading")))
6168 (defun org-goto-right ()
6169 "Finish `org-goto' by going to the new location."
6170 (interactive)
6171 (if (org-on-heading-p)
6172 (progn
6173 (setq org-goto-selected-point (point)
6174 org-goto-exit-command 'right)
6175 (throw 'exit nil))
6176 (error "Not on a heading")))
6178 (defun org-goto-quit ()
6179 "Finish `org-goto' without cursor motion."
6180 (interactive)
6181 (setq org-goto-selected-point nil)
6182 (setq org-goto-exit-command 'quit)
6183 (throw 'exit nil))
6185 ;;; Indirect buffer display of subtrees
6187 (defvar org-indirect-dedicated-frame nil
6188 "This is the frame being used for indirect tree display.")
6189 (defvar org-last-indirect-buffer nil)
6191 (defun org-tree-to-indirect-buffer (&optional arg)
6192 "Create indirect buffer and narrow it to current subtree.
6193 With numerical prefix ARG, go up to this level and then take that tree.
6194 If ARG is negative, go up that many levels.
6195 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6196 indirect buffer previously made with this command, to avoid proliferation of
6197 indirect buffers. However, when you call the command with a `C-u' prefix, or
6198 when `org-indirect-buffer-display' is `new-frame', the last buffer
6199 is kept so that you can work with several indirect buffers at the same time.
6200 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6201 requests that a new frame be made for the new buffer, so that the dedicated
6202 frame is not changed."
6203 (interactive "P")
6204 (let ((cbuf (current-buffer))
6205 (cwin (selected-window))
6206 (pos (point))
6207 beg end level heading ibuf)
6208 (save-excursion
6209 (org-back-to-heading t)
6210 (when (numberp arg)
6211 (setq level (org-outline-level))
6212 (if (< arg 0) (setq arg (+ level arg)))
6213 (while (> (setq level (org-outline-level)) arg)
6214 (outline-up-heading 1 t)))
6215 (setq beg (point)
6216 heading (org-get-heading))
6217 (org-end-of-subtree t t)
6218 (if (org-on-heading-p) (backward-char 1))
6219 (setq end (point)))
6220 (if (and (buffer-live-p org-last-indirect-buffer)
6221 (not (eq org-indirect-buffer-display 'new-frame))
6222 (not arg))
6223 (kill-buffer org-last-indirect-buffer))
6224 (setq ibuf (org-get-indirect-buffer cbuf)
6225 org-last-indirect-buffer ibuf)
6226 (cond
6227 ((or (eq org-indirect-buffer-display 'new-frame)
6228 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6229 (select-frame (make-frame))
6230 (delete-other-windows)
6231 (switch-to-buffer ibuf)
6232 (org-set-frame-title heading))
6233 ((eq org-indirect-buffer-display 'dedicated-frame)
6234 (raise-frame
6235 (select-frame (or (and org-indirect-dedicated-frame
6236 (frame-live-p org-indirect-dedicated-frame)
6237 org-indirect-dedicated-frame)
6238 (setq org-indirect-dedicated-frame (make-frame)))))
6239 (delete-other-windows)
6240 (switch-to-buffer ibuf)
6241 (org-set-frame-title (concat "Indirect: " heading)))
6242 ((eq org-indirect-buffer-display 'current-window)
6243 (switch-to-buffer ibuf))
6244 ((eq org-indirect-buffer-display 'other-window)
6245 (pop-to-buffer ibuf))
6246 (t (error "Invalid value")))
6247 (if (featurep 'xemacs)
6248 (save-excursion (org-mode) (turn-on-font-lock)))
6249 (narrow-to-region beg end)
6250 (show-all)
6251 (goto-char pos)
6252 (and (window-live-p cwin) (select-window cwin))))
6254 (defun org-get-indirect-buffer (&optional buffer)
6255 (setq buffer (or buffer (current-buffer)))
6256 (let ((n 1) (base (buffer-name buffer)) bname)
6257 (while (buffer-live-p
6258 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6259 (setq n (1+ n)))
6260 (condition-case nil
6261 (make-indirect-buffer buffer bname 'clone)
6262 (error (make-indirect-buffer buffer bname)))))
6264 (defun org-set-frame-title (title)
6265 "Set the title of the current frame to the string TITLE."
6266 ;; FIXME: how to name a single frame in XEmacs???
6267 (unless (featurep 'xemacs)
6268 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6270 ;;;; Structure editing
6272 ;;; Inserting headlines
6274 (defun org-previous-line-empty-p ()
6275 (save-excursion
6276 (and (not (bobp))
6277 (or (beginning-of-line 0) t)
6278 (save-match-data
6279 (looking-at "[ \t]*$")))))
6281 (defun org-insert-heading (&optional force-heading invisible-ok)
6282 "Insert a new heading or item with same depth at point.
6283 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6284 If point is at the beginning of a headline, insert a sibling before the
6285 current headline. If point is not at the beginning, do not split the line,
6286 but create the new headline after the current line.
6287 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6288 This is important for non-interactive uses of the command."
6289 (interactive "P")
6290 (if (or (= (buffer-size) 0)
6291 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6292 (org-on-heading-p))))
6293 (not (org-in-item-p))))
6294 (insert "\n* ")
6295 (when (or force-heading (not (org-insert-item)))
6296 (let* ((empty-line-p nil)
6297 (head (save-excursion
6298 (condition-case nil
6299 (progn
6300 (org-back-to-heading invisible-ok)
6301 (setq empty-line-p (org-previous-line-empty-p))
6302 (match-string 0))
6303 (error "*"))))
6304 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6305 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6306 pos hide-previous previous-pos)
6307 (cond
6308 ((and (org-on-heading-p) (bolp)
6309 (or (bobp)
6310 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6311 ;; insert before the current line
6312 (open-line (if blank 2 1)))
6313 ((and (bolp)
6314 (not org-insert-heading-respect-content)
6315 (or (bobp)
6316 (save-excursion
6317 (backward-char 1) (not (org-invisible-p)))))
6318 ;; insert right here
6319 nil)
6321 ;; somewhere in the line
6322 (save-excursion
6323 (setq previous-pos (point-at-bol))
6324 (end-of-line)
6325 (setq hide-previous (org-invisible-p)))
6326 (and org-insert-heading-respect-content (org-show-subtree))
6327 (let ((split
6328 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6329 (save-excursion
6330 (let ((p (point)))
6331 (goto-char (point-at-bol))
6332 (and (looking-at org-complex-heading-regexp)
6333 (> p (match-beginning 4)))))))
6334 tags pos)
6335 (cond
6336 (org-insert-heading-respect-content
6337 (org-end-of-subtree nil t)
6338 (or (bolp) (newline))
6339 (or (org-previous-line-empty-p)
6340 (and blank (newline)))
6341 (open-line 1))
6342 ((org-on-heading-p)
6343 (when hide-previous
6344 (show-children)
6345 (org-show-entry))
6346 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6347 (setq tags (and (match-end 2) (match-string 2)))
6348 (and (match-end 1)
6349 (delete-region (match-beginning 1) (match-end 1)))
6350 (setq pos (point-at-bol))
6351 (or split (end-of-line 1))
6352 (delete-horizontal-space)
6353 (if (string-match "\\`\\*+\\'"
6354 (buffer-substring (point-at-bol) (point)))
6355 (insert " "))
6356 (newline (if blank 2 1))
6357 (when tags
6358 (save-excursion
6359 (goto-char pos)
6360 (end-of-line 1)
6361 (insert " " tags)
6362 (org-set-tags nil 'align))))
6364 (or split (end-of-line 1))
6365 (newline (if blank 2 1)))))))
6366 (insert head) (just-one-space)
6367 (setq pos (point))
6368 (end-of-line 1)
6369 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6370 (when (and org-insert-heading-respect-content hide-previous)
6371 (save-excursion
6372 (goto-char previous-pos)
6373 (hide-subtree)))
6374 (run-hooks 'org-insert-heading-hook)))))
6376 (defun org-get-heading (&optional no-tags)
6377 "Return the heading of the current entry, without the stars."
6378 (save-excursion
6379 (org-back-to-heading t)
6380 (if (looking-at
6381 (if no-tags
6382 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6383 "\\*+[ \t]+\\([^\r\n]*\\)"))
6384 (match-string 1) "")))
6386 (defun org-heading-components ()
6387 "Return the components of the current heading.
6388 This is a list with the following elements:
6389 - the level as an integer
6390 - the reduced level, different if `org-odd-levels-only' is set.
6391 - the TODO keyword, or nil
6392 - the priority character, like ?A, or nil if no priority is given
6393 - the headline text itself, or the tags string if no headline text
6394 - the tags string, or nil."
6395 (save-excursion
6396 (org-back-to-heading t)
6397 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6398 (list (length (match-string 1))
6399 (org-reduced-level (length (match-string 1)))
6400 (org-match-string-no-properties 2)
6401 (and (match-end 3) (aref (match-string 3) 2))
6402 (org-match-string-no-properties 4)
6403 (org-match-string-no-properties 5)))))
6405 (defun org-get-entry ()
6406 "Get the entry text, after heading, entire subtree."
6407 (save-excursion
6408 (org-back-to-heading t)
6409 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6411 (defun org-insert-heading-after-current ()
6412 "Insert a new heading with same level as current, after current subtree."
6413 (interactive)
6414 (org-back-to-heading)
6415 (org-insert-heading)
6416 (org-move-subtree-down)
6417 (end-of-line 1))
6419 (defun org-insert-heading-respect-content ()
6420 (interactive)
6421 (let ((org-insert-heading-respect-content t))
6422 (org-insert-heading t)))
6424 (defun org-insert-todo-heading-respect-content (&optional force-state)
6425 (interactive "P")
6426 (let ((org-insert-heading-respect-content t))
6427 (org-insert-todo-heading force-state t)))
6429 (defun org-insert-todo-heading (arg &optional force-heading)
6430 "Insert a new heading with the same level and TODO state as current heading.
6431 If the heading has no TODO state, or if the state is DONE, use the first
6432 state (TODO by default). Also with prefix arg, force first state."
6433 (interactive "P")
6434 (when (or force-heading (not (org-insert-item 'checkbox)))
6435 (org-insert-heading force-heading)
6436 (save-excursion
6437 (org-back-to-heading)
6438 (outline-previous-heading)
6439 (looking-at org-todo-line-regexp))
6440 (let*
6441 ((new-mark-x
6442 (if (or arg
6443 (not (match-beginning 2))
6444 (member (match-string 2) org-done-keywords))
6445 (car org-todo-keywords-1)
6446 (match-string 2)))
6447 (new-mark
6449 (run-hook-with-args-until-success
6450 'org-todo-get-default-hook new-mark-x nil)
6451 new-mark-x)))
6452 (beginning-of-line 1)
6453 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6454 (if org-treat-insert-todo-heading-as-state-change
6455 (org-todo new-mark)
6456 (insert new-mark " "))))
6457 (when org-provide-todo-statistics
6458 (org-update-parent-todo-statistics))))
6460 (defun org-insert-subheading (arg)
6461 "Insert a new subheading and demote it.
6462 Works for outline headings and for plain lists alike."
6463 (interactive "P")
6464 (org-insert-heading arg)
6465 (cond
6466 ((org-on-heading-p) (org-do-demote))
6467 ((org-at-item-p) (org-indent-item 1))))
6469 (defun org-insert-todo-subheading (arg)
6470 "Insert a new subheading with TODO keyword or checkbox and demote it.
6471 Works for outline headings and for plain lists alike."
6472 (interactive "P")
6473 (org-insert-todo-heading arg)
6474 (cond
6475 ((org-on-heading-p) (org-do-demote))
6476 ((org-at-item-p) (org-indent-item 1))))
6478 ;;; Promotion and Demotion
6480 (defvar org-after-demote-entry-hook nil
6481 "Hook run after an entry has been demoted.
6482 The cursor will be at the beginning of the entry.
6483 When a subtree is being demoted, the hook will be called for each node.")
6485 (defvar org-after-promote-entry-hook nil
6486 "Hook run after an entry has been promoted.
6487 The cursor will be at the beginning of the entry.
6488 When a subtree is being promoted, the hook will be called for each node.")
6490 (defun org-promote-subtree ()
6491 "Promote the entire subtree.
6492 See also `org-promote'."
6493 (interactive)
6494 (save-excursion
6495 (org-map-tree 'org-promote))
6496 (org-fix-position-after-promote))
6498 (defun org-demote-subtree ()
6499 "Demote the entire subtree. See `org-demote'.
6500 See also `org-promote'."
6501 (interactive)
6502 (save-excursion
6503 (org-map-tree 'org-demote))
6504 (org-fix-position-after-promote))
6507 (defun org-do-promote ()
6508 "Promote the current heading higher up the tree.
6509 If the region is active in `transient-mark-mode', promote all headings
6510 in the region."
6511 (interactive)
6512 (save-excursion
6513 (if (org-region-active-p)
6514 (org-map-region 'org-promote (region-beginning) (region-end))
6515 (org-promote)))
6516 (org-fix-position-after-promote))
6518 (defun org-do-demote ()
6519 "Demote the current heading lower down the tree.
6520 If the region is active in `transient-mark-mode', demote all headings
6521 in the region."
6522 (interactive)
6523 (save-excursion
6524 (if (org-region-active-p)
6525 (org-map-region 'org-demote (region-beginning) (region-end))
6526 (org-demote)))
6527 (org-fix-position-after-promote))
6529 (defun org-fix-position-after-promote ()
6530 "Make sure that after pro/demotion cursor position is right."
6531 (let ((pos (point)))
6532 (when (save-excursion
6533 (beginning-of-line 1)
6534 (looking-at org-todo-line-regexp)
6535 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6536 (cond ((eobp) (insert " "))
6537 ((eolp) (insert " "))
6538 ((equal (char-after) ?\ ) (forward-char 1))))))
6540 (defun org-current-level ()
6541 "Return the level of the current entry, or nil if before the first headline.
6542 The level is the number of stars at the beginning of the headline."
6543 (save-excursion
6544 (condition-case nil
6545 (progn
6546 (org-back-to-heading t)
6547 (funcall outline-level))
6548 (error nil))))
6550 (defun org-get-previous-line-level ()
6551 "Return the outline depth of the last headline before the current line.
6552 Returns 0 for the first headline in the buffer, and nil if before the
6553 first headline."
6554 (let ((current-level (org-current-level))
6555 (prev-level (when (> (line-number-at-pos) 1)
6556 (save-excursion
6557 (beginning-of-line 0)
6558 (org-current-level)))))
6559 (cond ((null current-level) nil) ; Before first headline
6560 ((null prev-level) 0) ; At first headline
6561 (prev-level))))
6563 (defun org-reduced-level (l)
6564 "Compute the effective level of a heading.
6565 This takes into account the setting of `org-odd-levels-only'."
6566 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6568 (defun org-level-increment ()
6569 "Return the number of stars that will be added or removed at a
6570 time to headlines when structure editing, based on the value of
6571 `org-odd-levels-only'."
6572 (if org-odd-levels-only 2 1))
6574 (defun org-get-valid-level (level &optional change)
6575 "Rectify a level change under the influence of `org-odd-levels-only'
6576 LEVEL is a current level, CHANGE is by how much the level should be
6577 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6578 even level numbers will become the next higher odd number."
6579 (if org-odd-levels-only
6580 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6581 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6582 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6583 (max 1 (+ level (or change 0)))))
6585 (if (boundp 'define-obsolete-function-alias)
6586 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6587 (define-obsolete-function-alias 'org-get-legal-level
6588 'org-get-valid-level)
6589 (define-obsolete-function-alias 'org-get-legal-level
6590 'org-get-valid-level "23.1")))
6592 (defun org-promote ()
6593 "Promote the current heading higher up the tree.
6594 If the region is active in `transient-mark-mode', promote all headings
6595 in the region."
6596 (org-back-to-heading t)
6597 (let* ((level (save-match-data (funcall outline-level)))
6598 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6599 (diff (abs (- level (length up-head) -1))))
6600 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6601 (replace-match up-head nil t)
6602 ;; Fixup tag positioning
6603 (and org-auto-align-tags (org-set-tags nil t))
6604 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6605 (run-hooks 'org-after-promote-entry-hook)))
6607 (defun org-demote ()
6608 "Demote the current heading lower down the tree.
6609 If the region is active in `transient-mark-mode', demote all headings
6610 in the region."
6611 (org-back-to-heading t)
6612 (let* ((level (save-match-data (funcall outline-level)))
6613 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6614 (diff (abs (- level (length down-head) -1))))
6615 (replace-match down-head nil t)
6616 ;; Fixup tag positioning
6617 (and org-auto-align-tags (org-set-tags nil t))
6618 (if org-adapt-indentation (org-fixup-indentation diff))
6619 (run-hooks 'org-after-demote-entry-hook)))
6621 (defun org-cycle-level ()
6622 "Cycle the level of an empty headline through possible states.
6623 This goes first to child, then to parent, level, then up the hierarchy.
6624 After top level, it switches back to sibling level."
6625 (interactive)
6626 (let ((org-adapt-indentation nil))
6627 (when (org-point-at-end-of-empty-headline)
6628 (setq this-command 'org-cycle-level) ; Only needed for caching
6629 (let ((cur-level (org-current-level))
6630 (prev-level (org-get-previous-line-level)))
6631 (cond
6632 ;; If first headline in file, promote to top-level.
6633 ((= prev-level 0)
6634 (loop repeat (/ (- cur-level 1) (org-level-increment))
6635 do (org-do-promote)))
6636 ;; If same level as prev, demote one.
6637 ((= prev-level cur-level)
6638 (org-do-demote))
6639 ;; If parent is top-level, promote to top level if not already.
6640 ((= prev-level 1)
6641 (loop repeat (/ (- cur-level 1) (org-level-increment))
6642 do (org-do-promote)))
6643 ;; If top-level, return to prev-level.
6644 ((= cur-level 1)
6645 (loop repeat (/ (- prev-level 1) (org-level-increment))
6646 do (org-do-demote)))
6647 ;; If less than prev-level, promote one.
6648 ((< cur-level prev-level)
6649 (org-do-promote))
6650 ;; If deeper than prev-level, promote until higher than
6651 ;; prev-level.
6652 ((> cur-level prev-level)
6653 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6654 do (org-do-promote))))
6655 t))))
6657 (defun org-map-tree (fun)
6658 "Call FUN for every heading underneath the current one."
6659 (org-back-to-heading)
6660 (let ((level (funcall outline-level)))
6661 (save-excursion
6662 (funcall fun)
6663 (while (and (progn
6664 (outline-next-heading)
6665 (> (funcall outline-level) level))
6666 (not (eobp)))
6667 (funcall fun)))))
6669 (defun org-map-region (fun beg end)
6670 "Call FUN for every heading between BEG and END."
6671 (let ((org-ignore-region t))
6672 (save-excursion
6673 (setq end (copy-marker end))
6674 (goto-char beg)
6675 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6676 (< (point) end))
6677 (funcall fun))
6678 (while (and (progn
6679 (outline-next-heading)
6680 (< (point) end))
6681 (not (eobp)))
6682 (funcall fun)))))
6684 (defun org-fixup-indentation (diff)
6685 "Change the indentation in the current entry by DIFF
6686 However, if any line in the current entry has no indentation, or if it
6687 would end up with no indentation after the change, nothing at all is done."
6688 (save-excursion
6689 (let ((end (save-excursion (outline-next-heading)
6690 (point-marker)))
6691 (prohibit (if (> diff 0)
6692 "^\\S-"
6693 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6694 col)
6695 (unless (save-excursion (end-of-line 1)
6696 (re-search-forward prohibit end t))
6697 (while (and (< (point) end)
6698 (re-search-forward "^[ \t]+" end t))
6699 (goto-char (match-end 0))
6700 (setq col (current-column))
6701 (if (< diff 0) (replace-match ""))
6702 (org-indent-to-column (+ diff col))))
6703 (move-marker end nil))))
6705 (defun org-convert-to-odd-levels ()
6706 "Convert an org-mode file with all levels allowed to one with odd levels.
6707 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6708 level 5 etc."
6709 (interactive)
6710 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6711 (let ((outline-regexp org-outline-regexp)
6712 (outline-level 'org-outline-level)
6713 (org-odd-levels-only nil) n)
6714 (save-excursion
6715 (goto-char (point-min))
6716 (while (re-search-forward "^\\*\\*+ " nil t)
6717 (setq n (- (length (match-string 0)) 2))
6718 (while (>= (setq n (1- n)) 0)
6719 (org-demote))
6720 (end-of-line 1))))))
6722 (defun org-convert-to-oddeven-levels ()
6723 "Convert an org-mode file with only odd levels to one with odd and even levels.
6724 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6725 section with an even level, conversion would destroy the structure of the file. An error
6726 is signaled in this case."
6727 (interactive)
6728 (goto-char (point-min))
6729 ;; First check if there are no even levels
6730 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6731 (org-show-context t)
6732 (error "Not all levels are odd in this file. Conversion not possible"))
6733 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6734 (let ((outline-regexp org-outline-regexp)
6735 (outline-level 'org-outline-level)
6736 (org-odd-levels-only nil) n)
6737 (save-excursion
6738 (goto-char (point-min))
6739 (while (re-search-forward "^\\*\\*+ " nil t)
6740 (setq n (/ (1- (length (match-string 0))) 2))
6741 (while (>= (setq n (1- n)) 0)
6742 (org-promote))
6743 (end-of-line 1))))))
6745 (defun org-tr-level (n)
6746 "Make N odd if required."
6747 (if org-odd-levels-only (1+ (/ n 2)) n))
6749 ;;; Vertical tree motion, cutting and pasting of subtrees
6751 (defun org-move-subtree-up (&optional arg)
6752 "Move the current subtree up past ARG headlines of the same level."
6753 (interactive "p")
6754 (org-move-subtree-down (- (prefix-numeric-value arg))))
6756 (defun org-move-subtree-down (&optional arg)
6757 "Move the current subtree down past ARG headlines of the same level."
6758 (interactive "p")
6759 (setq arg (prefix-numeric-value arg))
6760 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6761 'org-get-last-sibling))
6762 (ins-point (make-marker))
6763 (cnt (abs arg))
6764 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6765 ;; Select the tree
6766 (org-back-to-heading)
6767 (setq beg0 (point))
6768 (save-excursion
6769 (setq ne-beg (org-back-over-empty-lines))
6770 (setq beg (point)))
6771 (save-match-data
6772 (save-excursion (outline-end-of-heading)
6773 (setq folded (org-invisible-p)))
6774 (outline-end-of-subtree))
6775 (outline-next-heading)
6776 (setq ne-end (org-back-over-empty-lines))
6777 (setq end (point))
6778 (goto-char beg0)
6779 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6780 ;; include less whitespace
6781 (save-excursion
6782 (goto-char beg)
6783 (forward-line (- ne-beg ne-end))
6784 (setq beg (point))))
6785 ;; Find insertion point, with error handling
6786 (while (> cnt 0)
6787 (or (and (funcall movfunc) (looking-at outline-regexp))
6788 (progn (goto-char beg0)
6789 (error "Cannot move past superior level or buffer limit")))
6790 (setq cnt (1- cnt)))
6791 (if (> arg 0)
6792 ;; Moving forward - still need to move over subtree
6793 (progn (org-end-of-subtree t t)
6794 (save-excursion
6795 (org-back-over-empty-lines)
6796 (or (bolp) (newline)))))
6797 (setq ne-ins (org-back-over-empty-lines))
6798 (move-marker ins-point (point))
6799 (setq txt (buffer-substring beg end))
6800 (org-save-markers-in-region beg end)
6801 (delete-region beg end)
6802 (org-remove-empty-overlays-at beg)
6803 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6804 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6805 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6806 (let ((bbb (point)))
6807 (insert-before-markers txt)
6808 (org-reinstall-markers-in-region bbb)
6809 (move-marker ins-point bbb))
6810 (or (bolp) (insert "\n"))
6811 (setq ins-end (point))
6812 (goto-char ins-point)
6813 (org-skip-whitespace)
6814 (when (and (< arg 0)
6815 (org-first-sibling-p)
6816 (> ne-ins ne-beg))
6817 ;; Move whitespace back to beginning
6818 (save-excursion
6819 (goto-char ins-end)
6820 (let ((kill-whole-line t))
6821 (kill-line (- ne-ins ne-beg)) (point)))
6822 (insert (make-string (- ne-ins ne-beg) ?\n)))
6823 (move-marker ins-point nil)
6824 (if folded
6825 (hide-subtree)
6826 (org-show-entry)
6827 (show-children)
6828 (org-cycle-hide-drawers 'children))
6829 (org-clean-visibility-after-subtree-move)))
6831 (defvar org-subtree-clip ""
6832 "Clipboard for cut and paste of subtrees.
6833 This is actually only a copy of the kill, because we use the normal kill
6834 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6836 (defvar org-subtree-clip-folded nil
6837 "Was the last copied subtree folded?
6838 This is used to fold the tree back after pasting.")
6840 (defun org-cut-subtree (&optional n)
6841 "Cut the current subtree into the clipboard.
6842 With prefix arg N, cut this many sequential subtrees.
6843 This is a short-hand for marking the subtree and then cutting it."
6844 (interactive "p")
6845 (org-copy-subtree n 'cut))
6847 (defun org-copy-subtree (&optional n cut force-store-markers)
6848 "Cut the current subtree into the clipboard.
6849 With prefix arg N, cut this many sequential subtrees.
6850 This is a short-hand for marking the subtree and then copying it.
6851 If CUT is non-nil, actually cut the subtree.
6852 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6853 of some markers in the region, even if CUT is non-nil. This is
6854 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6855 (interactive "p")
6856 (let (beg end folded (beg0 (point)))
6857 (if (interactive-p)
6858 (org-back-to-heading nil) ; take what looks like a subtree
6859 (org-back-to-heading t)) ; take what is really there
6860 (org-back-over-empty-lines)
6861 (setq beg (point))
6862 (skip-chars-forward " \t\r\n")
6863 (save-match-data
6864 (save-excursion (outline-end-of-heading)
6865 (setq folded (org-invisible-p)))
6866 (condition-case nil
6867 (org-forward-same-level (1- n) t)
6868 (error nil))
6869 (org-end-of-subtree t t))
6870 (org-back-over-empty-lines)
6871 (setq end (point))
6872 (goto-char beg0)
6873 (when (> end beg)
6874 (setq org-subtree-clip-folded folded)
6875 (when (or cut force-store-markers)
6876 (org-save-markers-in-region beg end))
6877 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6878 (setq org-subtree-clip (current-kill 0))
6879 (message "%s: Subtree(s) with %d characters"
6880 (if cut "Cut" "Copied")
6881 (length org-subtree-clip)))))
6883 (defun org-paste-subtree (&optional level tree for-yank)
6884 "Paste the clipboard as a subtree, with modification of headline level.
6885 The entire subtree is promoted or demoted in order to match a new headline
6886 level.
6888 If the cursor is at the beginning of a headline, the same level as
6889 that headline is used to paste the tree
6891 If not, the new level is derived from the *visible* headings
6892 before and after the insertion point, and taken to be the inferior headline
6893 level of the two. So if the previous visible heading is level 3 and the
6894 next is level 4 (or vice versa), level 4 will be used for insertion.
6895 This makes sure that the subtree remains an independent subtree and does
6896 not swallow low level entries.
6898 You can also force a different level, either by using a numeric prefix
6899 argument, or by inserting the heading marker by hand. For example, if the
6900 cursor is after \"*****\", then the tree will be shifted to level 5.
6902 If optional TREE is given, use this text instead of the kill ring.
6904 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6905 move back over whitespace before inserting, and move point to the end of
6906 the inserted text when done."
6907 (interactive "P")
6908 (setq tree (or tree (and kill-ring (current-kill 0))))
6909 (unless (org-kill-is-subtree-p tree)
6910 (error "%s"
6911 (substitute-command-keys
6912 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6913 (let* ((visp (not (org-invisible-p)))
6914 (txt tree)
6915 (^re (concat "^\\(" outline-regexp "\\)"))
6916 (re (concat "\\(" outline-regexp "\\)"))
6917 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6919 (old-level (if (string-match ^re txt)
6920 (- (match-end 0) (match-beginning 0) 1)
6921 -1))
6922 (force-level (cond (level (prefix-numeric-value level))
6923 ((and (looking-at "[ \t]*$")
6924 (string-match
6925 ^re_ (buffer-substring
6926 (point-at-bol) (point))))
6927 (- (match-end 1) (match-beginning 1)))
6928 ((and (bolp)
6929 (looking-at org-outline-regexp))
6930 (- (match-end 0) (point) 1))
6931 (t nil)))
6932 (previous-level (save-excursion
6933 (condition-case nil
6934 (progn
6935 (outline-previous-visible-heading 1)
6936 (if (looking-at re)
6937 (- (match-end 0) (match-beginning 0) 1)
6939 (error 1))))
6940 (next-level (save-excursion
6941 (condition-case nil
6942 (progn
6943 (or (looking-at outline-regexp)
6944 (outline-next-visible-heading 1))
6945 (if (looking-at re)
6946 (- (match-end 0) (match-beginning 0) 1)
6948 (error 1))))
6949 (new-level (or force-level (max previous-level next-level)))
6950 (shift (if (or (= old-level -1)
6951 (= new-level -1)
6952 (= old-level new-level))
6954 (- new-level old-level)))
6955 (delta (if (> shift 0) -1 1))
6956 (func (if (> shift 0) 'org-demote 'org-promote))
6957 (org-odd-levels-only nil)
6958 beg end newend)
6959 ;; Remove the forced level indicator
6960 (if force-level
6961 (delete-region (point-at-bol) (point)))
6962 ;; Paste
6963 (beginning-of-line 1)
6964 (unless for-yank (org-back-over-empty-lines))
6965 (setq beg (point))
6966 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6967 (insert-before-markers txt)
6968 (unless (string-match "\n\\'" txt) (insert "\n"))
6969 (setq newend (point))
6970 (org-reinstall-markers-in-region beg)
6971 (setq end (point))
6972 (goto-char beg)
6973 (skip-chars-forward " \t\n\r")
6974 (setq beg (point))
6975 (if (and (org-invisible-p) visp)
6976 (save-excursion (outline-show-heading)))
6977 ;; Shift if necessary
6978 (unless (= shift 0)
6979 (save-restriction
6980 (narrow-to-region beg end)
6981 (while (not (= shift 0))
6982 (org-map-region func (point-min) (point-max))
6983 (setq shift (+ delta shift)))
6984 (goto-char (point-min))
6985 (setq newend (point-max))))
6986 (when (or (interactive-p) for-yank)
6987 (message "Clipboard pasted as level %d subtree" new-level))
6988 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6989 kill-ring
6990 (eq org-subtree-clip (current-kill 0))
6991 org-subtree-clip-folded)
6992 ;; The tree was folded before it was killed/copied
6993 (hide-subtree))
6994 (and for-yank (goto-char newend))))
6996 (defun org-kill-is-subtree-p (&optional txt)
6997 "Check if the current kill is an outline subtree, or a set of trees.
6998 Returns nil if kill does not start with a headline, or if the first
6999 headline level is not the largest headline level in the tree.
7000 So this will actually accept several entries of equal levels as well,
7001 which is OK for `org-paste-subtree'.
7002 If optional TXT is given, check this string instead of the current kill."
7003 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7004 (start-level (and kill
7005 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7006 org-outline-regexp "\\)")
7007 kill)
7008 (- (match-end 2) (match-beginning 2) 1)))
7009 (re (concat "^" org-outline-regexp))
7010 (start (1+ (or (match-beginning 2) -1))))
7011 (if (not start-level)
7012 (progn
7013 nil) ;; does not even start with a heading
7014 (catch 'exit
7015 (while (setq start (string-match re kill (1+ start)))
7016 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7017 (throw 'exit nil)))
7018 t))))
7020 (defvar org-markers-to-move nil
7021 "Markers that should be moved with a cut-and-paste operation.
7022 Those markers are stored together with their positions relative to
7023 the start of the region.")
7025 (defun org-save-markers-in-region (beg end)
7026 "Check markers in region.
7027 If these markers are between BEG and END, record their position relative
7028 to BEG, so that after moving the block of text, we can put the markers back
7029 into place.
7030 This function gets called just before an entry or tree gets cut from the
7031 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7032 called immediately, to move the markers with the entries."
7033 (setq org-markers-to-move nil)
7034 (when (featurep 'org-clock)
7035 (org-clock-save-markers-for-cut-and-paste beg end))
7036 (when (featurep 'org-agenda)
7037 (org-agenda-save-markers-for-cut-and-paste beg end)))
7039 (defun org-check-and-save-marker (marker beg end)
7040 "Check if MARKER is between BEG and END.
7041 If yes, remember the marker and the distance to BEG."
7042 (when (and (marker-buffer marker)
7043 (equal (marker-buffer marker) (current-buffer)))
7044 (if (and (>= marker beg) (< marker end))
7045 (push (cons marker (- marker beg)) org-markers-to-move))))
7047 (defun org-reinstall-markers-in-region (beg)
7048 "Move all remembered markers to their position relative to BEG."
7049 (mapc (lambda (x)
7050 (move-marker (car x) (+ beg (cdr x))))
7051 org-markers-to-move)
7052 (setq org-markers-to-move nil))
7054 (defun org-narrow-to-subtree ()
7055 "Narrow buffer to the current subtree."
7056 (interactive)
7057 (save-excursion
7058 (save-match-data
7059 (narrow-to-region
7060 (progn (org-back-to-heading t) (point))
7061 (progn (org-end-of-subtree t t)
7062 (if (org-on-heading-p) (backward-char 1))
7063 (point))))))
7065 (defun org-clone-subtree-with-time-shift (n &optional shift)
7066 "Clone the task (subtree) at point N times.
7067 The clones will be inserted as siblings.
7069 In interactive use, the user will be prompted for the number of clones
7070 to be produced, and for a time SHIFT, which may be a repeater as used
7071 in time stamps, for example `+3d'.
7073 When a valid repeater is given and the entry contains any time stamps,
7074 the clones will become a sequence in time, with time stamps in the
7075 subtree shifted for each clone produced. If SHIFT is nil or the
7076 empty string, time stamps will be left alone.
7078 If the original subtree did contain time stamps with a repeater,
7079 the following will happen:
7080 - the repeater will be removed in each clone
7081 - an additional clone will be produced, with the current, unshifted
7082 date(s) in the entry.
7083 - the original entry will be placed *after* all the clones, with
7084 repeater intact.
7085 - the start days in the repeater in the original entry will be shifted
7086 to past the last clone.
7087 I this way you can spell out a number of instances of a repeating task,
7088 and still retain the repeater to cover future instances of the task."
7089 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7090 (let (beg end template task
7091 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7092 (if (not (and (integerp n) (> n 0)))
7093 (error "Invalid number of replications %s" n))
7094 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7095 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7096 shift)))
7097 (error "Invalid shift specification %s" shift))
7098 (when doshift
7099 (setq shift-n (string-to-number (match-string 1 shift))
7100 shift-what (cdr (assoc (match-string 2 shift)
7101 '(("d" . day) ("w" . week)
7102 ("m" . month) ("y" . year))))))
7103 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7104 (setq nmin 1 nmax n)
7105 (org-back-to-heading t)
7106 (setq beg (point))
7107 (org-end-of-subtree t t)
7108 (or (bolp) (insert "\n"))
7109 (setq end (point))
7110 (setq template (buffer-substring beg end))
7111 (when (and doshift
7112 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7113 (delete-region beg end)
7114 (setq end beg)
7115 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7116 (goto-char end)
7117 (loop for n from nmin to nmax do
7118 (if (not doshift)
7119 (setq task template)
7120 (with-temp-buffer
7121 (insert template)
7122 (org-mode)
7123 (goto-char (point-min))
7124 (while (re-search-forward org-ts-regexp-both nil t)
7125 (org-timestamp-change (* n shift-n) shift-what))
7126 (unless (= n n-no-remove)
7127 (goto-char (point-min))
7128 (while (re-search-forward org-ts-regexp nil t)
7129 (save-excursion
7130 (goto-char (match-beginning 0))
7131 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7132 (delete-region (match-beginning 1) (match-end 1))))))
7133 (setq task (buffer-string))))
7134 (insert task))
7135 (goto-char beg)))
7137 ;;; Outline Sorting
7139 (defun org-sort (with-case)
7140 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7141 Optional argument WITH-CASE means sort case-sensitively.
7142 With a double prefix argument, also remove duplicate entries."
7143 (interactive "P")
7144 (if (org-at-table-p)
7145 (org-call-with-arg 'org-table-sort-lines with-case)
7146 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7148 (defun org-sort-remove-invisible (s)
7149 (remove-text-properties 0 (length s) org-rm-props s)
7150 (while (string-match org-bracket-link-regexp s)
7151 (setq s (replace-match (if (match-end 2)
7152 (match-string 3 s)
7153 (match-string 1 s)) t t s)))
7156 (defvar org-priority-regexp) ; defined later in the file
7158 (defvar org-after-sorting-entries-or-items-hook nil
7159 "Hook that is run after a bunch of entries or items have been sorted.
7160 When children are sorted, the cursor is in the parent line when this
7161 hook gets called. When a region or a plain list is sorted, the cursor
7162 will be in the first entry of the sorted region/list.")
7164 (defun org-sort-entries-or-items
7165 (&optional with-case sorting-type getkey-func compare-func property)
7166 "Sort entries on a certain level of an outline tree, or plain list items.
7167 If there is an active region, the entries in the region are sorted.
7168 Else, if the cursor is before the first entry, sort the top-level items.
7169 Else, the children of the entry at point are sorted.
7170 If the cursor is at the first item in a plain list, the list items will be
7171 sorted.
7173 Sorting can be alphabetically, numerically, by date/time as given by
7174 a time stamp, by a property or by priority.
7176 The command prompts for the sorting type unless it has been given to the
7177 function through the SORTING-TYPE argument, which needs to be a character,
7178 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7179 precise meaning of each character:
7181 n Numerically, by converting the beginning of the entry/item to a number.
7182 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7183 t By date/time, either the first active time stamp in the entry, or, if
7184 none exist, by the first inactive one.
7185 In items, only the first line will be checked.
7186 s By the scheduled date/time.
7187 d By deadline date/time.
7188 c By creation time, which is assumed to be the first inactive time stamp
7189 at the beginning of a line.
7190 p By priority according to the cookie.
7191 r By the value of a property.
7193 Capital letters will reverse the sort order.
7195 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7196 called with point at the beginning of the record. It must return either
7197 a string or a number that should serve as the sorting key for that record.
7199 Comparing entries ignores case by default. However, with an optional argument
7200 WITH-CASE, the sorting considers case as well."
7201 (interactive "P")
7202 (let ((case-func (if with-case 'identity 'downcase))
7203 start beg end stars re re2
7204 txt what tmp plain-list-p)
7205 ;; Find beginning and end of region to sort
7206 (cond
7207 ((org-region-active-p)
7208 ;; we will sort the region
7209 (setq end (region-end)
7210 what "region")
7211 (goto-char (region-beginning))
7212 (if (not (org-on-heading-p)) (outline-next-heading))
7213 (setq start (point)))
7214 ((org-at-item-p)
7215 ;; we will sort this plain list
7216 (org-beginning-of-item-list) (setq start (point))
7217 (org-end-of-item-list)
7218 (or (bolp) (insert "\n"))
7219 (setq end (point))
7220 (goto-char start)
7221 (setq plain-list-p t
7222 what "plain list"))
7223 ((or (org-on-heading-p)
7224 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7225 ;; we will sort the children of the current headline
7226 (org-back-to-heading)
7227 (setq start (point)
7228 end (progn (org-end-of-subtree t t)
7229 (or (bolp) (insert "\n"))
7230 (org-back-over-empty-lines)
7231 (point))
7232 what "children")
7233 (goto-char start)
7234 (show-subtree)
7235 (outline-next-heading))
7237 ;; we will sort the top-level entries in this file
7238 (goto-char (point-min))
7239 (or (org-on-heading-p) (outline-next-heading))
7240 (setq start (point))
7241 (goto-char (point-max))
7242 (beginning-of-line 1)
7243 (when (looking-at ".*?\\S-")
7244 ;; File ends in a non-white line
7245 (end-of-line 1)
7246 (insert "\n"))
7247 (setq end (point-max))
7248 (setq what "top-level")
7249 (goto-char start)
7250 (show-all)))
7252 (setq beg (point))
7253 (if (>= beg end) (error "Nothing to sort"))
7255 (unless plain-list-p
7256 (looking-at "\\(\\*+\\)")
7257 (setq stars (match-string 1)
7258 re (concat "^" (regexp-quote stars) " +")
7259 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7260 txt (buffer-substring beg end))
7261 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7262 (if (and (not (equal stars "*")) (string-match re2 txt))
7263 (error "Region to sort contains a level above the first entry")))
7265 (unless sorting-type
7266 (message
7267 (if plain-list-p
7268 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7269 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7270 [t]ime [s]cheduled [d]eadline [c]reated
7271 A/N/T/S/D/C/P/O/F means reversed:")
7272 what)
7273 (setq sorting-type (read-char-exclusive))
7275 (and (= (downcase sorting-type) ?f)
7276 (setq getkey-func
7277 (org-icompleting-read "Sort using function: "
7278 obarray 'fboundp t nil nil))
7279 (setq getkey-func (intern getkey-func)))
7281 (and (= (downcase sorting-type) ?r)
7282 (setq property
7283 (org-icompleting-read "Property: "
7284 (mapcar 'list (org-buffer-property-keys t))
7285 nil t))))
7287 (message "Sorting entries...")
7289 (save-restriction
7290 (narrow-to-region start end)
7292 (let ((dcst (downcase sorting-type))
7293 (case-fold-search nil)
7294 (now (current-time)))
7295 (sort-subr
7296 (/= dcst sorting-type)
7297 ;; This function moves to the beginning character of the "record" to
7298 ;; be sorted.
7299 (if plain-list-p
7300 (lambda nil
7301 (if (org-at-item-p) t (goto-char (point-max))))
7302 (lambda nil
7303 (if (re-search-forward re nil t)
7304 (goto-char (match-beginning 0))
7305 (goto-char (point-max)))))
7306 ;; This function moves to the last character of the "record" being
7307 ;; sorted.
7308 (if plain-list-p
7309 'org-end-of-item
7310 (lambda nil
7311 (save-match-data
7312 (condition-case nil
7313 (outline-forward-same-level 1)
7314 (error
7315 (goto-char (point-max)))))))
7317 ;; This function returns the value that gets sorted against.
7318 (if plain-list-p
7319 (lambda nil
7320 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7321 (cond
7322 ((= dcst ?n)
7323 (string-to-number (buffer-substring (match-end 0)
7324 (point-at-eol))))
7325 ((= dcst ?a)
7326 (buffer-substring (match-end 0) (point-at-eol)))
7327 ((= dcst ?t)
7328 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7329 (re-search-forward org-ts-regexp-both
7330 (point-at-eol) t))
7331 (org-time-string-to-seconds (match-string 0))
7332 (org-float-time now)))
7333 ((= dcst ?f)
7334 (if getkey-func
7335 (progn
7336 (setq tmp (funcall getkey-func))
7337 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7338 tmp)
7339 (error "Invalid key function `%s'" getkey-func)))
7340 (t (error "Invalid sorting type `%c'" sorting-type)))))
7341 (lambda nil
7342 (cond
7343 ((= dcst ?n)
7344 (if (looking-at org-complex-heading-regexp)
7345 (string-to-number (match-string 4))
7346 nil))
7347 ((= dcst ?a)
7348 (if (looking-at org-complex-heading-regexp)
7349 (funcall case-func (match-string 4))
7350 nil))
7351 ((= dcst ?t)
7352 (let ((end (save-excursion (outline-next-heading) (point))))
7353 (if (or (re-search-forward org-ts-regexp end t)
7354 (re-search-forward org-ts-regexp-both end t))
7355 (org-time-string-to-seconds (match-string 0))
7356 (org-float-time now))))
7357 ((= dcst ?c)
7358 (let ((end (save-excursion (outline-next-heading) (point))))
7359 (if (re-search-forward
7360 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7361 end t)
7362 (org-time-string-to-seconds (match-string 0))
7363 (org-float-time now))))
7364 ((= dcst ?s)
7365 (let ((end (save-excursion (outline-next-heading) (point))))
7366 (if (re-search-forward org-scheduled-time-regexp end t)
7367 (org-time-string-to-seconds (match-string 1))
7368 (org-float-time now))))
7369 ((= dcst ?d)
7370 (let ((end (save-excursion (outline-next-heading) (point))))
7371 (if (re-search-forward org-deadline-time-regexp end t)
7372 (org-time-string-to-seconds (match-string 1))
7373 (org-float-time now))))
7374 ((= dcst ?p)
7375 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7376 (string-to-char (match-string 2))
7377 org-default-priority))
7378 ((= dcst ?r)
7379 (or (org-entry-get nil property) ""))
7380 ((= dcst ?o)
7381 (if (looking-at org-complex-heading-regexp)
7382 (- 9999 (length (member (match-string 2)
7383 org-todo-keywords-1)))))
7384 ((= dcst ?f)
7385 (if getkey-func
7386 (progn
7387 (setq tmp (funcall getkey-func))
7388 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7389 tmp)
7390 (error "Invalid key function `%s'" getkey-func)))
7391 (t (error "Invalid sorting type `%c'" sorting-type)))))
7393 (cond
7394 ((= dcst ?a) 'string<)
7395 ((= dcst ?f) compare-func)
7396 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7397 (t nil)))))
7398 (run-hooks 'org-after-sorting-entries-or-items-hook)
7399 (message "Sorting entries...done")))
7401 (defun org-do-sort (table what &optional with-case sorting-type)
7402 "Sort TABLE of WHAT according to SORTING-TYPE.
7403 The user will be prompted for the SORTING-TYPE if the call to this
7404 function does not specify it. WHAT is only for the prompt, to indicate
7405 what is being sorted. The sorting key will be extracted from
7406 the car of the elements of the table.
7407 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7408 (unless sorting-type
7409 (message
7410 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7411 what)
7412 (setq sorting-type (read-char-exclusive)))
7413 (let ((dcst (downcase sorting-type))
7414 extractfun comparefun)
7415 ;; Define the appropriate functions
7416 (cond
7417 ((= dcst ?n)
7418 (setq extractfun 'string-to-number
7419 comparefun (if (= dcst sorting-type) '< '>)))
7420 ((= dcst ?a)
7421 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7422 (lambda(x) (downcase (org-sort-remove-invisible x))))
7423 comparefun (if (= dcst sorting-type)
7424 'string<
7425 (lambda (a b) (and (not (string< a b))
7426 (not (string= a b)))))))
7427 ((= dcst ?t)
7428 (setq extractfun
7429 (lambda (x)
7430 (if (or (string-match org-ts-regexp x)
7431 (string-match org-ts-regexp-both x))
7432 (org-float-time
7433 (org-time-string-to-time (match-string 0 x)))
7435 comparefun (if (= dcst sorting-type) '< '>)))
7436 (t (error "Invalid sorting type `%c'" sorting-type)))
7438 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7439 table)
7440 (lambda (a b) (funcall comparefun (car a) (car b))))))
7443 ;;; The orgstruct minor mode
7445 ;; Define a minor mode which can be used in other modes in order to
7446 ;; integrate the org-mode structure editing commands.
7448 ;; This is really a hack, because the org-mode structure commands use
7449 ;; keys which normally belong to the major mode. Here is how it
7450 ;; works: The minor mode defines all the keys necessary to operate the
7451 ;; structure commands, but wraps the commands into a function which
7452 ;; tests if the cursor is currently at a headline or a plain list
7453 ;; item. If that is the case, the structure command is used,
7454 ;; temporarily setting many Org-mode variables like regular
7455 ;; expressions for filling etc. However, when any of those keys is
7456 ;; used at a different location, function uses `key-binding' to look
7457 ;; up if the key has an associated command in another currently active
7458 ;; keymap (minor modes, major mode, global), and executes that
7459 ;; command. There might be problems if any of the keys is otherwise
7460 ;; used as a prefix key.
7462 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7463 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7464 ;; addresses this by checking explicitly for both bindings.
7466 (defvar orgstruct-mode-map (make-sparse-keymap)
7467 "Keymap for the minor `orgstruct-mode'.")
7469 (defvar org-local-vars nil
7470 "List of local variables, for use by `orgstruct-mode'")
7472 ;;;###autoload
7473 (define-minor-mode orgstruct-mode
7474 "Toggle the minor mode `orgstruct-mode'.
7475 This mode is for using Org-mode structure commands in other
7476 modes. The following keys behave as if Org-mode were active, if
7477 the cursor is on a headline, or on a plain list item (both as
7478 defined by Org-mode).
7480 M-up Move entry/item up
7481 M-down Move entry/item down
7482 M-left Promote
7483 M-right Demote
7484 M-S-up Move entry/item up
7485 M-S-down Move entry/item down
7486 M-S-left Promote subtree
7487 M-S-right Demote subtree
7488 M-q Fill paragraph and items like in Org-mode
7489 C-c ^ Sort entries
7490 C-c - Cycle list bullet
7491 TAB Cycle item visibility
7492 M-RET Insert new heading/item
7493 S-M-RET Insert new TODO heading / Checkbox item
7494 C-c C-c Set tags / toggle checkbox"
7495 nil " OrgStruct" nil
7496 (org-load-modules-maybe)
7497 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7499 ;;;###autoload
7500 (defun turn-on-orgstruct ()
7501 "Unconditionally turn on `orgstruct-mode'."
7502 (orgstruct-mode 1))
7504 (defun orgstruct++-mode (&optional arg)
7505 "Toggle `orgstruct-mode', the enhanced version of it.
7506 In addition to setting orgstruct-mode, this also exports all indentation
7507 and autofilling variables from org-mode into the buffer. It will also
7508 recognize item context in multiline items.
7509 Note that turning off orgstruct-mode will *not* remove the
7510 indentation/paragraph settings. This can only be done by refreshing the
7511 major mode, for example with \\[normal-mode]."
7512 (interactive "P")
7513 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7514 (if (< arg 1)
7515 (orgstruct-mode -1)
7516 (orgstruct-mode 1)
7517 (let (var val)
7518 (mapc
7519 (lambda (x)
7520 (when (string-match
7521 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7522 (symbol-name (car x)))
7523 (setq var (car x) val (nth 1 x))
7524 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7525 org-local-vars)
7526 (org-set-local 'orgstruct-is-++ t))))
7528 (defvar orgstruct-is-++ nil
7529 "Is orgstruct-mode in ++ version in the current-buffer?")
7530 (make-variable-buffer-local 'orgstruct-is-++)
7532 ;;;###autoload
7533 (defun turn-on-orgstruct++ ()
7534 "Unconditionally turn on `orgstruct++-mode'."
7535 (orgstruct++-mode 1))
7537 (defun orgstruct-error ()
7538 "Error when there is no default binding for a structure key."
7539 (interactive)
7540 (error "This key has no function outside structure elements"))
7542 (defun orgstruct-setup ()
7543 "Setup orgstruct keymaps."
7544 (let ((nfunc 0)
7545 (bindings
7546 (list
7547 '([(meta up)] org-metaup)
7548 '([(meta down)] org-metadown)
7549 '([(meta left)] org-metaleft)
7550 '([(meta right)] org-metaright)
7551 '([(meta shift up)] org-shiftmetaup)
7552 '([(meta shift down)] org-shiftmetadown)
7553 '([(meta shift left)] org-shiftmetaleft)
7554 '([(meta shift right)] org-shiftmetaright)
7555 '([?\e (up)] org-metaup)
7556 '([?\e (down)] org-metadown)
7557 '([?\e (left)] org-metaleft)
7558 '([?\e (right)] org-metaright)
7559 '([?\e (shift up)] org-shiftmetaup)
7560 '([?\e (shift down)] org-shiftmetadown)
7561 '([?\e (shift left)] org-shiftmetaleft)
7562 '([?\e (shift right)] org-shiftmetaright)
7563 '([(shift up)] org-shiftup)
7564 '([(shift down)] org-shiftdown)
7565 '([(shift left)] org-shiftleft)
7566 '([(shift right)] org-shiftright)
7567 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7568 '("\M-q" fill-paragraph)
7569 '("\C-c^" org-sort)
7570 '("\C-c-" org-cycle-list-bullet)))
7571 elt key fun cmd)
7572 (while (setq elt (pop bindings))
7573 (setq nfunc (1+ nfunc))
7574 (setq key (org-key (car elt))
7575 fun (nth 1 elt)
7576 cmd (orgstruct-make-binding fun nfunc key))
7577 (org-defkey orgstruct-mode-map key cmd))
7579 ;; Special treatment needed for TAB and RET
7580 (org-defkey orgstruct-mode-map [(tab)]
7581 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7582 (org-defkey orgstruct-mode-map "\C-i"
7583 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7585 (org-defkey orgstruct-mode-map "\M-\C-m"
7586 (orgstruct-make-binding 'org-insert-heading 105
7587 "\M-\C-m" [(meta return)]))
7588 (org-defkey orgstruct-mode-map [(meta return)]
7589 (orgstruct-make-binding 'org-insert-heading 106
7590 [(meta return)] "\M-\C-m"))
7592 (org-defkey orgstruct-mode-map [(shift meta return)]
7593 (orgstruct-make-binding 'org-insert-todo-heading 107
7594 [(meta return)] "\M-\C-m"))
7596 (org-defkey orgstruct-mode-map "\e\C-m"
7597 (orgstruct-make-binding 'org-insert-heading 108
7598 "\e\C-m" [?\e (return)]))
7599 (org-defkey orgstruct-mode-map [?\e (return)]
7600 (orgstruct-make-binding 'org-insert-heading 109
7601 [?\e (return)] "\e\C-m"))
7602 (org-defkey orgstruct-mode-map [?\e (shift return)]
7603 (orgstruct-make-binding 'org-insert-todo-heading 110
7604 [?\e (return)] "\e\C-m"))
7606 (unless org-local-vars
7607 (setq org-local-vars (org-get-local-variables)))
7611 (defun orgstruct-make-binding (fun n &rest keys)
7612 "Create a function for binding in the structure minor mode.
7613 FUN is the command to call inside a table. N is used to create a unique
7614 command name. KEYS are keys that should be checked in for a command
7615 to execute outside of tables."
7616 (eval
7617 (list 'defun
7618 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7619 '(arg)
7620 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7621 "Outside of structure, run the binding of `"
7622 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7623 "'.")
7624 '(interactive "p")
7625 (list 'if
7626 `(org-context-p 'headline 'item
7627 (and orgstruct-is-++
7628 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7629 'item-body))
7630 (list 'org-run-like-in-org-mode (list 'quote fun))
7631 (list 'let '(orgstruct-mode)
7632 (list 'call-interactively
7633 (append '(or)
7634 (mapcar (lambda (k)
7635 (list 'key-binding k))
7636 keys)
7637 '('orgstruct-error))))))))
7639 (defun org-context-p (&rest contexts)
7640 "Check if local context is any of CONTEXTS.
7641 Possible values in the list of contexts are `table', `headline', and `item'."
7642 (let ((pos (point)))
7643 (goto-char (point-at-bol))
7644 (prog1 (or (and (memq 'table contexts)
7645 (looking-at "[ \t]*|"))
7646 (and (memq 'headline contexts)
7647 ;;????????? (looking-at "\\*+"))
7648 (looking-at outline-regexp))
7649 (and (memq 'item contexts)
7650 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7651 (and (memq 'item-body contexts)
7652 (org-in-item-p)))
7653 (goto-char pos))))
7655 (defun org-get-local-variables ()
7656 "Return a list of all local variables in an org-mode buffer."
7657 (let (varlist)
7658 (with-current-buffer (get-buffer-create "*Org tmp*")
7659 (erase-buffer)
7660 (org-mode)
7661 (setq varlist (buffer-local-variables)))
7662 (kill-buffer "*Org tmp*")
7663 (delq nil
7664 (mapcar
7665 (lambda (x)
7666 (setq x
7667 (if (symbolp x)
7668 (list x)
7669 (list (car x) (list 'quote (cdr x)))))
7670 (if (string-match
7671 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7672 (symbol-name (car x)))
7673 x nil))
7674 varlist))))
7676 ;;;###autoload
7677 (defun org-run-like-in-org-mode (cmd)
7678 "Run a command, pretending that the current buffer is in Org-mode.
7679 This will temporarily bind local variables that are typically bound in
7680 Org-mode to the values they have in Org-mode, and then interactively
7681 call CMD."
7682 (org-load-modules-maybe)
7683 (unless org-local-vars
7684 (setq org-local-vars (org-get-local-variables)))
7685 (eval (list 'let org-local-vars
7686 (list 'call-interactively (list 'quote cmd)))))
7688 ;;;; Archiving
7690 (defun org-get-category (&optional pos)
7691 "Get the category applying to position POS."
7692 (get-text-property (or pos (point)) 'org-category))
7694 (defun org-refresh-category-properties ()
7695 "Refresh category text properties in the buffer."
7696 (let ((def-cat (cond
7697 ((null org-category)
7698 (if buffer-file-name
7699 (file-name-sans-extension
7700 (file-name-nondirectory buffer-file-name))
7701 "???"))
7702 ((symbolp org-category) (symbol-name org-category))
7703 (t org-category)))
7704 beg end cat pos optionp)
7705 (org-unmodified
7706 (save-excursion
7707 (save-restriction
7708 (widen)
7709 (goto-char (point-min))
7710 (put-text-property (point) (point-max) 'org-category def-cat)
7711 (while (re-search-forward
7712 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7713 (setq pos (match-end 0)
7714 optionp (equal (char-after (match-beginning 0)) ?#)
7715 cat (org-trim (match-string 2)))
7716 (if optionp
7717 (setq beg (point-at-bol) end (point-max))
7718 (org-back-to-heading t)
7719 (setq beg (point) end (org-end-of-subtree t t)))
7720 (put-text-property beg end 'org-category cat)
7721 (goto-char pos)))))))
7724 ;;;; Link Stuff
7726 ;;; Link abbreviations
7728 (defun org-link-expand-abbrev (link)
7729 "Apply replacements as defined in `org-link-abbrev-alist."
7730 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7731 (let* ((key (match-string 1 link))
7732 (as (or (assoc key org-link-abbrev-alist-local)
7733 (assoc key org-link-abbrev-alist)))
7734 (tag (and (match-end 2) (match-string 3 link)))
7735 rpl)
7736 (if (not as)
7737 link
7738 (setq rpl (cdr as))
7739 (cond
7740 ((symbolp rpl) (funcall rpl tag))
7741 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7742 ((string-match "%h" rpl)
7743 (replace-match (url-hexify-string (or tag "")) t t rpl))
7744 (t (concat rpl tag)))))
7745 link))
7747 ;;; Storing and inserting links
7749 (defvar org-insert-link-history nil
7750 "Minibuffer history for links inserted with `org-insert-link'.")
7752 (defvar org-stored-links nil
7753 "Contains the links stored with `org-store-link'.")
7755 (defvar org-store-link-plist nil
7756 "Plist with info about the most recently link created with `org-store-link'.")
7758 (defvar org-link-protocols nil
7759 "Link protocols added to Org-mode using `org-add-link-type'.")
7761 (defvar org-store-link-functions nil
7762 "List of functions that are called to create and store a link.
7763 Each function will be called in turn until one returns a non-nil
7764 value. Each function should check if it is responsible for creating
7765 this link (for example by looking at the major mode).
7766 If not, it must exit and return nil.
7767 If yes, it should return a non-nil value after a calling
7768 `org-store-link-props' with a list of properties and values.
7769 Special properties are:
7771 :type The link prefix. like \"http\". This must be given.
7772 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7773 This is obligatory as well.
7774 :description Optional default description for the second pair
7775 of brackets in an Org-mode link. The user can still change
7776 this when inserting this link into an Org-mode buffer.
7778 In addition to these, any additional properties can be specified
7779 and then used in remember templates.")
7781 (defun org-add-link-type (type &optional follow export)
7782 "Add TYPE to the list of `org-link-types'.
7783 Re-compute all regular expressions depending on `org-link-types'
7785 FOLLOW and EXPORT are two functions.
7787 FOLLOW should take the link path as the single argument and do whatever
7788 is necessary to follow the link, for example find a file or display
7789 a mail message.
7791 EXPORT should format the link path for export to one of the export formats.
7792 It should be a function accepting three arguments:
7794 path the path of the link, the text after the prefix (like \"http:\")
7795 desc the description of the link, if any, nil if there was no description
7796 format the export format, a symbol like `html' or `latex'.
7798 The function may use the FORMAT information to return different values
7799 depending on the format. The return value will be put literally into
7800 the exported file.
7801 Org-mode has a built-in default for exporting links. If you are happy with
7802 this default, there is no need to define an export function for the link
7803 type. For a simple example of an export function, see `org-bbdb.el'."
7804 (add-to-list 'org-link-types type t)
7805 (org-make-link-regexps)
7806 (if (assoc type org-link-protocols)
7807 (setcdr (assoc type org-link-protocols) (list follow export))
7808 (push (list type follow export) org-link-protocols)))
7810 (defvar org-agenda-buffer-name)
7812 ;;;###autoload
7813 (defun org-store-link (arg)
7814 "\\<org-mode-map>Store an org-link to the current location.
7815 This link is added to `org-stored-links' and can later be inserted
7816 into an org-buffer with \\[org-insert-link].
7818 For some link types, a prefix arg is interpreted:
7819 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7820 For file links, arg negates `org-context-in-file-links'."
7821 (interactive "P")
7822 (org-load-modules-maybe)
7823 (setq org-store-link-plist nil) ; reset
7824 (let ((outline-regexp (org-get-limited-outline-regexp))
7825 link cpltxt desc description search txt custom-id)
7826 (cond
7828 ((run-hook-with-args-until-success 'org-store-link-functions)
7829 (setq link (plist-get org-store-link-plist :link)
7830 desc (or (plist-get org-store-link-plist :description) link)))
7832 ((equal (buffer-name) "*Org Edit Src Example*")
7833 (let (label gc)
7834 (while (or (not label)
7835 (save-excursion
7836 (save-restriction
7837 (widen)
7838 (goto-char (point-min))
7839 (re-search-forward
7840 (regexp-quote (format org-coderef-label-format label))
7841 nil t))))
7842 (when label (message "Label exists already") (sit-for 2))
7843 (setq label (read-string "Code line label: " label)))
7844 (end-of-line 1)
7845 (setq link (format org-coderef-label-format label))
7846 (setq gc (- 79 (length link)))
7847 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7848 (insert link)
7849 (setq link (concat "(" label ")") desc nil)))
7851 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7852 ;; We are in the agenda, link to referenced location
7853 (let ((m (or (get-text-property (point) 'org-hd-marker)
7854 (get-text-property (point) 'org-marker))))
7855 (when m
7856 (org-with-point-at m
7857 (call-interactively 'org-store-link)))))
7859 ((eq major-mode 'calendar-mode)
7860 (let ((cd (calendar-cursor-to-date)))
7861 (setq link
7862 (format-time-string
7863 (car org-time-stamp-formats)
7864 (apply 'encode-time
7865 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7866 nil nil nil))))
7867 (org-store-link-props :type "calendar" :date cd)))
7869 ((eq major-mode 'w3-mode)
7870 (setq cpltxt (if (and (buffer-name)
7871 (not (string-match "Untitled" (buffer-name))))
7872 (buffer-name)
7873 (url-view-url t))
7874 link (org-make-link (url-view-url t)))
7875 (org-store-link-props :type "w3" :url (url-view-url t)))
7877 ((eq major-mode 'w3m-mode)
7878 (setq cpltxt (or w3m-current-title w3m-current-url)
7879 link (org-make-link w3m-current-url))
7880 (org-store-link-props :type "w3m" :url (url-view-url t)))
7882 ((setq search (run-hook-with-args-until-success
7883 'org-create-file-search-functions))
7884 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7885 "::" search))
7886 (setq cpltxt (or description link)))
7888 ((eq major-mode 'image-mode)
7889 (setq cpltxt (concat "file:"
7890 (abbreviate-file-name buffer-file-name))
7891 link (org-make-link cpltxt))
7892 (org-store-link-props :type "image" :file buffer-file-name))
7894 ((eq major-mode 'dired-mode)
7895 ;; link to the file in the current line
7896 (let ((file (dired-get-filename nil t)))
7897 (setq file (if file
7898 (abbreviate-file-name
7899 (expand-file-name (dired-get-filename nil t)))
7900 ;; otherwise, no file so use current directory.
7901 default-directory))
7902 (setq cpltxt (concat "file:" file)
7903 link (org-make-link cpltxt))))
7905 ((and buffer-file-name (org-mode-p))
7906 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7907 (cond
7908 ((org-in-regexp "<<\\(.*?\\)>>")
7909 (setq cpltxt
7910 (concat "file:"
7911 (abbreviate-file-name buffer-file-name)
7912 "::" (match-string 1))
7913 link (org-make-link cpltxt)))
7914 ((and (featurep 'org-id)
7915 (or (eq org-link-to-org-use-id t)
7916 (and (eq org-link-to-org-use-id 'create-if-interactive)
7917 (interactive-p))
7918 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7919 (interactive-p)
7920 (not custom-id))
7921 (and org-link-to-org-use-id
7922 (condition-case nil
7923 (org-entry-get nil "ID")
7924 (error nil)))))
7925 ;; We can make a link using the ID.
7926 (setq link (condition-case nil
7927 (prog1 (org-id-store-link)
7928 (setq desc (plist-get org-store-link-plist
7929 :description)))
7930 (error
7931 ;; probably before first headline, link to file only
7932 (concat "file:"
7933 (abbreviate-file-name buffer-file-name))))))
7935 ;; Just link to current headline
7936 (setq cpltxt (concat "file:"
7937 (abbreviate-file-name buffer-file-name)))
7938 ;; Add a context search string
7939 (when (org-xor org-context-in-file-links arg)
7940 (setq txt (cond
7941 ((org-on-heading-p) nil)
7942 ((org-region-active-p)
7943 (buffer-substring (region-beginning) (region-end)))
7944 (t nil)))
7945 (when (or (null txt) (string-match "\\S-" txt))
7946 (setq cpltxt
7947 (concat cpltxt "::"
7948 (condition-case nil
7949 (org-make-org-heading-search-string txt)
7950 (error "")))
7951 desc (or (nth 4 (ignore-errors
7952 (org-heading-components))) "NONE"))))
7953 (if (string-match "::\\'" cpltxt)
7954 (setq cpltxt (substring cpltxt 0 -2)))
7955 (setq link (org-make-link cpltxt)))))
7957 ((buffer-file-name (buffer-base-buffer))
7958 ;; Just link to this file here.
7959 (setq cpltxt (concat "file:"
7960 (abbreviate-file-name
7961 (buffer-file-name (buffer-base-buffer)))))
7962 ;; Add a context string
7963 (when (org-xor org-context-in-file-links arg)
7964 (setq txt (if (org-region-active-p)
7965 (buffer-substring (region-beginning) (region-end))
7966 (buffer-substring (point-at-bol) (point-at-eol))))
7967 ;; Only use search option if there is some text.
7968 (when (string-match "\\S-" txt)
7969 (setq cpltxt
7970 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7971 desc "NONE")))
7972 (setq link (org-make-link cpltxt)))
7974 ((interactive-p)
7975 (error "Cannot link to a buffer which is not visiting a file"))
7977 (t (setq link nil)))
7979 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7980 (setq link (or link cpltxt)
7981 desc (or desc cpltxt))
7982 (if (equal desc "NONE") (setq desc nil))
7984 (if (and (or (interactive-p) executing-kbd-macro) link)
7985 (progn
7986 (setq org-stored-links
7987 (cons (list link desc) org-stored-links))
7988 (message "Stored: %s" (or desc link))
7989 (when custom-id
7990 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7991 "::#" custom-id))
7992 (setq org-stored-links
7993 (cons (list link desc) org-stored-links))))
7994 (and link (org-make-link-string link desc)))))
7996 (defun org-store-link-props (&rest plist)
7997 "Store link properties, extract names and addresses."
7998 (let (x adr)
7999 (when (setq x (plist-get plist :from))
8000 (setq adr (mail-extract-address-components x))
8001 (setq plist (plist-put plist :fromname (car adr)))
8002 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8003 (when (setq x (plist-get plist :to))
8004 (setq adr (mail-extract-address-components x))
8005 (setq plist (plist-put plist :toname (car adr)))
8006 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8007 (let ((from (plist-get plist :from))
8008 (to (plist-get plist :to)))
8009 (when (and from to org-from-is-user-regexp)
8010 (setq plist
8011 (plist-put plist :fromto
8012 (if (string-match org-from-is-user-regexp from)
8013 (concat "to %t")
8014 (concat "from %f"))))))
8015 (setq org-store-link-plist plist))
8017 (defun org-add-link-props (&rest plist)
8018 "Add these properties to the link property list."
8019 (let (key value)
8020 (while plist
8021 (setq key (pop plist) value (pop plist))
8022 (setq org-store-link-plist
8023 (plist-put org-store-link-plist key value)))))
8025 (defun org-email-link-description (&optional fmt)
8026 "Return the description part of an email link.
8027 This takes information from `org-store-link-plist' and formats it
8028 according to FMT (default from `org-email-link-description-format')."
8029 (setq fmt (or fmt org-email-link-description-format))
8030 (let* ((p org-store-link-plist)
8031 (to (plist-get p :toaddress))
8032 (from (plist-get p :fromaddress))
8033 (table
8034 (list
8035 (cons "%c" (plist-get p :fromto))
8036 (cons "%F" (plist-get p :from))
8037 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8038 (cons "%T" (plist-get p :to))
8039 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8040 (cons "%s" (plist-get p :subject))
8041 (cons "%m" (plist-get p :message-id)))))
8042 (when (string-match "%c" fmt)
8043 ;; Check if the user wrote this message
8044 (if (and org-from-is-user-regexp from to
8045 (save-match-data (string-match org-from-is-user-regexp from)))
8046 (setq fmt (replace-match "to %t" t t fmt))
8047 (setq fmt (replace-match "from %f" t t fmt))))
8048 (org-replace-escapes fmt table)))
8050 (defun org-make-org-heading-search-string (&optional string heading)
8051 "Make search string for STRING or current headline."
8052 (interactive)
8053 (let ((s (or string (org-get-heading))))
8054 (unless (and string (not heading))
8055 ;; We are using a headline, clean up garbage in there.
8056 (if (string-match org-todo-regexp s)
8057 (setq s (replace-match "" t t s)))
8058 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8059 (setq s (replace-match "" t t s)))
8060 (setq s (org-trim s))
8061 (if (string-match (concat "^\\(" org-quote-string "\\|"
8062 org-comment-string "\\)") s)
8063 (setq s (replace-match "" t t s)))
8064 (while (string-match org-ts-regexp s)
8065 (setq s (replace-match "" t t s))))
8066 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8067 (setq s (replace-match " " t t s)))
8068 (or string (setq s (concat "*" s))) ; Add * for headlines
8069 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8071 (defun org-make-link (&rest strings)
8072 "Concatenate STRINGS."
8073 (apply 'concat strings))
8075 (defun org-make-link-string (link &optional description)
8076 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8077 (unless (string-match "\\S-" link)
8078 (error "Empty link"))
8079 (when (and description
8080 (stringp description)
8081 (not (string-match "\\S-" description)))
8082 (setq description nil))
8083 (when (stringp description)
8084 ;; Remove brackets from the description, they are fatal.
8085 (while (string-match "\\[" description)
8086 (setq description (replace-match "{" t t description)))
8087 (while (string-match "\\]" description)
8088 (setq description (replace-match "}" t t description))))
8089 (when (equal (org-link-escape link) description)
8090 ;; No description needed, it is identical
8091 (setq description nil))
8092 (when (and (not description)
8093 (not (equal link (org-link-escape link))))
8094 (setq description (org-extract-attributes link)))
8095 (concat "[[" (org-link-escape link) "]"
8096 (if description (concat "[" description "]") "")
8097 "]"))
8099 (defconst org-link-escape-chars
8100 '((?\ . "%20")
8101 (?\[ . "%5B")
8102 (?\] . "%5D")
8103 (?\340 . "%E0") ; `a
8104 (?\342 . "%E2") ; ^a
8105 (?\347 . "%E7") ; ,c
8106 (?\350 . "%E8") ; `e
8107 (?\351 . "%E9") ; 'e
8108 (?\352 . "%EA") ; ^e
8109 (?\356 . "%EE") ; ^i
8110 (?\364 . "%F4") ; ^o
8111 (?\371 . "%F9") ; `u
8112 (?\373 . "%FB") ; ^u
8113 (?\; . "%3B")
8114 ;; (?? . "%3F")
8115 (?= . "%3D")
8116 (?+ . "%2B")
8118 "Association list of escapes for some characters problematic in links.
8119 This is the list that is used for internal purposes.")
8121 (defvar org-url-encoding-use-url-hexify nil)
8123 (defconst org-link-escape-chars-browser
8124 '((?\ . "%20")) ; 32 for the SPC char
8125 "Association list of escapes for some characters problematic in links.
8126 This is the list that is used before handing over to the browser.")
8128 (defun org-link-escape (text &optional table)
8129 "Escape characters in TEXT that are problematic for links."
8130 (if (and org-url-encoding-use-url-hexify (not table))
8131 (url-hexify-string text)
8132 (setq table (or table org-link-escape-chars))
8133 (when text
8134 (let ((re (mapconcat (lambda (x) (regexp-quote
8135 (char-to-string (car x))))
8136 table "\\|")))
8137 (while (string-match re text)
8138 (setq text
8139 (replace-match
8140 (cdr (assoc (string-to-char (match-string 0 text))
8141 table))
8142 t t text)))
8143 text))))
8145 (defun org-link-unescape (text &optional table)
8146 "Reverse the action of `org-link-escape'."
8147 (if (and org-url-encoding-use-url-hexify (not table))
8148 (url-unhex-string text)
8149 (setq table (or table org-link-escape-chars))
8150 (when text
8151 (let ((case-fold-search t)
8152 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8153 table "\\|")))
8154 (while (string-match re text)
8155 (setq text
8156 (replace-match
8157 (char-to-string (car (rassoc (upcase (match-string 0 text))
8158 table)))
8159 t t text)))
8160 text))))
8162 (defun org-xor (a b)
8163 "Exclusive or."
8164 (if a (not b) b))
8166 (defun org-fixup-message-id-for-http (s)
8167 "Replace special characters in a message id, so it can be used in an http query."
8168 (while (string-match "<" s)
8169 (setq s (replace-match "%3C" t t s)))
8170 (while (string-match ">" s)
8171 (setq s (replace-match "%3E" t t s)))
8172 (while (string-match "@" s)
8173 (setq s (replace-match "%40" t t s)))
8176 ;;;###autoload
8177 (defun org-insert-link-global ()
8178 "Insert a link like Org-mode does.
8179 This command can be called in any mode to insert a link in Org-mode syntax."
8180 (interactive)
8181 (org-load-modules-maybe)
8182 (org-run-like-in-org-mode 'org-insert-link))
8184 (defun org-insert-link (&optional complete-file link-location)
8185 "Insert a link. At the prompt, enter the link.
8187 Completion can be used to insert any of the link protocol prefixes like
8188 http or ftp in use.
8190 The history can be used to select a link previously stored with
8191 `org-store-link'. When the empty string is entered (i.e. if you just
8192 press RET at the prompt), the link defaults to the most recently
8193 stored link. As SPC triggers completion in the minibuffer, you need to
8194 use M-SPC or C-q SPC to force the insertion of a space character.
8196 You will also be prompted for a description, and if one is given, it will
8197 be displayed in the buffer instead of the link.
8199 If there is already a link at point, this command will allow you to edit link
8200 and description parts.
8202 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8203 be selected using completion. The path to the file will be relative to the
8204 current directory if the file is in the current directory or a subdirectory.
8205 Otherwise, the link will be the absolute path as completed in the minibuffer
8206 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8207 option `org-link-file-path-type'.
8209 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8210 the current directory or below.
8212 With three \\[universal-argument] prefixes, negate the meaning of
8213 `org-keep-stored-link-after-insertion'.
8215 If `org-make-link-description-function' is non-nil, this function will be
8216 called with the link target, and the result will be the default
8217 link description.
8219 If the LINK-LOCATION parameter is non-nil, this value will be
8220 used as the link location instead of reading one interactively."
8221 (interactive "P")
8222 (let* ((wcf (current-window-configuration))
8223 (region (if (org-region-active-p)
8224 (buffer-substring (region-beginning) (region-end))))
8225 (remove (and region (list (region-beginning) (region-end))))
8226 (desc region)
8227 tmphist ; byte-compile incorrectly complains about this
8228 (link link-location)
8229 entry file all-prefixes)
8230 (cond
8231 (link-location) ; specified by arg, just use it.
8232 ((org-in-regexp org-bracket-link-regexp 1)
8233 ;; We do have a link at point, and we are going to edit it.
8234 (setq remove (list (match-beginning 0) (match-end 0)))
8235 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8236 (setq link (read-string "Link: "
8237 (org-link-unescape
8238 (org-match-string-no-properties 1)))))
8239 ((or (org-in-regexp org-angle-link-re)
8240 (org-in-regexp org-plain-link-re))
8241 ;; Convert to bracket link
8242 (setq remove (list (match-beginning 0) (match-end 0))
8243 link (read-string "Link: "
8244 (org-remove-angle-brackets (match-string 0)))))
8245 ((member complete-file '((4) (16)))
8246 ;; Completing read for file names.
8247 (setq link (org-file-complete-link complete-file)))
8249 ;; Read link, with completion for stored links.
8250 (with-output-to-temp-buffer "*Org Links*"
8251 (princ "Insert a link.
8252 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8253 (when org-stored-links
8254 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8255 (princ (mapconcat
8256 (lambda (x)
8257 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8258 (reverse org-stored-links) "\n"))))
8259 (let ((cw (selected-window)))
8260 (select-window (get-buffer-window "*Org Links*" 'visible))
8261 (setq truncate-lines t)
8262 (unless (pos-visible-in-window-p (point-max))
8263 (org-fit-window-to-buffer))
8264 (and (window-live-p cw) (select-window cw)))
8265 ;; Fake a link history, containing the stored links.
8266 (setq tmphist (append (mapcar 'car org-stored-links)
8267 org-insert-link-history))
8268 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8269 (mapcar 'car org-link-abbrev-alist)
8270 org-link-types))
8271 (unwind-protect
8272 (progn
8273 (setq link
8274 (let ((org-completion-use-ido nil)
8275 (org-completion-use-iswitchb nil))
8276 (org-completing-read
8277 "Link: "
8278 (append
8279 (mapcar (lambda (x) (list (concat x ":")))
8280 all-prefixes)
8281 (mapcar 'car org-stored-links))
8282 nil nil nil
8283 'tmphist
8284 (car (car org-stored-links)))))
8285 (if (not (string-match "\\S-" link))
8286 (error "No link selected"))
8287 (if (or (member link all-prefixes)
8288 (and (equal ":" (substring link -1))
8289 (member (substring link 0 -1) all-prefixes)
8290 (setq link (substring link 0 -1))))
8291 (setq link (org-link-try-special-completion link))))
8292 (set-window-configuration wcf)
8293 (kill-buffer "*Org Links*"))
8294 (setq entry (assoc link org-stored-links))
8295 (or entry (push link org-insert-link-history))
8296 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8297 (not org-keep-stored-link-after-insertion))
8298 (setq org-stored-links (delq (assoc link org-stored-links)
8299 org-stored-links)))
8300 (setq desc (or desc (nth 1 entry)))))
8302 (if (string-match org-plain-link-re link)
8303 ;; URL-like link, normalize the use of angular brackets.
8304 (setq link (org-make-link (org-remove-angle-brackets link))))
8306 ;; Check if we are linking to the current file with a search option
8307 ;; If yes, simplify the link by using only the search option.
8308 (when (and buffer-file-name
8309 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8310 (let* ((path (match-string 1 link))
8311 (case-fold-search nil)
8312 (search (match-string 2 link)))
8313 (save-match-data
8314 (if (equal (file-truename buffer-file-name) (file-truename path))
8315 ;; We are linking to this same file, with a search option
8316 (setq link search)))))
8318 ;; Check if we can/should use a relative path. If yes, simplify the link
8319 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8320 (let* ((type (match-string 1 link))
8321 (path (match-string 2 link))
8322 (origpath path)
8323 (case-fold-search nil))
8324 (cond
8325 ((or (eq org-link-file-path-type 'absolute)
8326 (equal complete-file '(16)))
8327 (setq path (abbreviate-file-name (expand-file-name path))))
8328 ((eq org-link-file-path-type 'noabbrev)
8329 (setq path (expand-file-name path)))
8330 ((eq org-link-file-path-type 'relative)
8331 (setq path (file-relative-name path)))
8333 (save-match-data
8334 (if (string-match (concat "^" (regexp-quote
8335 (file-name-as-directory
8336 (expand-file-name "."))))
8337 (expand-file-name path))
8338 ;; We are linking a file with relative path name.
8339 (setq path (substring (expand-file-name path)
8340 (match-end 0)))
8341 (setq path (abbreviate-file-name (expand-file-name path)))))))
8342 (setq link (concat type path))
8343 (if (equal desc origpath)
8344 (setq desc path))))
8346 (if org-make-link-description-function
8347 (setq desc (funcall org-make-link-description-function link desc)))
8349 (setq desc (read-string "Description: " desc))
8350 (unless (string-match "\\S-" desc) (setq desc nil))
8351 (if remove (apply 'delete-region remove))
8352 (insert (org-make-link-string link desc))))
8354 (defun org-link-try-special-completion (type)
8355 "If there is completion support for link type TYPE, offer it."
8356 (let ((fun (intern (concat "org-" type "-complete-link"))))
8357 (if (functionp fun)
8358 (funcall fun)
8359 (read-string "Link (no completion support): " (concat type ":")))))
8361 (defun org-file-complete-link (&optional arg)
8362 "Create a file link using completion."
8363 (let (file link)
8364 (setq file (read-file-name "File: "))
8365 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8366 (pwd1 (file-name-as-directory (abbreviate-file-name
8367 (expand-file-name ".")))))
8368 (cond
8369 ((equal arg '(16))
8370 (setq link (org-make-link
8371 "file:"
8372 (abbreviate-file-name (expand-file-name file)))))
8373 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8374 (setq link (org-make-link "file:" (match-string 1 file))))
8375 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8376 (expand-file-name file))
8377 (setq link (org-make-link
8378 "file:" (match-string 1 (expand-file-name file)))))
8379 (t (setq link (org-make-link "file:" file)))))
8380 link))
8382 (defun org-completing-read (&rest args)
8383 "Completing-read with SPACE being a normal character."
8384 (let ((minibuffer-local-completion-map
8385 (copy-keymap minibuffer-local-completion-map)))
8386 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8387 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8388 (apply 'org-icompleting-read args)))
8390 (defun org-completing-read-no-i (&rest args)
8391 (let (org-completion-use-ido org-completion-use-iswitchb)
8392 (apply 'org-completing-read args)))
8394 (defun org-iswitchb-completing-read (prompt choices &rest args)
8395 "Use iswitch as a completing-read replacement to choose from choices.
8396 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8397 from."
8398 (let* ((iswitchb-use-virtual-buffers nil)
8399 (iswitchb-make-buflist-hook
8400 (lambda ()
8401 (setq iswitchb-temp-buflist choices))))
8402 (iswitchb-read-buffer prompt)))
8404 (defun org-icompleting-read (&rest args)
8405 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8406 (org-without-partial-completion
8407 (if (and org-completion-use-ido
8408 (fboundp 'ido-completing-read)
8409 (boundp 'ido-mode) ido-mode
8410 (listp (second args)))
8411 (let ((ido-enter-matching-directory nil))
8412 (apply 'ido-completing-read (concat (car args))
8413 (if (consp (car (nth 1 args)))
8414 (mapcar (lambda (x) (car x)) (nth 1 args))
8415 (nth 1 args))
8416 (cddr args)))
8417 (if (and org-completion-use-iswitchb
8418 (boundp 'iswitchb-mode) iswitchb-mode
8419 (listp (second args)))
8420 (apply 'org-iswitchb-completing-read (concat (car args))
8421 (if (consp (car (nth 1 args)))
8422 (mapcar (lambda (x) (car x)) (nth 1 args))
8423 (nth 1 args))
8424 (cddr args))
8425 (apply 'completing-read args)))))
8427 (defun org-extract-attributes (s)
8428 "Extract the attributes cookie from a string and set as text property."
8429 (let (a attr (start 0) key value)
8430 (save-match-data
8431 (when (string-match "{{\\([^}]+\\)}}$" s)
8432 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8433 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8434 (setq key (match-string 1 a) value (match-string 2 a)
8435 start (match-end 0)
8436 attr (plist-put attr (intern key) value))))
8437 (org-add-props s nil 'org-attr attr))
8440 (defun org-extract-attributes-from-string (tag)
8441 (let (key value attr)
8442 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8443 (setq key (match-string 1 tag) value (match-string 2 tag)
8444 tag (replace-match "" t t tag)
8445 attr (plist-put attr (intern key) value)))
8446 (cons tag attr)))
8448 (defun org-attributes-to-string (plist)
8449 "Format a property list into an HTML attribute list."
8450 (let ((s "") key value)
8451 (while plist
8452 (setq key (pop plist) value (pop plist))
8453 (and value
8454 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8457 ;;; Opening/following a link
8459 (defvar org-link-search-failed nil)
8461 (defvar org-open-link-functions nil
8462 "Hook for functions finding a plain text link.
8463 These functions must take a single argument, the link content.
8464 They will be called for links that look like [[link text][description]]
8465 when LINK TEXT does not have a protocol like \"http:\" and does not look
8466 like a filename (e.g. \"./blue.png\").
8468 These functions will be called *before* Org attempts to resolve the
8469 link by doing text searches in the current buffer - so if you want a
8470 link \"[[target]]\" to still find \"<<target>>\", your function should
8471 handle this as a special case.
8473 When the function does handle the link, it must return a non-nil value.
8474 If it decides that it is not responsible for this link, it must return
8475 nil to indicate that that Org-mode can continue with other options
8476 like exact and fuzzy text search.")
8478 (defun org-next-link ()
8479 "Move forward to the next link.
8480 If the link is in hidden text, expose it."
8481 (interactive)
8482 (when (and org-link-search-failed (eq this-command last-command))
8483 (goto-char (point-min))
8484 (message "Link search wrapped back to beginning of buffer"))
8485 (setq org-link-search-failed nil)
8486 (let* ((pos (point))
8487 (ct (org-context))
8488 (a (assoc :link ct)))
8489 (if a (goto-char (nth 2 a)))
8490 (if (re-search-forward org-any-link-re nil t)
8491 (progn
8492 (goto-char (match-beginning 0))
8493 (if (org-invisible-p) (org-show-context)))
8494 (goto-char pos)
8495 (setq org-link-search-failed t)
8496 (error "No further link found"))))
8498 (defun org-previous-link ()
8499 "Move backward to the previous link.
8500 If the link is in hidden text, expose it."
8501 (interactive)
8502 (when (and org-link-search-failed (eq this-command last-command))
8503 (goto-char (point-max))
8504 (message "Link search wrapped back to end of buffer"))
8505 (setq org-link-search-failed nil)
8506 (let* ((pos (point))
8507 (ct (org-context))
8508 (a (assoc :link ct)))
8509 (if a (goto-char (nth 1 a)))
8510 (if (re-search-backward org-any-link-re nil t)
8511 (progn
8512 (goto-char (match-beginning 0))
8513 (if (org-invisible-p) (org-show-context)))
8514 (goto-char pos)
8515 (setq org-link-search-failed t)
8516 (error "No further link found"))))
8518 (defun org-translate-link (s)
8519 "Translate a link string if a translation function has been defined."
8520 (if (and org-link-translation-function
8521 (fboundp org-link-translation-function)
8522 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8523 (progn
8524 (setq s (funcall org-link-translation-function
8525 (match-string 1) (match-string 2)))
8526 (concat (car s) ":" (cdr s)))
8529 (defun org-translate-link-from-planner (type path)
8530 "Translate a link from Emacs Planner syntax so that Org can follow it.
8531 This is still an experimental function, your mileage may vary."
8532 (cond
8533 ((member type '("http" "https" "news" "ftp"))
8534 ;; standard Internet links are the same.
8535 nil)
8536 ((and (equal type "irc") (string-match "^//" path))
8537 ;; Planner has two / at the beginning of an irc link, we have 1.
8538 ;; We should have zero, actually....
8539 (setq path (substring path 1)))
8540 ((and (equal type "lisp") (string-match "^/" path))
8541 ;; Planner has a slash, we do not.
8542 (setq type "elisp" path (substring path 1)))
8543 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8544 ;; A typical message link. Planner has the id after the final slash,
8545 ;; we separate it with a hash mark
8546 (setq path (concat (match-string 1 path) "#"
8547 (org-remove-angle-brackets (match-string 2 path)))))
8549 (cons type path))
8551 (defun org-find-file-at-mouse (ev)
8552 "Open file link or URL at mouse."
8553 (interactive "e")
8554 (mouse-set-point ev)
8555 (org-open-at-point 'in-emacs))
8557 (defun org-open-at-mouse (ev)
8558 "Open file link or URL at mouse."
8559 (interactive "e")
8560 (mouse-set-point ev)
8561 (if (eq major-mode 'org-agenda-mode)
8562 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8563 (org-open-at-point))
8565 (defvar org-window-config-before-follow-link nil
8566 "The window configuration before following a link.
8567 This is saved in case the need arises to restore it.")
8569 (defvar org-open-link-marker (make-marker)
8570 "Marker pointing to the location where `org-open-at-point; was called.")
8572 ;;;###autoload
8573 (defun org-open-at-point-global ()
8574 "Follow a link like Org-mode does.
8575 This command can be called in any mode to follow a link that has
8576 Org-mode syntax."
8577 (interactive)
8578 (org-run-like-in-org-mode 'org-open-at-point))
8580 ;;;###autoload
8581 (defun org-open-link-from-string (s &optional arg reference-buffer)
8582 "Open a link in the string S, as if it was in Org-mode."
8583 (interactive "sLink: \nP")
8584 (let ((reference-buffer (or reference-buffer (current-buffer))))
8585 (with-temp-buffer
8586 (let ((org-inhibit-startup t))
8587 (org-mode)
8588 (insert s)
8589 (goto-char (point-min))
8590 (when reference-buffer
8591 (setq org-link-abbrev-alist-local
8592 (with-current-buffer reference-buffer
8593 org-link-abbrev-alist-local)))
8594 (org-open-at-point arg reference-buffer)))))
8596 (defun org-open-at-point (&optional in-emacs reference-buffer)
8597 "Open link at or after point.
8598 If there is no link at point, this function will search forward up to
8599 the end of the current line.
8600 Normally, files will be opened by an appropriate application. If the
8601 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8602 With a double prefix argument, try to open outside of Emacs, in the
8603 application the system uses for this file type."
8604 (interactive "P")
8605 (org-load-modules-maybe)
8606 (move-marker org-open-link-marker (point))
8607 (setq org-window-config-before-follow-link (current-window-configuration))
8608 (org-remove-occur-highlights nil nil t)
8609 (cond
8610 ((and (org-on-heading-p)
8611 (not (org-in-regexp
8612 (concat org-plain-link-re "\\|"
8613 org-bracket-link-regexp "\\|"
8614 org-angle-link-re "\\|"
8615 "[ \t]:[^ \t\n]+:[ \t]*$")))
8616 (not (get-text-property (point) 'org-linked-text)))
8617 (or (org-offer-links-in-entry in-emacs)
8618 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8619 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8620 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8621 (org-footnote-action))
8623 (let (type path link line search (pos (point)))
8624 (catch 'match
8625 (save-excursion
8626 (skip-chars-forward "^]\n\r")
8627 (when (org-in-regexp org-bracket-link-regexp 1)
8628 (setq link (org-extract-attributes
8629 (org-link-unescape (org-match-string-no-properties 1))))
8630 (while (string-match " *\n *" link)
8631 (setq link (replace-match " " t t link)))
8632 (setq link (org-link-expand-abbrev link))
8633 (cond
8634 ((or (file-name-absolute-p link)
8635 (string-match "^\\.\\.?/" link))
8636 (setq type "file" path link))
8637 ((string-match org-link-re-with-space3 link)
8638 (setq type (match-string 1 link) path (match-string 2 link)))
8639 (t (setq type "thisfile" path link)))
8640 (throw 'match t)))
8642 (when (get-text-property (point) 'org-linked-text)
8643 (setq type "thisfile"
8644 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8645 (1+ (point)) (point))
8646 path (buffer-substring
8647 (previous-single-property-change pos 'org-linked-text)
8648 (next-single-property-change pos 'org-linked-text)))
8649 (throw 'match t))
8651 (save-excursion
8652 (when (or (org-in-regexp org-angle-link-re)
8653 (org-in-regexp org-plain-link-re))
8654 (setq type (match-string 1) path (match-string 2))
8655 (throw 'match t)))
8656 (save-excursion
8657 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8658 (setq type "tags"
8659 path (match-string 1))
8660 (while (string-match ":" path)
8661 (setq path (replace-match "+" t t path)))
8662 (throw 'match t)))
8663 (when (org-in-regexp "<\\([^><\n]+\\)>")
8664 (setq type "tree-match"
8665 path (match-string 1))
8666 (throw 'match t)))
8667 (unless path
8668 (error "No link found"))
8670 ;; switch back to reference buffer
8671 ;; needed when if called in a temporary buffer through
8672 ;; org-open-link-from-string
8673 (with-current-buffer (or reference-buffer (current-buffer))
8675 ;; Remove any trailing spaces in path
8676 (if (string-match " +\\'" path)
8677 (setq path (replace-match "" t t path)))
8678 (if (and org-link-translation-function
8679 (fboundp org-link-translation-function))
8680 ;; Check if we need to translate the link
8681 (let ((tmp (funcall org-link-translation-function type path)))
8682 (setq type (car tmp) path (cdr tmp))))
8684 (cond
8686 ((assoc type org-link-protocols)
8687 (funcall (nth 1 (assoc type org-link-protocols)) path))
8689 ((equal type "mailto")
8690 (let ((cmd (car org-link-mailto-program))
8691 (args (cdr org-link-mailto-program)) args1
8692 (address path) (subject "") a)
8693 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8694 (setq address (match-string 1 path)
8695 subject (org-link-escape (match-string 2 path))))
8696 (while args
8697 (cond
8698 ((not (stringp (car args))) (push (pop args) args1))
8699 (t (setq a (pop args))
8700 (if (string-match "%a" a)
8701 (setq a (replace-match address t t a)))
8702 (if (string-match "%s" a)
8703 (setq a (replace-match subject t t a)))
8704 (push a args1))))
8705 (apply cmd (nreverse args1))))
8707 ((member type '("http" "https" "ftp" "news"))
8708 (browse-url (concat type ":" (org-link-escape
8709 path org-link-escape-chars-browser))))
8711 ((string= type "doi")
8712 (browse-url (concat "http://dx.doi.org/"
8713 (org-link-escape
8714 path org-link-escape-chars-browser))))
8716 ((member type '("message"))
8717 (browse-url (concat type ":" path)))
8719 ((string= type "tags")
8720 (org-tags-view in-emacs path))
8722 ((string= type "tree-match")
8723 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8725 ((string= type "file")
8726 (if (string-match "::\\([0-9]+\\)\\'" path)
8727 (setq line (string-to-number (match-string 1 path))
8728 path (substring path 0 (match-beginning 0)))
8729 (if (string-match "::\\(.+\\)\\'" path)
8730 (setq search (match-string 1 path)
8731 path (substring path 0 (match-beginning 0)))))
8732 (if (string-match "[*?{]" (file-name-nondirectory path))
8733 (dired path)
8734 (org-open-file path in-emacs line search)))
8736 ((string= type "news")
8737 (require 'org-gnus)
8738 (org-gnus-follow-link path))
8740 ((string= type "shell")
8741 (let ((cmd path))
8742 (if (or (not org-confirm-shell-link-function)
8743 (funcall org-confirm-shell-link-function
8744 (format "Execute \"%s\" in shell? "
8745 (org-add-props cmd nil
8746 'face 'org-warning))))
8747 (progn
8748 (message "Executing %s" cmd)
8749 (shell-command cmd))
8750 (error "Abort"))))
8752 ((string= type "elisp")
8753 (let ((cmd path))
8754 (if (or (not org-confirm-elisp-link-function)
8755 (funcall org-confirm-elisp-link-function
8756 (format "Execute \"%s\" as elisp? "
8757 (org-add-props cmd nil
8758 'face 'org-warning))))
8759 (message "%s => %s" cmd
8760 (if (equal (string-to-char cmd) ?\()
8761 (eval (read cmd))
8762 (call-interactively (read cmd))))
8763 (error "Abort"))))
8765 ((and (string= type "thisfile")
8766 (run-hook-with-args-until-success
8767 'org-open-link-functions path)))
8769 ((string= type "thisfile")
8770 (if in-emacs
8771 (switch-to-buffer-other-window
8772 (org-get-buffer-for-internal-link (current-buffer)))
8773 (org-mark-ring-push))
8774 (let ((cmd `(org-link-search
8775 ,path
8776 ,(cond ((equal in-emacs '(4)) 'occur)
8777 ((equal in-emacs '(16)) 'org-occur)
8778 (t nil))
8779 ,pos)))
8780 (condition-case nil (eval cmd)
8781 (error (progn (widen) (eval cmd))))))
8784 (browse-url-at-point)))))))
8785 (move-marker org-open-link-marker nil)
8786 (run-hook-with-args 'org-follow-link-hook))
8788 (defun org-offer-links-in-entry (&optional nth zero)
8789 "Offer links in the current entry and follow the selected link.
8790 If there is only one link, follow it immediately as well.
8791 If NTH is an integer, immediately pick the NTH link found.
8792 If ZERO is a string, check also this string for a link, and if
8793 there is one, offer it as link number zero."
8794 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8795 "\\(" org-angle-link-re "\\)\\|"
8796 "\\(" org-plain-link-re "\\)"))
8797 (cnt ?0)
8798 (in-emacs (if (integerp nth) nil nth))
8799 have-zero end links link c)
8800 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8801 (push (match-string 0 zero) links)
8802 (setq cnt (1- cnt) have-zero t))
8803 (save-excursion
8804 (org-back-to-heading t)
8805 (setq end (save-excursion (outline-next-heading) (point)))
8806 (while (re-search-forward re end t)
8807 (push (match-string 0) links))
8808 (setq links (org-uniquify (reverse links))))
8810 (cond
8811 ((null links)
8812 (message "No links"))
8813 ((equal (length links) 1)
8814 (setq link (list (car links))))
8815 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8816 (setq link (nth (if have-zero nth (1- nth)) links)))
8817 (t ; we have to select a link
8818 (save-excursion
8819 (save-window-excursion
8820 (delete-other-windows)
8821 (with-output-to-temp-buffer "*Select Link*"
8822 (mapc (lambda (l)
8823 (if (not (string-match org-bracket-link-regexp l))
8824 (princ (format "[%c] %s\n" (incf cnt)
8825 (org-remove-angle-brackets l)))
8826 (if (match-end 3)
8827 (princ (format "[%c] %s (%s)\n" (incf cnt)
8828 (match-string 3 l) (match-string 1 l)))
8829 (princ (format "[%c] %s\n" (incf cnt)
8830 (match-string 1 l))))))
8831 links))
8832 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8833 (message "Select link to open, RET to open all:")
8834 (setq c (read-char-exclusive))
8835 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8836 (when (equal c ?q) (error "Abort"))
8837 (if (equal c ?\C-m)
8838 (setq link links)
8839 (setq nth (- c ?0))
8840 (if have-zero (setq nth (1+ nth)))
8841 (unless (and (integerp nth) (>= (length links) nth))
8842 (error "Invalid link selection"))
8843 (setq link (list (nth (1- nth) links))))))
8844 (if link
8845 (let ((buf (current-buffer)))
8846 (dolist (l link)
8847 (org-open-link-from-string l in-emacs buf))
8849 nil)))
8851 ;; Add special file links that specify the way of opening
8853 (org-add-link-type "file+sys" 'org-open-file-with-system)
8854 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8855 (defun org-open-file-with-system (path)
8856 "Open file at PATH using the system way of opeing it."
8857 (org-open-file path 'system))
8858 (defun org-open-file-with-emacs (path)
8859 "Open file at PATH in emacs."
8860 (org-open-file path 'emacs))
8861 (defun org-remove-file-link-modifiers ()
8862 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8863 (goto-char (point-min))
8864 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8865 (org-if-unprotected
8866 (replace-match "file:" t t))))
8867 (eval-after-load "org-exp"
8868 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8869 'org-remove-file-link-modifiers))
8871 ;;;; Time estimates
8873 (defun org-get-effort (&optional pom)
8874 "Get the effort estimate for the current entry."
8875 (org-entry-get pom org-effort-property))
8877 ;;; File search
8879 (defvar org-create-file-search-functions nil
8880 "List of functions to construct the right search string for a file link.
8881 These functions are called in turn with point at the location to
8882 which the link should point.
8884 A function in the hook should first test if it would like to
8885 handle this file type, for example by checking the major-mode or
8886 the file extension. If it decides not to handle this file, it
8887 should just return nil to give other functions a chance. If it
8888 does handle the file, it must return the search string to be used
8889 when following the link. The search string will be part of the
8890 file link, given after a double colon, and `org-open-at-point'
8891 will automatically search for it. If special measures must be
8892 taken to make the search successful, another function should be
8893 added to the companion hook `org-execute-file-search-functions',
8894 which see.
8896 A function in this hook may also use `setq' to set the variable
8897 `description' to provide a suggestion for the descriptive text to
8898 be used for this link when it gets inserted into an Org-mode
8899 buffer with \\[org-insert-link].")
8901 (defvar org-execute-file-search-functions nil
8902 "List of functions to execute a file search triggered by a link.
8904 Functions added to this hook must accept a single argument, the
8905 search string that was part of the file link, the part after the
8906 double colon. The function must first check if it would like to
8907 handle this search, for example by checking the major-mode or the
8908 file extension. If it decides not to handle this search, it
8909 should just return nil to give other functions a chance. If it
8910 does handle the search, it must return a non-nil value to keep
8911 other functions from trying.
8913 Each function can access the current prefix argument through the
8914 variable `current-prefix-argument'. Note that a single prefix is
8915 used to force opening a link in Emacs, so it may be good to only
8916 use a numeric or double prefix to guide the search function.
8918 In case this is needed, a function in this hook can also restore
8919 the window configuration before `org-open-at-point' was called using:
8921 (set-window-configuration org-window-config-before-follow-link)")
8923 (defun org-link-search (s &optional type avoid-pos)
8924 "Search for a link search option.
8925 If S is surrounded by forward slashes, it is interpreted as a
8926 regular expression. In org-mode files, this will create an `org-occur'
8927 sparse tree. In ordinary files, `occur' will be used to list matches.
8928 If the current buffer is in `dired-mode', grep will be used to search
8929 in all files. If AVOID-POS is given, ignore matches near that position."
8930 (let ((case-fold-search t)
8931 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8932 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8933 (append '(("") (" ") ("\t") ("\n"))
8934 org-emphasis-alist)
8935 "\\|") "\\)"))
8936 (pos (point))
8937 (pre nil) (post nil)
8938 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8939 (cond
8940 ;; First check if there are any special
8941 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8942 ;; Now try the builtin stuff
8943 ((and (equal (string-to-char s0) ?#)
8944 (> (length s0) 1)
8945 (save-excursion
8946 (goto-char (point-min))
8947 (and
8948 (re-search-forward
8949 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8950 (setq type 'dedicated
8951 pos (match-beginning 0))))
8952 ;; There is an exact target for this
8953 (goto-char pos)
8954 (org-back-to-heading t)))
8955 ((save-excursion
8956 (goto-char (point-min))
8957 (and
8958 (re-search-forward
8959 (concat "<<" (regexp-quote s0) ">>") nil t)
8960 (setq type 'dedicated
8961 pos (match-beginning 0))))
8962 ;; There is an exact target for this
8963 (goto-char pos))
8964 ((and (string-match "^(\\(.*\\))$" s0)
8965 (save-excursion
8966 (goto-char (point-min))
8967 (and
8968 (re-search-forward
8969 (concat "[^[]" (regexp-quote
8970 (format org-coderef-label-format
8971 (match-string 1 s0))))
8972 nil t)
8973 (setq type 'dedicated
8974 pos (1+ (match-beginning 0))))))
8975 ;; There is a coderef target for this
8976 (goto-char pos))
8977 ((string-match "^/\\(.*\\)/$" s)
8978 ;; A regular expression
8979 (cond
8980 ((org-mode-p)
8981 (org-occur (match-string 1 s)))
8982 ;;((eq major-mode 'dired-mode)
8983 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8984 (t (org-do-occur (match-string 1 s)))))
8986 ;; A normal search strings
8987 (when (equal (string-to-char s) ?*)
8988 ;; Anchor on headlines, post may include tags.
8989 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8990 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8991 s (substring s 1)))
8992 (remove-text-properties
8993 0 (length s)
8994 '(face nil mouse-face nil keymap nil fontified nil) s)
8995 ;; Make a series of regular expressions to find a match
8996 (setq words (org-split-string s "[ \n\r\t]+")
8998 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8999 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9000 "\\)" markers)
9001 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9002 re2a (concat "[ \t\r\n]" re2a_)
9003 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9004 re4 (concat "[^a-zA-Z_]" re4_)
9006 re1 (concat pre re2 post)
9007 re3 (concat pre (if pre re4_ re4) post)
9008 re5 (concat pre ".*" re4)
9009 re2 (concat pre re2)
9010 re2a (concat pre (if pre re2a_ re2a))
9011 re4 (concat pre (if pre re4_ re4))
9012 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9013 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9014 re5 "\\)"
9016 (cond
9017 ((eq type 'org-occur) (org-occur reall))
9018 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9019 (t (goto-char (point-min))
9020 (setq type 'fuzzy)
9021 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9022 (org-search-not-self 1 re1 nil t)
9023 (org-search-not-self 1 re2 nil t)
9024 (org-search-not-self 1 re2a nil t)
9025 (org-search-not-self 1 re3 nil t)
9026 (org-search-not-self 1 re4 nil t)
9027 (org-search-not-self 1 re5 nil t)
9029 (goto-char (match-beginning 1))
9030 (goto-char pos)
9031 (error "No match")))))
9033 ;; Normal string-search
9034 (goto-char (point-min))
9035 (if (search-forward s nil t)
9036 (goto-char (match-beginning 0))
9037 (error "No match"))))
9038 (and (org-mode-p) (org-show-context 'link-search))
9039 type))
9041 (defun org-search-not-self (group &rest args)
9042 "Execute `re-search-forward', but only accept matches that do not
9043 enclose the position of `org-open-link-marker'."
9044 (let ((m org-open-link-marker))
9045 (catch 'exit
9046 (while (apply 're-search-forward args)
9047 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9048 (goto-char (match-end group))
9049 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9050 (> (match-beginning 0) (marker-position m))
9051 (< (match-end 0) (marker-position m)))
9052 (save-match-data
9053 (or (not (org-in-regexp
9054 org-bracket-link-analytic-regexp 1))
9055 (not (match-end 4)) ; no description
9056 (and (<= (match-beginning 4) (point))
9057 (>= (match-end 4) (point))))))
9058 (throw 'exit (point))))))))
9060 (defun org-get-buffer-for-internal-link (buffer)
9061 "Return a buffer to be used for displaying the link target of internal links."
9062 (cond
9063 ((not org-display-internal-link-with-indirect-buffer)
9064 buffer)
9065 ((string-match "(Clone)$" (buffer-name buffer))
9066 (message "Buffer is already a clone, not making another one")
9067 ;; we also do not modify visibility in this case
9068 buffer)
9069 (t ; make a new indirect buffer for displaying the link
9070 (let* ((bn (buffer-name buffer))
9071 (ibn (concat bn "(Clone)"))
9072 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9073 (with-current-buffer ib (org-overview))
9074 ib))))
9076 (defun org-do-occur (regexp &optional cleanup)
9077 "Call the Emacs command `occur'.
9078 If CLEANUP is non-nil, remove the printout of the regular expression
9079 in the *Occur* buffer. This is useful if the regex is long and not useful
9080 to read."
9081 (occur regexp)
9082 (when cleanup
9083 (let ((cwin (selected-window)) win beg end)
9084 (when (setq win (get-buffer-window "*Occur*"))
9085 (select-window win))
9086 (goto-char (point-min))
9087 (when (re-search-forward "match[a-z]+" nil t)
9088 (setq beg (match-end 0))
9089 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9090 (setq end (1- (match-beginning 0)))))
9091 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9092 (goto-char (point-min))
9093 (select-window cwin))))
9095 ;;; The mark ring for links jumps
9097 (defvar org-mark-ring nil
9098 "Mark ring for positions before jumps in Org-mode.")
9099 (defvar org-mark-ring-last-goto nil
9100 "Last position in the mark ring used to go back.")
9101 ;; Fill and close the ring
9102 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9103 (loop for i from 1 to org-mark-ring-length do
9104 (push (make-marker) org-mark-ring))
9105 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9106 org-mark-ring)
9108 (defun org-mark-ring-push (&optional pos buffer)
9109 "Put the current position or POS into the mark ring and rotate it."
9110 (interactive)
9111 (setq pos (or pos (point)))
9112 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9113 (move-marker (car org-mark-ring)
9114 (or pos (point))
9115 (or buffer (current-buffer)))
9116 (message "%s"
9117 (substitute-command-keys
9118 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9120 (defun org-mark-ring-goto (&optional n)
9121 "Jump to the previous position in the mark ring.
9122 With prefix arg N, jump back that many stored positions. When
9123 called several times in succession, walk through the entire ring.
9124 Org-mode commands jumping to a different position in the current file,
9125 or to another Org-mode file, automatically push the old position
9126 onto the ring."
9127 (interactive "p")
9128 (let (p m)
9129 (if (eq last-command this-command)
9130 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9131 (setq p org-mark-ring))
9132 (setq org-mark-ring-last-goto p)
9133 (setq m (car p))
9134 (switch-to-buffer (marker-buffer m))
9135 (goto-char m)
9136 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9138 (defun org-remove-angle-brackets (s)
9139 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9140 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9142 (defun org-add-angle-brackets (s)
9143 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9144 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9146 (defun org-remove-double-quotes (s)
9147 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9148 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9151 ;;; Following specific links
9153 (defun org-follow-timestamp-link ()
9154 (cond
9155 ((org-at-date-range-p t)
9156 (let ((org-agenda-start-on-weekday)
9157 (t1 (match-string 1))
9158 (t2 (match-string 2)))
9159 (setq t1 (time-to-days (org-time-string-to-time t1))
9160 t2 (time-to-days (org-time-string-to-time t2)))
9161 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9162 ((org-at-timestamp-p t)
9163 (org-agenda-list nil (time-to-days (org-time-string-to-time
9164 (substring (match-string 1) 0 10)))
9166 (t (error "This should not happen"))))
9169 ;;; Following file links
9170 (defvar org-wait nil)
9171 (defun org-open-file (path &optional in-emacs line search)
9172 "Open the file at PATH.
9173 First, this expands any special file name abbreviations. Then the
9174 configuration variable `org-file-apps' is checked if it contains an
9175 entry for this file type, and if yes, the corresponding command is launched.
9177 If no application is found, Emacs simply visits the file.
9179 With optional prefix argument IN-EMACS, Emacs will visit the file.
9180 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9181 and to use an external application to visit the file.
9183 Optional LINE specifies a line to go to, optional SEARCH a string
9184 to search for. If LINE or SEARCH is given, the file will be
9185 opened in Emacs, unless an entry from org-file-apps that makes
9186 use of groups in a regexp matches.
9187 If the file does not exist, an error is thrown."
9188 (let* ((file (if (equal path "")
9189 buffer-file-name
9190 (substitute-in-file-name (expand-file-name path))))
9191 (file-apps (append org-file-apps (org-default-apps)))
9192 (apps (org-remove-if
9193 'org-file-apps-entry-match-against-dlink-p file-apps))
9194 (apps-dlink (org-remove-if-not
9195 'org-file-apps-entry-match-against-dlink-p file-apps))
9196 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9197 (dirp (if remp nil (file-directory-p file)))
9198 (file (if (and dirp org-open-directory-means-index-dot-org)
9199 (concat (file-name-as-directory file) "index.org")
9200 file))
9201 (a-m-a-p (assq 'auto-mode apps))
9202 (dfile (downcase file))
9203 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9204 (link (cond ((and (eq line nil)
9205 (eq search nil))
9206 file)
9207 (line
9208 (concat file "::" (number-to-string line)))
9209 (search
9210 (concat file "::" search))))
9211 (dlink (downcase link))
9212 (old-buffer (current-buffer))
9213 (old-pos (point))
9214 (old-mode major-mode)
9215 ext cmd link-match-data)
9216 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9217 (setq ext (match-string 1 dfile))
9218 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9219 (setq ext (match-string 1 dfile))))
9220 (cond
9221 ((member in-emacs '((16) system))
9222 (setq cmd (cdr (assoc 'system apps))))
9223 (in-emacs (setq cmd 'emacs))
9225 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9226 (and dirp (cdr (assoc 'directory apps)))
9227 ; first, try matching against apps-dlink
9228 ; if we get a match here, store the match data for later
9229 (let ((match (assoc-default dlink apps-dlink
9230 'string-match)))
9231 (if match
9232 (progn (setq link-match-data (match-data))
9233 match)
9234 (progn (setq in-emacs (or in-emacs line search))
9235 nil))) ; if we have no match in apps-dlink,
9236 ; always open the file in emacs if line or search
9237 ; is given (for backwards compatibility)
9238 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9239 'string-match)
9240 (cdr (assoc ext apps))
9241 (cdr (assoc t apps))))))
9242 (when (eq cmd 'system)
9243 (setq cmd (cdr (assoc 'system apps))))
9244 (when (eq cmd 'default)
9245 (setq cmd (cdr (assoc t apps))))
9246 (when (eq cmd 'mailcap)
9247 (require 'mailcap)
9248 (mailcap-parse-mailcaps)
9249 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9250 (command (mailcap-mime-info mime-type)))
9251 (if (stringp command)
9252 (setq cmd command)
9253 (setq cmd 'emacs))))
9254 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9255 (not (file-exists-p file))
9256 (not org-open-non-existing-files))
9257 (error "No such file: %s" file))
9258 (cond
9259 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9260 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9261 (while (string-match "['\"]%s['\"]" cmd)
9262 (setq cmd (replace-match "%s" t t cmd)))
9263 (while (string-match "%s" cmd)
9264 (setq cmd (replace-match
9265 (save-match-data
9266 (shell-quote-argument
9267 (convert-standard-filename file)))
9268 t t cmd)))
9270 ;; Replace "%1", "%2" etc. in command with group matches from regex
9271 (save-match-data
9272 (let ((match-index 1)
9273 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9274 (set-match-data link-match-data)
9275 (while (<= match-index number-of-groups)
9276 (let ((regex (concat "%" (number-to-string match-index)))
9277 (replace-with (match-string match-index dlink)))
9278 (while (string-match regex cmd)
9279 (setq cmd (replace-match replace-with t t cmd))))
9280 (setq match-index (+ match-index 1)))))
9282 (save-window-excursion
9283 (start-process-shell-command cmd nil cmd)
9284 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9286 ((or (stringp cmd)
9287 (eq cmd 'emacs))
9288 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9289 (widen)
9290 (if line (org-goto-line line)
9291 (if search (org-link-search search))))
9292 ((consp cmd)
9293 (let ((file (convert-standard-filename file)))
9294 (save-match-data
9295 (set-match-data link-match-data)
9296 (eval cmd))))
9297 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9298 (and (org-mode-p) (eq old-mode 'org-mode)
9299 (or (not (equal old-buffer (current-buffer)))
9300 (not (equal old-pos (point))))
9301 (org-mark-ring-push old-pos old-buffer))))
9303 (defun org-file-apps-entry-match-against-dlink-p (entry)
9304 "This function returns non-nil if `entry' uses a regular
9305 expression which should be matched against the whole link by
9306 org-open-file.
9308 It assumes that is the case when the entry uses a regular
9309 expression which has at least one grouping construct and the
9310 action is either a lisp form or a command string containing
9311 '%1', i.e. using at least one subexpression match as a
9312 parameter."
9313 (let ((selector (car entry))
9314 (action (cdr entry)))
9315 (if (stringp selector)
9316 (and (> (regexp-opt-depth selector) 0)
9317 (or (and (stringp action)
9318 (string-match "%[0-9]" action))
9319 (consp action)))
9320 nil)))
9322 (defun org-default-apps ()
9323 "Return the default applications for this operating system."
9324 (cond
9325 ((eq system-type 'darwin)
9326 org-file-apps-defaults-macosx)
9327 ((eq system-type 'windows-nt)
9328 org-file-apps-defaults-windowsnt)
9329 (t org-file-apps-defaults-gnu)))
9331 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9332 "Convert extensions to regular expressions in the cars of LIST.
9333 Also, weed out any non-string entries, because the return value is used
9334 only for regexp matching.
9335 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9336 point to the symbol `emacs', indicating that the file should
9337 be opened in Emacs."
9338 (append
9339 (delq nil
9340 (mapcar (lambda (x)
9341 (if (not (stringp (car x)))
9343 (if (string-match "\\W" (car x))
9345 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9346 list))
9347 (if add-auto-mode
9348 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9350 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9351 (defun org-file-remote-p (file)
9352 "Test whether FILE specifies a location on a remote system.
9353 Return non-nil if the location is indeed remote.
9355 For example, the filename \"/user@host:/foo\" specifies a location
9356 on the system \"/user@host:\"."
9357 (cond ((fboundp 'file-remote-p)
9358 (file-remote-p file))
9359 ((fboundp 'tramp-handle-file-remote-p)
9360 (tramp-handle-file-remote-p file))
9361 ((and (boundp 'ange-ftp-name-format)
9362 (string-match (car ange-ftp-name-format) file))
9364 (t nil)))
9367 ;;;; Refiling
9369 (defun org-get-org-file ()
9370 "Read a filename, with default directory `org-directory'."
9371 (let ((default (or org-default-notes-file remember-data-file)))
9372 (read-file-name (format "File name [%s]: " default)
9373 (file-name-as-directory org-directory)
9374 default)))
9376 (defun org-notes-order-reversed-p ()
9377 "Check if the current file should receive notes in reversed order."
9378 (cond
9379 ((not org-reverse-note-order) nil)
9380 ((eq t org-reverse-note-order) t)
9381 ((not (listp org-reverse-note-order)) nil)
9382 (t (catch 'exit
9383 (let ((all org-reverse-note-order)
9384 entry)
9385 (while (setq entry (pop all))
9386 (if (string-match (car entry) buffer-file-name)
9387 (throw 'exit (cdr entry))))
9388 nil)))))
9390 (defvar org-refile-target-table nil
9391 "The list of refile targets, created by `org-refile'.")
9393 (defvar org-agenda-new-buffers nil
9394 "Buffers created to visit agenda files.")
9396 (defun org-get-refile-targets (&optional default-buffer)
9397 "Produce a table with refile targets."
9398 (let ((case-fold-search nil)
9399 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9400 (entries (or org-refile-targets '((nil . (:level . 1)))))
9401 targets txt re files f desc descre fast-path-p level pos0)
9402 (message "Getting targets...")
9403 (with-current-buffer (or default-buffer (current-buffer))
9404 (while (setq entry (pop entries))
9405 (setq files (car entry) desc (cdr entry))
9406 (setq fast-path-p nil)
9407 (cond
9408 ((null files) (setq files (list (current-buffer))))
9409 ((eq files 'org-agenda-files)
9410 (setq files (org-agenda-files 'unrestricted)))
9411 ((and (symbolp files) (fboundp files))
9412 (setq files (funcall files)))
9413 ((and (symbolp files) (boundp files))
9414 (setq files (symbol-value files))))
9415 (if (stringp files) (setq files (list files)))
9416 (cond
9417 ((eq (car desc) :tag)
9418 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9419 ((eq (car desc) :todo)
9420 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9421 ((eq (car desc) :regexp)
9422 (setq descre (cdr desc)))
9423 ((eq (car desc) :level)
9424 (setq descre (concat "^\\*\\{" (number-to-string
9425 (if org-odd-levels-only
9426 (1- (* 2 (cdr desc)))
9427 (cdr desc)))
9428 "\\}[ \t]")))
9429 ((eq (car desc) :maxlevel)
9430 (setq fast-path-p t)
9431 (setq descre (concat "^\\*\\{1," (number-to-string
9432 (if org-odd-levels-only
9433 (1- (* 2 (cdr desc)))
9434 (cdr desc)))
9435 "\\}[ \t]")))
9436 (t (error "Bad refiling target description %s" desc)))
9437 (while (setq f (pop files))
9438 (with-current-buffer
9439 (if (bufferp f) f (org-get-agenda-file-buffer f))
9440 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9441 (setq f (and f (expand-file-name f)))
9442 (if (eq org-refile-use-outline-path 'file)
9443 (push (list (file-name-nondirectory f) f nil nil) targets))
9444 (save-excursion
9445 (save-restriction
9446 (widen)
9447 (goto-char (point-min))
9448 (while (re-search-forward descre nil t)
9449 (goto-char (setq pos0 (point-at-bol)))
9450 (catch 'next
9451 (when org-refile-target-verify-function
9452 (save-match-data
9453 (or (funcall org-refile-target-verify-function)
9454 (throw 'next t))))
9455 (when (looking-at org-complex-heading-regexp)
9456 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9457 txt (org-link-display-format (match-string 4))
9458 re (concat "^" (regexp-quote
9459 (buffer-substring (match-beginning 1)
9460 (match-end 4)))))
9461 (if (match-end 5) (setq re (concat re "[ \t]+"
9462 (regexp-quote
9463 (match-string 5)))))
9464 (setq re (concat re "[ \t]*$"))
9465 (when org-refile-use-outline-path
9466 (setq txt (mapconcat 'org-protect-slash
9467 (append
9468 (if (eq org-refile-use-outline-path 'file)
9469 (list (file-name-nondirectory
9470 (buffer-file-name (buffer-base-buffer))))
9471 (if (eq org-refile-use-outline-path 'full-file-path)
9472 (list (buffer-file-name (buffer-base-buffer)))))
9473 (org-get-outline-path fast-path-p level txt)
9474 (list txt))
9475 "/")))
9476 (push (list txt f re (point)) targets)))
9477 (when (= (point) pos0)
9478 ;; verification function has not moved point
9479 (goto-char (point-at-eol))))))))))
9480 (message "Getting targets...done")
9481 (nreverse targets)))
9483 (defun org-protect-slash (s)
9484 (while (string-match "/" s)
9485 (setq s (replace-match "\\" t t s)))
9488 (defvar org-olpa (make-vector 20 nil))
9490 (defun org-get-outline-path (&optional fastp level heading)
9491 "Return the outline path to the current entry, as a list.
9492 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9493 routine which makes outline path derivations for an entire file,
9494 avoiding backtracing."
9495 (if fastp
9496 (progn
9497 (if (> level 19)
9498 (error "Outline path failure, more than 19 levels."))
9499 (loop for i from level upto 19 do
9500 (aset org-olpa i nil))
9501 (prog1
9502 (delq nil (append org-olpa nil))
9503 (aset org-olpa level heading)))
9504 (let (rtn case-fold-search)
9505 (save-excursion
9506 (save-restriction
9507 (widen)
9508 (while (org-up-heading-safe)
9509 (when (looking-at org-complex-heading-regexp)
9510 (push (org-match-string-no-properties 4) rtn)))
9511 rtn)))))
9513 (defun org-format-outline-path (path &optional width prefix)
9514 "Format the outlie path PATH for display.
9515 Width is the maximum number of characters that is available.
9516 Prefix is a prefix to be included in the returned string,
9517 such as the file name."
9518 (setq width (or width 79))
9519 (if prefix (setq width (- width (length prefix))))
9520 (if (not path)
9521 (or prefix "")
9522 (let* ((nsteps (length path))
9523 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9524 (maxwidth (if (<= total-width width)
9525 10000 ;; everything fits
9526 ;; we need to shorten the level headings
9527 (/ (- width nsteps) nsteps)))
9528 (org-odd-levels-only nil)
9529 (n 0)
9530 (total (1+ (length prefix))))
9531 (setq maxwidth (max maxwidth 10))
9532 (concat prefix
9533 (mapconcat
9534 (lambda (h)
9535 (setq n (1+ n))
9536 (if (and (= n nsteps) (< maxwidth 10000))
9537 (setq maxwidth (- total-width total)))
9538 (if (< (length h) maxwidth)
9539 (progn (setq total (+ total (length h) 1)) h)
9540 (setq h (substring h 0 (- maxwidth 2))
9541 total (+ total maxwidth 1))
9542 (if (string-match "[ \t]+\\'" h)
9543 (setq h (substring h 0 (match-beginning 0))))
9544 (setq h (concat h "..")))
9545 (org-add-props h nil 'face
9546 (nth (% (1- n) org-n-level-faces)
9547 org-level-faces))
9549 path "/")))))
9551 (defun org-display-outline-path (&optional file current)
9552 "Display the current outline path in the echo area."
9553 (interactive "P")
9554 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9555 (case-fold-search nil)
9556 (path (and (org-mode-p) (org-get-outline-path))))
9557 (if current (setq path (append path
9558 (save-excursion
9559 (org-back-to-heading t)
9560 (if (looking-at org-complex-heading-regexp)
9561 (list (match-string 4)))))))
9562 (message "%s"
9563 (org-format-outline-path
9564 path
9565 (1- (frame-width))
9566 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9568 (defvar org-refile-history nil
9569 "History for refiling operations.")
9571 (defvar org-after-refile-insert-hook nil
9572 "Hook run after `org-refile' has inserted its stuff at the new location.
9573 Note that this is still *before* the stuff will be removed from
9574 the *old* location.")
9576 (defun org-refile (&optional goto default-buffer rfloc)
9577 "Move the entry at point to another heading.
9578 The list of target headings is compiled using the information in
9579 `org-refile-targets', which see. This list is created before each use
9580 and will therefore always be up-to-date.
9582 At the target location, the entry is filed as a subitem of the target heading.
9583 Depending on `org-reverse-note-order', the new subitem will either be the
9584 first or the last subitem.
9586 If there is an active region, all entries in that region will be moved.
9587 However, the region must fulfil the requirement that the first heading
9588 is the first one sets the top-level of the moved text - at most siblings
9589 below it are allowed.
9591 With prefix arg GOTO, the command will only visit the target location,
9592 not actually move anything.
9593 With a double prefix `C-u C-u', go to the location where the last refiling
9594 operation has put the subtree.
9595 With a prefix argument of `2', refile to the running clock.
9597 RFLOC can be a refile location obtained in a different way.
9599 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9600 (interactive "P")
9601 (let* ((cbuf (current-buffer))
9602 (regionp (org-region-active-p))
9603 (region-start (and regionp (region-beginning)))
9604 (region-end (and regionp (region-end)))
9605 (region-length (and regionp (- region-end region-start)))
9606 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9607 pos it nbuf file re level reversed)
9608 (setq last-command nil)
9609 (when regionp
9610 (goto-char region-start)
9611 (or (bolp) (goto-char (point-at-bol)))
9612 (setq region-start (point))
9613 (unless (org-kill-is-subtree-p
9614 (buffer-substring region-start region-end))
9615 (error "The region is not a (sequence of) subtree(s)")))
9616 (if (equal goto '(16))
9617 (org-refile-goto-last-stored)
9618 (when (or
9619 (and (equal goto 2)
9620 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9621 (prog1
9622 (setq it (list (or org-clock-heading "running clock")
9623 (buffer-file-name
9624 (marker-buffer org-clock-hd-marker))
9626 (marker-position org-clock-hd-marker)))
9627 (setq goto nil)))
9628 (setq it (or rfloc
9629 (save-excursion
9630 (org-refile-get-location
9631 (if goto "Goto: " "Refile to: ") default-buffer
9632 org-refile-allow-creating-parent-nodes)))))
9633 (setq file (nth 1 it)
9634 re (nth 2 it)
9635 pos (nth 3 it))
9636 (if (and (not goto)
9638 (equal (buffer-file-name) file)
9639 (if regionp
9640 (and (>= pos region-start)
9641 (<= pos region-end))
9642 (and (>= pos (point))
9643 (< pos (save-excursion
9644 (org-end-of-subtree t t))))))
9645 (error "Cannot refile to position inside the tree or region"))
9647 (setq nbuf (or (find-buffer-visiting file)
9648 (find-file-noselect file)))
9649 (if goto
9650 (progn
9651 (switch-to-buffer nbuf)
9652 (goto-char pos)
9653 (org-show-context 'org-goto))
9654 (if regionp
9655 (progn
9656 (org-kill-new (buffer-substring region-start region-end))
9657 (org-save-markers-in-region region-start region-end))
9658 (org-copy-subtree 1 nil t))
9659 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9660 (find-file-noselect file)))
9661 (setq reversed (org-notes-order-reversed-p))
9662 (save-excursion
9663 (save-restriction
9664 (widen)
9665 (if pos
9666 (progn
9667 (goto-char pos)
9668 (looking-at outline-regexp)
9669 (setq level (org-get-valid-level (funcall outline-level) 1))
9670 (goto-char
9671 (if reversed
9672 (or (outline-next-heading) (point-max))
9673 (or (save-excursion (org-get-next-sibling))
9674 (org-end-of-subtree t t)
9675 (point-max)))))
9676 (setq level 1)
9677 (if (not reversed)
9678 (goto-char (point-max))
9679 (goto-char (point-min))
9680 (or (outline-next-heading) (goto-char (point-max)))))
9681 (if (not (bolp)) (newline))
9682 (org-paste-subtree level)
9683 (when org-log-refile
9684 (org-add-log-setup 'refile nil nil 'findpos
9685 org-log-refile)
9686 (unless (eq org-log-refile 'note)
9687 (save-excursion (org-add-log-note))))
9688 (and org-auto-align-tags (org-set-tags nil t))
9689 (bookmark-set "org-refile-last-stored")
9690 (if (fboundp 'deactivate-mark) (deactivate-mark))
9691 (run-hooks 'org-after-refile-insert-hook))))
9692 (if regionp
9693 (delete-region (point) (+ (point) region-length))
9694 (org-cut-subtree))
9695 (when (featurep 'org-inlinetask)
9696 (org-inlinetask-remove-END-maybe))
9697 (setq org-markers-to-move nil)
9698 (message "Refiled to \"%s\"" (car it)))))))
9700 (defun org-refile-goto-last-stored ()
9701 "Go to the location where the last refile was stored."
9702 (interactive)
9703 (bookmark-jump "org-refile-last-stored")
9704 (message "This is the location of the last refile"))
9706 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9707 "Prompt the user for a refile location, using PROMPT."
9708 (let ((org-refile-targets org-refile-targets)
9709 (org-refile-use-outline-path org-refile-use-outline-path))
9710 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9711 (unless org-refile-target-table
9712 (error "No refile targets"))
9713 (let* ((cbuf (current-buffer))
9714 (partial-completion-mode nil)
9715 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9716 (cfunc (if (and org-refile-use-outline-path
9717 org-outline-path-complete-in-steps)
9718 'org-olpath-completing-read
9719 'org-icompleting-read))
9720 (extra (if org-refile-use-outline-path "/" ""))
9721 (filename (and cfn (expand-file-name cfn)))
9722 (tbl (mapcar
9723 (lambda (x)
9724 (if (and (not (member org-refile-use-outline-path
9725 '(file full-file-path)))
9726 (not (equal filename (nth 1 x))))
9727 (cons (concat (car x) extra " ("
9728 (file-name-nondirectory (nth 1 x)) ")")
9729 (cdr x))
9730 (cons (concat (car x) extra) (cdr x))))
9731 org-refile-target-table))
9732 (completion-ignore-case t)
9733 pa answ parent-target child parent old-hist)
9734 (setq old-hist org-refile-history)
9735 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9736 nil 'org-refile-history))
9737 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9738 (if pa
9739 (progn
9740 (when (or (not org-refile-history)
9741 (not (eq old-hist org-refile-history))
9742 (not (equal (car pa) (car org-refile-history))))
9743 (setq org-refile-history
9744 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9745 org-refile-history
9746 (cdr org-refile-history))))
9747 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9748 (pop org-refile-history)))
9750 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9751 (progn
9752 (setq parent (match-string 1 answ)
9753 child (match-string 2 answ))
9754 (setq parent-target (or (assoc parent tbl)
9755 (assoc (concat parent "/") tbl)))
9756 (when (and parent-target
9757 (or (eq new-nodes t)
9758 (and (eq new-nodes 'confirm)
9759 (y-or-n-p (format "Create new node \"%s\"? "
9760 child)))))
9761 (org-refile-new-child parent-target child)))
9762 (error "Invalid target location")))))
9764 (defun org-refile-new-child (parent-target child)
9765 "Use refile target PARENT-TARGET to add new CHILD below it."
9766 (unless parent-target
9767 (error "Cannot find parent for new node"))
9768 (let ((file (nth 1 parent-target))
9769 (pos (nth 3 parent-target))
9770 level)
9771 (with-current-buffer (or (find-buffer-visiting file)
9772 (find-file-noselect file))
9773 (save-excursion
9774 (save-restriction
9775 (widen)
9776 (if pos
9777 (goto-char pos)
9778 (goto-char (point-max))
9779 (if (not (bolp)) (newline)))
9780 (when (looking-at outline-regexp)
9781 (setq level (funcall outline-level))
9782 (org-end-of-subtree t t))
9783 (org-back-over-empty-lines)
9784 (insert "\n" (make-string
9785 (if pos (org-get-valid-level level 1) 1) ?*)
9786 " " child "\n")
9787 (beginning-of-line 0)
9788 (list (concat (car parent-target) "/" child) file "" (point)))))))
9790 (defun org-olpath-completing-read (prompt collection &rest args)
9791 "Read an outline path like a file name."
9792 (let ((thetable collection)
9793 (org-completion-use-ido nil) ; does not work with ido.
9794 (org-completion-use-iswitchb nil)) ; or iswitchb
9795 (apply
9796 'org-icompleting-read prompt
9797 (lambda (string predicate &optional flag)
9798 (let (rtn r f (l (length string)))
9799 (cond
9800 ((eq flag nil)
9801 ;; try completion
9802 (try-completion string thetable))
9803 ((eq flag t)
9804 ;; all-completions
9805 (setq rtn (all-completions string thetable predicate))
9806 (mapcar
9807 (lambda (x)
9808 (setq r (substring x l))
9809 (if (string-match " ([^)]*)$" x)
9810 (setq f (match-string 0 x))
9811 (setq f ""))
9812 (if (string-match "/" r)
9813 (concat string (substring r 0 (match-end 0)) f)
9815 rtn))
9816 ((eq flag 'lambda)
9817 ;; exact match?
9818 (assoc string thetable)))
9820 args)))
9822 ;;;; Dynamic blocks
9824 (defun org-find-dblock (name)
9825 "Find the first dynamic block with name NAME in the buffer.
9826 If not found, stay at current position and return nil."
9827 (let (pos)
9828 (save-excursion
9829 (goto-char (point-min))
9830 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9831 nil t)
9832 (match-beginning 0))))
9833 (if pos (goto-char pos))
9834 pos))
9836 (defconst org-dblock-start-re
9837 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9838 "Matches the start line of a dynamic block, with parameters.")
9840 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9841 "Matches the end of a dynamic block.")
9843 (defun org-create-dblock (plist)
9844 "Create a dynamic block section, with parameters taken from PLIST.
9845 PLIST must contain a :name entry which is used as name of the block."
9846 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9847 (end-of-line 1)
9848 (newline))
9849 (let ((col (current-column))
9850 (name (plist-get plist :name)))
9851 (insert "#+BEGIN: " name)
9852 (while plist
9853 (if (eq (car plist) :name)
9854 (setq plist (cddr plist))
9855 (insert " " (prin1-to-string (pop plist)))))
9856 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9857 (beginning-of-line -2)))
9859 (defun org-prepare-dblock ()
9860 "Prepare dynamic block for refresh.
9861 This empties the block, puts the cursor at the insert position and returns
9862 the property list including an extra property :name with the block name."
9863 (unless (looking-at org-dblock-start-re)
9864 (error "Not at a dynamic block"))
9865 (let* ((begdel (1+ (match-end 0)))
9866 (name (org-no-properties (match-string 1)))
9867 (params (append (list :name name)
9868 (read (concat "(" (match-string 3) ")")))))
9869 (save-excursion
9870 (beginning-of-line 1)
9871 (skip-chars-forward " \t")
9872 (setq params (plist-put params :indentation-column (current-column))))
9873 (unless (re-search-forward org-dblock-end-re nil t)
9874 (error "Dynamic block not terminated"))
9875 (setq params
9876 (append params
9877 (list :content (buffer-substring
9878 begdel (match-beginning 0)))))
9879 (delete-region begdel (match-beginning 0))
9880 (goto-char begdel)
9881 (open-line 1)
9882 params))
9884 (defun org-map-dblocks (&optional command)
9885 "Apply COMMAND to all dynamic blocks in the current buffer.
9886 If COMMAND is not given, use `org-update-dblock'."
9887 (let ((cmd (or command 'org-update-dblock)))
9888 (save-excursion
9889 (goto-char (point-min))
9890 (while (re-search-forward org-dblock-start-re nil t)
9891 (goto-char (match-beginning 0))
9892 (save-excursion
9893 (condition-case nil
9894 (funcall cmd)
9895 (error (message "Error during update of dynamic block"))))
9896 (unless (re-search-forward org-dblock-end-re nil t)
9897 (error "Dynamic block not terminated"))))))
9899 (defun org-dblock-update (&optional arg)
9900 "User command for updating dynamic blocks.
9901 Update the dynamic block at point. With prefix ARG, update all dynamic
9902 blocks in the buffer."
9903 (interactive "P")
9904 (if arg
9905 (org-update-all-dblocks)
9906 (or (looking-at org-dblock-start-re)
9907 (org-beginning-of-dblock))
9908 (org-update-dblock)))
9910 (defun org-update-dblock ()
9911 "Update the dynamic block at point
9912 This means to empty the block, parse for parameters and then call
9913 the correct writing function."
9914 (save-window-excursion
9915 (let* ((pos (point))
9916 (line (org-current-line))
9917 (params (org-prepare-dblock))
9918 (name (plist-get params :name))
9919 (indent (plist-get params :indentation-column))
9920 (cmd (intern (concat "org-dblock-write:" name))))
9921 (message "Updating dynamic block `%s' at line %d..." name line)
9922 (funcall cmd params)
9923 (message "Updating dynamic block `%s' at line %d...done" name line)
9924 (goto-char pos)
9925 (when (and indent (> indent 0))
9926 (setq indent (make-string indent ?\ ))
9927 (save-excursion
9928 (org-beginning-of-dblock)
9929 (forward-line 1)
9930 (while (not (looking-at org-dblock-end-re))
9931 (insert indent)
9932 (beginning-of-line 2))
9933 (when (looking-at org-dblock-end-re)
9934 (and (looking-at "[ \t]+")
9935 (replace-match ""))
9936 (insert indent)))))))
9938 (defun org-beginning-of-dblock ()
9939 "Find the beginning of the dynamic block at point.
9940 Error if there is no such block at point."
9941 (let ((pos (point))
9942 beg)
9943 (end-of-line 1)
9944 (if (and (re-search-backward org-dblock-start-re nil t)
9945 (setq beg (match-beginning 0))
9946 (re-search-forward org-dblock-end-re nil t)
9947 (> (match-end 0) pos))
9948 (goto-char beg)
9949 (goto-char pos)
9950 (error "Not in a dynamic block"))))
9952 (defun org-update-all-dblocks ()
9953 "Update all dynamic blocks in the buffer.
9954 This function can be used in a hook."
9955 (when (org-mode-p)
9956 (org-map-dblocks 'org-update-dblock)))
9959 ;;;; Completion
9961 (defconst org-additional-option-like-keywords
9962 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9963 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9964 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9965 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9966 "BEGIN:" "END:"
9967 "ORGTBL" "TBLFM:" "TBLNAME:"
9968 "BEGIN_EXAMPLE" "END_EXAMPLE"
9969 "BEGIN_QUOTE" "END_QUOTE"
9970 "BEGIN_VERSE" "END_VERSE"
9971 "BEGIN_CENTER" "END_CENTER"
9972 "BEGIN_SRC" "END_SRC"
9973 "CATEGORY" "COLUMNS"
9974 "CAPTION" "LABEL"
9975 "SETUPFILE"
9976 "BIND"
9977 "MACRO"))
9979 (defcustom org-structure-template-alist
9981 ("s" "#+begin_src ?\n\n#+end_src"
9982 "<src lang=\"?\">\n\n</src>")
9983 ("e" "#+begin_example\n?\n#+end_example"
9984 "<example>\n?\n</example>")
9985 ("q" "#+begin_quote\n?\n#+end_quote"
9986 "<quote>\n?\n</quote>")
9987 ("v" "#+begin_verse\n?\n#+end_verse"
9988 "<verse>\n?\n/verse>")
9989 ("c" "#+begin_center\n?\n#+end_center"
9990 "<center>\n?\n/center>")
9991 ("l" "#+begin_latex\n?\n#+end_latex"
9992 "<literal style=\"latex\">\n?\n</literal>")
9993 ("L" "#+latex: "
9994 "<literal style=\"latex\">?</literal>")
9995 ("h" "#+begin_html\n?\n#+end_html"
9996 "<literal style=\"html\">\n?\n</literal>")
9997 ("H" "#+html: "
9998 "<literal style=\"html\">?</literal>")
9999 ("a" "#+begin_ascii\n?\n#+end_ascii")
10000 ("A" "#+ascii: ")
10001 ("i" "#+include %file ?"
10002 "<include file=%file markup=\"?\">")
10004 "Structure completion elements.
10005 This is a list of abbreviation keys and values. The value gets inserted
10006 if you type `<' followed by the key and then press the completion key,
10007 usually `M-TAB'. %file will be replaced by a file name after prompting
10008 for the file using completion.
10009 There are two templates for each key, the first uses the original Org syntax,
10010 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10011 the default when the /org-mtags.el/ module has been loaded. See also the
10012 variable `org-mtags-prefer-muse-templates'.
10013 This is an experimental feature, it is undecided if it is going to stay in."
10014 :group 'org-completion
10015 :type '(repeat
10016 (string :tag "Key")
10017 (string :tag "Template")
10018 (string :tag "Muse Template")))
10020 (defun org-try-structure-completion ()
10021 "Try to complete a structure template before point.
10022 This looks for strings like \"<e\" on an otherwise empty line and
10023 expands them."
10024 (let ((l (buffer-substring (point-at-bol) (point)))
10026 (when (and (looking-at "[ \t]*$")
10027 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10028 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10029 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10030 (match-beginning 1)) a)
10031 t)))
10033 (defun org-complete-expand-structure-template (start cell)
10034 "Expand a structure template."
10035 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10036 (rpl (nth (if musep 2 1) cell))
10037 (ind ""))
10038 (delete-region start (point))
10039 (when (string-match "\\`#\\+" rpl)
10040 (cond
10041 ((bolp))
10042 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10043 (setq ind (buffer-substring (point-at-bol) (point))))
10044 (t (newline))))
10045 (setq start (point))
10046 (if (string-match "%file" rpl)
10047 (setq rpl (replace-match
10048 (concat
10049 "\""
10050 (save-match-data
10051 (abbreviate-file-name (read-file-name "Include file: ")))
10052 "\"")
10053 t t rpl)))
10054 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10055 (concat "\n" ind)))
10056 (insert rpl)
10057 (if (re-search-backward "\\?" start t) (delete-char 1))))
10060 (defun org-complete (&optional arg)
10061 "Perform completion on word at point.
10062 At the beginning of a headline, this completes TODO keywords as given in
10063 `org-todo-keywords'.
10064 If the current word is preceded by a backslash, completes the TeX symbols
10065 that are supported for HTML support.
10066 If the current word is preceded by \"#+\", completes special words for
10067 setting file options.
10068 In the line after \"#+STARTUP:, complete valid keywords.\"
10069 At all other locations, this simply calls the value of
10070 `org-completion-fallback-command'."
10071 (interactive "P")
10072 (org-without-partial-completion
10073 (catch 'exit
10074 (let* ((a nil)
10075 (end (point))
10076 (beg1 (save-excursion
10077 (skip-chars-backward (org-re "[:alnum:]_@"))
10078 (point)))
10079 (beg (save-excursion
10080 (skip-chars-backward "a-zA-Z0-9_:$")
10081 (point)))
10082 (confirm (lambda (x) (stringp (car x))))
10083 (searchhead (equal (char-before beg) ?*))
10084 (struct
10085 (when (and (member (char-before beg1) '(?. ?<))
10086 (setq a (assoc (buffer-substring beg1 (point))
10087 org-structure-template-alist)))
10088 (org-complete-expand-structure-template (1- beg1) a)
10089 (throw 'exit t)))
10090 (tag (and (equal (char-before beg1) ?:)
10091 (equal (char-after (point-at-bol)) ?*)))
10092 (prop (and (equal (char-before beg1) ?:)
10093 (not (equal (char-after (point-at-bol)) ?*))))
10094 (texp (equal (char-before beg) ?\\))
10095 (link (equal (char-before beg) ?\[))
10096 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10097 beg)
10098 "#+"))
10099 (startup (string-match "^#\\+STARTUP:.*"
10100 (buffer-substring (point-at-bol) (point))))
10101 (completion-ignore-case opt)
10102 (type nil)
10103 (tbl nil)
10104 (table (cond
10105 (opt
10106 (setq type :opt)
10107 (require 'org-exp)
10108 (append
10109 (delq nil
10110 (mapcar
10111 (lambda (x)
10112 (if (string-match
10113 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10114 (cons (match-string 2 x)
10115 (match-string 1 x))))
10116 (org-split-string (org-get-current-options) "\n")))
10117 (mapcar 'list org-additional-option-like-keywords)))
10118 (startup
10119 (setq type :startup)
10120 org-startup-options)
10121 (link (append org-link-abbrev-alist-local
10122 org-link-abbrev-alist))
10123 (texp
10124 (setq type :tex)
10125 (append org-entities-user org-entities))
10126 ((string-match "\\`\\*+[ \t]+\\'"
10127 (buffer-substring (point-at-bol) beg))
10128 (setq type :todo)
10129 (mapcar 'list org-todo-keywords-1))
10130 (searchhead
10131 (setq type :searchhead)
10132 (save-excursion
10133 (goto-char (point-min))
10134 (while (re-search-forward org-todo-line-regexp nil t)
10135 (push (list
10136 (org-make-org-heading-search-string
10137 (match-string 3) t))
10138 tbl)))
10139 tbl)
10140 (tag (setq type :tag beg beg1)
10141 (or org-tag-alist (org-get-buffer-tags)))
10142 (prop (setq type :prop beg beg1)
10143 (mapcar 'list (org-buffer-property-keys nil t t)))
10144 (t (progn
10145 (call-interactively org-completion-fallback-command)
10146 (throw 'exit nil)))))
10147 (pattern (buffer-substring-no-properties beg end))
10148 (completion (try-completion pattern table confirm)))
10149 (cond ((eq completion t)
10150 (if (not (assoc (upcase pattern) table))
10151 (message "Already complete")
10152 (if (and (equal type :opt)
10153 (not (member (car (assoc (upcase pattern) table))
10154 org-additional-option-like-keywords)))
10155 (insert (substring (cdr (assoc (upcase pattern) table))
10156 (length pattern)))
10157 (if (memq type '(:tag :prop)) (insert ":")))))
10158 ((null completion)
10159 (message "Can't find completion for \"%s\"" pattern)
10160 (ding))
10161 ((not (string= pattern completion))
10162 (delete-region beg end)
10163 (if (string-match " +$" completion)
10164 (setq completion (replace-match "" t t completion)))
10165 (insert completion)
10166 (if (get-buffer-window "*Completions*")
10167 (delete-window (get-buffer-window "*Completions*")))
10168 (if (assoc completion table)
10169 (if (eq type :todo) (insert " ")
10170 (if (memq type '(:tag :prop)) (insert ":"))))
10171 (if (and (equal type :opt) (assoc completion table))
10172 (message "%s" (substitute-command-keys
10173 "Press \\[org-complete] again to insert example settings"))))
10175 (message "Making completion list...")
10176 (let ((list (sort (all-completions pattern table confirm)
10177 'string<)))
10178 (with-output-to-temp-buffer "*Completions*"
10179 (condition-case nil
10180 ;; Protection needed for XEmacs and emacs 21
10181 (display-completion-list list pattern)
10182 (error (display-completion-list list)))))
10183 (message "Making completion list...%s" "done")))))))
10185 ;;;; TODO, DEADLINE, Comments
10187 (defun org-toggle-comment ()
10188 "Change the COMMENT state of an entry."
10189 (interactive)
10190 (save-excursion
10191 (org-back-to-heading)
10192 (let (case-fold-search)
10193 (if (looking-at (concat outline-regexp
10194 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10195 (replace-match "" t t nil 1)
10196 (if (looking-at outline-regexp)
10197 (progn
10198 (goto-char (match-end 0))
10199 (insert org-comment-string " ")))))))
10201 (defvar org-last-todo-state-is-todo nil
10202 "This is non-nil when the last TODO state change led to a TODO state.
10203 If the last change removed the TODO tag or switched to DONE, then
10204 this is nil.")
10206 (defvar org-setting-tags nil) ; dynamically skipped
10208 (defun org-parse-local-options (string var)
10209 "Parse STRING for startup setting relevant for variable VAR."
10210 (let ((rtn (symbol-value var))
10211 e opts)
10212 (save-match-data
10213 (if (or (not string) (not (string-match "\\S-" string)))
10215 (setq opts (delq nil (mapcar (lambda (x)
10216 (setq e (assoc x org-startup-options))
10217 (if (eq (nth 1 e) var) e nil))
10218 (org-split-string string "[ \t]+"))))
10219 (if (not opts)
10221 (setq rtn nil)
10222 (while (setq e (pop opts))
10223 (if (not (nth 3 e))
10224 (setq rtn (nth 2 e))
10225 (if (not (listp rtn)) (setq rtn nil))
10226 (push (nth 2 e) rtn)))
10227 rtn)))))
10229 (defvar org-todo-setup-filter-hook nil
10230 "Hook for functions that pre-filter todo specs.
10232 Each function takes a todo spec and returns either `nil' or the spec
10233 transformed into canonical form." )
10235 (defvar org-todo-get-default-hook nil
10236 "Hook for functions that get a default item for todo.
10238 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10239 `nil' or a string to be used for the todo mark." )
10241 (defvar org-agenda-headline-snapshot-before-repeat)
10243 (defun org-todo (&optional arg)
10244 "Change the TODO state of an item.
10245 The state of an item is given by a keyword at the start of the heading,
10246 like
10247 *** TODO Write paper
10248 *** DONE Call mom
10250 The different keywords are specified in the variable `org-todo-keywords'.
10251 By default the available states are \"TODO\" and \"DONE\".
10252 So for this example: when the item starts with TODO, it is changed to DONE.
10253 When it starts with DONE, the DONE is removed. And when neither TODO nor
10254 DONE are present, add TODO at the beginning of the heading.
10256 With C-u prefix arg, use completion to determine the new state.
10257 With numeric prefix arg, switch to that state.
10258 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10259 With a triple C-u prefix, circumvent any state blocking.
10261 For calling through lisp, arg is also interpreted in the following way:
10262 'none -> empty state
10263 \"\"(empty string) -> switch to empty state
10264 'done -> switch to DONE
10265 'nextset -> switch to the next set of keywords
10266 'previousset -> switch to the previous set of keywords
10267 \"WAITING\" -> switch to the specified keyword, but only if it
10268 really is a member of `org-todo-keywords'."
10269 (interactive "P")
10270 (if (equal arg '(16)) (setq arg 'nextset))
10271 (let ((org-blocker-hook org-blocker-hook)
10272 (case-fold-search nil))
10273 (when (equal arg '(64))
10274 (setq arg nil org-blocker-hook nil))
10275 (when (and org-blocker-hook
10276 (or org-inhibit-blocking
10277 (org-entry-get nil "NOBLOCKING")))
10278 (setq org-blocker-hook nil))
10279 (save-excursion
10280 (catch 'exit
10281 (org-back-to-heading t)
10282 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10283 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10284 (looking-at " *"))
10285 (let* ((match-data (match-data))
10286 (startpos (point-at-bol))
10287 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10288 (org-log-done org-log-done)
10289 (org-log-repeat org-log-repeat)
10290 (org-todo-log-states org-todo-log-states)
10291 (this (match-string 1))
10292 (hl-pos (match-beginning 0))
10293 (head (org-get-todo-sequence-head this))
10294 (ass (assoc head org-todo-kwd-alist))
10295 (interpret (nth 1 ass))
10296 (done-word (nth 3 ass))
10297 (final-done-word (nth 4 ass))
10298 (last-state (or this ""))
10299 (completion-ignore-case t)
10300 (member (member this org-todo-keywords-1))
10301 (tail (cdr member))
10302 (state (cond
10303 ((and org-todo-key-trigger
10304 (or (and (equal arg '(4))
10305 (eq org-use-fast-todo-selection 'prefix))
10306 (and (not arg) org-use-fast-todo-selection
10307 (not (eq org-use-fast-todo-selection
10308 'prefix)))))
10309 ;; Use fast selection
10310 (org-fast-todo-selection))
10311 ((and (equal arg '(4))
10312 (or (not org-use-fast-todo-selection)
10313 (not org-todo-key-trigger)))
10314 ;; Read a state with completion
10315 (org-icompleting-read
10316 "State: " (mapcar (lambda(x) (list x))
10317 org-todo-keywords-1)
10318 nil t))
10319 ((eq arg 'right)
10320 (if this
10321 (if tail (car tail) nil)
10322 (car org-todo-keywords-1)))
10323 ((eq arg 'left)
10324 (if (equal member org-todo-keywords-1)
10326 (if this
10327 (nth (- (length org-todo-keywords-1)
10328 (length tail) 2)
10329 org-todo-keywords-1)
10330 (org-last org-todo-keywords-1))))
10331 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10332 (setq arg nil))) ; hack to fall back to cycling
10333 (arg
10334 ;; user or caller requests a specific state
10335 (cond
10336 ((equal arg "") nil)
10337 ((eq arg 'none) nil)
10338 ((eq arg 'done) (or done-word (car org-done-keywords)))
10339 ((eq arg 'nextset)
10340 (or (car (cdr (member head org-todo-heads)))
10341 (car org-todo-heads)))
10342 ((eq arg 'previousset)
10343 (let ((org-todo-heads (reverse org-todo-heads)))
10344 (or (car (cdr (member head org-todo-heads)))
10345 (car org-todo-heads))))
10346 ((car (member arg org-todo-keywords-1)))
10347 ((stringp arg)
10348 (error "State `%s' not valid in this file" arg))
10349 ((nth (1- (prefix-numeric-value arg))
10350 org-todo-keywords-1))))
10351 ((null member) (or head (car org-todo-keywords-1)))
10352 ((equal this final-done-word) nil) ;; -> make empty
10353 ((null tail) nil) ;; -> first entry
10354 ((memq interpret '(type priority))
10355 (if (eq this-command last-command)
10356 (car tail)
10357 (if (> (length tail) 0)
10358 (or done-word (car org-done-keywords))
10359 nil)))
10361 (car tail))))
10362 (state (or
10363 (run-hook-with-args-until-success
10364 'org-todo-get-default-hook state last-state)
10365 state))
10366 (next (if state (concat " " state " ") " "))
10367 (change-plist (list :type 'todo-state-change :from this :to state
10368 :position startpos))
10369 dolog now-done-p)
10370 (when org-blocker-hook
10371 (setq org-last-todo-state-is-todo
10372 (not (member this org-done-keywords)))
10373 (unless (save-excursion
10374 (save-match-data
10375 (run-hook-with-args-until-failure
10376 'org-blocker-hook change-plist)))
10377 (if (interactive-p)
10378 (error "TODO state change from %s to %s blocked" this state)
10379 ;; fail silently
10380 (message "TODO state change from %s to %s blocked" this state)
10381 (throw 'exit nil))))
10382 (store-match-data match-data)
10383 (replace-match next t t)
10384 (unless (pos-visible-in-window-p hl-pos)
10385 (message "TODO state changed to %s" (org-trim next)))
10386 (unless head
10387 (setq head (org-get-todo-sequence-head state)
10388 ass (assoc head org-todo-kwd-alist)
10389 interpret (nth 1 ass)
10390 done-word (nth 3 ass)
10391 final-done-word (nth 4 ass)))
10392 (when (memq arg '(nextset previousset))
10393 (message "Keyword-Set %d/%d: %s"
10394 (- (length org-todo-sets) -1
10395 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10396 (length org-todo-sets)
10397 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10398 (setq org-last-todo-state-is-todo
10399 (not (member state org-done-keywords)))
10400 (setq now-done-p (and (member state org-done-keywords)
10401 (not (member this org-done-keywords))))
10402 (and logging (org-local-logging logging))
10403 (when (and (or org-todo-log-states org-log-done)
10404 (not (eq org-inhibit-logging t))
10405 (not (memq arg '(nextset previousset))))
10406 ;; we need to look at recording a time and note
10407 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10408 (nth 2 (assoc this org-todo-log-states))))
10409 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10410 (setq dolog 'time))
10411 (when (and state
10412 (member state org-not-done-keywords)
10413 (not (member this org-not-done-keywords)))
10414 ;; This is now a todo state and was not one before
10415 ;; If there was a CLOSED time stamp, get rid of it.
10416 (org-add-planning-info nil nil 'closed))
10417 (when (and now-done-p org-log-done)
10418 ;; It is now done, and it was not done before
10419 (org-add-planning-info 'closed (org-current-time))
10420 (if (and (not dolog) (eq 'note org-log-done))
10421 (org-add-log-setup 'done state this 'findpos 'note)))
10422 (when (and state dolog)
10423 ;; This is a non-nil state, and we need to log it
10424 (org-add-log-setup 'state state this 'findpos dolog)))
10425 ;; Fixup tag positioning
10426 (org-todo-trigger-tag-changes state)
10427 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10428 (when org-provide-todo-statistics
10429 (org-update-parent-todo-statistics))
10430 (run-hooks 'org-after-todo-state-change-hook)
10431 (if (and arg (not (member state org-done-keywords)))
10432 (setq head (org-get-todo-sequence-head state)))
10433 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10434 ;; Do we need to trigger a repeat?
10435 (when now-done-p
10436 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10437 ;; This is for the agenda, take a snapshot of the headline.
10438 (save-match-data
10439 (setq org-agenda-headline-snapshot-before-repeat
10440 (org-get-heading))))
10441 (org-auto-repeat-maybe state))
10442 ;; Fixup cursor location if close to the keyword
10443 (if (and (outline-on-heading-p)
10444 (not (bolp))
10445 (save-excursion (beginning-of-line 1)
10446 (looking-at org-todo-line-regexp))
10447 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10448 (progn
10449 (goto-char (or (match-end 2) (match-end 1)))
10450 (and (looking-at " ") (just-one-space))))
10451 (when org-trigger-hook
10452 (save-excursion
10453 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10455 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10456 "Block turning an entry into a TODO, using the hierarchy.
10457 This checks whether the current task should be blocked from state
10458 changes. Such blocking occurs when:
10460 1. The task has children which are not all in a completed state.
10462 2. A task has a parent with the property :ORDERED:, and there
10463 are siblings prior to the current task with incomplete
10464 status.
10466 3. The parent of the task is blocked because it has siblings that should
10467 be done first, or is child of a block grandparent TODO entry."
10469 (if (not org-enforce-todo-dependencies)
10470 t ; if locally turned off don't block
10471 (catch 'dont-block
10472 ;; If this is not a todo state change, or if this entry is already DONE,
10473 ;; do not block
10474 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10475 (member (plist-get change-plist :from)
10476 (cons 'done org-done-keywords))
10477 (member (plist-get change-plist :to)
10478 (cons 'todo org-not-done-keywords))
10479 (not (plist-get change-plist :to)))
10480 (throw 'dont-block t))
10481 ;; If this task has children, and any are undone, it's blocked
10482 (save-excursion
10483 (org-back-to-heading t)
10484 (let ((this-level (funcall outline-level)))
10485 (outline-next-heading)
10486 (let ((child-level (funcall outline-level)))
10487 (while (and (not (eobp))
10488 (> child-level this-level))
10489 ;; this todo has children, check whether they are all
10490 ;; completed
10491 (if (and (not (org-entry-is-done-p))
10492 (org-entry-is-todo-p))
10493 (throw 'dont-block nil))
10494 (outline-next-heading)
10495 (setq child-level (funcall outline-level))))))
10496 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10497 ;; any previous siblings are undone, it's blocked
10498 (save-excursion
10499 (org-back-to-heading t)
10500 (let* ((pos (point))
10501 (parent-pos (and (org-up-heading-safe) (point))))
10502 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10503 (when (and (org-entry-get (point) "ORDERED")
10504 (forward-line 1)
10505 (re-search-forward org-not-done-heading-regexp pos t))
10506 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10507 ;; Search further up the hierarchy, to see if an anchestor is blocked
10508 (while t
10509 (goto-char parent-pos)
10510 (if (not (looking-at org-not-done-heading-regexp))
10511 (throw 'dont-block t)) ; do not block, parent is not a TODO
10512 (setq pos (point))
10513 (setq parent-pos (and (org-up-heading-safe) (point)))
10514 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10515 (when (and (org-entry-get (point) "ORDERED")
10516 (forward-line 1)
10517 (re-search-forward org-not-done-heading-regexp pos t))
10518 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10520 (defcustom org-track-ordered-property-with-tag nil
10521 "Should the ORDERED property also be shown as a tag?
10522 The ORDERED property decides if an entry should require subtasks to be
10523 completed in sequence. Since a property is not very visible, setting
10524 this option means that toggling the ORDERED property with the command
10525 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10526 not relevant for the behavior, but it makes things more visible.
10528 Note that toggling the tag with tags commands will not change the property
10529 and therefore not influence behavior!
10531 This can be t, meaning the tag ORDERED should be used, It can also be a
10532 string to select a different tag for this task."
10533 :group 'org-todo
10534 :type '(choice
10535 (const :tag "No tracking" nil)
10536 (const :tag "Track with ORDERED tag" t)
10537 (string :tag "Use other tag")))
10539 (defun org-toggle-ordered-property ()
10540 "Toggle the ORDERED property of the current entry.
10541 For better visibility, you can track the value of this property with a tag.
10542 See variable `org-track-ordered-property-with-tag'."
10543 (interactive)
10544 (let* ((t1 org-track-ordered-property-with-tag)
10545 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10546 (save-excursion
10547 (org-back-to-heading)
10548 (if (org-entry-get nil "ORDERED")
10549 (progn
10550 (org-delete-property "ORDERED")
10551 (and tag (org-toggle-tag tag 'off))
10552 (message "Subtasks can be completed in arbitrary order"))
10553 (org-entry-put nil "ORDERED" "t")
10554 (and tag (org-toggle-tag tag 'on))
10555 (message "Subtasks must be completed in sequence")))))
10557 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10558 (defun org-block-todo-from-checkboxes (change-plist)
10559 "Block turning an entry into a TODO, using checkboxes.
10560 This checks whether the current task should be blocked from state
10561 changes because there are unchecked boxes in this entry."
10562 (if (not org-enforce-todo-checkbox-dependencies)
10563 t ; if locally turned off don't block
10564 (catch 'dont-block
10565 ;; If this is not a todo state change, or if this entry is already DONE,
10566 ;; do not block
10567 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10568 (member (plist-get change-plist :from)
10569 (cons 'done org-done-keywords))
10570 (member (plist-get change-plist :to)
10571 (cons 'todo org-not-done-keywords))
10572 (not (plist-get change-plist :to)))
10573 (throw 'dont-block t))
10574 ;; If this task has checkboxes that are not checked, it's blocked
10575 (save-excursion
10576 (org-back-to-heading t)
10577 (let ((beg (point)) end)
10578 (outline-next-heading)
10579 (setq end (point))
10580 (goto-char beg)
10581 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10582 end t)
10583 (progn
10584 (if (boundp 'org-blocked-by-checkboxes)
10585 (setq org-blocked-by-checkboxes t))
10586 (throw 'dont-block nil)))))
10587 t))) ; do not block
10589 (defun org-entry-blocked-p ()
10590 "Is the current entry blocked?"
10591 (if (org-entry-get nil "NOBLOCKING")
10592 nil ;; Never block this entry
10593 (not
10594 (run-hook-with-args-until-failure
10595 'org-blocker-hook
10596 (list :type 'todo-state-change
10597 :position (point)
10598 :from 'todo
10599 :to 'done)))))
10601 (defun org-update-statistics-cookies (all)
10602 "Update the statistics cookie, either from TODO or from checkboxes.
10603 This should be called with the cursor in a line with a statistics cookie."
10604 (interactive "P")
10605 (if all
10606 (progn
10607 (org-update-checkbox-count 'all)
10608 (org-map-entries 'org-update-parent-todo-statistics))
10609 (if (not (org-on-heading-p))
10610 (org-update-checkbox-count)
10611 (let ((pos (move-marker (make-marker) (point)))
10612 end l1 l2)
10613 (ignore-errors (org-back-to-heading t))
10614 (if (not (org-on-heading-p))
10615 (org-update-checkbox-count)
10616 (setq l1 (org-outline-level))
10617 (setq end (save-excursion
10618 (outline-next-heading)
10619 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10620 (point)))
10621 (if (and (save-excursion
10622 (re-search-forward
10623 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10624 (not (save-excursion (re-search-forward
10625 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10626 (org-update-checkbox-count)
10627 (if (and l2 (> l2 l1))
10628 (progn
10629 (goto-char end)
10630 (org-update-parent-todo-statistics))
10631 (goto-char pos)
10632 (beginning-of-line 1)
10633 (while (re-search-forward
10634 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10635 (point-at-eol) t)
10636 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10637 (goto-char pos)
10638 (move-marker pos nil)))))
10640 (defvar org-entry-property-inherited-from) ;; defined below
10641 (defun org-update-parent-todo-statistics ()
10642 "Update any statistics cookie in the parent of the current headline.
10643 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10644 the entire subtree and this will travel up the hierarchy and update
10645 statistics everywhere."
10646 (interactive)
10647 (let* ((lim 0) prop
10648 (recursive (or (not org-hierarchical-todo-statistics)
10649 (string-match
10650 "\\<recursive\\>"
10651 (or (setq prop (org-entry-get
10652 nil "COOKIE_DATA" 'inherit)) ""))))
10653 (lim (or (and prop (marker-position
10654 org-entry-property-inherited-from))
10655 lim))
10656 (first t)
10657 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10658 level ltoggle l1 new ndel
10659 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10660 (catch 'exit
10661 (save-excursion
10662 (beginning-of-line 1)
10663 (if (org-at-heading-p)
10664 (setq ltoggle (funcall outline-level))
10665 (error "This should not happen"))
10666 (while (and (setq level (org-up-heading-safe))
10667 (or recursive first)
10668 (>= (point) lim))
10669 (setq first nil cookie-present nil)
10670 (unless (and level
10671 (not (string-match
10672 "\\<checkbox\\>"
10673 (downcase
10674 (or (org-entry-get
10675 nil "COOKIE_DATA")
10676 "")))))
10677 (throw 'exit nil))
10678 (while (re-search-forward box-re (point-at-eol) t)
10679 (setq cnt-all 0 cnt-done 0 cookie-present t)
10680 (setq is-percent (match-end 2))
10681 (save-match-data
10682 (unless (outline-next-heading) (throw 'exit nil))
10683 (while (and (looking-at org-complex-heading-regexp)
10684 (> (setq l1 (length (match-string 1))) level))
10685 (setq kwd (and (or recursive (= l1 ltoggle))
10686 (match-string 2)))
10687 (if (or (eq org-provide-todo-statistics 'all-headlines)
10688 (and (listp org-provide-todo-statistics)
10689 (or (member kwd org-provide-todo-statistics)
10690 (member kwd org-done-keywords))))
10691 (setq cnt-all (1+ cnt-all))
10692 (if (eq org-provide-todo-statistics t)
10693 (and kwd (setq cnt-all (1+ cnt-all)))))
10694 (and (member kwd org-done-keywords)
10695 (setq cnt-done (1+ cnt-done)))
10696 (outline-next-heading)))
10697 (setq new
10698 (if is-percent
10699 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10700 (format "[%d/%d]" cnt-done cnt-all))
10701 ndel (- (match-end 0) (match-beginning 0)))
10702 (goto-char (match-beginning 0))
10703 (insert new)
10704 (delete-region (point) (+ (point) ndel)))
10705 (when cookie-present
10706 (run-hook-with-args 'org-after-todo-statistics-hook
10707 cnt-done (- cnt-all cnt-done))))))
10708 (run-hooks 'org-todo-statistics-hook)))
10710 (defvar org-after-todo-statistics-hook nil
10711 "Hook that is called after a TODO statistics cookie has been updated.
10712 Each function is called with two arguments: the number of not-done entries
10713 and the number of done entries.
10715 For example, the following function, when added to this hook, will switch
10716 an entry to DONE when all children are done, and back to TODO when new
10717 entries are set to a TODO status. Note that this hook is only called
10718 when there is a statistics cookie in the headline!
10720 (defun org-summary-todo (n-done n-not-done)
10721 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10722 (let (org-log-done org-log-states) ; turn off logging
10723 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10726 (defvar org-todo-statistics-hook nil
10727 "Hook that is run whenever Org thinks TODO statistics should be updated.
10728 This hook runs even if there is no statistics cookie present, in which case
10729 `org-after-todo-statistics-hook' would not run.")
10731 (defun org-todo-trigger-tag-changes (state)
10732 "Apply the changes defined in `org-todo-state-tags-triggers'."
10733 (let ((l org-todo-state-tags-triggers)
10734 changes)
10735 (when (or (not state) (equal state ""))
10736 (setq changes (append changes (cdr (assoc "" l)))))
10737 (when (and (stringp state) (> (length state) 0))
10738 (setq changes (append changes (cdr (assoc state l)))))
10739 (when (member state org-not-done-keywords)
10740 (setq changes (append changes (cdr (assoc 'todo l)))))
10741 (when (member state org-done-keywords)
10742 (setq changes (append changes (cdr (assoc 'done l)))))
10743 (dolist (c changes)
10744 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10746 (defun org-local-logging (value)
10747 "Get logging settings from a property VALUE."
10748 (let* (words w a)
10749 ;; directly set the variables, they are already local.
10750 (setq org-log-done nil
10751 org-log-repeat nil
10752 org-todo-log-states nil)
10753 (setq words (org-split-string value))
10754 (while (setq w (pop words))
10755 (cond
10756 ((setq a (assoc w org-startup-options))
10757 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10758 (set (nth 1 a) (nth 2 a))))
10759 ((setq a (org-extract-log-state-settings w))
10760 (and (member (car a) org-todo-keywords-1)
10761 (push a org-todo-log-states)))))))
10763 (defun org-get-todo-sequence-head (kwd)
10764 "Return the head of the TODO sequence to which KWD belongs.
10765 If KWD is not set, check if there is a text property remembering the
10766 right sequence."
10767 (let (p)
10768 (cond
10769 ((not kwd)
10770 (or (get-text-property (point-at-bol) 'org-todo-head)
10771 (progn
10772 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10773 nil (point-at-eol)))
10774 (get-text-property p 'org-todo-head))))
10775 ((not (member kwd org-todo-keywords-1))
10776 (car org-todo-keywords-1))
10777 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10779 (defun org-fast-todo-selection ()
10780 "Fast TODO keyword selection with single keys.
10781 Returns the new TODO keyword, or nil if no state change should occur."
10782 (let* ((fulltable org-todo-key-alist)
10783 (done-keywords org-done-keywords) ;; needed for the faces.
10784 (maxlen (apply 'max (mapcar
10785 (lambda (x)
10786 (if (stringp (car x)) (string-width (car x)) 0))
10787 fulltable)))
10788 (expert nil)
10789 (fwidth (+ maxlen 3 1 3))
10790 (ncol (/ (- (window-width) 4) fwidth))
10791 tg cnt e c tbl
10792 groups ingroup)
10793 (save-excursion
10794 (save-window-excursion
10795 (if expert
10796 (set-buffer (get-buffer-create " *Org todo*"))
10797 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10798 (erase-buffer)
10799 (org-set-local 'org-done-keywords done-keywords)
10800 (setq tbl fulltable cnt 0)
10801 (while (setq e (pop tbl))
10802 (cond
10803 ((equal e '(:startgroup))
10804 (push '() groups) (setq ingroup t)
10805 (when (not (= cnt 0))
10806 (setq cnt 0)
10807 (insert "\n"))
10808 (insert "{ "))
10809 ((equal e '(:endgroup))
10810 (setq ingroup nil cnt 0)
10811 (insert "}\n"))
10812 ((equal e '(:newline))
10813 (when (not (= cnt 0))
10814 (setq cnt 0)
10815 (insert "\n")
10816 (setq e (car tbl))
10817 (while (equal (car tbl) '(:newline))
10818 (insert "\n")
10819 (setq tbl (cdr tbl)))))
10821 (setq tg (car e) c (cdr e))
10822 (if ingroup (push tg (car groups)))
10823 (setq tg (org-add-props tg nil 'face
10824 (org-get-todo-face tg)))
10825 (if (and (= cnt 0) (not ingroup)) (insert " "))
10826 (insert "[" c "] " tg (make-string
10827 (- fwidth 4 (length tg)) ?\ ))
10828 (when (= (setq cnt (1+ cnt)) ncol)
10829 (insert "\n")
10830 (if ingroup (insert " "))
10831 (setq cnt 0)))))
10832 (insert "\n")
10833 (goto-char (point-min))
10834 (if (not expert) (org-fit-window-to-buffer))
10835 (message "[a-z..]:Set [SPC]:clear")
10836 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10837 (cond
10838 ((or (= c ?\C-g)
10839 (and (= c ?q) (not (rassoc c fulltable))))
10840 (setq quit-flag t))
10841 ((= c ?\ ) nil)
10842 ((setq e (rassoc c fulltable) tg (car e))
10844 (t (setq quit-flag t)))))))
10846 (defun org-entry-is-todo-p ()
10847 (member (org-get-todo-state) org-not-done-keywords))
10849 (defun org-entry-is-done-p ()
10850 (member (org-get-todo-state) org-done-keywords))
10852 (defun org-get-todo-state ()
10853 (save-excursion
10854 (org-back-to-heading t)
10855 (and (looking-at org-todo-line-regexp)
10856 (match-end 2)
10857 (match-string 2))))
10859 (defun org-at-date-range-p (&optional inactive-ok)
10860 "Is the cursor inside a date range?"
10861 (interactive)
10862 (save-excursion
10863 (catch 'exit
10864 (let ((pos (point)))
10865 (skip-chars-backward "^[<\r\n")
10866 (skip-chars-backward "<[")
10867 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10868 (>= (match-end 0) pos)
10869 (throw 'exit t))
10870 (skip-chars-backward "^<[\r\n")
10871 (skip-chars-backward "<[")
10872 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10873 (>= (match-end 0) pos)
10874 (throw 'exit t)))
10875 nil)))
10877 (defun org-get-repeat (&optional tagline)
10878 "Check if there is a deadline/schedule with repeater in this entry."
10879 (save-match-data
10880 (save-excursion
10881 (org-back-to-heading t)
10882 (and (re-search-forward (if tagline
10883 (concat tagline "\\s-*" org-repeat-re)
10884 org-repeat-re)
10885 (org-entry-end-position) t)
10886 (match-string-no-properties 1)))))
10888 (defvar org-last-changed-timestamp)
10889 (defvar org-last-inserted-timestamp)
10890 (defvar org-log-post-message)
10891 (defvar org-log-note-purpose)
10892 (defvar org-log-note-how)
10893 (defvar org-log-note-extra)
10894 (defun org-auto-repeat-maybe (done-word)
10895 "Check if the current headline contains a repeated deadline/schedule.
10896 If yes, set TODO state back to what it was and change the base date
10897 of repeating deadline/scheduled time stamps to new date.
10898 This function is run automatically after each state change to a DONE state."
10899 ;; last-state is dynamically scoped into this function
10900 (let* ((repeat (org-get-repeat))
10901 (aa (assoc last-state org-todo-kwd-alist))
10902 (interpret (nth 1 aa))
10903 (head (nth 2 aa))
10904 (whata '(("d" . day) ("m" . month) ("y" . year)))
10905 (msg "Entry repeats: ")
10906 (org-log-done nil)
10907 (org-todo-log-states nil)
10908 (nshiftmax 10) (nshift 0)
10909 re type n what ts time to-state)
10910 (when repeat
10911 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10912 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
10913 org-todo-repeat-to-state))
10914 (unless (and to-state (member to-state org-todo-keywords-1))
10915 (setq to-state (if (eq interpret 'type) last-state head)))
10916 (org-todo to-state)
10917 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
10918 (org-entry-put nil "LAST_REPEAT" (format-time-string
10919 (org-time-stamp-format t t))))
10920 (when org-log-repeat
10921 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10922 (memq 'org-add-log-note post-command-hook))
10923 ;; OK, we are already setup for some record
10924 (if (eq org-log-repeat 'note)
10925 ;; make sure we take a note, not only a time stamp
10926 (setq org-log-note-how 'note))
10927 ;; Set up for taking a record
10928 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10929 last-state
10930 'findpos org-log-repeat)))
10931 (org-back-to-heading t)
10932 (org-add-planning-info nil nil 'closed)
10933 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10934 org-deadline-time-regexp "\\)\\|\\("
10935 org-ts-regexp "\\)"))
10936 (while (re-search-forward
10937 re (save-excursion (outline-next-heading) (point)) t)
10938 (setq type (if (match-end 1) org-scheduled-string
10939 (if (match-end 3) org-deadline-string "Plain:"))
10940 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10941 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10942 (setq n (string-to-number (match-string 2 ts))
10943 what (match-string 3 ts))
10944 (if (equal what "w") (setq n (* n 7) what "d"))
10945 ;; Preparation, see if we need to modify the start date for the change
10946 (when (match-end 1)
10947 (setq time (save-match-data (org-time-string-to-time ts)))
10948 (cond
10949 ((equal (match-string 1 ts) ".")
10950 ;; Shift starting date to today
10951 (org-timestamp-change
10952 (- (time-to-days (current-time)) (time-to-days time))
10953 'day))
10954 ((equal (match-string 1 ts) "+")
10955 (while (or (= nshift 0)
10956 (<= (time-to-days time) (time-to-days (current-time))))
10957 (when (= (incf nshift) nshiftmax)
10958 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10959 (error "Abort")))
10960 (org-timestamp-change n (cdr (assoc what whata)))
10961 (org-at-timestamp-p t)
10962 (setq ts (match-string 1))
10963 (setq time (save-match-data (org-time-string-to-time ts))))
10964 (org-timestamp-change (- n) (cdr (assoc what whata)))
10965 ;; rematch, so that we have everything in place for the real shift
10966 (org-at-timestamp-p t)
10967 (setq ts (match-string 1))
10968 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10969 (org-timestamp-change n (cdr (assoc what whata)))
10970 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10971 (setq org-log-post-message msg)
10972 (message "%s" msg))))
10974 (defun org-show-todo-tree (arg)
10975 "Make a compact tree which shows all headlines marked with TODO.
10976 The tree will show the lines where the regexp matches, and all higher
10977 headlines above the match.
10978 With a \\[universal-argument] prefix, prompt for a regexp to match.
10979 With a numeric prefix N, construct a sparse tree for the Nth element
10980 of `org-todo-keywords-1'."
10981 (interactive "P")
10982 (let ((case-fold-search nil)
10983 (kwd-re
10984 (cond ((null arg) org-not-done-regexp)
10985 ((equal arg '(4))
10986 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10987 (mapcar 'list org-todo-keywords-1))))
10988 (concat "\\("
10989 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10990 "\\)\\>")))
10991 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10992 (regexp-quote (nth (1- (prefix-numeric-value arg))
10993 org-todo-keywords-1)))
10994 (t (error "Invalid prefix argument: %s" arg)))))
10995 (message "%d TODO entries found"
10996 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10998 (defun org-deadline (&optional remove time)
10999 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11000 With argument REMOVE, remove any deadline from the item.
11001 When TIME is set, it should be an internal time specification, and the
11002 scheduling will use the corresponding date."
11003 (interactive "P")
11004 (let* ((old-date (org-entry-get nil "DEADLINE"))
11005 (repeater (and old-date
11006 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11007 (match-string 1 old-date))))
11008 (if remove
11009 (progn
11010 (when (and old-date org-log-redeadline)
11011 (org-add-log-setup 'deldeadline nil old-date 'findpos
11012 org-log-redeadline))
11013 (org-remove-timestamp-with-keyword org-deadline-string)
11014 (message "Item no longer has a deadline."))
11015 (org-add-planning-info 'deadline time 'closed)
11016 (when (and old-date org-log-redeadline
11017 (not (equal old-date
11018 (substring org-last-inserted-timestamp 1 -1))))
11019 (org-add-log-setup 'redeadline nil old-date 'findpos
11020 org-log-redeadline))
11021 (when repeater
11022 (save-excursion
11023 (org-back-to-heading t)
11024 (when (re-search-forward (concat org-deadline-string " "
11025 org-last-inserted-timestamp)
11026 (save-excursion
11027 (outline-next-heading) (point)) t)
11028 (goto-char (1- (match-end 0)))
11029 (insert " " repeater)
11030 (setq org-last-inserted-timestamp
11031 (concat (substring org-last-inserted-timestamp 0 -1)
11032 " " repeater
11033 (substring org-last-inserted-timestamp -1))))))
11034 (message "Deadline on %s" org-last-inserted-timestamp))))
11036 (defun org-schedule (&optional remove time)
11037 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11038 With argument REMOVE, remove any scheduling date from the item.
11039 When TIME is set, it should be an internal time specification, and the
11040 scheduling will use the corresponding date."
11041 (interactive "P")
11042 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11043 (repeater (and old-date
11044 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11045 (match-string 1 old-date))))
11046 (if remove
11047 (progn
11048 (when (and old-date org-log-reschedule)
11049 (org-add-log-setup 'delschedule nil old-date 'findpos
11050 org-log-reschedule))
11051 (org-remove-timestamp-with-keyword org-scheduled-string)
11052 (message "Item is no longer scheduled."))
11053 (org-add-planning-info 'scheduled time 'closed)
11054 (when (and old-date org-log-reschedule
11055 (not (equal old-date
11056 (substring org-last-inserted-timestamp 1 -1))))
11057 (org-add-log-setup 'reschedule nil old-date 'findpos
11058 org-log-reschedule))
11059 (when repeater
11060 (save-excursion
11061 (org-back-to-heading t)
11062 (when (re-search-forward (concat org-scheduled-string " "
11063 org-last-inserted-timestamp)
11064 (save-excursion
11065 (outline-next-heading) (point)) t)
11066 (goto-char (1- (match-end 0)))
11067 (insert " " repeater)
11068 (setq org-last-inserted-timestamp
11069 (concat (substring org-last-inserted-timestamp 0 -1)
11070 " " repeater
11071 (substring org-last-inserted-timestamp -1))))))
11072 (message "Scheduled to %s" org-last-inserted-timestamp))))
11074 (defun org-get-scheduled-time (pom &optional inherit)
11075 "Get the scheduled time as a time tuple, of a format suitable
11076 for calling org-schedule with, or if there is no scheduling,
11077 returns nil."
11078 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11079 (when time
11080 (apply 'encode-time (org-parse-time-string time)))))
11082 (defun org-get-deadline-time (pom &optional inherit)
11083 "Get the deadine as a time tuple, of a format suitable for
11084 calling org-deadline with, or if there is no scheduling, returns
11085 nil."
11086 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11087 (when time
11088 (apply 'encode-time (org-parse-time-string time)))))
11090 (defun org-remove-timestamp-with-keyword (keyword)
11091 "Remove all time stamps with KEYWORD in the current entry."
11092 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11093 beg)
11094 (save-excursion
11095 (org-back-to-heading t)
11096 (setq beg (point))
11097 (outline-next-heading)
11098 (while (re-search-backward re beg t)
11099 (replace-match "")
11100 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11101 (equal (char-before) ?\ ))
11102 (backward-delete-char 1)
11103 (if (string-match "^[ \t]*$" (buffer-substring
11104 (point-at-bol) (point-at-eol)))
11105 (delete-region (point-at-bol)
11106 (min (point-max) (1+ (point-at-eol))))))))))
11108 (defun org-add-planning-info (what &optional time &rest remove)
11109 "Insert new timestamp with keyword in the line directly after the headline.
11110 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11111 If non is given, the user is prompted for a date.
11112 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11113 be removed."
11114 (interactive)
11115 (let (org-time-was-given org-end-time-was-given ts
11116 end default-time default-input)
11118 (catch 'exit
11119 (when (and (not time) (memq what '(scheduled deadline)))
11120 ;; Try to get a default date/time from existing timestamp
11121 (save-excursion
11122 (org-back-to-heading t)
11123 (setq end (save-excursion (outline-next-heading) (point)))
11124 (when (re-search-forward (if (eq what 'scheduled)
11125 org-scheduled-time-regexp
11126 org-deadline-time-regexp)
11127 end t)
11128 (setq ts (match-string 1)
11129 default-time
11130 (apply 'encode-time (org-parse-time-string ts))
11131 default-input (and ts (org-get-compact-tod ts))))))
11132 (when what
11133 ;; If necessary, get the time from the user
11134 (setq time (or time (org-read-date nil 'to-time nil nil
11135 default-time default-input))))
11137 (when (and org-insert-labeled-timestamps-at-point
11138 (member what '(scheduled deadline)))
11139 (insert
11140 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11141 (org-insert-time-stamp time org-time-was-given
11142 nil nil nil (list org-end-time-was-given))
11143 (setq what nil))
11144 (save-excursion
11145 (save-restriction
11146 (let (col list elt ts buffer-invisibility-spec)
11147 (org-back-to-heading t)
11148 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11149 (goto-char (match-end 1))
11150 (setq col (current-column))
11151 (goto-char (match-end 0))
11152 (if (eobp) (insert "\n") (forward-char 1))
11153 (when (and (not what)
11154 (not (looking-at
11155 (concat "[ \t]*"
11156 org-keyword-time-not-clock-regexp))))
11157 ;; Nothing to add, nothing to remove...... :-)
11158 (throw 'exit nil))
11159 (if (and (not (looking-at outline-regexp))
11160 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11161 "[^\r\n]*"))
11162 (not (equal (match-string 1) org-clock-string)))
11163 (narrow-to-region (match-beginning 0) (match-end 0))
11164 (insert-before-markers "\n")
11165 (backward-char 1)
11166 (narrow-to-region (point) (point))
11167 (and org-adapt-indentation (org-indent-to-column col)))
11168 ;; Check if we have to remove something.
11169 (setq list (cons what remove))
11170 (while list
11171 (setq elt (pop list))
11172 (goto-char (point-min))
11173 (when (or (and (eq elt 'scheduled)
11174 (re-search-forward org-scheduled-time-regexp nil t))
11175 (and (eq elt 'deadline)
11176 (re-search-forward org-deadline-time-regexp nil t))
11177 (and (eq elt 'closed)
11178 (re-search-forward org-closed-time-regexp nil t)))
11179 (replace-match "")
11180 (if (looking-at "--+<[^>]+>") (replace-match ""))
11181 (skip-chars-backward " ")
11182 (if (looking-at " +") (replace-match ""))))
11183 (goto-char (point-max))
11184 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11185 (when what
11186 (insert
11187 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11188 (cond ((eq what 'scheduled) org-scheduled-string)
11189 ((eq what 'deadline) org-deadline-string)
11190 ((eq what 'closed) org-closed-string))
11191 " ")
11192 (setq ts (org-insert-time-stamp
11193 time
11194 (or org-time-was-given
11195 (and (eq what 'closed) org-log-done-with-time))
11196 (eq what 'closed)
11197 nil nil (list org-end-time-was-given)))
11198 (end-of-line 1))
11199 (goto-char (point-min))
11200 (widen)
11201 (if (and (looking-at "[ \t]+\n")
11202 (equal (char-before) ?\n))
11203 (delete-region (1- (point)) (point-at-eol)))
11204 ts))))))
11206 (defvar org-log-note-marker (make-marker))
11207 (defvar org-log-note-purpose nil)
11208 (defvar org-log-note-state nil)
11209 (defvar org-log-note-previous-state nil)
11210 (defvar org-log-note-how nil)
11211 (defvar org-log-note-extra nil)
11212 (defvar org-log-note-window-configuration nil)
11213 (defvar org-log-note-return-to (make-marker))
11214 (defvar org-log-post-message nil
11215 "Message to be displayed after a log note has been stored.
11216 The auto-repeater uses this.")
11218 (defun org-add-note ()
11219 "Add a note to the current entry.
11220 This is done in the same way as adding a state change note."
11221 (interactive)
11222 (org-add-log-setup 'note nil nil 'findpos nil))
11224 (defvar org-property-end-re)
11225 (defun org-add-log-setup (&optional purpose state prev-state
11226 findpos how &optional extra)
11227 "Set up the post command hook to take a note.
11228 If this is about to TODO state change, the new state is expected in STATE.
11229 When FINDPOS is non-nil, find the correct position for the note in
11230 the current entry. If not, assume that it can be inserted at point.
11231 HOW is an indicator what kind of note should be created.
11232 EXTRA is additional text that will be inserted into the notes buffer."
11233 (let* ((org-log-into-drawer (org-log-into-drawer))
11234 (drawer (cond ((stringp org-log-into-drawer)
11235 org-log-into-drawer)
11236 (org-log-into-drawer "LOGBOOK")
11237 (t nil))))
11238 (save-restriction
11239 (save-excursion
11240 (when findpos
11241 (org-back-to-heading t)
11242 (narrow-to-region (point) (save-excursion
11243 (outline-next-heading) (point)))
11244 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11245 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11246 "[^\r\n]*\\)?"))
11247 (goto-char (match-end 0))
11248 (cond
11249 (drawer
11250 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11251 nil t)
11252 (progn
11253 (goto-char (match-end 0))
11254 (or org-log-states-order-reversed
11255 (and (re-search-forward org-property-end-re nil t)
11256 (goto-char (1- (match-beginning 0))))))
11257 (insert "\n:" drawer ":\n:END:")
11258 (beginning-of-line 0)
11259 (org-indent-line-function)
11260 (beginning-of-line 2)
11261 (org-indent-line-function)
11262 (end-of-line 0)))
11263 ((and org-log-state-notes-insert-after-drawers
11264 (save-excursion
11265 (forward-line) (looking-at org-drawer-regexp)))
11266 (forward-line)
11267 (while (looking-at org-drawer-regexp)
11268 (goto-char (match-end 0))
11269 (re-search-forward org-property-end-re (point-max) t)
11270 (forward-line))
11271 (forward-line -1)))
11272 (unless org-log-states-order-reversed
11273 (and (= (char-after) ?\n) (forward-char 1))
11274 (org-skip-over-state-notes)
11275 (skip-chars-backward " \t\n\r")))
11276 (move-marker org-log-note-marker (point))
11277 (setq org-log-note-purpose purpose
11278 org-log-note-state state
11279 org-log-note-previous-state prev-state
11280 org-log-note-how how
11281 org-log-note-extra extra)
11282 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11284 (defun org-skip-over-state-notes ()
11285 "Skip past the list of State notes in an entry."
11286 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11287 (while (looking-at "[ \t]*- State")
11288 (condition-case nil
11289 (org-next-item)
11290 (error (org-end-of-item)))))
11292 (defun org-add-log-note (&optional purpose)
11293 "Pop up a window for taking a note, and add this note later at point."
11294 (remove-hook 'post-command-hook 'org-add-log-note)
11295 (setq org-log-note-window-configuration (current-window-configuration))
11296 (delete-other-windows)
11297 (move-marker org-log-note-return-to (point))
11298 (switch-to-buffer (marker-buffer org-log-note-marker))
11299 (goto-char org-log-note-marker)
11300 (org-switch-to-buffer-other-window "*Org Note*")
11301 (erase-buffer)
11302 (if (memq org-log-note-how '(time state))
11303 (let (current-prefix-arg) (org-store-log-note))
11304 (let ((org-inhibit-startup t)) (org-mode))
11305 (insert (format "# Insert note for %s.
11306 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11307 (cond
11308 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11309 ((eq org-log-note-purpose 'done) "closed todo item")
11310 ((eq org-log-note-purpose 'state)
11311 (format "state change from \"%s\" to \"%s\""
11312 (or org-log-note-previous-state "")
11313 (or org-log-note-state "")))
11314 ((eq org-log-note-purpose 'reschedule)
11315 "rescheduling")
11316 ((eq org-log-note-purpose 'delschedule)
11317 "no longer scheduled")
11318 ((eq org-log-note-purpose 'redeadline)
11319 "changing deadline")
11320 ((eq org-log-note-purpose 'deldeadline)
11321 "removing deadline")
11322 ((eq org-log-note-purpose 'refile)
11323 "refiling")
11324 ((eq org-log-note-purpose 'note)
11325 "this entry")
11326 (t (error "This should not happen")))))
11327 (if org-log-note-extra (insert org-log-note-extra))
11328 (org-set-local 'org-finish-function 'org-store-log-note)))
11330 (defvar org-note-abort nil) ; dynamically scoped
11331 (defun org-store-log-note ()
11332 "Finish taking a log note, and insert it to where it belongs."
11333 (let ((txt (buffer-string))
11334 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11335 lines ind)
11336 (kill-buffer (current-buffer))
11337 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11338 (setq txt (replace-match "" t t txt)))
11339 (if (string-match "\\s-+\\'" txt)
11340 (setq txt (replace-match "" t t txt)))
11341 (setq lines (org-split-string txt "\n"))
11342 (when (and note (string-match "\\S-" note))
11343 (setq note
11344 (org-replace-escapes
11345 note
11346 (list (cons "%u" (user-login-name))
11347 (cons "%U" user-full-name)
11348 (cons "%t" (format-time-string
11349 (org-time-stamp-format 'long 'inactive)
11350 (current-time)))
11351 (cons "%s" (if org-log-note-state
11352 (concat "\"" org-log-note-state "\"")
11353 ""))
11354 (cons "%S" (if org-log-note-previous-state
11355 (concat "\"" org-log-note-previous-state "\"")
11356 "\"\"")))))
11357 (if lines (setq note (concat note " \\\\")))
11358 (push note lines))
11359 (when (or current-prefix-arg org-note-abort)
11360 (when org-log-into-drawer
11361 (org-remove-empty-drawer-at
11362 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11363 org-log-note-marker))
11364 (setq lines nil))
11365 (when lines
11366 (with-current-buffer (marker-buffer org-log-note-marker)
11367 (save-excursion
11368 (goto-char org-log-note-marker)
11369 (move-marker org-log-note-marker nil)
11370 (end-of-line 1)
11371 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11372 (insert "- " (pop lines))
11373 (org-indent-line-function)
11374 (beginning-of-line 1)
11375 (looking-at "[ \t]*")
11376 (setq ind (concat (match-string 0) " "))
11377 (end-of-line 1)
11378 (while lines (insert "\n" ind (pop lines)))
11379 (message "Note stored")
11380 (org-back-to-heading t)
11381 (org-cycle-hide-drawers 'children)))))
11382 (set-window-configuration org-log-note-window-configuration)
11383 (with-current-buffer (marker-buffer org-log-note-return-to)
11384 (goto-char org-log-note-return-to))
11385 (move-marker org-log-note-return-to nil)
11386 (and org-log-post-message (message "%s" org-log-post-message)))
11388 (defun org-remove-empty-drawer-at (drawer pos)
11389 "Remove an empty drawer DRAWER at position POS.
11390 POS may also be a marker."
11391 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11392 (save-excursion
11393 (save-restriction
11394 (widen)
11395 (goto-char pos)
11396 (if (org-in-regexp
11397 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11398 (replace-match ""))))))
11400 (defun org-sparse-tree (&optional arg)
11401 "Create a sparse tree, prompt for the details.
11402 This command can create sparse trees. You first need to select the type
11403 of match used to create the tree:
11405 t Show entries with a specific TODO keyword.
11406 m Show entries selected by a tags/property match.
11407 p Enter a property name and its value (both with completion on existing
11408 names/values) and show entries with that property.
11409 / Show entries matching a regular expression (`r' can be used as well)
11410 d Show deadlines due within `org-deadline-warning-days'.
11411 b Show deadlines and scheduled items before a date.
11412 a Show deadlines and scheduled items after a date."
11413 (interactive "P")
11414 (let (ans kwd value)
11415 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11416 (setq ans (read-char-exclusive))
11417 (cond
11418 ((equal ans ?d)
11419 (call-interactively 'org-check-deadlines))
11420 ((equal ans ?b)
11421 (call-interactively 'org-check-before-date))
11422 ((equal ans ?a)
11423 (call-interactively 'org-check-after-date))
11424 ((equal ans ?t)
11425 (org-show-todo-tree '(4)))
11426 ((member ans '(?T ?m))
11427 (call-interactively 'org-match-sparse-tree))
11428 ((member ans '(?p ?P))
11429 (setq kwd (org-icompleting-read "Property: "
11430 (mapcar 'list (org-buffer-property-keys))))
11431 (setq value (org-icompleting-read "Value: "
11432 (mapcar 'list (org-property-values kwd))))
11433 (unless (string-match "\\`{.*}\\'" value)
11434 (setq value (concat "\"" value "\"")))
11435 (org-match-sparse-tree arg (concat kwd "=" value)))
11436 ((member ans '(?r ?R ?/))
11437 (call-interactively 'org-occur))
11438 (t (error "No such sparse tree command \"%c\"" ans)))))
11440 (defvar org-occur-highlights nil
11441 "List of overlays used for occur matches.")
11442 (make-variable-buffer-local 'org-occur-highlights)
11443 (defvar org-occur-parameters nil
11444 "Parameters of the active org-occur calls.
11445 This is a list, each call to org-occur pushes as cons cell,
11446 containing the regular expression and the callback, onto the list.
11447 The list can contain several entries if `org-occur' has been called
11448 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11449 will only contain one set of parameters. When the highlights are
11450 removed (for example with `C-c C-c', or with the next edit (depending
11451 on `org-remove-highlights-with-change'), this variable is emptied
11452 as well.")
11453 (make-variable-buffer-local 'org-occur-parameters)
11455 (defun org-occur (regexp &optional keep-previous callback)
11456 "Make a compact tree which shows all matches of REGEXP.
11457 The tree will show the lines where the regexp matches, and all higher
11458 headlines above the match. It will also show the heading after the match,
11459 to make sure editing the matching entry is easy.
11460 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11461 call to `org-occur' will be kept, to allow stacking of calls to this
11462 command.
11463 If CALLBACK is non-nil, it is a function which is called to confirm
11464 that the match should indeed be shown."
11465 (interactive "sRegexp: \nP")
11466 (when (equal regexp "")
11467 (error "Regexp cannot be empty"))
11468 (unless keep-previous
11469 (org-remove-occur-highlights nil nil t))
11470 (push (cons regexp callback) org-occur-parameters)
11471 (let ((cnt 0))
11472 (save-excursion
11473 (goto-char (point-min))
11474 (if (or (not keep-previous) ; do not want to keep
11475 (not org-occur-highlights)) ; no previous matches
11476 ;; hide everything
11477 (org-overview))
11478 (while (re-search-forward regexp nil t)
11479 (when (or (not callback)
11480 (save-match-data (funcall callback)))
11481 (setq cnt (1+ cnt))
11482 (when org-highlight-sparse-tree-matches
11483 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11484 (org-show-context 'occur-tree))))
11485 (when org-remove-highlights-with-change
11486 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11487 nil 'local))
11488 (unless org-sparse-tree-open-archived-trees
11489 (org-hide-archived-subtrees (point-min) (point-max)))
11490 (run-hooks 'org-occur-hook)
11491 (if (interactive-p)
11492 (message "%d match(es) for regexp %s" cnt regexp))
11493 cnt))
11495 (defun org-show-context (&optional key)
11496 "Make sure point and context and visible.
11497 How much context is shown depends upon the variables
11498 `org-show-hierarchy-above', `org-show-following-heading'. and
11499 `org-show-siblings'."
11500 (let ((heading-p (org-on-heading-p t))
11501 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11502 (following-p (org-get-alist-option org-show-following-heading key))
11503 (entry-p (org-get-alist-option org-show-entry-below key))
11504 (siblings-p (org-get-alist-option org-show-siblings key)))
11505 (catch 'exit
11506 ;; Show heading or entry text
11507 (if (and heading-p (not entry-p))
11508 (org-flag-heading nil) ; only show the heading
11509 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11510 (org-show-hidden-entry))) ; show entire entry
11511 (when following-p
11512 ;; Show next sibling, or heading below text
11513 (save-excursion
11514 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11515 (org-flag-heading nil))))
11516 (when siblings-p (org-show-siblings))
11517 (when hierarchy-p
11518 ;; show all higher headings, possibly with siblings
11519 (save-excursion
11520 (while (and (condition-case nil
11521 (progn (org-up-heading-all 1) t)
11522 (error nil))
11523 (not (bobp)))
11524 (org-flag-heading nil)
11525 (when siblings-p (org-show-siblings))))))))
11527 (defvar org-reveal-start-hook nil
11528 "Hook run before revealing a location.")
11530 (defun org-reveal (&optional siblings)
11531 "Show current entry, hierarchy above it, and the following headline.
11532 This can be used to show a consistent set of context around locations
11533 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11534 not t for the search context.
11536 With optional argument SIBLINGS, on each level of the hierarchy all
11537 siblings are shown. This repairs the tree structure to what it would
11538 look like when opened with hierarchical calls to `org-cycle'.
11539 With double optional argument `C-u C-u', go to the parent and show the
11540 entire tree."
11541 (interactive "P")
11542 (run-hooks 'org-reveal-start-hook)
11543 (let ((org-show-hierarchy-above t)
11544 (org-show-following-heading t)
11545 (org-show-siblings (if siblings t org-show-siblings)))
11546 (org-show-context nil))
11547 (when (equal siblings '(16))
11548 (save-excursion
11549 (when (org-up-heading-safe)
11550 (org-show-subtree)
11551 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11553 (defun org-highlight-new-match (beg end)
11554 "Highlight from BEG to END and mark the highlight is an occur headline."
11555 (let ((ov (make-overlay beg end)))
11556 (overlay-put ov 'face 'secondary-selection)
11557 (push ov org-occur-highlights)))
11559 (defun org-remove-occur-highlights (&optional beg end noremove)
11560 "Remove the occur highlights from the buffer.
11561 BEG and END are ignored. If NOREMOVE is nil, remove this function
11562 from the `before-change-functions' in the current buffer."
11563 (interactive)
11564 (unless org-inhibit-highlight-removal
11565 (mapc 'delete-overlay org-occur-highlights)
11566 (setq org-occur-highlights nil)
11567 (setq org-occur-parameters nil)
11568 (unless noremove
11569 (remove-hook 'before-change-functions
11570 'org-remove-occur-highlights 'local))))
11572 ;;;; Priorities
11574 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11575 "Regular expression matching the priority indicator.")
11577 (defvar org-remove-priority-next-time nil)
11579 (defun org-priority-up ()
11580 "Increase the priority of the current item."
11581 (interactive)
11582 (org-priority 'up))
11584 (defun org-priority-down ()
11585 "Decrease the priority of the current item."
11586 (interactive)
11587 (org-priority 'down))
11589 (defun org-priority (&optional action)
11590 "Change the priority of an item by ARG.
11591 ACTION can be `set', `up', `down', or a character."
11592 (interactive)
11593 (unless org-enable-priority-commands
11594 (error "Priority commands are disabled"))
11595 (setq action (or action 'set))
11596 (let (current new news have remove)
11597 (save-excursion
11598 (org-back-to-heading t)
11599 (if (looking-at org-priority-regexp)
11600 (setq current (string-to-char (match-string 2))
11601 have t)
11602 (setq current org-default-priority))
11603 (cond
11604 ((eq action 'remove)
11605 (setq remove t new ?\ ))
11606 ((or (eq action 'set)
11607 (if (featurep 'xemacs) (characterp action) (integerp action)))
11608 (if (not (eq action 'set))
11609 (setq new action)
11610 (message "Priority %c-%c, SPC to remove: "
11611 org-highest-priority org-lowest-priority)
11612 (setq new (read-char-exclusive)))
11613 (if (and (= (upcase org-highest-priority) org-highest-priority)
11614 (= (upcase org-lowest-priority) org-lowest-priority))
11615 (setq new (upcase new)))
11616 (cond ((equal new ?\ ) (setq remove t))
11617 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11618 (error "Priority must be between `%c' and `%c'"
11619 org-highest-priority org-lowest-priority))))
11620 ((eq action 'up)
11621 (if (and (not have) (eq last-command this-command))
11622 (setq new org-lowest-priority)
11623 (setq new (if (and org-priority-start-cycle-with-default (not have))
11624 org-default-priority (1- current)))))
11625 ((eq action 'down)
11626 (if (and (not have) (eq last-command this-command))
11627 (setq new org-highest-priority)
11628 (setq new (if (and org-priority-start-cycle-with-default (not have))
11629 org-default-priority (1+ current)))))
11630 (t (error "Invalid action")))
11631 (if (or (< (upcase new) org-highest-priority)
11632 (> (upcase new) org-lowest-priority))
11633 (setq remove t))
11634 (setq news (format "%c" new))
11635 (if have
11636 (if remove
11637 (replace-match "" t t nil 1)
11638 (replace-match news t t nil 2))
11639 (if remove
11640 (error "No priority cookie found in line")
11641 (let ((case-fold-search nil))
11642 (looking-at org-todo-line-regexp))
11643 (if (match-end 2)
11644 (progn
11645 (goto-char (match-end 2))
11646 (insert " [#" news "]"))
11647 (goto-char (match-beginning 3))
11648 (insert "[#" news "] "))))
11649 (org-preserve-lc (org-set-tags nil 'align)))
11650 (if remove
11651 (message "Priority removed")
11652 (message "Priority of current item set to %s" news))))
11654 (defun org-get-priority (s)
11655 "Find priority cookie and return priority."
11656 (save-match-data
11657 (if (not (string-match org-priority-regexp s))
11658 (* 1000 (- org-lowest-priority org-default-priority))
11659 (* 1000 (- org-lowest-priority
11660 (string-to-char (match-string 2 s)))))))
11662 ;;;; Tags
11664 (defvar org-agenda-archives-mode)
11665 (defvar org-map-continue-from nil
11666 "Position from where mapping should continue.
11667 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11669 (defvar org-scanner-tags nil
11670 "The current tag list while the tags scanner is running.")
11671 (defvar org-trust-scanner-tags nil
11672 "Should `org-get-tags-at' use the tags fro the scanner.
11673 This is for internal dynamical scoping only.
11674 When this is non-nil, the function `org-get-tags-at' will return the value
11675 of `org-scanner-tags' instead of building the list by itself. This
11676 can lead to large speed-ups when the tags scanner is used in a file with
11677 many entries, and when the list of tags is retrieved, for example to
11678 obtain a list of properties. Building the tags list for each entry in such
11679 a file becomes an N^2 operation - but with this variable set, it scales
11680 as N.")
11682 (defun org-scan-tags (action matcher &optional todo-only)
11683 "Scan headline tags with inheritance and produce output ACTION.
11685 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11686 or `agenda' to produce an entry list for an agenda view. It can also be
11687 a Lisp form or a function that should be called at each matched headline, in
11688 this case the return value is a list of all return values from these calls.
11690 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11691 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11692 only lines with a TODO keyword are included in the output."
11693 (require 'org-agenda)
11694 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11695 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11696 (org-re
11697 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11698 (props (list 'face 'default
11699 'done-face 'org-agenda-done
11700 'undone-face 'default
11701 'mouse-face 'highlight
11702 'org-not-done-regexp org-not-done-regexp
11703 'org-todo-regexp org-todo-regexp
11704 'help-echo
11705 (format "mouse-2 or RET jump to org file %s"
11706 (abbreviate-file-name
11707 (or (buffer-file-name (buffer-base-buffer))
11708 (buffer-name (buffer-base-buffer)))))))
11709 (case-fold-search nil)
11710 (org-map-continue-from nil)
11711 lspos tags tags-list
11712 (tags-alist (list (cons 0 org-file-tags)))
11713 (llast 0) rtn rtn1 level category i txt
11714 todo marker entry priority)
11715 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11716 (setq action (list 'lambda nil action)))
11717 (save-excursion
11718 (goto-char (point-min))
11719 (when (eq action 'sparse-tree)
11720 (org-overview)
11721 (org-remove-occur-highlights))
11722 (while (re-search-forward re nil t)
11723 (catch :skip
11724 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11725 tags (if (match-end 4) (org-match-string-no-properties 4)))
11726 (goto-char (setq lspos (match-beginning 0)))
11727 (setq level (org-reduced-level (funcall outline-level))
11728 category (org-get-category))
11729 (setq i llast llast level)
11730 ;; remove tag lists from same and sublevels
11731 (while (>= i level)
11732 (when (setq entry (assoc i tags-alist))
11733 (setq tags-alist (delete entry tags-alist)))
11734 (setq i (1- i)))
11735 ;; add the next tags
11736 (when tags
11737 (setq tags (org-split-string tags ":")
11738 tags-alist
11739 (cons (cons level tags) tags-alist)))
11740 ;; compile tags for current headline
11741 (setq tags-list
11742 (if org-use-tag-inheritance
11743 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11744 tags)
11745 org-scanner-tags tags-list)
11746 (when org-use-tag-inheritance
11747 (setcdr (car tags-alist)
11748 (mapcar (lambda (x)
11749 (setq x (copy-sequence x))
11750 (org-add-prop-inherited x))
11751 (cdar tags-alist))))
11752 (when (and tags org-use-tag-inheritance
11753 (or (not (eq t org-use-tag-inheritance))
11754 org-tags-exclude-from-inheritance))
11755 ;; selective inheritance, remove uninherited ones
11756 (setcdr (car tags-alist)
11757 (org-remove-uniherited-tags (cdar tags-alist))))
11758 (when (and (or (not todo-only)
11759 (and (member todo org-not-done-keywords)
11760 (or (not org-agenda-tags-todo-honor-ignore-options)
11761 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11762 (let ((case-fold-search t)) (eval matcher))
11764 (not (member org-archive-tag tags-list))
11765 ;; we have an archive tag, should we use this anyway?
11766 (or (not org-agenda-skip-archived-trees)
11767 (and (eq action 'agenda) org-agenda-archives-mode))))
11768 (unless (eq action 'sparse-tree) (org-agenda-skip))
11770 ;; select this headline
11772 (cond
11773 ((eq action 'sparse-tree)
11774 (and org-highlight-sparse-tree-matches
11775 (org-get-heading) (match-end 0)
11776 (org-highlight-new-match
11777 (match-beginning 0) (match-beginning 1)))
11778 (org-show-context 'tags-tree))
11779 ((eq action 'agenda)
11780 (setq txt (org-format-agenda-item
11782 (concat
11783 (if (eq org-tags-match-list-sublevels 'indented)
11784 (make-string (1- level) ?.) "")
11785 (org-get-heading))
11786 category
11787 tags-list
11789 priority (org-get-priority txt))
11790 (goto-char lspos)
11791 (setq marker (org-agenda-new-marker))
11792 (org-add-props txt props
11793 'org-marker marker 'org-hd-marker marker 'org-category category
11794 'todo-state todo
11795 'priority priority 'type "tagsmatch")
11796 (push txt rtn))
11797 ((functionp action)
11798 (setq org-map-continue-from nil)
11799 (save-excursion
11800 (setq rtn1 (funcall action))
11801 (push rtn1 rtn)))
11802 (t (error "Invalid action")))
11804 ;; if we are to skip sublevels, jump to end of subtree
11805 (unless org-tags-match-list-sublevels
11806 (org-end-of-subtree t)
11807 (backward-char 1))))
11808 ;; Get the correct position from where to continue
11809 (if org-map-continue-from
11810 (goto-char org-map-continue-from)
11811 (and (= (point) lspos) (end-of-line 1)))))
11812 (when (and (eq action 'sparse-tree)
11813 (not org-sparse-tree-open-archived-trees))
11814 (org-hide-archived-subtrees (point-min) (point-max)))
11815 (nreverse rtn)))
11817 (defun org-remove-uniherited-tags (tags)
11818 "Remove all tags that are not inherited from the list TAGS."
11819 (cond
11820 ((eq org-use-tag-inheritance t)
11821 (if org-tags-exclude-from-inheritance
11822 (org-delete-all org-tags-exclude-from-inheritance tags)
11823 tags))
11824 ((not org-use-tag-inheritance) nil)
11825 ((stringp org-use-tag-inheritance)
11826 (delq nil (mapcar
11827 (lambda (x)
11828 (if (and (string-match org-use-tag-inheritance x)
11829 (not (member x org-tags-exclude-from-inheritance)))
11830 x nil))
11831 tags)))
11832 ((listp org-use-tag-inheritance)
11833 (delq nil (mapcar
11834 (lambda (x)
11835 (if (member x org-use-tag-inheritance) x nil))
11836 tags)))))
11838 (defvar todo-only) ;; dynamically scoped
11840 (defun org-match-sparse-tree (&optional todo-only match)
11841 "Create a sparse tree according to tags string MATCH.
11842 MATCH can contain positive and negative selection of tags, like
11843 \"+WORK+URGENT-WITHBOSS\".
11844 If optional argument TODO-ONLY is non-nil, only select lines that are
11845 also TODO lines."
11846 (interactive "P")
11847 (org-prepare-agenda-buffers (list (current-buffer)))
11848 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11850 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11852 (defvar org-cached-props nil)
11853 (defun org-cached-entry-get (pom property)
11854 (if (or (eq t org-use-property-inheritance)
11855 (and (stringp org-use-property-inheritance)
11856 (string-match org-use-property-inheritance property))
11857 (and (listp org-use-property-inheritance)
11858 (member property org-use-property-inheritance)))
11859 ;; Caching is not possible, check it directly
11860 (org-entry-get pom property 'inherit)
11861 ;; Get all properties, so that we can do complicated checks easily
11862 (cdr (assoc property (or org-cached-props
11863 (setq org-cached-props
11864 (org-entry-properties pom)))))))
11866 (defun org-global-tags-completion-table (&optional files)
11867 "Return the list of all tags in all agenda buffer/files."
11868 (save-excursion
11869 (org-uniquify
11870 (delq nil
11871 (apply 'append
11872 (mapcar
11873 (lambda (file)
11874 (set-buffer (find-file-noselect file))
11875 (append (org-get-buffer-tags)
11876 (mapcar (lambda (x) (if (stringp (car-safe x))
11877 (list (car-safe x)) nil))
11878 org-tag-alist)))
11879 (if (and files (car files))
11880 files
11881 (org-agenda-files))))))))
11883 (defun org-make-tags-matcher (match)
11884 "Create the TAGS//TODO matcher form for the selection string MATCH."
11885 ;; todo-only is scoped dynamically into this function, and the function
11886 ;; may change it if the matcher asks for it.
11887 (unless match
11888 ;; Get a new match request, with completion
11889 (let ((org-last-tags-completion-table
11890 (org-global-tags-completion-table)))
11891 (setq match (org-completing-read-no-i
11892 "Match: " 'org-tags-completion-function nil nil nil
11893 'org-tags-history))))
11895 ;; Parse the string and create a lisp form
11896 (let ((match0 match)
11897 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11898 minus tag mm
11899 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11900 orterms term orlist re-p str-p level-p level-op time-p
11901 prop-p pn pv po cat-p gv rest)
11902 (if (string-match "/+" match)
11903 ;; match contains also a todo-matching request
11904 (progn
11905 (setq tagsmatch (substring match 0 (match-beginning 0))
11906 todomatch (substring match (match-end 0)))
11907 (if (string-match "^!" todomatch)
11908 (setq todo-only t todomatch (substring todomatch 1)))
11909 (if (string-match "^\\s-*$" todomatch)
11910 (setq todomatch nil)))
11911 ;; only matching tags
11912 (setq tagsmatch match todomatch nil))
11914 ;; Make the tags matcher
11915 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11916 (setq tagsmatcher t)
11917 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11918 (while (setq term (pop orterms))
11919 (while (and (equal (substring term -1) "\\") orterms)
11920 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11921 (while (string-match re term)
11922 (setq rest (substring term (match-end 0))
11923 minus (and (match-end 1)
11924 (equal (match-string 1 term) "-"))
11925 tag (match-string 2 term)
11926 re-p (equal (string-to-char tag) ?{)
11927 level-p (match-end 4)
11928 prop-p (match-end 5)
11929 mm (cond
11930 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11931 (level-p
11932 (setq level-op (org-op-to-function (match-string 3 term)))
11933 `(,level-op level ,(string-to-number
11934 (match-string 4 term))))
11935 (prop-p
11936 (setq pn (match-string 5 term)
11937 po (match-string 6 term)
11938 pv (match-string 7 term)
11939 cat-p (equal pn "CATEGORY")
11940 re-p (equal (string-to-char pv) ?{)
11941 str-p (equal (string-to-char pv) ?\")
11942 time-p (save-match-data
11943 (string-match "^\"[[<].*[]>]\"$" pv))
11944 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11945 (if time-p (setq pv (org-matcher-time pv)))
11946 (setq po (org-op-to-function po (if time-p 'time str-p)))
11947 (cond
11948 ((equal pn "CATEGORY")
11949 (setq gv '(get-text-property (point) 'org-category)))
11950 ((equal pn "TODO")
11951 (setq gv 'todo))
11953 (setq gv `(org-cached-entry-get nil ,pn))))
11954 (if re-p
11955 (if (eq po 'org<>)
11956 `(not (string-match ,pv (or ,gv "")))
11957 `(string-match ,pv (or ,gv "")))
11958 (if str-p
11959 `(,po (or ,gv "") ,pv)
11960 `(,po (string-to-number (or ,gv ""))
11961 ,(string-to-number pv) ))))
11962 (t `(member ,tag tags-list)))
11963 mm (if minus (list 'not mm) mm)
11964 term rest)
11965 (push mm tagsmatcher))
11966 (push (if (> (length tagsmatcher) 1)
11967 (cons 'and tagsmatcher)
11968 (car tagsmatcher))
11969 orlist)
11970 (setq tagsmatcher nil))
11971 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11972 (setq tagsmatcher
11973 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11974 ;; Make the todo matcher
11975 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11976 (setq todomatcher t)
11977 (setq orterms (org-split-string todomatch "|") orlist nil)
11978 (while (setq term (pop orterms))
11979 (while (string-match re term)
11980 (setq minus (and (match-end 1)
11981 (equal (match-string 1 term) "-"))
11982 kwd (match-string 2 term)
11983 re-p (equal (string-to-char kwd) ?{)
11984 term (substring term (match-end 0))
11985 mm (if re-p
11986 `(string-match ,(substring kwd 1 -1) todo)
11987 (list 'equal 'todo kwd))
11988 mm (if minus (list 'not mm) mm))
11989 (push mm todomatcher))
11990 (push (if (> (length todomatcher) 1)
11991 (cons 'and todomatcher)
11992 (car todomatcher))
11993 orlist)
11994 (setq todomatcher nil))
11995 (setq todomatcher (if (> (length orlist) 1)
11996 (cons 'or orlist) (car orlist))))
11998 ;; Return the string and lisp forms of the matcher
11999 (setq matcher (if todomatcher
12000 (list 'and tagsmatcher todomatcher)
12001 tagsmatcher))
12002 (cons match0 matcher)))
12004 (defun org-op-to-function (op &optional stringp)
12005 "Turn an operator into the appropriate function."
12006 (setq op
12007 (cond
12008 ((equal op "<" ) '(< string< org-time<))
12009 ((equal op ">" ) '(> org-string> org-time>))
12010 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12011 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12012 ((member op '("=" "==")) '(= string= org-time=))
12013 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12014 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12016 (defun org<> (a b) (not (= a b)))
12017 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12018 (defun org-string>= (a b) (not (string< a b)))
12019 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12020 (defun org-string<> (a b) (not (string= a b)))
12021 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12022 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12023 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12024 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12025 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12026 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12027 (defun org-2ft (s)
12028 "Convert S to a floating point time.
12029 If S is already a number, just return it. If it is a string, parse
12030 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12031 (cond
12032 ((numberp s) s)
12033 ((stringp s)
12034 (condition-case nil
12035 (float-time (apply 'encode-time (org-parse-time-string s)))
12036 (error 0.)))
12037 (t 0.)))
12039 (defun org-time-today ()
12040 "Time in seconds today at 0:00.
12041 Returns the float number of seconds since the beginning of the
12042 epoch to the beginning of today (00:00)."
12043 (float-time (apply 'encode-time
12044 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12046 (defun org-matcher-time (s)
12047 "Interpret a time comparison value."
12048 (save-match-data
12049 (cond
12050 ((string= s "<now>") (float-time))
12051 ((string= s "<today>") (org-time-today))
12052 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12053 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12054 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12055 (+ (org-time-today)
12056 (* (string-to-number (match-string 1 s))
12057 (cdr (assoc (match-string 2 s)
12058 '(("d" . 86400.0) ("w" . 604800.0)
12059 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12060 (t (org-2ft s)))))
12062 (defun org-match-any-p (re list)
12063 "Does re match any element of list?"
12064 (setq list (mapcar (lambda (x) (string-match re x)) list))
12065 (delq nil list))
12067 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12068 (defvar org-tags-overlay (make-overlay 1 1))
12069 (org-detach-overlay org-tags-overlay)
12071 (defun org-get-local-tags-at (&optional pos)
12072 "Get a list of tags defined in the current headline."
12073 (org-get-tags-at pos 'local))
12075 (defun org-get-local-tags ()
12076 "Get a list of tags defined in the current headline."
12077 (org-get-tags-at nil 'local))
12079 (defun org-get-tags-at (&optional pos local)
12080 "Get a list of all headline tags applicable at POS.
12081 POS defaults to point. If tags are inherited, the list contains
12082 the targets in the same sequence as the headlines appear, i.e.
12083 the tags of the current headline come last.
12084 When LOCAL is non-nil, only return tags from the current headline,
12085 ignore inherited ones."
12086 (interactive)
12087 (if (and org-trust-scanner-tags
12088 (or (not pos) (equal pos (point)))
12089 (not local))
12090 org-scanner-tags
12091 (let (tags ltags lastpos parent)
12092 (save-excursion
12093 (save-restriction
12094 (widen)
12095 (goto-char (or pos (point)))
12096 (save-match-data
12097 (catch 'done
12098 (condition-case nil
12099 (progn
12100 (org-back-to-heading t)
12101 (while (not (equal lastpos (point)))
12102 (setq lastpos (point))
12103 (when (looking-at
12104 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12105 (setq ltags (org-split-string
12106 (org-match-string-no-properties 1) ":"))
12107 (when parent
12108 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12109 (setq tags (append
12110 (if parent
12111 (org-remove-uniherited-tags ltags)
12112 ltags)
12113 tags)))
12114 (or org-use-tag-inheritance (throw 'done t))
12115 (if local (throw 'done t))
12116 (or (org-up-heading-safe) (error nil))
12117 (setq parent t)))
12118 (error nil)))))
12119 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12121 (defun org-add-prop-inherited (s)
12122 (add-text-properties 0 (length s) '(inherited t) s)
12125 (defun org-toggle-tag (tag &optional onoff)
12126 "Toggle the tag TAG for the current line.
12127 If ONOFF is `on' or `off', don't toggle but set to this state."
12128 (let (res current)
12129 (save-excursion
12130 (org-back-to-heading t)
12131 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12132 (point-at-eol) t)
12133 (progn
12134 (setq current (match-string 1))
12135 (replace-match ""))
12136 (setq current ""))
12137 (setq current (nreverse (org-split-string current ":")))
12138 (cond
12139 ((eq onoff 'on)
12140 (setq res t)
12141 (or (member tag current) (push tag current)))
12142 ((eq onoff 'off)
12143 (or (not (member tag current)) (setq current (delete tag current))))
12144 (t (if (member tag current)
12145 (setq current (delete tag current))
12146 (setq res t)
12147 (push tag current))))
12148 (end-of-line 1)
12149 (if current
12150 (progn
12151 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12152 (org-set-tags nil t))
12153 (delete-horizontal-space))
12154 (run-hooks 'org-after-tags-change-hook))
12155 res))
12157 (defun org-align-tags-here (to-col)
12158 ;; Assumes that this is a headline
12159 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12160 (beginning-of-line 1)
12161 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12162 (< pos (match-beginning 2)))
12163 (progn
12164 (setq tags-l (- (match-end 2) (match-beginning 2)))
12165 (goto-char (match-beginning 1))
12166 (insert " ")
12167 (delete-region (point) (1+ (match-beginning 2)))
12168 (setq ncol (max (1+ (current-column))
12169 (1+ col)
12170 (if (> to-col 0)
12171 to-col
12172 (- (abs to-col) tags-l))))
12173 (setq p (point))
12174 (insert (make-string (- ncol (current-column)) ?\ ))
12175 (setq ncol (current-column))
12176 (when indent-tabs-mode (tabify p (point-at-eol)))
12177 (org-move-to-column (min ncol col) t))
12178 (goto-char pos))))
12180 (defun org-set-tags-command (&optional arg just-align)
12181 "Call the set-tags command for the current entry."
12182 (interactive "P")
12183 (if (org-on-heading-p)
12184 (org-set-tags arg just-align)
12185 (save-excursion
12186 (org-back-to-heading t)
12187 (org-set-tags arg just-align))))
12189 (defun org-set-tags-to (data)
12190 "Set the tags of the current entry to DATA, replacing the current tags.
12191 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12192 If DATA is nil or the empty string, any tags will be removed."
12193 (interactive "sTags: ")
12194 (setq data
12195 (cond
12196 ((eq data nil) "")
12197 ((equal data "") "")
12198 ((stringp data)
12199 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12200 ":"))
12201 ((listp data)
12202 (concat ":" (mapconcat 'identity data ":") ":"))
12203 (t nil)))
12204 (when data
12205 (save-excursion
12206 (org-back-to-heading t)
12207 (when (looking-at org-complex-heading-regexp)
12208 (if (match-end 5)
12209 (progn
12210 (goto-char (match-beginning 5))
12211 (insert data)
12212 (delete-region (point) (point-at-eol))
12213 (org-set-tags nil 'align))
12214 (goto-char (point-at-eol))
12215 (insert " " data)
12216 (org-set-tags nil 'align)))
12217 (beginning-of-line 1)
12218 (if (looking-at ".*?\\([ \t]+\\)$")
12219 (delete-region (match-beginning 1) (match-end 1))))))
12221 (defun org-align-all-tags ()
12222 "Align the tags i all headings."
12223 (interactive)
12224 (save-excursion
12225 (or (ignore-errors (org-back-to-heading t))
12226 (outline-next-heading))
12227 (if (org-on-heading-p)
12228 (org-set-tags t)
12229 (message "No headings"))))
12231 (defun org-set-tags (&optional arg just-align)
12232 "Set the tags for the current headline.
12233 With prefix ARG, realign all tags in headings in the current buffer."
12234 (interactive "P")
12235 (let* ((re (concat "^" outline-regexp))
12236 (current (org-get-tags-string))
12237 (col (current-column))
12238 (org-setting-tags t)
12239 table current-tags inherited-tags ; computed below when needed
12240 tags p0 c0 c1 rpl)
12241 (if arg
12242 (save-excursion
12243 (goto-char (point-min))
12244 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12245 (while (re-search-forward re nil t)
12246 (org-set-tags nil t)
12247 (end-of-line 1)))
12248 (message "All tags realigned to column %d" org-tags-column))
12249 (if just-align
12250 (setq tags current)
12251 ;; Get a new set of tags from the user
12252 (save-excursion
12253 (setq table (append org-tag-persistent-alist
12254 (or org-tag-alist (org-get-buffer-tags))
12255 (and org-complete-tags-always-offer-all-agenda-tags
12256 (org-global-tags-completion-table (org-agenda-files))))
12257 org-last-tags-completion-table table
12258 current-tags (org-split-string current ":")
12259 inherited-tags (nreverse
12260 (nthcdr (length current-tags)
12261 (nreverse (org-get-tags-at))))
12262 tags
12263 (if (or (eq t org-use-fast-tag-selection)
12264 (and org-use-fast-tag-selection
12265 (delq nil (mapcar 'cdr table))))
12266 (org-fast-tag-selection
12267 current-tags inherited-tags table
12268 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12269 (let ((org-add-colon-after-tag-completion t))
12270 (org-trim
12271 (org-without-partial-completion
12272 (org-icompleting-read "Tags: " 'org-tags-completion-function
12273 nil nil current 'org-tags-history)))))))
12274 (while (string-match "[-+&]+" tags)
12275 ;; No boolean logic, just a list
12276 (setq tags (replace-match ":" t t tags))))
12278 (if org-tags-sort-function
12279 (setq tags (mapconcat 'identity
12280 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12281 org-tags-sort-function) ":")))
12283 (if (string-match "\\`[\t ]*\\'" tags)
12284 (setq tags "")
12285 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12286 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12288 ;; Insert new tags at the correct column
12289 (beginning-of-line 1)
12290 (cond
12291 ((and (equal current "") (equal tags "")))
12292 ((re-search-forward
12293 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12294 (point-at-eol) t)
12295 (if (equal tags "")
12296 (setq rpl "")
12297 (goto-char (match-beginning 0))
12298 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12299 (1+ (point)) (point))
12300 c1 (max (1+ c0) (if (> org-tags-column 0)
12301 org-tags-column
12302 (- (- org-tags-column) (length tags))))
12303 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12304 (replace-match rpl t t)
12305 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12306 tags)
12307 (t (error "Tags alignment failed")))
12308 (org-move-to-column col)
12309 (unless just-align
12310 (run-hooks 'org-after-tags-change-hook)))))
12312 (defun org-change-tag-in-region (beg end tag off)
12313 "Add or remove TAG for each entry in the region.
12314 This works in the agenda, and also in an org-mode buffer."
12315 (interactive
12316 (list (region-beginning) (region-end)
12317 (let ((org-last-tags-completion-table
12318 (if (org-mode-p)
12319 (org-get-buffer-tags)
12320 (org-global-tags-completion-table))))
12321 (org-icompleting-read
12322 "Tag: " 'org-tags-completion-function nil nil nil
12323 'org-tags-history))
12324 (progn
12325 (message "[s]et or [r]emove? ")
12326 (equal (read-char-exclusive) ?r))))
12327 (if (fboundp 'deactivate-mark) (deactivate-mark))
12328 (let ((agendap (equal major-mode 'org-agenda-mode))
12329 l1 l2 m buf pos newhead (cnt 0))
12330 (goto-char end)
12331 (setq l2 (1- (org-current-line)))
12332 (goto-char beg)
12333 (setq l1 (org-current-line))
12334 (loop for l from l1 to l2 do
12335 (org-goto-line l)
12336 (setq m (get-text-property (point) 'org-hd-marker))
12337 (when (or (and (org-mode-p) (org-on-heading-p))
12338 (and agendap m))
12339 (setq buf (if agendap (marker-buffer m) (current-buffer))
12340 pos (if agendap m (point)))
12341 (with-current-buffer buf
12342 (save-excursion
12343 (save-restriction
12344 (goto-char pos)
12345 (setq cnt (1+ cnt))
12346 (org-toggle-tag tag (if off 'off 'on))
12347 (setq newhead (org-get-heading)))))
12348 (and agendap (org-agenda-change-all-lines newhead m))))
12349 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12351 (defun org-tags-completion-function (string predicate &optional flag)
12352 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12353 (confirm (lambda (x) (stringp (car x)))))
12354 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12355 (setq s1 (match-string 1 string)
12356 s2 (match-string 2 string))
12357 (setq s1 "" s2 string))
12358 (cond
12359 ((eq flag nil)
12360 ;; try completion
12361 (setq rtn (try-completion s2 ctable confirm))
12362 (if (stringp rtn)
12363 (setq rtn
12364 (concat s1 s2 (substring rtn (length s2))
12365 (if (and org-add-colon-after-tag-completion
12366 (assoc rtn ctable))
12367 ":" ""))))
12368 rtn)
12369 ((eq flag t)
12370 ;; all-completions
12371 (all-completions s2 ctable confirm)
12373 ((eq flag 'lambda)
12374 ;; exact match?
12375 (assoc s2 ctable)))
12378 (defun org-fast-tag-insert (kwd tags face &optional end)
12379 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12380 (insert (format "%-12s" (concat kwd ":"))
12381 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12382 (or end "")))
12384 (defun org-fast-tag-show-exit (flag)
12385 (save-excursion
12386 (org-goto-line 3)
12387 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12388 (replace-match ""))
12389 (when flag
12390 (end-of-line 1)
12391 (org-move-to-column (- (window-width) 19) t)
12392 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12394 (defun org-set-current-tags-overlay (current prefix)
12395 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12396 (if (featurep 'xemacs)
12397 (org-overlay-display org-tags-overlay (concat prefix s)
12398 'secondary-selection)
12399 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12400 (org-overlay-display org-tags-overlay (concat prefix s)))))
12402 (defvar org-last-tag-selection-key nil)
12403 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12404 "Fast tag selection with single keys.
12405 CURRENT is the current list of tags in the headline, INHERITED is the
12406 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12407 possibly with grouping information. TODO-TABLE is a similar table with
12408 TODO keywords, should these have keys assigned to them.
12409 If the keys are nil, a-z are automatically assigned.
12410 Returns the new tags string, or nil to not change the current settings."
12411 (let* ((fulltable (append table todo-table))
12412 (maxlen (apply 'max (mapcar
12413 (lambda (x)
12414 (if (stringp (car x)) (string-width (car x)) 0))
12415 fulltable)))
12416 (buf (current-buffer))
12417 (expert (eq org-fast-tag-selection-single-key 'expert))
12418 (buffer-tags nil)
12419 (fwidth (+ maxlen 3 1 3))
12420 (ncol (/ (- (window-width) 4) fwidth))
12421 (i-face 'org-done)
12422 (c-face 'org-todo)
12423 tg cnt e c char c1 c2 ntable tbl rtn
12424 ov-start ov-end ov-prefix
12425 (exit-after-next org-fast-tag-selection-single-key)
12426 (done-keywords org-done-keywords)
12427 groups ingroup)
12428 (save-excursion
12429 (beginning-of-line 1)
12430 (if (looking-at
12431 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12432 (setq ov-start (match-beginning 1)
12433 ov-end (match-end 1)
12434 ov-prefix "")
12435 (setq ov-start (1- (point-at-eol))
12436 ov-end (1+ ov-start))
12437 (skip-chars-forward "^\n\r")
12438 (setq ov-prefix
12439 (concat
12440 (buffer-substring (1- (point)) (point))
12441 (if (> (current-column) org-tags-column)
12443 (make-string (- org-tags-column (current-column)) ?\ ))))))
12444 (move-overlay org-tags-overlay ov-start ov-end)
12445 (save-window-excursion
12446 (if expert
12447 (set-buffer (get-buffer-create " *Org tags*"))
12448 (delete-other-windows)
12449 (split-window-vertically)
12450 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12451 (erase-buffer)
12452 (org-set-local 'org-done-keywords done-keywords)
12453 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12454 (org-fast-tag-insert "Current" current c-face "\n\n")
12455 (org-fast-tag-show-exit exit-after-next)
12456 (org-set-current-tags-overlay current ov-prefix)
12457 (setq tbl fulltable char ?a cnt 0)
12458 (while (setq e (pop tbl))
12459 (cond
12460 ((equal (car e) :startgroup)
12461 (push '() groups) (setq ingroup t)
12462 (when (not (= cnt 0))
12463 (setq cnt 0)
12464 (insert "\n"))
12465 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12466 ((equal (car e) :endgroup)
12467 (setq ingroup nil cnt 0)
12468 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12469 ((equal e '(:newline))
12470 (when (not (= cnt 0))
12471 (setq cnt 0)
12472 (insert "\n")
12473 (setq e (car tbl))
12474 (while (equal (car tbl) '(:newline))
12475 (insert "\n")
12476 (setq tbl (cdr tbl)))))
12478 (setq tg (copy-sequence (car e)) c2 nil)
12479 (if (cdr e)
12480 (setq c (cdr e))
12481 ;; automatically assign a character.
12482 (setq c1 (string-to-char
12483 (downcase (substring
12484 tg (if (= (string-to-char tg) ?@) 1 0)))))
12485 (if (or (rassoc c1 ntable) (rassoc c1 table))
12486 (while (or (rassoc char ntable) (rassoc char table))
12487 (setq char (1+ char)))
12488 (setq c2 c1))
12489 (setq c (or c2 char)))
12490 (if ingroup (push tg (car groups)))
12491 (setq tg (org-add-props tg nil 'face
12492 (cond
12493 ((not (assoc tg table))
12494 (org-get-todo-face tg))
12495 ((member tg current) c-face)
12496 ((member tg inherited) i-face)
12497 (t nil))))
12498 (if (and (= cnt 0) (not ingroup)) (insert " "))
12499 (insert "[" c "] " tg (make-string
12500 (- fwidth 4 (length tg)) ?\ ))
12501 (push (cons tg c) ntable)
12502 (when (= (setq cnt (1+ cnt)) ncol)
12503 (insert "\n")
12504 (if ingroup (insert " "))
12505 (setq cnt 0)))))
12506 (setq ntable (nreverse ntable))
12507 (insert "\n")
12508 (goto-char (point-min))
12509 (if (not expert) (org-fit-window-to-buffer))
12510 (setq rtn
12511 (catch 'exit
12512 (while t
12513 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12514 (if (not groups) "no " "")
12515 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12516 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12517 (setq org-last-tag-selection-key c)
12518 (cond
12519 ((= c ?\r) (throw 'exit t))
12520 ((= c ?!)
12521 (setq groups (not groups))
12522 (goto-char (point-min))
12523 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12524 ((= c ?\C-c)
12525 (if (not expert)
12526 (org-fast-tag-show-exit
12527 (setq exit-after-next (not exit-after-next)))
12528 (setq expert nil)
12529 (delete-other-windows)
12530 (split-window-vertically)
12531 (org-switch-to-buffer-other-window " *Org tags*")
12532 (org-fit-window-to-buffer)))
12533 ((or (= c ?\C-g)
12534 (and (= c ?q) (not (rassoc c ntable))))
12535 (org-detach-overlay org-tags-overlay)
12536 (setq quit-flag t))
12537 ((= c ?\ )
12538 (setq current nil)
12539 (if exit-after-next (setq exit-after-next 'now)))
12540 ((= c ?\t)
12541 (condition-case nil
12542 (setq tg (org-icompleting-read
12543 "Tag: "
12544 (or buffer-tags
12545 (with-current-buffer buf
12546 (org-get-buffer-tags)))))
12547 (quit (setq tg "")))
12548 (when (string-match "\\S-" tg)
12549 (add-to-list 'buffer-tags (list tg))
12550 (if (member tg current)
12551 (setq current (delete tg current))
12552 (push tg current)))
12553 (if exit-after-next (setq exit-after-next 'now)))
12554 ((setq e (rassoc c todo-table) tg (car e))
12555 (with-current-buffer buf
12556 (save-excursion (org-todo tg)))
12557 (if exit-after-next (setq exit-after-next 'now)))
12558 ((setq e (rassoc c ntable) tg (car e))
12559 (if (member tg current)
12560 (setq current (delete tg current))
12561 (loop for g in groups do
12562 (if (member tg g)
12563 (mapc (lambda (x)
12564 (setq current (delete x current)))
12565 g)))
12566 (push tg current))
12567 (if exit-after-next (setq exit-after-next 'now))))
12569 ;; Create a sorted list
12570 (setq current
12571 (sort current
12572 (lambda (a b)
12573 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12574 (if (eq exit-after-next 'now) (throw 'exit t))
12575 (goto-char (point-min))
12576 (beginning-of-line 2)
12577 (delete-region (point) (point-at-eol))
12578 (org-fast-tag-insert "Current" current c-face)
12579 (org-set-current-tags-overlay current ov-prefix)
12580 (while (re-search-forward
12581 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12582 (setq tg (match-string 1))
12583 (add-text-properties
12584 (match-beginning 1) (match-end 1)
12585 (list 'face
12586 (cond
12587 ((member tg current) c-face)
12588 ((member tg inherited) i-face)
12589 (t (get-text-property (match-beginning 1) 'face))))))
12590 (goto-char (point-min)))))
12591 (org-detach-overlay org-tags-overlay)
12592 (if rtn
12593 (mapconcat 'identity current ":")
12594 nil))))
12596 (defun org-get-tags-string ()
12597 "Get the TAGS string in the current headline."
12598 (unless (org-on-heading-p t)
12599 (error "Not on a heading"))
12600 (save-excursion
12601 (beginning-of-line 1)
12602 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12603 (org-match-string-no-properties 1)
12604 "")))
12606 (defun org-get-tags ()
12607 "Get the list of tags specified in the current headline."
12608 (org-split-string (org-get-tags-string) ":"))
12610 (defun org-get-buffer-tags ()
12611 "Get a table of all tags used in the buffer, for completion."
12612 (let (tags)
12613 (save-excursion
12614 (goto-char (point-min))
12615 (while (re-search-forward
12616 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12617 (when (equal (char-after (point-at-bol 0)) ?*)
12618 (mapc (lambda (x) (add-to-list 'tags x))
12619 (org-split-string (org-match-string-no-properties 1) ":")))))
12620 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12621 (mapcar 'list tags)))
12623 ;;;; The mapping API
12625 ;;;###autoload
12626 (defun org-map-entries (func &optional match scope &rest skip)
12627 "Call FUNC at each headline selected by MATCH in SCOPE.
12629 FUNC is a function or a lisp form. The function will be called without
12630 arguments, with the cursor positioned at the beginning of the headline.
12631 The return values of all calls to the function will be collected and
12632 returned as a list.
12634 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12635 does not need to preserve point. After evaluation, the cursor will be
12636 moved to the end of the line (presumably of the headline of the
12637 processed entry) and search continues from there. Under some
12638 circumstances, this may not produce the wanted results. For example,
12639 if you have removed (e.g. archived) the current (sub)tree it could
12640 mean that the next entry will be skipped entirely. In such cases, you
12641 can specify the position from where search should continue by making
12642 FUNC set the variable `org-map-continue-from' to the desired buffer
12643 position.
12645 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12646 Only headlines that are matched by this query will be considered during
12647 the iteration. When MATCH is nil or t, all headlines will be
12648 visited by the iteration.
12650 SCOPE determines the scope of this command. It can be any of:
12652 nil The current buffer, respecting the restriction if any
12653 tree The subtree started with the entry at point
12654 file The current buffer, without restriction
12655 file-with-archives
12656 The current buffer, and any archives associated with it
12657 agenda All agenda files
12658 agenda-with-archives
12659 All agenda files with any archive files associated with them
12660 \(file1 file2 ...)
12661 If this is a list, all files in the list will be scanned
12663 The remaining args are treated as settings for the skipping facilities of
12664 the scanner. The following items can be given here:
12666 archive skip trees with the archive tag.
12667 comment skip trees with the COMMENT keyword
12668 function or Emacs Lisp form:
12669 will be used as value for `org-agenda-skip-function', so whenever
12670 the function returns t, FUNC will not be called for that
12671 entry and search will continue from the point where the
12672 function leaves it.
12674 If your function needs to retrieve the tags including inherited tags
12675 at the *current* entry, you can use the value of the variable
12676 `org-scanner-tags' which will be much faster than getting the value
12677 with `org-get-tags-at'. If your function gets properties with
12678 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12679 to t around the call to `org-entry-properties' to get the same speedup.
12680 Note that if your function moves around to retrieve tags and properties at
12681 a *different* entry, you cannot use these techniques."
12682 (let* ((org-agenda-archives-mode nil) ; just to make sure
12683 (org-agenda-skip-archived-trees (memq 'archive skip))
12684 (org-agenda-skip-comment-trees (memq 'comment skip))
12685 (org-agenda-skip-function
12686 (car (org-delete-all '(comment archive) skip)))
12687 (org-tags-match-list-sublevels t)
12688 matcher file res
12689 org-todo-keywords-for-agenda
12690 org-done-keywords-for-agenda
12691 org-todo-keyword-alist-for-agenda
12692 org-drawers-for-agenda
12693 org-tag-alist-for-agenda)
12695 (cond
12696 ((eq match t) (setq matcher t))
12697 ((eq match nil) (setq matcher t))
12698 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12700 (save-excursion
12701 (save-restriction
12702 (when (eq scope 'tree)
12703 (org-back-to-heading t)
12704 (org-narrow-to-subtree)
12705 (setq scope nil))
12707 (if (not scope)
12708 (progn
12709 (org-prepare-agenda-buffers
12710 (list (buffer-file-name (current-buffer))))
12711 (setq res (org-scan-tags func matcher)))
12712 ;; Get the right scope
12713 (cond
12714 ((and scope (listp scope) (symbolp (car scope)))
12715 (setq scope (eval scope)))
12716 ((eq scope 'agenda)
12717 (setq scope (org-agenda-files t)))
12718 ((eq scope 'agenda-with-archives)
12719 (setq scope (org-agenda-files t))
12720 (setq scope (org-add-archive-files scope)))
12721 ((eq scope 'file)
12722 (setq scope (list (buffer-file-name))))
12723 ((eq scope 'file-with-archives)
12724 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12725 (org-prepare-agenda-buffers scope)
12726 (while (setq file (pop scope))
12727 (with-current-buffer (org-find-base-buffer-visiting file)
12728 (save-excursion
12729 (save-restriction
12730 (widen)
12731 (goto-char (point-min))
12732 (setq res (append res (org-scan-tags func matcher))))))))))
12733 res))
12735 ;;;; Properties
12737 ;;; Setting and retrieving properties
12739 (defconst org-special-properties
12740 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12741 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12742 "The special properties valid in Org-mode.
12744 These are properties that are not defined in the property drawer,
12745 but in some other way.")
12747 (defconst org-default-properties
12748 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12749 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12750 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12751 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12752 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
12753 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12754 "Some properties that are used by Org-mode for various purposes.
12755 Being in this list makes sure that they are offered for completion.")
12757 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12758 "Regular expression matching the first line of a property drawer.")
12760 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12761 "Regular expression matching the last line of a property drawer.")
12763 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12764 "Regular expression matching the first line of a property drawer.")
12766 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12767 "Regular expression matching the first line of a property drawer.")
12769 (defconst org-property-drawer-re
12770 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12771 org-property-end-re "\\)\n?")
12772 "Matches an entire property drawer.")
12774 (defconst org-clock-drawer-re
12775 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12776 org-property-end-re "\\)\n?")
12777 "Matches an entire clock drawer.")
12779 (defun org-property-action ()
12780 "Do an action on properties."
12781 (interactive)
12782 (let (c)
12783 (org-at-property-p)
12784 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12785 (setq c (read-char-exclusive))
12786 (cond
12787 ((equal c ?s)
12788 (call-interactively 'org-set-property))
12789 ((equal c ?d)
12790 (call-interactively 'org-delete-property))
12791 ((equal c ?D)
12792 (call-interactively 'org-delete-property-globally))
12793 ((equal c ?c)
12794 (call-interactively 'org-compute-property-at-point))
12795 (t (error "No such property action %c" c)))))
12797 (defun org-set-effort (&optional value)
12798 "Set the effort property of the current entry.
12799 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12800 allowed value."
12801 (interactive "P")
12802 (if (equal value 0) (setq value 10))
12803 (let* ((completion-ignore-case t)
12804 (prop org-effort-property)
12805 (cur (org-entry-get nil prop))
12806 (allowed (org-property-get-allowed-values nil prop 'table))
12807 (existing (mapcar 'list (org-property-values prop)))
12809 (val (cond
12810 ((stringp value) value)
12811 ((and allowed (integerp value))
12812 (or (car (nth (1- value) allowed))
12813 (car (org-last allowed))))
12814 (allowed
12815 (message "Select 1-9,0, [RET%s]: %s"
12816 (if cur (concat "=" cur) "")
12817 (mapconcat 'car allowed " "))
12818 (setq rpl (read-char-exclusive))
12819 (if (equal rpl ?\r)
12821 (setq rpl (- rpl ?0))
12822 (if (equal rpl 0) (setq rpl 10))
12823 (if (and (> rpl 0) (<= rpl (length allowed)))
12824 (car (nth (1- rpl) allowed))
12825 (org-completing-read "Effort: " allowed nil))))
12827 (let (org-completion-use-ido org-completion-use-iswitchb)
12828 (org-completing-read
12829 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12830 (concat "[" cur "]") "")
12831 ": ")
12832 existing nil nil "" nil cur))))))
12833 (unless (equal (org-entry-get nil prop) val)
12834 (org-entry-put nil prop val))
12835 (message "%s is now %s" prop val)))
12837 (defun org-at-property-p ()
12838 "Is cursor inside a property drawer?"
12839 (save-excursion
12840 (beginning-of-line 1)
12841 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12842 (let ((match (match-data)) ;; Keep match-data for use by calling
12843 (p (point)) ;; procedures.
12844 (range (unless (org-before-first-heading-p)
12845 (org-get-property-block))))
12846 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12847 (set-match-data match))))))
12849 (defun org-get-property-block (&optional beg end force)
12850 "Return the (beg . end) range of the body of the property drawer.
12851 BEG and END can be beginning and end of subtree, if not given
12852 they will be found.
12853 If the drawer does not exist and FORCE is non-nil, create the drawer."
12854 (catch 'exit
12855 (save-excursion
12856 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12857 (end (or end (progn (outline-next-heading) (point)))))
12858 (goto-char beg)
12859 (if (re-search-forward org-property-start-re end t)
12860 (setq beg (1+ (match-end 0)))
12861 (if force
12862 (save-excursion
12863 (org-insert-property-drawer)
12864 (setq end (progn (outline-next-heading) (point))))
12865 (throw 'exit nil))
12866 (goto-char beg)
12867 (if (re-search-forward org-property-start-re end t)
12868 (setq beg (1+ (match-end 0)))))
12869 (if (re-search-forward org-property-end-re end t)
12870 (setq end (match-beginning 0))
12871 (or force (throw 'exit nil))
12872 (goto-char beg)
12873 (setq end beg)
12874 (org-indent-line-function)
12875 (insert ":END:\n"))
12876 (cons beg end)))))
12878 (defun org-entry-properties (&optional pom which specific)
12879 "Get all properties of the entry at point-or-marker POM.
12880 This includes the TODO keyword, the tags, time strings for deadline,
12881 scheduled, and clocking, and any additional properties defined in the
12882 entry. The return value is an alist, keys may occur multiple times
12883 if the property key was used several times.
12884 POM may also be nil, in which case the current entry is used.
12885 If WHICH is nil or `all', get all properties. If WHICH is
12886 `special' or `standard', only get that subclass. If WHICH
12887 is a string only get exactly this property. Specific can be a string, the
12888 specific property we are interested in. Specifying it can speed
12889 things up because then unnecessary parsing is avoided."
12890 (setq which (or which 'all))
12891 (org-with-point-at pom
12892 (let ((clockstr (substring org-clock-string 0 -1))
12893 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12894 (case-fold-search nil)
12895 beg end range props sum-props key value string clocksum)
12896 (save-excursion
12897 (when (condition-case nil
12898 (and (org-mode-p) (org-back-to-heading t))
12899 (error nil))
12900 (setq beg (point))
12901 (setq sum-props (get-text-property (point) 'org-summaries))
12902 (setq clocksum (get-text-property (point) :org-clock-minutes))
12903 (outline-next-heading)
12904 (setq end (point))
12905 (when (memq which '(all special))
12906 ;; Get the special properties, like TODO and tags
12907 (goto-char beg)
12908 (when (and (or (not specific) (string= specific "TODO"))
12909 (looking-at org-todo-line-regexp) (match-end 2))
12910 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12911 (when (and (or (not specific) (string= specific "PRIORITY"))
12912 (looking-at org-priority-regexp))
12913 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12914 (when (and (or (not specific) (string= specific "TAGS"))
12915 (setq value (org-get-tags-string))
12916 (string-match "\\S-" value))
12917 (push (cons "TAGS" value) props))
12918 (when (and (or (not specific) (string= specific "ALLTAGS"))
12919 (setq value (org-get-tags-at)))
12920 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12921 ":"))
12922 props))
12923 (when (or (not specific) (string= specific "BLOCKED"))
12924 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12925 (when (or (not specific)
12926 (member specific org-all-time-keywords)
12927 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12928 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12929 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12930 string (if (equal key clockstr)
12931 (org-no-properties
12932 (org-trim
12933 (buffer-substring
12934 (match-beginning 3) (goto-char (point-at-eol)))))
12935 (substring (org-match-string-no-properties 3) 1 -1)))
12936 (unless key
12937 (if (= (char-after (match-beginning 3)) ?\[)
12938 (setq key "TIMESTAMP_IA")
12939 (setq key "TIMESTAMP")))
12940 (when (or (equal key clockstr) (not (assoc key props)))
12941 (push (cons key string) props))))
12945 (when (memq which '(all standard))
12946 ;; Get the standard properties, like :PROP: ...
12947 (setq range (org-get-property-block beg end))
12948 (when range
12949 (goto-char (car range))
12950 (while (re-search-forward
12951 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12952 (cdr range) t)
12953 (setq key (org-match-string-no-properties 1)
12954 value (org-trim (or (org-match-string-no-properties 2) "")))
12955 (unless (member key excluded)
12956 (push (cons key (or value "")) props)))))
12957 (if clocksum
12958 (push (cons "CLOCKSUM"
12959 (org-columns-number-to-string (/ (float clocksum) 60.)
12960 'add_times))
12961 props))
12962 (unless (assoc "CATEGORY" props)
12963 (setq value (or (org-get-category)
12964 (progn (org-refresh-category-properties)
12965 (org-get-category))))
12966 (push (cons "CATEGORY" value) props))
12967 (append sum-props (nreverse props)))))))
12969 (defun org-entry-get (pom property &optional inherit)
12970 "Get value of PROPERTY for entry at point-or-marker POM.
12971 If INHERIT is non-nil and the entry does not have the property,
12972 then also check higher levels of the hierarchy.
12973 If INHERIT is the symbol `selective', use inheritance only if the setting
12974 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12975 If the property is present but empty, the return value is the empty string.
12976 If the property is not present at all, nil is returned."
12977 (org-with-point-at pom
12978 (if (and inherit (if (eq inherit 'selective)
12979 (org-property-inherit-p property)
12981 (org-entry-get-with-inheritance property)
12982 (if (member property org-special-properties)
12983 ;; We need a special property. Use `org-entry-properties' to
12984 ;; retrieve it, but specify the wanted property
12985 (cdr (assoc property (org-entry-properties nil 'special property)))
12986 (let ((range (org-get-property-block)))
12987 (if (and range
12988 (goto-char (car range))
12989 (re-search-forward
12990 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12991 (cdr range) t))
12992 ;; Found the property, return it.
12993 (if (match-end 1)
12994 (org-match-string-no-properties 1)
12995 "")))))))
12997 (defun org-property-or-variable-value (var &optional inherit)
12998 "Check if there is a property fixing the value of VAR.
12999 If yes, return this value. If not, return the current value of the variable."
13000 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13001 (if (and prop (stringp prop) (string-match "\\S-" prop))
13002 (read prop)
13003 (symbol-value var))))
13005 (defun org-entry-delete (pom property)
13006 "Delete the property PROPERTY from entry at point-or-marker POM."
13007 (org-with-point-at pom
13008 (if (member property org-special-properties)
13009 nil ; cannot delete these properties.
13010 (let ((range (org-get-property-block)))
13011 (if (and range
13012 (goto-char (car range))
13013 (re-search-forward
13014 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13015 (cdr range) t))
13016 (progn
13017 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13019 nil)))))
13021 ;; Multi-values properties are properties that contain multiple values
13022 ;; These values are assumed to be single words, separated by whitespace.
13023 (defun org-entry-add-to-multivalued-property (pom property value)
13024 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13025 (let* ((old (org-entry-get pom property))
13026 (values (and old (org-split-string old "[ \t]"))))
13027 (setq value (org-entry-protect-space value))
13028 (unless (member value values)
13029 (setq values (cons value values))
13030 (org-entry-put pom property
13031 (mapconcat 'identity values " ")))))
13033 (defun org-entry-remove-from-multivalued-property (pom property value)
13034 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13035 (let* ((old (org-entry-get pom property))
13036 (values (and old (org-split-string old "[ \t]"))))
13037 (setq value (org-entry-protect-space value))
13038 (when (member value values)
13039 (setq values (delete value values))
13040 (org-entry-put pom property
13041 (mapconcat 'identity values " ")))))
13043 (defun org-entry-member-in-multivalued-property (pom property value)
13044 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13045 (let* ((old (org-entry-get pom property))
13046 (values (and old (org-split-string old "[ \t]"))))
13047 (setq value (org-entry-protect-space value))
13048 (member value values)))
13050 (defun org-entry-get-multivalued-property (pom property)
13051 "Return a list of values in a multivalued property."
13052 (let* ((value (org-entry-get pom property))
13053 (values (and value (org-split-string value "[ \t]"))))
13054 (mapcar 'org-entry-restore-space values)))
13056 (defun org-entry-put-multivalued-property (pom property &rest values)
13057 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13058 VALUES should be a list of strings. Spaces will be protected."
13059 (org-entry-put pom property
13060 (mapconcat 'org-entry-protect-space values " "))
13061 (let* ((value (org-entry-get pom property))
13062 (values (and value (org-split-string value "[ \t]"))))
13063 (mapcar 'org-entry-restore-space values)))
13065 (defun org-entry-protect-space (s)
13066 "Protect spaces and newline in string S."
13067 (while (string-match " " s)
13068 (setq s (replace-match "%20" t t s)))
13069 (while (string-match "\n" s)
13070 (setq s (replace-match "%0A" t t s)))
13073 (defun org-entry-restore-space (s)
13074 "Restore spaces and newline in string S."
13075 (while (string-match "%20" s)
13076 (setq s (replace-match " " t t s)))
13077 (while (string-match "%0A" s)
13078 (setq s (replace-match "\n" t t s)))
13081 (defvar org-entry-property-inherited-from (make-marker)
13082 "Marker pointing to the entry from where a property was inherited.
13083 Each call to `org-entry-get-with-inheritance' will set this marker to the
13084 location of the entry where the inheritance search matched. If there was
13085 no match, the marker will point nowhere.
13086 Note that also `org-entry-get' calls this function, if the INHERIT flag
13087 is set.")
13089 (defun org-entry-get-with-inheritance (property)
13090 "Get entry property, and search higher levels if not present."
13091 (move-marker org-entry-property-inherited-from nil)
13092 (let (tmp)
13093 (save-excursion
13094 (save-restriction
13095 (widen)
13096 (catch 'ex
13097 (while t
13098 (when (setq tmp (org-entry-get nil property))
13099 (org-back-to-heading t)
13100 (move-marker org-entry-property-inherited-from (point))
13101 (throw 'ex tmp))
13102 (or (org-up-heading-safe) (throw 'ex nil)))))
13103 (or tmp
13104 (cdr (assoc property org-file-properties))
13105 (cdr (assoc property org-global-properties))
13106 (cdr (assoc property org-global-properties-fixed))))))
13108 (defvar org-property-changed-functions nil
13109 "Hook called when the value of a property has changed.
13110 Each hook function should accept two arguments, the name of the property
13111 and the new value.")
13113 (defun org-entry-put (pom property value)
13114 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13115 (org-with-point-at pom
13116 (org-back-to-heading t)
13117 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13118 range)
13119 (cond
13120 ((equal property "TODO")
13121 (when (and (stringp value) (string-match "\\S-" value)
13122 (not (member value org-todo-keywords-1)))
13123 (error "\"%s\" is not a valid TODO state" value))
13124 (if (or (not value)
13125 (not (string-match "\\S-" value)))
13126 (setq value 'none))
13127 (org-todo value)
13128 (org-set-tags nil 'align))
13129 ((equal property "PRIORITY")
13130 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13131 (string-to-char value) ?\ ))
13132 (org-set-tags nil 'align))
13133 ((equal property "SCHEDULED")
13134 (if (re-search-forward org-scheduled-time-regexp end t)
13135 (cond
13136 ((eq value 'earlier) (org-timestamp-change -1 'day))
13137 ((eq value 'later) (org-timestamp-change 1 'day))
13138 (t (call-interactively 'org-schedule)))
13139 (call-interactively 'org-schedule)))
13140 ((equal property "DEADLINE")
13141 (if (re-search-forward org-deadline-time-regexp end t)
13142 (cond
13143 ((eq value 'earlier) (org-timestamp-change -1 'day))
13144 ((eq value 'later) (org-timestamp-change 1 'day))
13145 (t (call-interactively 'org-deadline)))
13146 (call-interactively 'org-deadline)))
13147 ((member property org-special-properties)
13148 (error "The %s property can not yet be set with `org-entry-put'"
13149 property))
13150 (t ; a non-special property
13151 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13152 (setq range (org-get-property-block beg end 'force))
13153 (goto-char (car range))
13154 (if (re-search-forward
13155 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13156 (progn
13157 (delete-region (match-beginning 1) (match-end 1))
13158 (goto-char (match-beginning 1)))
13159 (goto-char (cdr range))
13160 (insert "\n")
13161 (backward-char 1)
13162 (org-indent-line-function)
13163 (insert ":" property ":"))
13164 (and value (insert " " value))
13165 (org-indent-line-function)))))
13166 (run-hook-with-args 'org-property-changed-functions property value)))
13168 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13169 "Get all property keys in the current buffer.
13170 With INCLUDE-SPECIALS, also list the special properties that reflect things
13171 like tags and TODO state.
13172 With INCLUDE-DEFAULTS, also include properties that has special meaning
13173 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13174 With INCLUDE-COLUMNS, also include property names given in COLUMN
13175 formats in the current buffer."
13176 (let (rtn range cfmt s p)
13177 (save-excursion
13178 (save-restriction
13179 (widen)
13180 (goto-char (point-min))
13181 (while (re-search-forward org-property-start-re nil t)
13182 (setq range (org-get-property-block))
13183 (goto-char (car range))
13184 (while (re-search-forward
13185 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13186 (cdr range) t)
13187 (add-to-list 'rtn (org-match-string-no-properties 1)))
13188 (outline-next-heading))))
13190 (when include-specials
13191 (setq rtn (append org-special-properties rtn)))
13193 (when include-defaults
13194 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13195 (add-to-list 'rtn org-effort-property))
13197 (when include-columns
13198 (save-excursion
13199 (save-restriction
13200 (widen)
13201 (goto-char (point-min))
13202 (while (re-search-forward
13203 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13204 nil t)
13205 (setq cfmt (match-string 2) s 0)
13206 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13207 cfmt s)
13208 (setq s (match-end 0)
13209 p (match-string 1 cfmt))
13210 (unless (or (equal p "ITEM")
13211 (member p org-special-properties))
13212 (add-to-list 'rtn (match-string 1 cfmt))))))))
13214 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13216 (defun org-property-values (key)
13217 "Return a list of all values of property KEY."
13218 (save-excursion
13219 (save-restriction
13220 (widen)
13221 (goto-char (point-min))
13222 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13223 values)
13224 (while (re-search-forward re nil t)
13225 (add-to-list 'values (org-trim (match-string 1))))
13226 (delete "" values)))))
13228 (defun org-insert-property-drawer ()
13229 "Insert a property drawer into the current entry."
13230 (interactive)
13231 (org-back-to-heading t)
13232 (looking-at outline-regexp)
13233 (let ((indent (if org-adapt-indentation
13234 (- (match-end 0)(match-beginning 0))
13236 (beg (point))
13237 (re (concat "^[ \t]*" org-keyword-time-regexp))
13238 end hiddenp)
13239 (outline-next-heading)
13240 (setq end (point))
13241 (goto-char beg)
13242 (while (re-search-forward re end t))
13243 (setq hiddenp (org-invisible-p))
13244 (end-of-line 1)
13245 (and (equal (char-after) ?\n) (forward-char 1))
13246 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13247 (if (member (match-string 1) '("CLOCK:" ":END:"))
13248 ;; just skip this line
13249 (beginning-of-line 2)
13250 ;; Drawer start, find the end
13251 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13252 (beginning-of-line 1)))
13253 (org-skip-over-state-notes)
13254 (skip-chars-backward " \t\n\r")
13255 (if (eq (char-before) ?*) (forward-char 1))
13256 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13257 (beginning-of-line 0)
13258 (org-indent-to-column indent)
13259 (beginning-of-line 2)
13260 (org-indent-to-column indent)
13261 (beginning-of-line 0)
13262 (if hiddenp
13263 (save-excursion
13264 (org-back-to-heading t)
13265 (hide-entry))
13266 (org-flag-drawer t))))
13268 (defun org-set-property (property value)
13269 "In the current entry, set PROPERTY to VALUE.
13270 When called interactively, this will prompt for a property name, offering
13271 completion on existing and default properties. And then it will prompt
13272 for a value, offering completion either on allowed values (via an inherited
13273 xxx_ALL property) or on existing values in other instances of this property
13274 in the current file."
13275 (interactive
13276 (let* ((completion-ignore-case t)
13277 (keys (org-buffer-property-keys nil t t))
13278 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13279 (prop (if (member prop0 keys)
13280 prop0
13281 (or (cdr (assoc (downcase prop0)
13282 (mapcar (lambda (x) (cons (downcase x) x))
13283 keys)))
13284 prop0)))
13285 (cur (org-entry-get nil prop))
13286 (prompt (concat prop " value"
13287 (if (and cur (string-match "\\S-" cur))
13288 (concat " [" cur "]") "") ": "))
13289 (allowed (org-property-get-allowed-values nil prop 'table))
13290 (existing (mapcar 'list (org-property-values prop)))
13291 (val (if allowed
13292 (org-completing-read prompt allowed nil
13293 (not (get-text-property 0 'org-unrestricted
13294 (caar allowed))))
13295 (let (org-completion-use-ido org-completion-use-iswitchb)
13296 (org-completing-read prompt existing nil nil "" nil cur)))))
13297 (list prop (if (equal val "") cur val))))
13298 (unless (equal (org-entry-get nil property) value)
13299 (org-entry-put nil property value)))
13301 (defun org-delete-property (property)
13302 "In the current entry, delete PROPERTY."
13303 (interactive
13304 (let* ((completion-ignore-case t)
13305 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13306 (list prop)))
13307 (message "Property %s %s" property
13308 (if (org-entry-delete nil property)
13309 "deleted"
13310 "was not present in the entry")))
13312 (defun org-delete-property-globally (property)
13313 "Remove PROPERTY globally, from all entries."
13314 (interactive
13315 (let* ((completion-ignore-case t)
13316 (prop (org-icompleting-read
13317 "Globally remove property: "
13318 (mapcar 'list (org-buffer-property-keys)))))
13319 (list prop)))
13320 (save-excursion
13321 (save-restriction
13322 (widen)
13323 (goto-char (point-min))
13324 (let ((cnt 0))
13325 (while (re-search-forward
13326 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13327 nil t)
13328 (setq cnt (1+ cnt))
13329 (replace-match ""))
13330 (message "Property \"%s\" removed from %d entries" property cnt)))))
13332 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13334 (defun org-compute-property-at-point ()
13335 "Compute the property at point.
13336 This looks for an enclosing column format, extracts the operator and
13337 then applies it to the property in the column format's scope."
13338 (interactive)
13339 (unless (org-at-property-p)
13340 (error "Not at a property"))
13341 (let ((prop (org-match-string-no-properties 2)))
13342 (org-columns-get-format-and-top-level)
13343 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13344 (error "No operator defined for property %s" prop))
13345 (org-columns-compute prop)))
13347 (defvar org-property-allowed-value-functions nil
13348 "Hook for functions supplying allowed values for a specific property.
13349 The functions must take a single argument, the name of the property, and
13350 return a flat list of allowed values. If \":ETC\" is one of
13351 the values, this means that these values are intended as defaults for
13352 completion, but that other values should be allowed too.
13353 The functions must return nil if they are not responsible for this
13354 property.")
13356 (defun org-property-get-allowed-values (pom property &optional table)
13357 "Get allowed values for the property PROPERTY.
13358 When TABLE is non-nil, return an alist that can directly be used for
13359 completion."
13360 (let (vals)
13361 (cond
13362 ((equal property "TODO")
13363 (setq vals (org-with-point-at pom
13364 (append org-todo-keywords-1 '("")))))
13365 ((equal property "PRIORITY")
13366 (let ((n org-lowest-priority))
13367 (while (>= n org-highest-priority)
13368 (push (char-to-string n) vals)
13369 (setq n (1- n)))))
13370 ((member property org-special-properties))
13371 ((setq vals (run-hook-with-args-until-success
13372 'org-property-allowed-value-functions property)))
13374 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13375 (when (and vals (string-match "\\S-" vals))
13376 (setq vals (car (read-from-string (concat "(" vals ")"))))
13377 (setq vals (mapcar (lambda (x)
13378 (cond ((stringp x) x)
13379 ((numberp x) (number-to-string x))
13380 ((symbolp x) (symbol-name x))
13381 (t "???")))
13382 vals)))))
13383 (when (member ":ETC" vals)
13384 (setq vals (remove ":ETC" vals))
13385 (org-add-props (car vals) '(org-unrestricted t)))
13386 (if table (mapcar 'list vals) vals)))
13388 (defun org-property-previous-allowed-value (&optional previous)
13389 "Switch to the next allowed value for this property."
13390 (interactive)
13391 (org-property-next-allowed-value t))
13393 (defun org-property-next-allowed-value (&optional previous)
13394 "Switch to the next allowed value for this property."
13395 (interactive)
13396 (unless (org-at-property-p)
13397 (error "Not at a property"))
13398 (let* ((key (match-string 2))
13399 (value (match-string 3))
13400 (allowed (or (org-property-get-allowed-values (point) key)
13401 (and (member value '("[ ]" "[-]" "[X]"))
13402 '("[ ]" "[X]"))))
13403 nval)
13404 (unless allowed
13405 (error "Allowed values for this property have not been defined"))
13406 (if previous (setq allowed (reverse allowed)))
13407 (if (member value allowed)
13408 (setq nval (car (cdr (member value allowed)))))
13409 (setq nval (or nval (car allowed)))
13410 (if (equal nval value)
13411 (error "Only one allowed value for this property"))
13412 (org-at-property-p)
13413 (replace-match (concat " :" key ": " nval) t t)
13414 (org-indent-line-function)
13415 (beginning-of-line 1)
13416 (skip-chars-forward " \t")
13417 (run-hook-with-args 'org-property-changed-functions key nval)))
13419 (defun org-find-entry-with-id (ident)
13420 "Locate the entry that contains the ID property with exact value IDENT.
13421 IDENT can be a string, a symbol or a number, this function will search for
13422 the string representation of it.
13423 Return the position where this entry starts, or nil if there is no such entry."
13424 (interactive "sID: ")
13425 (let ((id (cond
13426 ((stringp ident) ident)
13427 ((symbol-name ident) (symbol-name ident))
13428 ((numberp ident) (number-to-string ident))
13429 (t (error "IDENT %s must be a string, symbol or number" ident))))
13430 (case-fold-search nil))
13431 (save-excursion
13432 (save-restriction
13433 (widen)
13434 (goto-char (point-min))
13435 (when (re-search-forward
13436 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13437 nil t)
13438 (org-back-to-heading t)
13439 (point))))))
13441 ;;;; Timestamps
13443 (defvar org-last-changed-timestamp nil)
13444 (defvar org-last-inserted-timestamp nil
13445 "The last time stamp inserted with `org-insert-time-stamp'.")
13446 (defvar org-time-was-given) ; dynamically scoped parameter
13447 (defvar org-end-time-was-given) ; dynamically scoped parameter
13448 (defvar org-ts-what) ; dynamically scoped parameter
13450 (defun org-time-stamp (arg &optional inactive)
13451 "Prompt for a date/time and insert a time stamp.
13452 If the user specifies a time like HH:MM, or if this command is called
13453 with a prefix argument, the time stamp will contain date and time.
13454 Otherwise, only the date will be included. All parts of a date not
13455 specified by the user will be filled in from the current date/time.
13456 So if you press just return without typing anything, the time stamp
13457 will represent the current date/time. If there is already a timestamp
13458 at the cursor, it will be modified."
13459 (interactive "P")
13460 (let* ((ts nil)
13461 (default-time
13462 ;; Default time is either today, or, when entering a range,
13463 ;; the range start.
13464 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13465 (save-excursion
13466 (re-search-backward
13467 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13468 (- (point) 20) t)))
13469 (apply 'encode-time (org-parse-time-string (match-string 1)))
13470 (current-time)))
13471 (default-input (and ts (org-get-compact-tod ts)))
13472 org-time-was-given org-end-time-was-given time)
13473 (cond
13474 ((and (org-at-timestamp-p t)
13475 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13476 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13477 (insert "--")
13478 (setq time (let ((this-command this-command))
13479 (org-read-date arg 'totime nil nil
13480 default-time default-input)))
13481 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13482 ((org-at-timestamp-p t)
13483 (setq time (let ((this-command this-command))
13484 (org-read-date arg 'totime nil nil default-time default-input)))
13485 (when (org-at-timestamp-p t) ; just to get the match data
13486 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13487 (replace-match "")
13488 (setq org-last-changed-timestamp
13489 (org-insert-time-stamp
13490 time (or org-time-was-given arg)
13491 inactive nil nil (list org-end-time-was-given))))
13492 (message "Timestamp updated"))
13494 (setq time (let ((this-command this-command))
13495 (org-read-date arg 'totime nil nil default-time default-input)))
13496 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13497 nil nil (list org-end-time-was-given))))))
13499 ;; FIXME: can we use this for something else, like computing time differences?
13500 (defun org-get-compact-tod (s)
13501 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13502 (let* ((t1 (match-string 1 s))
13503 (h1 (string-to-number (match-string 2 s)))
13504 (m1 (string-to-number (match-string 3 s)))
13505 (t2 (and (match-end 4) (match-string 5 s)))
13506 (h2 (and t2 (string-to-number (match-string 6 s))))
13507 (m2 (and t2 (string-to-number (match-string 7 s))))
13508 dh dm)
13509 (if (not t2)
13511 (setq dh (- h2 h1) dm (- m2 m1))
13512 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13513 (concat t1 "+" (number-to-string dh)
13514 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13516 (defun org-time-stamp-inactive (&optional arg)
13517 "Insert an inactive time stamp.
13518 An inactive time stamp is enclosed in square brackets instead of angle
13519 brackets. It is inactive in the sense that it does not trigger agenda entries,
13520 does not link to the calendar and cannot be changed with the S-cursor keys.
13521 So these are more for recording a certain time/date."
13522 (interactive "P")
13523 (org-time-stamp arg 'inactive))
13525 (defvar org-date-ovl (make-overlay 1 1))
13526 (overlay-put org-date-ovl 'face 'org-warning)
13527 (org-detach-overlay org-date-ovl)
13529 (defvar org-ans1) ; dynamically scoped parameter
13530 (defvar org-ans2) ; dynamically scoped parameter
13532 (defvar org-plain-time-of-day-regexp) ; defined below
13534 (defvar org-overriding-default-time nil) ; dynamically scoped
13535 (defvar org-read-date-overlay nil)
13536 (defvar org-dcst nil) ; dynamically scoped
13537 (defvar org-read-date-history nil)
13538 (defvar org-read-date-final-answer nil)
13540 (defun org-read-date (&optional with-time to-time from-string prompt
13541 default-time default-input)
13542 "Read a date, possibly a time, and make things smooth for the user.
13543 The prompt will suggest to enter an ISO date, but you can also enter anything
13544 which will at least partially be understood by `parse-time-string'.
13545 Unrecognized parts of the date will default to the current day, month, year,
13546 hour and minute. If this command is called to replace a timestamp at point,
13547 of to enter the second timestamp of a range, the default time is taken from the
13548 existing stamp. For example,
13549 3-2-5 --> 2003-02-05
13550 feb 15 --> currentyear-02-15
13551 sep 12 9 --> 2009-09-12
13552 12:45 --> today 12:45
13553 22 sept 0:34 --> currentyear-09-22 0:34
13554 12 --> currentyear-currentmonth-12
13555 Fri --> nearest Friday (today or later)
13556 etc.
13558 Furthermore you can specify a relative date by giving, as the *first* thing
13559 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13560 change in days weeks, months, years.
13561 With a single plus or minus, the date is relative to today. With a double
13562 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13563 +4d --> four days from today
13564 +4 --> same as above
13565 +2w --> two weeks from today
13566 ++5 --> five days from default date
13568 The function understands only English month and weekday abbreviations,
13569 but this can be configured with the variables `parse-time-months' and
13570 `parse-time-weekdays'.
13572 While prompting, a calendar is popped up - you can also select the
13573 date with the mouse (button 1). The calendar shows a period of three
13574 months. To scroll it to other months, use the keys `>' and `<'.
13575 If you don't like the calendar, turn it off with
13576 \(setq org-read-date-popup-calendar nil)
13578 With optional argument TO-TIME, the date will immediately be converted
13579 to an internal time.
13580 With an optional argument WITH-TIME, the prompt will suggest to also
13581 insert a time. Note that when WITH-TIME is not set, you can still
13582 enter a time, and this function will inform the calling routine about
13583 this change. The calling routine may then choose to change the format
13584 used to insert the time stamp into the buffer to include the time.
13585 With optional argument FROM-STRING, read from this string instead from
13586 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13587 the time/date that is used for everything that is not specified by the
13588 user."
13589 (require 'parse-time)
13590 (let* ((org-time-stamp-rounding-minutes
13591 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13592 (org-dcst org-display-custom-times)
13593 (ct (org-current-time))
13594 (def (or org-overriding-default-time default-time ct))
13595 (defdecode (decode-time def))
13596 (dummy (progn
13597 (when (< (nth 2 defdecode) org-extend-today-until)
13598 (setcar (nthcdr 2 defdecode) -1)
13599 (setcar (nthcdr 1 defdecode) 59)
13600 (setq def (apply 'encode-time defdecode)
13601 defdecode (decode-time def)))))
13602 (calendar-frame-setup nil)
13603 (calendar-move-hook nil)
13604 (calendar-view-diary-initially-flag nil)
13605 (calendar-view-holidays-initially-flag nil)
13606 (timestr (format-time-string
13607 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13608 (prompt (concat (if prompt (concat prompt " ") "")
13609 (format "Date+time [%s]: " timestr)))
13610 ans (org-ans0 "") org-ans1 org-ans2 final)
13612 (cond
13613 (from-string (setq ans from-string))
13614 (org-read-date-popup-calendar
13615 (save-excursion
13616 (save-window-excursion
13617 (calendar)
13618 (calendar-forward-day (- (time-to-days def)
13619 (calendar-absolute-from-gregorian
13620 (calendar-current-date))))
13621 (org-eval-in-calendar nil t)
13622 (let* ((old-map (current-local-map))
13623 (map (copy-keymap calendar-mode-map))
13624 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13625 (org-defkey map (kbd "RET") 'org-calendar-select)
13626 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
13627 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
13628 (org-defkey minibuffer-local-map [(meta shift left)]
13629 (lambda () (interactive)
13630 (org-eval-in-calendar '(calendar-backward-month 1))))
13631 (org-defkey minibuffer-local-map [(meta shift right)]
13632 (lambda () (interactive)
13633 (org-eval-in-calendar '(calendar-forward-month 1))))
13634 (org-defkey minibuffer-local-map [(meta shift up)]
13635 (lambda () (interactive)
13636 (org-eval-in-calendar '(calendar-backward-year 1))))
13637 (org-defkey minibuffer-local-map [(meta shift down)]
13638 (lambda () (interactive)
13639 (org-eval-in-calendar '(calendar-forward-year 1))))
13640 (org-defkey minibuffer-local-map [?\e (shift left)]
13641 (lambda () (interactive)
13642 (org-eval-in-calendar '(calendar-backward-month 1))))
13643 (org-defkey minibuffer-local-map [?\e (shift right)]
13644 (lambda () (interactive)
13645 (org-eval-in-calendar '(calendar-forward-month 1))))
13646 (org-defkey minibuffer-local-map [?\e (shift up)]
13647 (lambda () (interactive)
13648 (org-eval-in-calendar '(calendar-backward-year 1))))
13649 (org-defkey minibuffer-local-map [?\e (shift down)]
13650 (lambda () (interactive)
13651 (org-eval-in-calendar '(calendar-forward-year 1))))
13652 (org-defkey minibuffer-local-map [(shift up)]
13653 (lambda () (interactive)
13654 (org-eval-in-calendar '(calendar-backward-week 1))))
13655 (org-defkey minibuffer-local-map [(shift down)]
13656 (lambda () (interactive)
13657 (org-eval-in-calendar '(calendar-forward-week 1))))
13658 (org-defkey minibuffer-local-map [(shift left)]
13659 (lambda () (interactive)
13660 (org-eval-in-calendar '(calendar-backward-day 1))))
13661 (org-defkey minibuffer-local-map [(shift right)]
13662 (lambda () (interactive)
13663 (org-eval-in-calendar '(calendar-forward-day 1))))
13664 (org-defkey minibuffer-local-map ">"
13665 (lambda () (interactive)
13666 (org-eval-in-calendar '(scroll-calendar-left 1))))
13667 (org-defkey minibuffer-local-map "<"
13668 (lambda () (interactive)
13669 (org-eval-in-calendar '(scroll-calendar-right 1))))
13670 (run-hooks 'org-read-date-minibuffer-setup-hook)
13671 (unwind-protect
13672 (progn
13673 (use-local-map map)
13674 (add-hook 'post-command-hook 'org-read-date-display)
13675 (setq org-ans0 (read-string prompt default-input
13676 'org-read-date-history nil))
13677 ;; org-ans0: from prompt
13678 ;; org-ans1: from mouse click
13679 ;; org-ans2: from calendar motion
13680 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13681 (remove-hook 'post-command-hook 'org-read-date-display)
13682 (use-local-map old-map)
13683 (when org-read-date-overlay
13684 (delete-overlay org-read-date-overlay)
13685 (setq org-read-date-overlay nil)))))))
13687 (t ; Naked prompt only
13688 (unwind-protect
13689 (setq ans (read-string prompt default-input
13690 'org-read-date-history timestr))
13691 (when org-read-date-overlay
13692 (delete-overlay org-read-date-overlay)
13693 (setq org-read-date-overlay nil)))))
13695 (setq final (org-read-date-analyze ans def defdecode))
13696 (setq org-read-date-final-answer ans)
13698 (if to-time
13699 (apply 'encode-time final)
13700 (if (and (boundp 'org-time-was-given) org-time-was-given)
13701 (format "%04d-%02d-%02d %02d:%02d"
13702 (nth 5 final) (nth 4 final) (nth 3 final)
13703 (nth 2 final) (nth 1 final))
13704 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13706 (defvar def)
13707 (defvar defdecode)
13708 (defvar with-time)
13709 (defvar org-read-date-analyze-futurep nil)
13710 (defun org-read-date-display ()
13711 "Display the current date prompt interpretation in the minibuffer."
13712 (when org-read-date-display-live
13713 (when org-read-date-overlay
13714 (delete-overlay org-read-date-overlay))
13715 (let ((p (point)))
13716 (end-of-line 1)
13717 (while (not (equal (buffer-substring
13718 (max (point-min) (- (point) 4)) (point))
13719 " "))
13720 (insert " "))
13721 (goto-char p))
13722 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13723 " " (or org-ans1 org-ans2)))
13724 (org-end-time-was-given nil)
13725 (f (org-read-date-analyze ans def defdecode))
13726 (fmts (if org-dcst
13727 org-time-stamp-custom-formats
13728 org-time-stamp-formats))
13729 (fmt (if (or with-time
13730 (and (boundp 'org-time-was-given) org-time-was-given))
13731 (cdr fmts)
13732 (car fmts)))
13733 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13734 (when (and org-end-time-was-given
13735 (string-match org-plain-time-of-day-regexp txt))
13736 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13737 org-end-time-was-given
13738 (substring txt (match-end 0)))))
13739 (when org-read-date-analyze-futurep
13740 (setq txt (concat txt " (=>F)")))
13741 (setq org-read-date-overlay
13742 (make-overlay (1- (point-at-eol)) (point-at-eol)))
13743 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13745 (defun org-read-date-analyze (ans def defdecode)
13746 "Analyse the combined answer of the date prompt."
13747 ;; FIXME: cleanup and comment
13748 (let ((nowdecode (decode-time (current-time)))
13749 delta deltan deltaw deltadef year month day
13750 hour minute second wday pm h2 m2 tl wday1
13751 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13752 (setq org-read-date-analyze-futurep nil)
13753 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13754 (setq ans "+0"))
13756 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13757 (setq ans (replace-match "" t t ans)
13758 deltan (car delta)
13759 deltaw (nth 1 delta)
13760 deltadef (nth 2 delta)))
13762 ;; Check if there is an iso week date in there
13763 ;; If yes, store the info and postpone interpreting it until the rest
13764 ;; of the parsing is done
13765 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13766 (setq iso-year (if (match-end 1)
13767 (org-small-year-to-year
13768 (string-to-number (match-string 1 ans))))
13769 iso-weekday (if (match-end 3)
13770 (string-to-number (match-string 3 ans)))
13771 iso-week (string-to-number (match-string 2 ans)))
13772 (setq ans (replace-match "" t t ans)))
13774 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13775 (when (string-match
13776 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13777 (setq year (if (match-end 2)
13778 (string-to-number (match-string 2 ans))
13779 (progn (setq kill-year t)
13780 (string-to-number (format-time-string "%Y"))))
13781 month (string-to-number (match-string 3 ans))
13782 day (string-to-number (match-string 4 ans)))
13783 (if (< year 100) (setq year (+ 2000 year)))
13784 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13785 t nil ans)))
13786 ;; Help matching american dates, like 5/30 or 5/30/7
13787 (when (string-match
13788 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13789 (setq year (if (match-end 4)
13790 (string-to-number (match-string 4 ans))
13791 (progn (setq kill-year t)
13792 (string-to-number (format-time-string "%Y"))))
13793 month (string-to-number (match-string 1 ans))
13794 day (string-to-number (match-string 2 ans)))
13795 (if (< year 100) (setq year (+ 2000 year)))
13796 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13797 t nil ans)))
13798 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13799 ;; If there is a time with am/pm, and *no* time without it, we convert
13800 ;; so that matching will be successful.
13801 (loop for i from 1 to 2 do ; twice, for end time as well
13802 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13803 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13804 (setq hour (string-to-number (match-string 1 ans))
13805 minute (if (match-end 3)
13806 (string-to-number (match-string 3 ans))
13808 pm (equal ?p
13809 (string-to-char (downcase (match-string 4 ans)))))
13810 (if (and (= hour 12) (not pm))
13811 (setq hour 0)
13812 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13813 (setq ans (replace-match (format "%02d:%02d" hour minute)
13814 t t ans))))
13816 ;; Check if a time range is given as a duration
13817 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13818 (setq hour (string-to-number (match-string 1 ans))
13819 h2 (+ hour (string-to-number (match-string 3 ans)))
13820 minute (string-to-number (match-string 2 ans))
13821 m2 (+ minute (if (match-end 5) (string-to-number
13822 (match-string 5 ans))0)))
13823 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13824 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13825 t t ans)))
13827 ;; Check if there is a time range
13828 (when (boundp 'org-end-time-was-given)
13829 (setq org-time-was-given nil)
13830 (when (and (string-match org-plain-time-of-day-regexp ans)
13831 (match-end 8))
13832 (setq org-end-time-was-given (match-string 8 ans))
13833 (setq ans (concat (substring ans 0 (match-beginning 7))
13834 (substring ans (match-end 7))))))
13836 (setq tl (parse-time-string ans)
13837 day (or (nth 3 tl) (nth 3 defdecode))
13838 month (or (nth 4 tl)
13839 (if (and org-read-date-prefer-future
13840 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13841 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13842 (nth 4 defdecode)))
13843 year (or (and (not kill-year) (nth 5 tl))
13844 (if (and org-read-date-prefer-future
13845 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13846 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13847 (nth 5 defdecode)))
13848 hour (or (nth 2 tl) (nth 2 defdecode))
13849 minute (or (nth 1 tl) (nth 1 defdecode))
13850 second (or (nth 0 tl) 0)
13851 wday (nth 6 tl))
13853 (when (and (eq org-read-date-prefer-future 'time)
13854 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13855 (equal day (nth 3 nowdecode))
13856 (equal month (nth 4 nowdecode))
13857 (equal year (nth 5 nowdecode))
13858 (nth 2 tl)
13859 (or (< (nth 2 tl) (nth 2 nowdecode))
13860 (and (= (nth 2 tl) (nth 2 nowdecode))
13861 (nth 1 tl)
13862 (< (nth 1 tl) (nth 1 nowdecode)))))
13863 (setq day (1+ day)
13864 futurep t))
13866 ;; Special date definitions below
13867 (cond
13868 (iso-week
13869 ;; There was an iso week
13870 (require 'cal-iso)
13871 (setq futurep nil)
13872 (setq year (or iso-year year)
13873 day (or iso-weekday wday 1)
13874 wday nil ; to make sure that the trigger below does not match
13875 iso-date (calendar-gregorian-from-absolute
13876 (calendar-absolute-from-iso
13877 (list iso-week day year))))
13878 ; FIXME: Should we also push ISO weeks into the future?
13879 ; (when (and org-read-date-prefer-future
13880 ; (not iso-year)
13881 ; (< (calendar-absolute-from-gregorian iso-date)
13882 ; (time-to-days (current-time))))
13883 ; (setq year (1+ year)
13884 ; iso-date (calendar-gregorian-from-absolute
13885 ; (calendar-absolute-from-iso
13886 ; (list iso-week day year)))))
13887 (setq month (car iso-date)
13888 year (nth 2 iso-date)
13889 day (nth 1 iso-date)))
13890 (deltan
13891 (setq futurep nil)
13892 (unless deltadef
13893 (let ((now (decode-time (current-time))))
13894 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13895 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13896 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13897 ((equal deltaw "m") (setq month (+ month deltan)))
13898 ((equal deltaw "y") (setq year (+ year deltan)))))
13899 ((and wday (not (nth 3 tl)))
13900 (setq futurep nil)
13901 ;; Weekday was given, but no day, so pick that day in the week
13902 ;; on or after the derived date.
13903 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13904 (unless (equal wday wday1)
13905 (setq day (+ day (% (- wday wday1 -7) 7))))))
13906 (if (and (boundp 'org-time-was-given)
13907 (nth 2 tl))
13908 (setq org-time-was-given t))
13909 (if (< year 100) (setq year (+ 2000 year)))
13910 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13911 (setq org-read-date-analyze-futurep futurep)
13912 (list second minute hour day month year)))
13914 (defvar parse-time-weekdays)
13916 (defun org-read-date-get-relative (s today default)
13917 "Check string S for special relative date string.
13918 TODAY and DEFAULT are internal times, for today and for a default.
13919 Return shift list (N what def-flag)
13920 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13921 N is the number of WHATs to shift.
13922 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13923 the DEFAULT date rather than TODAY."
13924 (when (and
13925 (string-match
13926 (concat
13927 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13928 "\\([0-9]+\\)?"
13929 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13930 "\\([ \t]\\|$\\)") s)
13931 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13932 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13933 (string-to-char (substring (match-string 1 s) -1))
13934 ?+))
13935 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13936 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13937 (what (if (match-end 3) (match-string 3 s) "d"))
13938 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13939 (date (if rel default today))
13940 (wday (nth 6 (decode-time date)))
13941 delta)
13942 (if wday1
13943 (progn
13944 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13945 (if (= dir ?-) (setq delta (- delta 7)))
13946 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13947 (list delta "d" rel))
13948 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13950 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13951 "Turn a user-specified date into the internal representation.
13952 The internal representation needed by the calendar is (month day year).
13953 This is a wrapper to handle the brain-dead convention in calendar that
13954 user function argument order change dependent on argument order."
13955 (if (boundp 'calendar-date-style)
13956 (cond
13957 ((eq calendar-date-style 'american)
13958 (list arg1 arg2 arg3))
13959 ((eq calendar-date-style 'european)
13960 (list arg2 arg1 arg3))
13961 ((eq calendar-date-style 'iso)
13962 (list arg2 arg3 arg1)))
13963 (if (org-bound-and-true-p european-calendar-style)
13964 (list arg2 arg1 arg3)
13965 (list arg1 arg2 arg3))))
13967 (defun org-eval-in-calendar (form &optional keepdate)
13968 "Eval FORM in the calendar window and return to current window.
13969 Also, store the cursor date in variable org-ans2."
13970 (let ((sf (selected-frame))
13971 (sw (selected-window)))
13972 (select-window (get-buffer-window "*Calendar*" t))
13973 (eval form)
13974 (when (and (not keepdate) (calendar-cursor-to-date))
13975 (let* ((date (calendar-cursor-to-date))
13976 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13977 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13978 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13979 (select-window sw)
13980 (org-select-frame-set-input-focus sf)))
13982 (defun org-calendar-select ()
13983 "Return to `org-read-date' with the date currently selected.
13984 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13985 (interactive)
13986 (when (calendar-cursor-to-date)
13987 (let* ((date (calendar-cursor-to-date))
13988 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13989 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13990 (if (active-minibuffer-window) (exit-minibuffer))))
13992 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13993 "Insert a date stamp for the date given by the internal TIME.
13994 WITH-HM means use the stamp format that includes the time of the day.
13995 INACTIVE means use square brackets instead of angular ones, so that the
13996 stamp will not contribute to the agenda.
13997 PRE and POST are optional strings to be inserted before and after the
13998 stamp.
13999 The command returns the inserted time stamp."
14000 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14001 stamp)
14002 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14003 (insert-before-markers (or pre ""))
14004 (insert-before-markers (setq stamp (format-time-string fmt time)))
14005 (when (listp extra)
14006 (setq extra (car extra))
14007 (if (and (stringp extra)
14008 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14009 (setq extra (format "-%02d:%02d"
14010 (string-to-number (match-string 1 extra))
14011 (string-to-number (match-string 2 extra))))
14012 (setq extra nil)))
14013 (when extra
14014 (backward-char 1)
14015 (insert-before-markers extra)
14016 (forward-char 1))
14017 (insert-before-markers (or post ""))
14018 (setq org-last-inserted-timestamp stamp)))
14020 (defun org-toggle-time-stamp-overlays ()
14021 "Toggle the use of custom time stamp formats."
14022 (interactive)
14023 (setq org-display-custom-times (not org-display-custom-times))
14024 (unless org-display-custom-times
14025 (let ((p (point-min)) (bmp (buffer-modified-p)))
14026 (while (setq p (next-single-property-change p 'display))
14027 (if (and (get-text-property p 'display)
14028 (eq (get-text-property p 'face) 'org-date))
14029 (remove-text-properties
14030 p (setq p (next-single-property-change p 'display))
14031 '(display t))))
14032 (set-buffer-modified-p bmp)))
14033 (if (featurep 'xemacs)
14034 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14035 (org-restart-font-lock)
14036 (setq org-table-may-need-update t)
14037 (if org-display-custom-times
14038 (message "Time stamps are overlayed with custom format")
14039 (message "Time stamp overlays removed")))
14041 (defun org-display-custom-time (beg end)
14042 "Overlay modified time stamp format over timestamp between BEG and END."
14043 (let* ((ts (buffer-substring beg end))
14044 t1 w1 with-hm tf time str w2 (off 0))
14045 (save-match-data
14046 (setq t1 (org-parse-time-string ts t))
14047 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14048 (setq off (- (match-end 0) (match-beginning 0)))))
14049 (setq end (- end off))
14050 (setq w1 (- end beg)
14051 with-hm (and (nth 1 t1) (nth 2 t1))
14052 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14053 time (org-fix-decoded-time t1)
14054 str (org-add-props
14055 (format-time-string
14056 (substring tf 1 -1) (apply 'encode-time time))
14057 nil 'mouse-face 'highlight)
14058 w2 (length str))
14059 (if (not (= w2 w1))
14060 (add-text-properties (1+ beg) (+ 2 beg)
14061 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14062 (if (featurep 'xemacs)
14063 (progn
14064 (put-text-property beg end 'invisible t)
14065 (put-text-property beg end 'end-glyph (make-glyph str)))
14066 (put-text-property beg end 'display str))))
14068 (defun org-translate-time (string)
14069 "Translate all timestamps in STRING to custom format.
14070 But do this only if the variable `org-display-custom-times' is set."
14071 (when org-display-custom-times
14072 (save-match-data
14073 (let* ((start 0)
14074 (re org-ts-regexp-both)
14075 t1 with-hm inactive tf time str beg end)
14076 (while (setq start (string-match re string start))
14077 (setq beg (match-beginning 0)
14078 end (match-end 0)
14079 t1 (save-match-data
14080 (org-parse-time-string (substring string beg end) t))
14081 with-hm (and (nth 1 t1) (nth 2 t1))
14082 inactive (equal (substring string beg (1+ beg)) "[")
14083 tf (funcall (if with-hm 'cdr 'car)
14084 org-time-stamp-custom-formats)
14085 time (org-fix-decoded-time t1)
14086 str (format-time-string
14087 (concat
14088 (if inactive "[" "<") (substring tf 1 -1)
14089 (if inactive "]" ">"))
14090 (apply 'encode-time time))
14091 string (replace-match str t t string)
14092 start (+ start (length str)))))))
14093 string)
14095 (defun org-fix-decoded-time (time)
14096 "Set 0 instead of nil for the first 6 elements of time.
14097 Don't touch the rest."
14098 (let ((n 0))
14099 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14101 (defun org-days-to-time (timestamp-string)
14102 "Difference between TIMESTAMP-STRING and now in days."
14103 (- (time-to-days (org-time-string-to-time timestamp-string))
14104 (time-to-days (current-time))))
14106 (defun org-deadline-close (timestamp-string &optional ndays)
14107 "Is the time in TIMESTAMP-STRING close to the current date?"
14108 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14109 (and (< (org-days-to-time timestamp-string) ndays)
14110 (not (org-entry-is-done-p))))
14112 (defun org-get-wdays (ts)
14113 "Get the deadline lead time appropriate for timestring TS."
14114 (cond
14115 ((<= org-deadline-warning-days 0)
14116 ;; 0 or negative, enforce this value no matter what
14117 (- org-deadline-warning-days))
14118 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14119 ;; lead time is specified.
14120 (floor (* (string-to-number (match-string 1 ts))
14121 (cdr (assoc (match-string 2 ts)
14122 '(("d" . 1) ("w" . 7)
14123 ("m" . 30.4) ("y" . 365.25)))))))
14124 ;; go for the default.
14125 (t org-deadline-warning-days)))
14127 (defun org-calendar-select-mouse (ev)
14128 "Return to `org-read-date' with the date currently selected.
14129 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14130 (interactive "e")
14131 (mouse-set-point ev)
14132 (when (calendar-cursor-to-date)
14133 (let* ((date (calendar-cursor-to-date))
14134 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14135 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14136 (if (active-minibuffer-window) (exit-minibuffer))))
14138 (defun org-check-deadlines (ndays)
14139 "Check if there are any deadlines due or past due.
14140 A deadline is considered due if it happens within `org-deadline-warning-days'
14141 days from today's date. If the deadline appears in an entry marked DONE,
14142 it is not shown. The prefix arg NDAYS can be used to test that many
14143 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14144 (interactive "P")
14145 (let* ((org-warn-days
14146 (cond
14147 ((equal ndays '(4)) 100000)
14148 (ndays (prefix-numeric-value ndays))
14149 (t (abs org-deadline-warning-days))))
14150 (case-fold-search nil)
14151 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14152 (callback
14153 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14155 (message "%d deadlines past-due or due within %d days"
14156 (org-occur regexp nil callback)
14157 org-warn-days)))
14159 (defun org-check-before-date (date)
14160 "Check if there are deadlines or scheduled entries before DATE."
14161 (interactive (list (org-read-date)))
14162 (let ((case-fold-search nil)
14163 (regexp (concat "\\<\\(" org-deadline-string
14164 "\\|" org-scheduled-string
14165 "\\) *<\\([^>]+\\)>"))
14166 (callback
14167 (lambda () (time-less-p
14168 (org-time-string-to-time (match-string 2))
14169 (org-time-string-to-time date)))))
14170 (message "%d entries before %s"
14171 (org-occur regexp nil callback) date)))
14173 (defun org-check-after-date (date)
14174 "Check if there are deadlines or scheduled entries after DATE."
14175 (interactive (list (org-read-date)))
14176 (let ((case-fold-search nil)
14177 (regexp (concat "\\<\\(" org-deadline-string
14178 "\\|" org-scheduled-string
14179 "\\) *<\\([^>]+\\)>"))
14180 (callback
14181 (lambda () (not
14182 (time-less-p
14183 (org-time-string-to-time (match-string 2))
14184 (org-time-string-to-time date))))))
14185 (message "%d entries after %s"
14186 (org-occur regexp nil callback) date)))
14188 (defun org-evaluate-time-range (&optional to-buffer)
14189 "Evaluate a time range by computing the difference between start and end.
14190 Normally the result is just printed in the echo area, but with prefix arg
14191 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14192 If the time range is actually in a table, the result is inserted into the
14193 next column.
14194 For time difference computation, a year is assumed to be exactly 365
14195 days in order to avoid rounding problems."
14196 (interactive "P")
14198 (org-clock-update-time-maybe)
14199 (save-excursion
14200 (unless (org-at-date-range-p t)
14201 (goto-char (point-at-bol))
14202 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14203 (if (not (org-at-date-range-p t))
14204 (error "Not at a time-stamp range, and none found in current line")))
14205 (let* ((ts1 (match-string 1))
14206 (ts2 (match-string 2))
14207 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14208 (match-end (match-end 0))
14209 (time1 (org-time-string-to-time ts1))
14210 (time2 (org-time-string-to-time ts2))
14211 (t1 (org-float-time time1))
14212 (t2 (org-float-time time2))
14213 (diff (abs (- t2 t1)))
14214 (negative (< (- t2 t1) 0))
14215 ;; (ys (floor (* 365 24 60 60)))
14216 (ds (* 24 60 60))
14217 (hs (* 60 60))
14218 (fy "%dy %dd %02d:%02d")
14219 (fy1 "%dy %dd")
14220 (fd "%dd %02d:%02d")
14221 (fd1 "%dd")
14222 (fh "%02d:%02d")
14223 y d h m align)
14224 (if havetime
14225 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14227 d (floor (/ diff ds)) diff (mod diff ds)
14228 h (floor (/ diff hs)) diff (mod diff hs)
14229 m (floor (/ diff 60)))
14230 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14232 d (floor (+ (/ diff ds) 0.5))
14233 h 0 m 0))
14234 (if (not to-buffer)
14235 (message "%s" (org-make-tdiff-string y d h m))
14236 (if (org-at-table-p)
14237 (progn
14238 (goto-char match-end)
14239 (setq align t)
14240 (and (looking-at " *|") (goto-char (match-end 0))))
14241 (goto-char match-end))
14242 (if (looking-at
14243 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14244 (replace-match ""))
14245 (if negative (insert " -"))
14246 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14247 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14248 (insert " " (format fh h m))))
14249 (if align (org-table-align))
14250 (message "Time difference inserted")))))
14252 (defun org-make-tdiff-string (y d h m)
14253 (let ((fmt "")
14254 (l nil))
14255 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14256 l (push y l)))
14257 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14258 l (push d l)))
14259 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14260 l (push h l)))
14261 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14262 l (push m l)))
14263 (apply 'format fmt (nreverse l))))
14265 (defun org-time-string-to-time (s)
14266 (apply 'encode-time (org-parse-time-string s)))
14267 (defun org-time-string-to-seconds (s)
14268 (org-float-time (org-time-string-to-time s)))
14270 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14271 "Convert a time stamp to an absolute day number.
14272 If there is a specifyer for a cyclic time stamp, get the closest date to
14273 DAYNR.
14274 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14275 the variable date is bound by the calendar when this is called."
14276 (cond
14277 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14278 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14279 daynr
14280 (+ daynr 1000)))
14281 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14282 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14283 (time-to-days (current-time))) (match-string 0 s)
14284 prefer show-all))
14285 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14287 (defun org-days-to-iso-week (days)
14288 "Return the iso week number."
14289 (require 'cal-iso)
14290 (car (calendar-iso-from-absolute days)))
14292 (defun org-small-year-to-year (year)
14293 "Convert 2-digit years into 4-digit years.
14294 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14295 The year 2000 cannot be abbreviated. Any year larger than 99
14296 is returned unchanged."
14297 (if (< year 38)
14298 (setq year (+ 2000 year))
14299 (if (< year 100)
14300 (setq year (+ 1900 year))))
14301 year)
14303 (defun org-time-from-absolute (d)
14304 "Return the time corresponding to date D.
14305 D may be an absolute day number, or a calendar-type list (month day year)."
14306 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14307 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14309 (defun org-calendar-holiday ()
14310 "List of holidays, for Diary display in Org-mode."
14311 (require 'holidays)
14312 (let ((hl (funcall
14313 (if (fboundp 'calendar-check-holidays)
14314 'calendar-check-holidays 'check-calendar-holidays) date)))
14315 (if hl (mapconcat 'identity hl "; "))))
14317 (defun org-diary-sexp-entry (sexp entry date)
14318 "Process a SEXP diary ENTRY for DATE."
14319 (require 'diary-lib)
14320 (let ((result (if calendar-debug-sexp
14321 (let ((stack-trace-on-error t))
14322 (eval (car (read-from-string sexp))))
14323 (condition-case nil
14324 (eval (car (read-from-string sexp)))
14325 (error
14326 (beep)
14327 (message "Bad sexp at line %d in %s: %s"
14328 (org-current-line)
14329 (buffer-file-name) sexp)
14330 (sleep-for 2))))))
14331 (cond ((stringp result) result)
14332 ((and (consp result)
14333 (stringp (cdr result))) (cdr result))
14334 (result entry)
14335 (t nil))))
14337 (defun org-diary-to-ical-string (frombuf)
14338 "Get iCalendar entries from diary entries in buffer FROMBUF.
14339 This uses the icalendar.el library."
14340 (let* ((tmpdir (if (featurep 'xemacs)
14341 (temp-directory)
14342 temporary-file-directory))
14343 (tmpfile (make-temp-name
14344 (expand-file-name "orgics" tmpdir)))
14345 buf rtn b e)
14346 (with-current-buffer frombuf
14347 (icalendar-export-region (point-min) (point-max) tmpfile)
14348 (setq buf (find-buffer-visiting tmpfile))
14349 (set-buffer buf)
14350 (goto-char (point-min))
14351 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14352 (setq b (match-beginning 0)))
14353 (goto-char (point-max))
14354 (if (re-search-backward "^END:VEVENT" nil t)
14355 (setq e (match-end 0)))
14356 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14357 (kill-buffer buf)
14358 (delete-file tmpfile)
14359 rtn))
14361 (defun org-closest-date (start current change prefer show-all)
14362 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14363 When PREFER is `past' return a date that is either CURRENT or past.
14364 When PREFER is `future', return a date that is either CURRENT or future.
14365 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14366 ;; Make the proper lists from the dates
14367 (catch 'exit
14368 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14369 dn dw sday cday n1 n2 n0
14370 d m y y1 y2 date1 date2 nmonths nm ny m2)
14372 (setq start (org-date-to-gregorian start)
14373 current (org-date-to-gregorian
14374 (if show-all
14375 current
14376 (time-to-days (current-time))))
14377 sday (calendar-absolute-from-gregorian start)
14378 cday (calendar-absolute-from-gregorian current))
14380 (if (<= cday sday) (throw 'exit sday))
14382 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14383 (setq dn (string-to-number (match-string 1 change))
14384 dw (cdr (assoc (match-string 2 change) a1)))
14385 (error "Invalid change specifyer: %s" change))
14386 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14387 (cond
14388 ((eq dw 'day)
14389 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14390 n2 (+ n1 dn)))
14391 ((eq dw 'year)
14392 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14393 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14394 (setq date1 (list m d y1)
14395 n1 (calendar-absolute-from-gregorian date1)
14396 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14397 n2 (calendar-absolute-from-gregorian date2)))
14398 ((eq dw 'month)
14399 ;; approx number of month between the two dates
14400 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14401 ;; How often does dn fit in there?
14402 (setq d (nth 1 start) m (car start) y (nth 2 start)
14403 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14404 m (+ m nm)
14405 ny (floor (/ m 12))
14406 y (+ y ny)
14407 m (- m (* ny 12)))
14408 (while (> m 12) (setq m (- m 12) y (1+ y)))
14409 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14410 (setq m2 (+ m dn) y2 y)
14411 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14412 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14413 (while (<= n2 cday)
14414 (setq n1 n2 m m2 y y2)
14415 (setq m2 (+ m dn) y2 y)
14416 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14417 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14418 ;; Make sure n1 is the earlier date
14419 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14420 (if show-all
14421 (cond
14422 ((eq prefer 'past) (if (= cday n2) n2 n1))
14423 ((eq prefer 'future) (if (= cday n1) n1 n2))
14424 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14425 (cond
14426 ((eq prefer 'past) (if (= cday n2) n2 n1))
14427 ((eq prefer 'future) (if (= cday n1) n1 n2))
14428 (t (if (= cday n1) n1 n2)))))))
14430 (defun org-date-to-gregorian (date)
14431 "Turn any specification of DATE into a gregorian date for the calendar."
14432 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14433 ((and (listp date) (= (length date) 3)) date)
14434 ((stringp date)
14435 (setq date (org-parse-time-string date))
14436 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14437 ((listp date)
14438 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14440 (defun org-parse-time-string (s &optional nodefault)
14441 "Parse the standard Org-mode time string.
14442 This should be a lot faster than the normal `parse-time-string'.
14443 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14444 hour and minute fields will be nil if not given."
14445 (if (string-match org-ts-regexp0 s)
14446 (list 0
14447 (if (or (match-beginning 8) (not nodefault))
14448 (string-to-number (or (match-string 8 s) "0")))
14449 (if (or (match-beginning 7) (not nodefault))
14450 (string-to-number (or (match-string 7 s) "0")))
14451 (string-to-number (match-string 4 s))
14452 (string-to-number (match-string 3 s))
14453 (string-to-number (match-string 2 s))
14454 nil nil nil)
14455 (error "Not a standard Org-mode time string: %s" s)))
14457 (defun org-timestamp-up (&optional arg)
14458 "Increase the date item at the cursor by one.
14459 If the cursor is on the year, change the year. If it is on the month or
14460 the day, change that.
14461 With prefix ARG, change by that many units."
14462 (interactive "p")
14463 (org-timestamp-change (prefix-numeric-value arg)))
14465 (defun org-timestamp-down (&optional arg)
14466 "Decrease the date item at the cursor by one.
14467 If the cursor is on the year, change the year. If it is on the month or
14468 the day, change that.
14469 With prefix ARG, change by that many units."
14470 (interactive "p")
14471 (org-timestamp-change (- (prefix-numeric-value arg))))
14473 (defun org-timestamp-up-day (&optional arg)
14474 "Increase the date in the time stamp by one day.
14475 With prefix ARG, change that many days."
14476 (interactive "p")
14477 (if (and (not (org-at-timestamp-p t))
14478 (org-on-heading-p))
14479 (org-todo 'up)
14480 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14482 (defun org-timestamp-down-day (&optional arg)
14483 "Decrease the date in the time stamp by one day.
14484 With prefix ARG, change that many days."
14485 (interactive "p")
14486 (if (and (not (org-at-timestamp-p t))
14487 (org-on-heading-p))
14488 (org-todo 'down)
14489 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14491 (defun org-at-timestamp-p (&optional inactive-ok)
14492 "Determine if the cursor is in or at a timestamp."
14493 (interactive)
14494 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14495 (pos (point))
14496 (ans (or (looking-at tsr)
14497 (save-excursion
14498 (skip-chars-backward "^[<\n\r\t")
14499 (if (> (point) (point-min)) (backward-char 1))
14500 (and (looking-at tsr)
14501 (> (- (match-end 0) pos) -1))))))
14502 (and ans
14503 (boundp 'org-ts-what)
14504 (setq org-ts-what
14505 (cond
14506 ((= pos (match-beginning 0)) 'bracket)
14507 ((= pos (1- (match-end 0))) 'bracket)
14508 ((org-pos-in-match-range pos 2) 'year)
14509 ((org-pos-in-match-range pos 3) 'month)
14510 ((org-pos-in-match-range pos 7) 'hour)
14511 ((org-pos-in-match-range pos 8) 'minute)
14512 ((or (org-pos-in-match-range pos 4)
14513 (org-pos-in-match-range pos 5)) 'day)
14514 ((and (> pos (or (match-end 8) (match-end 5)))
14515 (< pos (match-end 0)))
14516 (- pos (or (match-end 8) (match-end 5))))
14517 (t 'day))))
14518 ans))
14520 (defun org-toggle-timestamp-type ()
14521 "Toggle the type (<active> or [inactive]) of a time stamp."
14522 (interactive)
14523 (when (org-at-timestamp-p t)
14524 (let ((beg (match-beginning 0)) (end (match-end 0))
14525 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14526 (save-excursion
14527 (goto-char beg)
14528 (while (re-search-forward "[][<>]" end t)
14529 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14530 t t)))
14531 (message "Timestamp is now %sactive"
14532 (if (equal (char-after beg) ?<) "" "in")))))
14534 (defun org-timestamp-change (n &optional what)
14535 "Change the date in the time stamp at point.
14536 The date will be changed by N times WHAT. WHAT can be `day', `month',
14537 `year', `minute', `second'. If WHAT is not given, the cursor position
14538 in the timestamp determines what will be changed."
14539 (let ((pos (point))
14540 with-hm inactive
14541 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14542 org-ts-what
14543 extra rem
14544 ts time time0)
14545 (if (not (org-at-timestamp-p t))
14546 (error "Not at a timestamp"))
14547 (if (and (not what) (eq org-ts-what 'bracket))
14548 (org-toggle-timestamp-type)
14549 (if (and (not what) (not (eq org-ts-what 'day))
14550 org-display-custom-times
14551 (get-text-property (point) 'display)
14552 (not (get-text-property (1- (point)) 'display)))
14553 (setq org-ts-what 'day))
14554 (setq org-ts-what (or what org-ts-what)
14555 inactive (= (char-after (match-beginning 0)) ?\[)
14556 ts (match-string 0))
14557 (replace-match "")
14558 (if (string-match
14559 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14561 (setq extra (match-string 1 ts)))
14562 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14563 (setq with-hm t))
14564 (setq time0 (org-parse-time-string ts))
14565 (when (and (eq org-ts-what 'minute)
14566 (eq current-prefix-arg nil))
14567 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14568 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14569 (setcar (cdr time0) (+ (nth 1 time0)
14570 (if (> n 0) (- rem) (- dm rem))))))
14571 (setq time
14572 (encode-time (or (car time0) 0)
14573 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14574 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14575 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14576 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14577 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14578 (nthcdr 6 time0)))
14579 (when (and (member org-ts-what '(hour minute))
14580 extra
14581 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14582 (setq extra (org-modify-ts-extra
14583 extra
14584 (if (eq org-ts-what 'hour) 2 5)
14585 n dm)))
14586 (when (integerp org-ts-what)
14587 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14588 (if (eq what 'calendar)
14589 (let ((cal-date (org-get-date-from-calendar)))
14590 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14591 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14592 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14593 (setcar time0 (or (car time0) 0))
14594 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14595 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14596 (setq time (apply 'encode-time time0))))
14597 (setq org-last-changed-timestamp
14598 (org-insert-time-stamp time with-hm inactive nil nil extra))
14599 (org-clock-update-time-maybe)
14600 (goto-char pos)
14601 ;; Try to recenter the calendar window, if any
14602 (if (and org-calendar-follow-timestamp-change
14603 (get-buffer-window "*Calendar*" t)
14604 (memq org-ts-what '(day month year)))
14605 (org-recenter-calendar (time-to-days time))))))
14607 (defun org-modify-ts-extra (s pos n dm)
14608 "Change the different parts of the lead-time and repeat fields in timestamp."
14609 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14610 ng h m new rem)
14611 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14612 (cond
14613 ((or (org-pos-in-match-range pos 2)
14614 (org-pos-in-match-range pos 3))
14615 (setq m (string-to-number (match-string 3 s))
14616 h (string-to-number (match-string 2 s)))
14617 (if (org-pos-in-match-range pos 2)
14618 (setq h (+ h n))
14619 (setq n (* dm (org-no-warnings (signum n))))
14620 (when (not (= 0 (setq rem (% m dm))))
14621 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14622 (setq m (+ m n)))
14623 (if (< m 0) (setq m (+ m 60) h (1- h)))
14624 (if (> m 59) (setq m (- m 60) h (1+ h)))
14625 (setq h (min 24 (max 0 h)))
14626 (setq ng 1 new (format "-%02d:%02d" h m)))
14627 ((org-pos-in-match-range pos 6)
14628 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14629 ((org-pos-in-match-range pos 5)
14630 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14632 ((org-pos-in-match-range pos 9)
14633 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14634 ((org-pos-in-match-range pos 8)
14635 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14637 (when ng
14638 (setq s (concat
14639 (substring s 0 (match-beginning ng))
14641 (substring s (match-end ng))))))
14644 (defun org-recenter-calendar (date)
14645 "If the calendar is visible, recenter it to DATE."
14646 (let* ((win (selected-window))
14647 (cwin (get-buffer-window "*Calendar*" t))
14648 (calendar-move-hook nil))
14649 (when cwin
14650 (select-window cwin)
14651 (calendar-goto-date (if (listp date) date
14652 (calendar-gregorian-from-absolute date)))
14653 (select-window win))))
14655 (defun org-goto-calendar (&optional arg)
14656 "Go to the Emacs calendar at the current date.
14657 If there is a time stamp in the current line, go to that date.
14658 A prefix ARG can be used to force the current date."
14659 (interactive "P")
14660 (let ((tsr org-ts-regexp) diff
14661 (calendar-move-hook nil)
14662 (calendar-view-holidays-initially-flag nil)
14663 (calendar-view-diary-initially-flag nil))
14664 (if (or (org-at-timestamp-p)
14665 (save-excursion
14666 (beginning-of-line 1)
14667 (looking-at (concat ".*" tsr))))
14668 (let ((d1 (time-to-days (current-time)))
14669 (d2 (time-to-days
14670 (org-time-string-to-time (match-string 1)))))
14671 (setq diff (- d2 d1))))
14672 (calendar)
14673 (calendar-goto-today)
14674 (if (and diff (not arg)) (calendar-forward-day diff))))
14676 (defun org-get-date-from-calendar ()
14677 "Return a list (month day year) of date at point in calendar."
14678 (with-current-buffer "*Calendar*"
14679 (save-match-data
14680 (calendar-cursor-to-date))))
14682 (defun org-date-from-calendar ()
14683 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14684 If there is already a time stamp at the cursor position, update it."
14685 (interactive)
14686 (if (org-at-timestamp-p t)
14687 (org-timestamp-change 0 'calendar)
14688 (let ((cal-date (org-get-date-from-calendar)))
14689 (org-insert-time-stamp
14690 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14692 (defun org-minutes-to-hh:mm-string (m)
14693 "Compute H:MM from a number of minutes."
14694 (let ((h (/ m 60)))
14695 (setq m (- m (* 60 h)))
14696 (format org-time-clocksum-format h m)))
14698 (defun org-hh:mm-string-to-minutes (s)
14699 "Convert a string H:MM to a number of minutes.
14700 If the string is just a number, interpret it as minutes.
14701 In fact, the first hh:mm or number in the string will be taken,
14702 there can be extra stuff in the string.
14703 If no number is found, the return value is 0."
14704 (cond
14705 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14706 (+ (* (string-to-number (match-string 1 s)) 60)
14707 (string-to-number (match-string 2 s))))
14708 ((string-match "\\([0-9]+\\)" s)
14709 (string-to-number (match-string 1 s)))
14710 (t 0)))
14712 ;;;; Files
14714 (defun org-save-all-org-buffers ()
14715 "Save all Org-mode buffers without user confirmation."
14716 (interactive)
14717 (message "Saving all Org-mode buffers...")
14718 (save-some-buffers t 'org-mode-p)
14719 (when (featurep 'org-id) (org-id-locations-save))
14720 (message "Saving all Org-mode buffers... done"))
14722 (defun org-revert-all-org-buffers ()
14723 "Revert all Org-mode buffers.
14724 Prompt for confirmation when there are unsaved changes.
14725 Be sure you know what you are doing before letting this function
14726 overwrite your changes.
14728 This function is useful in a setup where one tracks org files
14729 with a version control system, to revert on one machine after pulling
14730 changes from another. I believe the procedure must be like this:
14732 1. M-x org-save-all-org-buffers
14733 2. Pull changes from the other machine, resolve conflicts
14734 3. M-x org-revert-all-org-buffers"
14735 (interactive)
14736 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14737 (error "Abort"))
14738 (save-excursion
14739 (save-window-excursion
14740 (mapc
14741 (lambda (b)
14742 (when (and (with-current-buffer b (org-mode-p))
14743 (with-current-buffer b buffer-file-name))
14744 (switch-to-buffer b)
14745 (revert-buffer t 'no-confirm)))
14746 (buffer-list))
14747 (when (and (featurep 'org-id) org-id-track-globally)
14748 (org-id-locations-load)))))
14750 ;;;; Agenda files
14752 ;;;###autoload
14753 (defun org-iswitchb (&optional arg)
14754 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14755 With a prefix argument, restrict available to files.
14756 With two prefix arguments, restrict available buffers to agenda files."
14757 (interactive "P")
14758 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14759 ((equal arg '(16)) (org-buffer-list 'agenda))
14760 (t (org-buffer-list)))))
14761 (switch-to-buffer
14762 (org-icompleting-read "Org buffer: "
14763 (mapcar 'list (mapcar 'buffer-name blist))
14764 nil t))))
14766 ;;;###autoload
14767 (defalias 'org-ido-switchb 'org-iswitchb)
14769 (defun org-buffer-list (&optional predicate exclude-tmp)
14770 "Return a list of Org buffers.
14771 PREDICATE can be `export', `files' or `agenda'.
14773 export restrict the list to Export buffers.
14774 files restrict the list to buffers visiting Org files.
14775 agenda restrict the list to buffers visiting agenda files.
14777 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14778 (let* ((bfn nil)
14779 (agenda-files (and (eq predicate 'agenda)
14780 (mapcar 'file-truename (org-agenda-files t))))
14781 (filter
14782 (cond
14783 ((eq predicate 'files)
14784 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14785 ((eq predicate 'export)
14786 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14787 ((eq predicate 'agenda)
14788 (lambda (b)
14789 (with-current-buffer b
14790 (and (eq major-mode 'org-mode)
14791 (setq bfn (buffer-file-name b))
14792 (member (file-truename bfn) agenda-files)))))
14793 (t (lambda (b) (with-current-buffer b
14794 (or (eq major-mode 'org-mode)
14795 (string-match "\*Org .*Export"
14796 (buffer-name b)))))))))
14797 (delq nil
14798 (mapcar
14799 (lambda(b)
14800 (if (and (funcall filter b)
14801 (or (not exclude-tmp)
14802 (not (string-match "tmp" (buffer-name b)))))
14804 nil))
14805 (buffer-list)))))
14807 (defun org-agenda-files (&optional unrestricted archives)
14808 "Get the list of agenda files.
14809 Optional UNRESTRICTED means return the full list even if a restriction
14810 is currently in place.
14811 When ARCHIVES is t, include all archive files that are really being
14812 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14813 `org-agenda-archives-mode' is t."
14814 (let ((files
14815 (cond
14816 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14817 ((stringp org-agenda-files) (org-read-agenda-file-list))
14818 ((listp org-agenda-files) org-agenda-files)
14819 (t (error "Invalid value of `org-agenda-files'")))))
14820 (setq files (apply 'append
14821 (mapcar (lambda (f)
14822 (if (file-directory-p f)
14823 (directory-files
14824 f t org-agenda-file-regexp)
14825 (list f)))
14826 files)))
14827 (when org-agenda-skip-unavailable-files
14828 (setq files (delq nil
14829 (mapcar (function
14830 (lambda (file)
14831 (and (file-readable-p file) file)))
14832 files))))
14833 (when (or (eq archives t)
14834 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14835 (setq files (org-add-archive-files files)))
14836 files))
14838 (defun org-edit-agenda-file-list ()
14839 "Edit the list of agenda files.
14840 Depending on setup, this either uses customize to edit the variable
14841 `org-agenda-files', or it visits the file that is holding the list. In the
14842 latter case, the buffer is set up in a way that saving it automatically kills
14843 the buffer and restores the previous window configuration."
14844 (interactive)
14845 (if (stringp org-agenda-files)
14846 (let ((cw (current-window-configuration)))
14847 (find-file org-agenda-files)
14848 (org-set-local 'org-window-configuration cw)
14849 (org-add-hook 'after-save-hook
14850 (lambda ()
14851 (set-window-configuration
14852 (prog1 org-window-configuration
14853 (kill-buffer (current-buffer))))
14854 (org-install-agenda-files-menu)
14855 (message "New agenda file list installed"))
14856 nil 'local)
14857 (message "%s" (substitute-command-keys
14858 "Edit list and finish with \\[save-buffer]")))
14859 (customize-variable 'org-agenda-files)))
14861 (defun org-store-new-agenda-file-list (list)
14862 "Set new value for the agenda file list and save it correctly."
14863 (if (stringp org-agenda-files)
14864 (let ((fe (org-read-agenda-file-list t)) b u)
14865 (while (setq b (find-buffer-visiting org-agenda-files))
14866 (kill-buffer b))
14867 (with-temp-file org-agenda-files
14868 (insert
14869 (mapconcat
14870 (lambda (f) ;; Keep un-expanded entries.
14871 (if (setq u (assoc f fe))
14872 (cdr u)
14874 list "\n")
14875 "\n")))
14876 (let ((org-mode-hook nil) (org-inhibit-startup t)
14877 (org-insert-mode-line-in-empty-file nil))
14878 (setq org-agenda-files list)
14879 (customize-save-variable 'org-agenda-files org-agenda-files))))
14881 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14882 "Read the list of agenda files from a file.
14883 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14884 filenames, used by `org-store-new-agenda-file-list' to write back
14885 un-expanded file names."
14886 (when (file-directory-p org-agenda-files)
14887 (error "`org-agenda-files' cannot be a single directory"))
14888 (when (stringp org-agenda-files)
14889 (with-temp-buffer
14890 (insert-file-contents org-agenda-files)
14891 (mapcar
14892 (lambda (f)
14893 (let ((e (expand-file-name (substitute-in-file-name f)
14894 org-directory)))
14895 (if pair-with-expansion
14896 (cons e f)
14897 e)))
14898 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14900 ;;;###autoload
14901 (defun org-cycle-agenda-files ()
14902 "Cycle through the files in `org-agenda-files'.
14903 If the current buffer visits an agenda file, find the next one in the list.
14904 If the current buffer does not, find the first agenda file."
14905 (interactive)
14906 (let* ((fs (org-agenda-files t))
14907 (files (append fs (list (car fs))))
14908 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14909 file)
14910 (unless files (error "No agenda files"))
14911 (catch 'exit
14912 (while (setq file (pop files))
14913 (if (equal (file-truename file) tcf)
14914 (when (car files)
14915 (find-file (car files))
14916 (throw 'exit t))))
14917 (find-file (car fs)))
14918 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14920 (defun org-agenda-file-to-front (&optional to-end)
14921 "Move/add the current file to the top of the agenda file list.
14922 If the file is not present in the list, it is added to the front. If it is
14923 present, it is moved there. With optional argument TO-END, add/move to the
14924 end of the list."
14925 (interactive "P")
14926 (let ((org-agenda-skip-unavailable-files nil)
14927 (file-alist (mapcar (lambda (x)
14928 (cons (file-truename x) x))
14929 (org-agenda-files t)))
14930 (ctf (file-truename buffer-file-name))
14931 x had)
14932 (setq x (assoc ctf file-alist) had x)
14934 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14935 (if to-end
14936 (setq file-alist (append (delq x file-alist) (list x)))
14937 (setq file-alist (cons x (delq x file-alist))))
14938 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14939 (org-install-agenda-files-menu)
14940 (message "File %s to %s of agenda file list"
14941 (if had "moved" "added") (if to-end "end" "front"))))
14943 (defun org-remove-file (&optional file)
14944 "Remove current file from the list of files in variable `org-agenda-files'.
14945 These are the files which are being checked for agenda entries.
14946 Optional argument FILE means use this file instead of the current."
14947 (interactive)
14948 (let* ((org-agenda-skip-unavailable-files nil)
14949 (file (or file buffer-file-name))
14950 (true-file (file-truename file))
14951 (afile (abbreviate-file-name file))
14952 (files (delq nil (mapcar
14953 (lambda (x)
14954 (if (equal true-file
14955 (file-truename x))
14956 nil x))
14957 (org-agenda-files t)))))
14958 (if (not (= (length files) (length (org-agenda-files t))))
14959 (progn
14960 (org-store-new-agenda-file-list files)
14961 (org-install-agenda-files-menu)
14962 (message "Removed file: %s" afile))
14963 (message "File was not in list: %s (not removed)" afile))))
14965 (defun org-file-menu-entry (file)
14966 (vector file (list 'find-file file) t))
14968 (defun org-check-agenda-file (file)
14969 "Make sure FILE exists. If not, ask user what to do."
14970 (when (not (file-exists-p file))
14971 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14972 (abbreviate-file-name file))
14973 (let ((r (downcase (read-char-exclusive))))
14974 (cond
14975 ((equal r ?r)
14976 (org-remove-file file)
14977 (throw 'nextfile t))
14978 (t (error "Abort"))))))
14980 (defun org-get-agenda-file-buffer (file)
14981 "Get a buffer visiting FILE. If the buffer needs to be created, add
14982 it to the list of buffers which might be released later."
14983 (let ((buf (org-find-base-buffer-visiting file)))
14984 (if buf
14985 buf ; just return it
14986 ;; Make a new buffer and remember it
14987 (setq buf (find-file-noselect file))
14988 (if buf (push buf org-agenda-new-buffers))
14989 buf)))
14991 (defun org-release-buffers (blist)
14992 "Release all buffers in list, asking the user for confirmation when needed.
14993 When a buffer is unmodified, it is just killed. When modified, it is saved
14994 \(if the user agrees) and then killed."
14995 (let (buf file)
14996 (while (setq buf (pop blist))
14997 (setq file (buffer-file-name buf))
14998 (when (and (buffer-modified-p buf)
14999 file
15000 (y-or-n-p (format "Save file %s? " file)))
15001 (with-current-buffer buf (save-buffer)))
15002 (kill-buffer buf))))
15004 (defun org-prepare-agenda-buffers (files)
15005 "Create buffers for all agenda files, protect archived trees and comments."
15006 (interactive)
15007 (let ((pa '(:org-archived t))
15008 (pc '(:org-comment t))
15009 (pall '(:org-archived t :org-comment t))
15010 (inhibit-read-only t)
15011 (rea (concat ":" org-archive-tag ":"))
15012 bmp file re)
15013 (save-excursion
15014 (save-restriction
15015 (while (setq file (pop files))
15016 (catch 'nextfile
15017 (if (bufferp file)
15018 (set-buffer file)
15019 (org-check-agenda-file file)
15020 (set-buffer (org-get-agenda-file-buffer file)))
15021 (widen)
15022 (setq bmp (buffer-modified-p))
15023 (org-refresh-category-properties)
15024 (setq org-todo-keywords-for-agenda
15025 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15026 (setq org-done-keywords-for-agenda
15027 (append org-done-keywords-for-agenda org-done-keywords))
15028 (setq org-todo-keyword-alist-for-agenda
15029 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15030 (setq org-drawers-for-agenda
15031 (append org-drawers-for-agenda org-drawers))
15032 (setq org-tag-alist-for-agenda
15033 (append org-tag-alist-for-agenda org-tag-alist))
15035 (save-excursion
15036 (remove-text-properties (point-min) (point-max) pall)
15037 (when org-agenda-skip-archived-trees
15038 (goto-char (point-min))
15039 (while (re-search-forward rea nil t)
15040 (if (org-on-heading-p t)
15041 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15042 (goto-char (point-min))
15043 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15044 (while (re-search-forward re nil t)
15045 (add-text-properties
15046 (match-beginning 0) (org-end-of-subtree t) pc)))
15047 (set-buffer-modified-p bmp)))))
15048 (setq org-todo-keywords-for-agenda
15049 (org-uniquify org-todo-keywords-for-agenda))
15050 (setq org-todo-keyword-alist-for-agenda
15051 (org-uniquify org-todo-keyword-alist-for-agenda)
15052 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15054 ;;;; Embedded LaTeX
15056 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15057 "Keymap for the minor `org-cdlatex-mode'.")
15059 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15060 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15061 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15062 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15063 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15065 (defvar org-cdlatex-texmathp-advice-is-done nil
15066 "Flag remembering if we have applied the advice to texmathp already.")
15068 (define-minor-mode org-cdlatex-mode
15069 "Toggle the minor `org-cdlatex-mode'.
15070 This mode supports entering LaTeX environment and math in LaTeX fragments
15071 in Org-mode.
15072 \\{org-cdlatex-mode-map}"
15073 nil " OCDL" nil
15074 (when org-cdlatex-mode (require 'cdlatex))
15075 (unless org-cdlatex-texmathp-advice-is-done
15076 (setq org-cdlatex-texmathp-advice-is-done t)
15077 (defadvice texmathp (around org-math-always-on activate)
15078 "Always return t in org-mode buffers.
15079 This is because we want to insert math symbols without dollars even outside
15080 the LaTeX math segments. If Orgmode thinks that point is actually inside
15081 an embedded LaTeX fragment, let texmathp do its job.
15082 \\[org-cdlatex-mode-map]"
15083 (interactive)
15084 (let (p)
15085 (cond
15086 ((not (org-mode-p)) ad-do-it)
15087 ((eq this-command 'cdlatex-math-symbol)
15088 (setq ad-return-value t
15089 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15091 (let ((p (org-inside-LaTeX-fragment-p)))
15092 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15093 (setq ad-return-value t
15094 texmathp-why '("Org-mode embedded math" . 0))
15095 (if p ad-do-it)))))))))
15097 (defun turn-on-org-cdlatex ()
15098 "Unconditionally turn on `org-cdlatex-mode'."
15099 (org-cdlatex-mode 1))
15101 (defun org-inside-LaTeX-fragment-p ()
15102 "Test if point is inside a LaTeX fragment.
15103 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15104 sequence appearing also before point.
15105 Even though the matchers for math are configurable, this function assumes
15106 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15107 delimiters are skipped when they have been removed by customization.
15108 The return value is nil, or a cons cell with the delimiter and
15109 and the position of this delimiter.
15111 This function does a reasonably good job, but can locally be fooled by
15112 for example currency specifications. For example it will assume being in
15113 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15114 fragments that are properly closed, but during editing, we have to live
15115 with the uncertainty caused by missing closing delimiters. This function
15116 looks only before point, not after."
15117 (catch 'exit
15118 (let ((pos (point))
15119 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15120 (lim (progn
15121 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15122 (point)))
15123 dd-on str (start 0) m re)
15124 (goto-char pos)
15125 (when dodollar
15126 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15127 re (nth 1 (assoc "$" org-latex-regexps)))
15128 (while (string-match re str start)
15129 (cond
15130 ((= (match-end 0) (length str))
15131 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15132 ((= (match-end 0) (- (length str) 5))
15133 (throw 'exit nil))
15134 (t (setq start (match-end 0))))))
15135 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15136 (goto-char pos)
15137 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15138 (and (match-beginning 2) (throw 'exit nil))
15139 ;; count $$
15140 (while (re-search-backward "\\$\\$" lim t)
15141 (setq dd-on (not dd-on)))
15142 (goto-char pos)
15143 (if dd-on (cons "$$" m))))))
15145 (defun org-inside-latex-macro-p ()
15146 "Is point inside a LaTeX macro or its arguments?"
15147 (save-match-data
15148 (org-in-regexp
15149 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15151 (defun test ()
15152 (interactive)
15153 (message "%s" (org-inside-latex-macro-p)))
15155 (defun org-try-cdlatex-tab ()
15156 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15157 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15158 - inside a LaTeX fragment, or
15159 - after the first word in a line, where an abbreviation expansion could
15160 insert a LaTeX environment."
15161 (when org-cdlatex-mode
15162 (cond
15163 ((save-excursion
15164 (skip-chars-backward "a-zA-Z0-9*")
15165 (skip-chars-backward " \t")
15166 (bolp))
15167 (cdlatex-tab) t)
15168 ((org-inside-LaTeX-fragment-p)
15169 (cdlatex-tab) t)
15170 (t nil))))
15172 (defun org-cdlatex-underscore-caret (&optional arg)
15173 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15174 Revert to the normal definition outside of these fragments."
15175 (interactive "P")
15176 (if (org-inside-LaTeX-fragment-p)
15177 (call-interactively 'cdlatex-sub-superscript)
15178 (let (org-cdlatex-mode)
15179 (call-interactively (key-binding (vector last-input-event))))))
15181 (defun org-cdlatex-math-modify (&optional arg)
15182 "Execute `cdlatex-math-modify' in LaTeX fragments.
15183 Revert to the normal definition outside of these fragments."
15184 (interactive "P")
15185 (if (org-inside-LaTeX-fragment-p)
15186 (call-interactively 'cdlatex-math-modify)
15187 (let (org-cdlatex-mode)
15188 (call-interactively (key-binding (vector last-input-event))))))
15190 (defvar org-latex-fragment-image-overlays nil
15191 "List of overlays carrying the images of latex fragments.")
15192 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15194 (defun org-remove-latex-fragment-image-overlays ()
15195 "Remove all overlays with LaTeX fragment images in current buffer."
15196 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15197 (setq org-latex-fragment-image-overlays nil))
15199 (defun org-preview-latex-fragment (&optional subtree)
15200 "Preview the LaTeX fragment at point, or all locally or globally.
15201 If the cursor is in a LaTeX fragment, create the image and overlay
15202 it over the source code. If there is no fragment at point, display
15203 all fragments in the current text, from one headline to the next. With
15204 prefix SUBTREE, display all fragments in the current subtree. With a
15205 double prefix `C-u C-u', or when the cursor is before the first headline,
15206 display all fragments in the buffer.
15207 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15208 (interactive "P")
15209 (org-remove-latex-fragment-image-overlays)
15210 (save-excursion
15211 (save-restriction
15212 (let (beg end at msg)
15213 (cond
15214 ((or (equal subtree '(16))
15215 (not (save-excursion
15216 (re-search-backward (concat "^" outline-regexp) nil t))))
15217 (setq beg (point-min) end (point-max)
15218 msg "Creating images for buffer...%s"))
15219 ((equal subtree '(4))
15220 (org-back-to-heading)
15221 (setq beg (point) end (org-end-of-subtree t)
15222 msg "Creating images for subtree...%s"))
15224 (if (setq at (org-inside-LaTeX-fragment-p))
15225 (goto-char (max (point-min) (- (cdr at) 2)))
15226 (org-back-to-heading))
15227 (setq beg (point) end (progn (outline-next-heading) (point))
15228 msg (if at "Creating image...%s"
15229 "Creating images for entry...%s"))))
15230 (message msg "")
15231 (narrow-to-region beg end)
15232 (goto-char beg)
15233 (org-format-latex
15234 (concat "ltxpng/" (file-name-sans-extension
15235 (file-name-nondirectory
15236 buffer-file-name)))
15237 default-directory 'overlays msg at 'forbuffer)
15238 (message msg "done. Use `C-c C-c' to remove images.")))))
15240 (defvar org-latex-regexps
15241 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15242 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15243 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15244 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15245 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15246 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15247 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15248 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15249 "Regular expressions for matching embedded LaTeX.")
15251 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15252 "Replace LaTeX fragments with links to an image, and produce images.
15253 Some of the options can be changed using the variable
15254 `org-format-latex-options'."
15255 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15256 (let* ((prefixnodir (file-name-nondirectory prefix))
15257 (absprefix (expand-file-name prefix dir))
15258 (todir (file-name-directory absprefix))
15259 (opt org-format-latex-options)
15260 (matchers (plist-get opt :matchers))
15261 (re-list org-latex-regexps)
15262 (org-format-latex-header-extra
15263 (plist-get (org-infile-export-plist) :latex-header-extra))
15264 (cnt 0) txt hash link beg end re e checkdir
15265 executables-checked
15266 m n block linkfile movefile ov)
15267 ;; Check the different regular expressions
15268 (while (setq e (pop re-list))
15269 (setq m (car e) re (nth 1 e) n (nth 2 e)
15270 block (if (nth 3 e) "\n\n" ""))
15271 (when (member m matchers)
15272 (goto-char (point-min))
15273 (while (re-search-forward re nil t)
15274 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15275 (not (get-text-property (match-beginning n)
15276 'org-protected))
15277 (or (not overlays)
15278 (not (eq (get-char-property (match-beginning n)
15279 'org-overlay-type)
15280 'org-latex-overlay))))
15281 (setq txt (match-string n)
15282 beg (match-beginning n) end (match-end n)
15283 cnt (1+ cnt))
15284 (let (print-length print-level) ; make sure full list is printed
15285 (setq hash (sha1 (prin1-to-string
15286 (list org-format-latex-header
15287 org-format-latex-header-extra
15288 org-export-latex-default-packages-alist
15289 org-export-latex-packages-alist
15290 org-format-latex-options
15291 forbuffer txt)))
15292 linkfile (format "%s_%s.png" prefix hash)
15293 movefile (format "%s_%s.png" absprefix hash)))
15294 (setq link (concat block "[[file:" linkfile "]]" block))
15295 (if msg (message msg cnt))
15296 (goto-char beg)
15297 (unless checkdir ; make sure the directory exists
15298 (setq checkdir t)
15299 (or (file-directory-p todir) (make-directory todir)))
15301 (unless executables-checked
15302 (org-check-external-command
15303 "latex" "needed to convert LaTeX fragments to images")
15304 (org-check-external-command
15305 "dvipng" "needed to convert LaTeX fragments to images")
15306 (setq executables-checked t))
15308 (unless (file-exists-p movefile)
15309 (org-create-formula-image
15310 txt movefile opt forbuffer))
15311 (if overlays
15312 (progn
15313 (mapc (lambda (o)
15314 (if (eq (overlay-get o 'org-overlay-type)
15315 'org-latex-overlay)
15316 (delete-overlay o)))
15317 (overlays-in beg end))
15318 (setq ov (make-overlay beg end))
15319 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15320 (if (featurep 'xemacs)
15321 (progn
15322 (overlay-put ov 'invisible t)
15323 (overlay-put
15324 ov 'end-glyph
15325 (make-glyph (vector 'png :file movefile))))
15326 (overlay-put
15327 ov 'display
15328 (list 'image :type 'png :file movefile :ascent 'center)))
15329 (push ov org-latex-fragment-image-overlays)
15330 (goto-char end))
15331 (delete-region beg end)
15332 (insert (org-add-props link
15333 (list 'org-latex-src
15334 (replace-regexp-in-string "\"" "" txt)))))))))))
15336 ;; This function borrows from Ganesh Swami's latex2png.el
15337 (defun org-create-formula-image (string tofile options buffer)
15338 "This calls dvipng."
15339 (require 'org-latex)
15340 (let* ((tmpdir (if (featurep 'xemacs)
15341 (temp-directory)
15342 temporary-file-directory))
15343 (texfilebase (make-temp-name
15344 (expand-file-name "orgtex" tmpdir)))
15345 (texfile (concat texfilebase ".tex"))
15346 (dvifile (concat texfilebase ".dvi"))
15347 (pngfile (concat texfilebase ".png"))
15348 (fnh (if (featurep 'xemacs)
15349 (font-height (get-face-font 'default))
15350 (face-attribute 'default :height nil)))
15351 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15352 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15353 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15354 "Black"))
15355 (bg (or (plist-get options (if buffer :background :html-background))
15356 "Transparent")))
15357 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15358 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15359 (with-temp-file texfile
15360 (insert (org-splice-latex-header
15361 org-format-latex-header
15362 org-export-latex-default-packages-alist
15363 org-export-latex-packages-alist t
15364 org-format-latex-header-extra))
15365 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15366 (require 'org-latex)
15367 (org-export-latex-fix-inputenc))
15368 (let ((dir default-directory))
15369 (condition-case nil
15370 (progn
15371 (cd tmpdir)
15372 (call-process "latex" nil nil nil texfile))
15373 (error nil))
15374 (cd dir))
15375 (if (not (file-exists-p dvifile))
15376 (progn (message "Failed to create dvi file from %s" texfile) nil)
15377 (condition-case nil
15378 (call-process "dvipng" nil nil nil
15379 "-fg" fg "-bg" bg
15380 "-D" dpi
15381 ;;"-x" scale "-y" scale
15382 "-T" "tight"
15383 "-o" pngfile
15384 dvifile)
15385 (error nil))
15386 (if (not (file-exists-p pngfile))
15387 (if org-format-latex-signal-error
15388 (error "Failed to create png file from %s" texfile)
15389 (message "Failed to create png file from %s" texfile)
15390 nil)
15391 ;; Use the requested file name and clean up
15392 (copy-file pngfile tofile 'replace)
15393 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15394 (delete-file (concat texfilebase e)))
15395 pngfile))))
15397 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15398 "Fill a LaTeX header template TPL.
15399 In the template, the following place holders will be recognized:
15401 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15402 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15403 [PACKAGES] \\usepackage statements for PKG
15404 [NO-PACKAGES] do not include PKG
15405 [EXTRA] the string EXTRA
15406 [NO-EXTRA] do not include EXTRA
15408 For backward compatibility, if both the positive and the negative place
15409 holder is missing, the positive one (without the \"NO-\") will be
15410 assumed to be present at the end of the template.
15411 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15412 EXTRA is a string.
15413 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15414 (let (rpl (end ""))
15415 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15416 (setq rpl (if (or (match-end 1) (not def-pkg))
15417 "" (org-latex-packages-to-string def-pkg snippets-p t))
15418 tpl (replace-match rpl t t tpl))
15419 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15421 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15422 (setq rpl (if (or (match-end 1) (not pkg))
15423 "" (org-latex-packages-to-string pkg snippets-p t))
15424 tpl (replace-match rpl t t tpl))
15425 (if pkg (setq end
15426 (concat end "\n"
15427 (org-latex-packages-to-string pkg snippets-p)))))
15429 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15430 (setq rpl (if (or (match-end 1) (not extra))
15431 "" (concat extra "\n"))
15432 tpl (replace-match rpl t t tpl))
15433 (if (and extra (string-match "\\S-" extra))
15434 (setq end (concat end "\n" extra))))
15436 (if (string-match "\\S-" end)
15437 (concat tpl "\n" end)
15438 tpl)))
15440 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
15441 "Turn an alist of packages into a string with the \\usepackage macros."
15442 (setq pkg (mapconcat (lambda(p)
15443 (cond
15444 ((stringp p) p)
15445 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
15446 (format "%% Package %s omitted" (cadr p)))
15447 ((equal "" (car p))
15448 (format "\\usepackage{%s}" (cadr p)))
15450 (format "\\usepackage[%s]{%s}"
15451 (car p) (cadr p)))))
15453 "\n"))
15454 (if newline (concat pkg "\n") pkg))
15456 (defun org-dvipng-color (attr)
15457 "Return an rgb color specification for dvipng."
15458 (apply 'format "rgb %s %s %s"
15459 (mapcar 'org-normalize-color
15460 (color-values (face-attribute 'default attr nil)))))
15462 (defun org-normalize-color (value)
15463 "Return string to be used as color value for an RGB component."
15464 (format "%g" (/ value 65535.0)))
15466 ;;;; Key bindings
15468 ;; Make `C-c C-x' a prefix key
15469 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15471 ;; TAB key with modifiers
15472 (org-defkey org-mode-map "\C-i" 'org-cycle)
15473 (org-defkey org-mode-map [(tab)] 'org-cycle)
15474 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15475 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15476 (org-defkey org-mode-map "\M-\t" 'org-complete)
15477 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15478 ;; The following line is necessary under Suse GNU/Linux
15479 (unless (featurep 'xemacs)
15480 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15481 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15482 (define-key org-mode-map [backtab] 'org-shifttab)
15484 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15485 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15486 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15488 ;; Cursor keys with modifiers
15489 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15490 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15491 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15492 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15494 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15495 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15496 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15497 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15499 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15500 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15501 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15502 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15504 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15505 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15507 ;;; Extra keys for tty access.
15508 ;; We only set them when really needed because otherwise the
15509 ;; menus don't show the simple keys
15511 (when (or org-use-extra-keys
15512 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15513 (not window-system))
15514 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15515 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15516 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15517 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15518 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15519 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15520 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15521 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15522 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15523 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15524 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15525 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15526 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15527 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15528 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15529 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15530 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15531 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15532 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15533 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15534 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15535 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15536 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15537 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15538 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15539 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15540 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15541 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15543 ;; All the other keys
15545 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15546 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15547 (if (boundp 'narrow-map)
15548 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15549 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15550 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15551 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15552 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15553 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15554 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15555 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15556 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15557 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15558 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15559 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15560 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15561 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15562 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15563 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15564 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15565 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15566 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15567 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15568 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15569 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15570 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15571 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15572 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15573 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15574 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15575 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15576 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15577 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15578 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15579 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15580 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15581 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15582 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15583 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15584 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15585 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15586 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15587 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15588 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15589 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15590 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15591 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15592 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15593 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15594 (org-defkey org-mode-map "\C-c^" 'org-sort)
15595 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15596 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15597 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15598 (org-defkey org-mode-map "\C-m" 'org-return)
15599 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15600 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15601 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15602 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15603 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15604 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15605 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15606 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15607 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15608 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15609 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15610 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15611 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15612 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15613 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15614 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15615 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15616 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15617 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15618 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15619 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15621 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15622 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15623 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15624 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15626 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15627 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15628 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15629 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15630 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15631 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15632 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15633 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15634 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15635 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15636 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15637 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15638 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15639 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15640 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15642 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15643 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15644 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15645 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15647 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15649 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15651 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15652 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15654 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15657 (when (featurep 'xemacs)
15658 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15661 (defconst org-speed-commands-default
15663 ("Outline Navigation")
15664 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15665 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15666 ("f" . (org-speed-move-safe 'org-forward-same-level))
15667 ("b" . (org-speed-move-safe 'org-backward-same-level))
15668 ("u" . (org-speed-move-safe 'outline-up-heading))
15669 ("j" . org-goto)
15670 ("g" . (org-refile t))
15671 ("Outline Visibility")
15672 ("c" . org-cycle)
15673 ("C" . org-shifttab)
15674 (" " . org-display-outline-path)
15675 ("Outline Structure Editing")
15676 ("U" . org-shiftmetaup)
15677 ("D" . org-shiftmetadown)
15678 ("r" . org-metaright)
15679 ("l" . org-metaleft)
15680 ("R" . org-shiftmetaright)
15681 ("L" . org-shiftmetaleft)
15682 ("i" . (progn (forward-char 1) (call-interactively
15683 'org-insert-heading-respect-content)))
15684 ("^" . org-sort)
15685 ("w" . org-refile)
15686 ("a" . org-archive-subtree-default-with-confirmation)
15687 ("." . outline-mark-subtree)
15688 ("Clock Commands")
15689 ("I" . org-clock-in)
15690 ("O" . org-clock-out)
15691 ("Meta Data Editing")
15692 ("t" . org-todo)
15693 ("0" . (org-priority ?\ ))
15694 ("1" . (org-priority ?A))
15695 ("2" . (org-priority ?B))
15696 ("3" . (org-priority ?C))
15697 (";" . org-set-tags-command)
15698 ("e" . org-set-effort)
15699 ("Agenda Views etc")
15700 ("v" . org-agenda)
15701 ("/" . org-sparse-tree)
15702 ("Misc")
15703 ("o" . org-open-at-point)
15704 ("?" . org-speed-command-help)
15706 "The default speed commands.")
15708 (defun org-print-speed-command (e)
15709 (if (> (length (car e)) 1)
15710 (progn
15711 (princ "\n")
15712 (princ (car e))
15713 (princ "\n")
15714 (princ (make-string (length (car e)) ?-))
15715 (princ "\n"))
15716 (princ (car e))
15717 (princ " ")
15718 (if (symbolp (cdr e))
15719 (princ (symbol-name (cdr e)))
15720 (prin1 (cdr e)))
15721 (princ "\n")))
15723 (defun org-speed-command-help ()
15724 "Show the available speed commands."
15725 (interactive)
15726 (if (not org-use-speed-commands)
15727 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15728 (with-output-to-temp-buffer "*Help*"
15729 (princ "User-defined Speed commands\n===========================\n")
15730 (mapc 'org-print-speed-command org-speed-commands-user)
15731 (princ "\n")
15732 (princ "Built-in Speed commands\n=======================\n")
15733 (mapc 'org-print-speed-command org-speed-commands-default))
15734 (with-current-buffer "*Help*"
15735 (setq truncate-lines t))))
15737 (defun org-speed-move-safe (cmd)
15738 "Execute CMD, but make sure that the cursor always ends up in a headline.
15739 If not, return to the original position and throw an error."
15740 (interactive)
15741 (let ((pos (point)))
15742 (call-interactively cmd)
15743 (unless (and (bolp) (org-on-heading-p))
15744 (goto-char pos)
15745 (error "Boundary reached while executing %s" cmd))))
15747 (defvar org-self-insert-command-undo-counter 0)
15749 (defvar org-table-auto-blank-field) ; defined in org-table.el
15750 (defvar org-speed-command nil)
15751 (defun org-self-insert-command (N)
15752 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15753 If the cursor is in a table looking at whitespace, the whitespace is
15754 overwritten, and the table is not marked as requiring realignment."
15755 (interactive "p")
15756 (cond
15757 ((and org-use-speed-commands
15758 (or (and (bolp) (looking-at outline-regexp))
15759 (and (functionp org-use-speed-commands)
15760 (funcall org-use-speed-commands)))
15761 (setq
15762 org-speed-command
15763 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15764 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15765 (cond
15766 ((commandp org-speed-command)
15767 (setq this-command org-speed-command)
15768 (call-interactively org-speed-command))
15769 ((functionp org-speed-command)
15770 (funcall org-speed-command))
15771 ((and org-speed-command (listp org-speed-command))
15772 (eval org-speed-command))
15773 (t (let (org-use-speed-commands)
15774 (call-interactively 'org-self-insert-command)))))
15775 ((and
15776 (org-table-p)
15777 (progn
15778 ;; check if we blank the field, and if that triggers align
15779 (and (featurep 'org-table) org-table-auto-blank-field
15780 (member last-command
15781 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15782 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15783 ;; got extra space, this field does not determine column width
15784 (let (org-table-may-need-update) (org-table-blank-field))
15785 ;; no extra space, this field may determine column width
15786 (org-table-blank-field)))
15788 (eq N 1)
15789 (looking-at "[^|\n]* |"))
15790 (let (org-table-may-need-update)
15791 (goto-char (1- (match-end 0)))
15792 (delete-backward-char 1)
15793 (goto-char (match-beginning 0))
15794 (self-insert-command N)))
15796 (setq org-table-may-need-update t)
15797 (self-insert-command N)
15798 (org-fix-tags-on-the-fly)
15799 (if org-self-insert-cluster-for-undo
15800 (if (not (eq last-command 'org-self-insert-command))
15801 (setq org-self-insert-command-undo-counter 1)
15802 (if (>= org-self-insert-command-undo-counter 20)
15803 (setq org-self-insert-command-undo-counter 1)
15804 (and (> org-self-insert-command-undo-counter 0)
15805 buffer-undo-list
15806 (not (cadr buffer-undo-list)) ; remove nil entry
15807 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15808 (setq org-self-insert-command-undo-counter
15809 (1+ org-self-insert-command-undo-counter))))))))
15811 (defun org-fix-tags-on-the-fly ()
15812 (when (and (equal (char-after (point-at-bol)) ?*)
15813 (org-on-heading-p))
15814 (org-align-tags-here org-tags-column)))
15816 (defun org-delete-backward-char (N)
15817 "Like `delete-backward-char', insert whitespace at field end in tables.
15818 When deleting backwards, in tables this function will insert whitespace in
15819 front of the next \"|\" separator, to keep the table aligned. The table will
15820 still be marked for re-alignment if the field did fill the entire column,
15821 because, in this case the deletion might narrow the column."
15822 (interactive "p")
15823 (if (and (org-table-p)
15824 (eq N 1)
15825 (string-match "|" (buffer-substring (point-at-bol) (point)))
15826 (looking-at ".*?|"))
15827 (let ((pos (point))
15828 (noalign (looking-at "[^|\n\r]* |"))
15829 (c org-table-may-need-update))
15830 (backward-delete-char N)
15831 (skip-chars-forward "^|")
15832 (insert " ")
15833 (goto-char (1- pos))
15834 ;; noalign: if there were two spaces at the end, this field
15835 ;; does not determine the width of the column.
15836 (if noalign (setq org-table-may-need-update c)))
15837 (backward-delete-char N)
15838 (org-fix-tags-on-the-fly)))
15840 (defun org-delete-char (N)
15841 "Like `delete-char', but insert whitespace at field end in tables.
15842 When deleting characters, in tables this function will insert whitespace in
15843 front of the next \"|\" separator, to keep the table aligned. The table will
15844 still be marked for re-alignment if the field did fill the entire column,
15845 because, in this case the deletion might narrow the column."
15846 (interactive "p")
15847 (if (and (org-table-p)
15848 (not (bolp))
15849 (not (= (char-after) ?|))
15850 (eq N 1))
15851 (if (looking-at ".*?|")
15852 (let ((pos (point))
15853 (noalign (looking-at "[^|\n\r]* |"))
15854 (c org-table-may-need-update))
15855 (replace-match (concat
15856 (substring (match-string 0) 1 -1)
15857 " |"))
15858 (goto-char pos)
15859 ;; noalign: if there were two spaces at the end, this field
15860 ;; does not determine the width of the column.
15861 (if noalign (setq org-table-may-need-update c)))
15862 (delete-char N))
15863 (delete-char N)
15864 (org-fix-tags-on-the-fly)))
15866 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15867 (put 'org-self-insert-command 'delete-selection t)
15868 (put 'orgtbl-self-insert-command 'delete-selection t)
15869 (put 'org-delete-char 'delete-selection 'supersede)
15870 (put 'org-delete-backward-char 'delete-selection 'supersede)
15871 (put 'org-yank 'delete-selection 'yank)
15873 ;; Make `flyspell-mode' delay after some commands
15874 (put 'org-self-insert-command 'flyspell-delayed t)
15875 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15876 (put 'org-delete-char 'flyspell-delayed t)
15877 (put 'org-delete-backward-char 'flyspell-delayed t)
15879 ;; Make pabbrev-mode expand after org-mode commands
15880 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15881 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15883 ;; How to do this: Measure non-white length of current string
15884 ;; If equal to column width, we should realign.
15886 (defun org-remap (map &rest commands)
15887 "In MAP, remap the functions given in COMMANDS.
15888 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15889 (let (new old)
15890 (while commands
15891 (setq old (pop commands) new (pop commands))
15892 (if (fboundp 'command-remapping)
15893 (org-defkey map (vector 'remap old) new)
15894 (substitute-key-definition old new map global-map)))))
15896 (when (eq org-enable-table-editor 'optimized)
15897 ;; If the user wants maximum table support, we need to hijack
15898 ;; some standard editing functions
15899 (org-remap org-mode-map
15900 'self-insert-command 'org-self-insert-command
15901 'delete-char 'org-delete-char
15902 'delete-backward-char 'org-delete-backward-char)
15903 (org-defkey org-mode-map "|" 'org-force-self-insert))
15905 (defvar org-ctrl-c-ctrl-c-hook nil
15906 "Hook for functions attaching themselves to `C-c C-c'.
15907 This can be used to add additional functionality to the C-c C-c key which
15908 executes context-dependent commands.
15909 Each function will be called with no arguments. The function must check
15910 if the context is appropriate for it to act. If yes, it should do its
15911 thing and then return a non-nil value. If the context is wrong,
15912 just do nothing and return nil.")
15914 (defvar org-tab-first-hook nil
15915 "Hook for functions to attach themselves to TAB.
15916 See `org-ctrl-c-ctrl-c-hook' for more information.
15917 This hook runs as the first action when TAB is pressed, even before
15918 `org-cycle' messes around with the `outline-regexp' to cater for
15919 inline tasks and plain list item folding.
15920 If any function in this hook returns t, any other actions that
15921 would have been caused by TAB (such as table field motion or visibility
15922 cycling) will not occur.")
15924 (defvar org-tab-after-check-for-table-hook nil
15925 "Hook for functions to attach themselves to TAB.
15926 See `org-ctrl-c-ctrl-c-hook' for more information.
15927 This hook runs after it has been established that the cursor is not in a
15928 table, but before checking if the cursor is in a headline or if global cycling
15929 should be done.
15930 If any function in this hook returns t, not other actions like visibility
15931 cycling will be done.")
15933 (defvar org-tab-after-check-for-cycling-hook nil
15934 "Hook for functions to attach themselves to TAB.
15935 See `org-ctrl-c-ctrl-c-hook' for more information.
15936 This hook runs after it has been established that not table field motion and
15937 not visibility should be done because of current context. This is probably
15938 the place where a package like yasnippets can hook in.")
15940 (defvar org-tab-before-tab-emulation-hook nil
15941 "Hook for functions to attach themselves to TAB.
15942 See `org-ctrl-c-ctrl-c-hook' for more information.
15943 This hook runs after every other options for TAB have been exhausted, but
15944 before indentation and \t insertion takes place.")
15946 (defvar org-metaleft-hook nil
15947 "Hook for functions attaching themselves to `M-left'.
15948 See `org-ctrl-c-ctrl-c-hook' for more information.")
15949 (defvar org-metaright-hook nil
15950 "Hook for functions attaching themselves to `M-right'.
15951 See `org-ctrl-c-ctrl-c-hook' for more information.")
15952 (defvar org-metaup-hook nil
15953 "Hook for functions attaching themselves to `M-up'.
15954 See `org-ctrl-c-ctrl-c-hook' for more information.")
15955 (defvar org-metadown-hook nil
15956 "Hook for functions attaching themselves to `M-down'.
15957 See `org-ctrl-c-ctrl-c-hook' for more information.")
15958 (defvar org-shiftmetaleft-hook nil
15959 "Hook for functions attaching themselves to `M-S-left'.
15960 See `org-ctrl-c-ctrl-c-hook' for more information.")
15961 (defvar org-shiftmetaright-hook nil
15962 "Hook for functions attaching themselves to `M-S-right'.
15963 See `org-ctrl-c-ctrl-c-hook' for more information.")
15964 (defvar org-shiftmetaup-hook nil
15965 "Hook for functions attaching themselves to `M-S-up'.
15966 See `org-ctrl-c-ctrl-c-hook' for more information.")
15967 (defvar org-shiftmetadown-hook nil
15968 "Hook for functions attaching themselves to `M-S-down'.
15969 See `org-ctrl-c-ctrl-c-hook' for more information.")
15970 (defvar org-metareturn-hook nil
15971 "Hook for functions attaching themselves to `M-RET'.
15972 See `org-ctrl-c-ctrl-c-hook' for more information.")
15973 (defvar org-shiftup-hook nil
15974 "Hook for functions attaching themselves to `S-up'.
15975 See `org-ctrl-c-ctrl-c-hook' for more information.")
15976 (defvar org-shiftup-final-hook nil
15977 "Hook for functions attaching themselves to `S-up'.
15978 This one runs after all other options except shift-select have been excluded.
15979 See `org-ctrl-c-ctrl-c-hook' for more information.")
15980 (defvar org-shiftdown-hook nil
15981 "Hook for functions attaching themselves to `S-down'.
15982 See `org-ctrl-c-ctrl-c-hook' for more information.")
15983 (defvar org-shiftdown-final-hook nil
15984 "Hook for functions attaching themselves to `S-down'.
15985 This one runs after all other options except shift-select have been excluded.
15986 See `org-ctrl-c-ctrl-c-hook' for more information.")
15987 (defvar org-shiftleft-hook nil
15988 "Hook for functions attaching themselves to `S-left'.
15989 See `org-ctrl-c-ctrl-c-hook' for more information.")
15990 (defvar org-shiftleft-final-hook nil
15991 "Hook for functions attaching themselves to `S-left'.
15992 This one runs after all other options except shift-select have been excluded.
15993 See `org-ctrl-c-ctrl-c-hook' for more information.")
15994 (defvar org-shiftright-hook nil
15995 "Hook for functions attaching themselves to `S-right'.
15996 See `org-ctrl-c-ctrl-c-hook' for more information.")
15997 (defvar org-shiftright-final-hook nil
15998 "Hook for functions attaching themselves to `S-right'.
15999 This one runs after all other options except shift-select have been excluded.
16000 See `org-ctrl-c-ctrl-c-hook' for more information.")
16002 (defun org-modifier-cursor-error ()
16003 "Throw an error, a modified cursor command was applied in wrong context."
16004 (error "This command is active in special context like tables, headlines or items"))
16006 (defun org-shiftselect-error ()
16007 "Throw an error because Shift-Cursor command was applied in wrong context."
16008 (if (and (boundp 'shift-select-mode) shift-select-mode)
16009 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16010 (error "This command works only in special context like headlines or timestamps")))
16012 (defun org-call-for-shift-select (cmd)
16013 (let ((this-command-keys-shift-translated t))
16014 (call-interactively cmd)))
16016 (defun org-shifttab (&optional arg)
16017 "Global visibility cycling or move to previous table field.
16018 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16019 on context.
16020 See the individual commands for more information."
16021 (interactive "P")
16022 (cond
16023 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16024 ((integerp arg)
16025 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16026 (message "Content view to level: %d" arg)
16027 (org-content (prefix-numeric-value arg2))
16028 (setq org-cycle-global-status 'overview)))
16029 (t (call-interactively 'org-global-cycle))))
16031 (defun org-shiftmetaleft ()
16032 "Promote subtree or delete table column.
16033 Calls `org-promote-subtree', `org-outdent-item',
16034 or `org-table-delete-column', depending on context.
16035 See the individual commands for more information."
16036 (interactive)
16037 (cond
16038 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16039 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16040 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16041 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16042 (t (org-modifier-cursor-error))))
16044 (defun org-shiftmetaright ()
16045 "Demote subtree or insert table column.
16046 Calls `org-demote-subtree', `org-indent-item',
16047 or `org-table-insert-column', depending on context.
16048 See the individual commands for more information."
16049 (interactive)
16050 (cond
16051 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16052 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16053 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16054 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16055 (t (org-modifier-cursor-error))))
16057 (defun org-shiftmetaup (&optional arg)
16058 "Move subtree up or kill table row.
16059 Calls `org-move-subtree-up' or `org-table-kill-row' or
16060 `org-move-item-up' depending on context. See the individual commands
16061 for more information."
16062 (interactive "P")
16063 (cond
16064 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16065 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16066 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16067 ((org-at-item-p) (call-interactively 'org-move-item-up))
16068 (t (org-modifier-cursor-error))))
16070 (defun org-shiftmetadown (&optional arg)
16071 "Move subtree down or insert table row.
16072 Calls `org-move-subtree-down' or `org-table-insert-row' or
16073 `org-move-item-down', depending on context. See the individual
16074 commands for more information."
16075 (interactive "P")
16076 (cond
16077 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16078 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16079 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16080 ((org-at-item-p) (call-interactively 'org-move-item-down))
16081 (t (org-modifier-cursor-error))))
16083 (defsubst org-hidden-tree-error ()
16084 (error
16085 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16087 (defun org-metaleft (&optional arg)
16088 "Promote heading or move table column to left.
16089 Calls `org-do-promote' or `org-table-move-column', depending on context.
16090 With no specific context, calls the Emacs default `backward-word'.
16091 See the individual commands for more information."
16092 (interactive "P")
16093 (cond
16094 ((run-hook-with-args-until-success 'org-metaleft-hook))
16095 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16096 ((or (org-on-heading-p)
16097 (and (org-region-active-p)
16098 (save-excursion
16099 (goto-char (region-beginning))
16100 (org-on-heading-p))))
16101 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16102 (call-interactively 'org-do-promote))
16103 ((or (org-at-item-p)
16104 (and (org-region-active-p)
16105 (save-excursion
16106 (goto-char (region-beginning))
16107 (org-at-item-p))))
16108 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16109 (call-interactively 'org-outdent-item))
16110 (t (call-interactively 'backward-word))))
16112 (defun org-metaright (&optional arg)
16113 "Demote subtree or move table column to right.
16114 Calls `org-do-demote' or `org-table-move-column', depending on context.
16115 With no specific context, calls the Emacs default `forward-word'.
16116 See the individual commands for more information."
16117 (interactive "P")
16118 (cond
16119 ((run-hook-with-args-until-success 'org-metaright-hook))
16120 ((org-at-table-p) (call-interactively 'org-table-move-column))
16121 ((or (org-on-heading-p)
16122 (and (org-region-active-p)
16123 (save-excursion
16124 (goto-char (region-beginning))
16125 (org-on-heading-p))))
16126 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16127 (call-interactively 'org-do-demote))
16128 ((or (org-at-item-p)
16129 (and (org-region-active-p)
16130 (save-excursion
16131 (goto-char (region-beginning))
16132 (org-at-item-p))))
16133 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16134 (call-interactively 'org-indent-item))
16135 (t (call-interactively 'forward-word))))
16137 (defun org-check-for-hidden (what)
16138 "Check if there are hidden headlines/items in the current visual line.
16139 WHAT can be either `headlines' or `items'. If the current line is
16140 an outline or item heading and it has a folded subtree below it,
16141 this fucntion returns t, nil otherwise."
16142 (let ((re (cond
16143 ((eq what 'headlines) (concat "^" org-outline-regexp))
16144 ((eq what 'items) (concat "^" (org-item-re t)))
16145 (t (error "This should not happen"))))
16146 beg end)
16147 (save-excursion
16148 (catch 'exit
16149 (unless (org-region-active-p)
16150 (setq beg (point-at-bol))
16151 (beginning-of-line 2)
16152 (while (and (not (eobp)) ;; this is like `next-line'
16153 (get-char-property (1- (point)) 'invisible))
16154 (beginning-of-line 2))
16155 (setq end (point))
16156 (goto-char beg)
16157 (goto-char (point-at-eol))
16158 (setq end (max end (point)))
16159 (while (re-search-forward re end t)
16160 (if (get-char-property (match-beginning 0) 'invisible)
16161 (throw 'exit t))))
16162 nil))))
16164 (defun org-metaup (&optional arg)
16165 "Move subtree up or move table row up.
16166 Calls `org-move-subtree-up' or `org-table-move-row' or
16167 `org-move-item-up', depending on context. See the individual commands
16168 for more information."
16169 (interactive "P")
16170 (cond
16171 ((run-hook-with-args-until-success 'org-metaup-hook))
16172 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16173 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16174 ((org-at-item-p) (call-interactively 'org-move-item-up))
16175 (t (transpose-lines 1) (beginning-of-line -1))))
16177 (defun org-metadown (&optional arg)
16178 "Move subtree down or move table row down.
16179 Calls `org-move-subtree-down' or `org-table-move-row' or
16180 `org-move-item-down', depending on context. See the individual
16181 commands for more information."
16182 (interactive "P")
16183 (cond
16184 ((run-hook-with-args-until-success 'org-metadown-hook))
16185 ((org-at-table-p) (call-interactively 'org-table-move-row))
16186 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16187 ((org-at-item-p) (call-interactively 'org-move-item-down))
16188 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16190 (defun org-shiftup (&optional arg)
16191 "Increase item in timestamp or increase priority of current headline.
16192 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16193 depending on context. See the individual commands for more information."
16194 (interactive "P")
16195 (cond
16196 ((run-hook-with-args-until-success 'org-shiftup-hook))
16197 ((and org-support-shift-select (org-region-active-p))
16198 (org-call-for-shift-select 'previous-line))
16199 ((org-at-timestamp-p t)
16200 (call-interactively (if org-edit-timestamp-down-means-later
16201 'org-timestamp-down 'org-timestamp-up)))
16202 ((and (not (eq org-support-shift-select 'always))
16203 org-enable-priority-commands
16204 (org-on-heading-p))
16205 (call-interactively 'org-priority-up))
16206 ((and (not org-support-shift-select) (org-at-item-p))
16207 (call-interactively 'org-previous-item))
16208 ((org-clocktable-try-shift 'up arg))
16209 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16210 (org-support-shift-select
16211 (org-call-for-shift-select 'previous-line))
16212 (t (org-shiftselect-error))))
16214 (defun org-shiftdown (&optional arg)
16215 "Decrease item in timestamp or decrease priority of current headline.
16216 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16217 depending on context. See the individual commands for more information."
16218 (interactive "P")
16219 (cond
16220 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16221 ((and org-support-shift-select (org-region-active-p))
16222 (org-call-for-shift-select 'next-line))
16223 ((org-at-timestamp-p t)
16224 (call-interactively (if org-edit-timestamp-down-means-later
16225 'org-timestamp-up 'org-timestamp-down)))
16226 ((and (not (eq org-support-shift-select 'always))
16227 org-enable-priority-commands
16228 (org-on-heading-p))
16229 (call-interactively 'org-priority-down))
16230 ((and (not org-support-shift-select) (org-at-item-p))
16231 (call-interactively 'org-next-item))
16232 ((org-clocktable-try-shift 'down arg))
16233 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16234 (org-support-shift-select
16235 (org-call-for-shift-select 'next-line))
16236 (t (org-shiftselect-error))))
16238 (defun org-shiftright (&optional arg)
16239 "Cycle the thing at point or in the current line, depending on context.
16240 Depending on context, this does one of the following:
16242 - switch a timestamp at point one day into the future
16243 - on a headline, switch to the next TODO keyword.
16244 - on an item, switch entire list to the next bullet type
16245 - on a property line, switch to the next allowed value
16246 - on a clocktable definition line, move time block into the future"
16247 (interactive "P")
16248 (cond
16249 ((run-hook-with-args-until-success 'org-shiftright-hook))
16250 ((and org-support-shift-select (org-region-active-p))
16251 (org-call-for-shift-select 'forward-char))
16252 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16253 ((and (not (eq org-support-shift-select 'always))
16254 (org-on-heading-p))
16255 (let ((org-inhibit-logging
16256 (not org-treat-S-cursor-todo-selection-as-state-change))
16257 (org-inhibit-blocking
16258 (not org-treat-S-cursor-todo-selection-as-state-change)))
16259 (org-call-with-arg 'org-todo 'right)))
16260 ((or (and org-support-shift-select
16261 (not (eq org-support-shift-select 'always))
16262 (org-at-item-bullet-p))
16263 (and (not org-support-shift-select) (org-at-item-p)))
16264 (org-call-with-arg 'org-cycle-list-bullet nil))
16265 ((and (not (eq org-support-shift-select 'always))
16266 (org-at-property-p))
16267 (call-interactively 'org-property-next-allowed-value))
16268 ((org-clocktable-try-shift 'right arg))
16269 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16270 (org-support-shift-select
16271 (org-call-for-shift-select 'forward-char))
16272 (t (org-shiftselect-error))))
16274 (defun org-shiftleft (&optional arg)
16275 "Cycle the thing at point or in the current line, depending on context.
16276 Depending on context, this does one of the following:
16278 - switch a timestamp at point one day into the past
16279 - on a headline, switch to the previous TODO keyword.
16280 - on an item, switch entire list to the previous bullet type
16281 - on a property line, switch to the previous allowed value
16282 - on a clocktable definition line, move time block into the past"
16283 (interactive "P")
16284 (cond
16285 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16286 ((and org-support-shift-select (org-region-active-p))
16287 (org-call-for-shift-select 'backward-char))
16288 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16289 ((and (not (eq org-support-shift-select 'always))
16290 (org-on-heading-p))
16291 (let ((org-inhibit-logging
16292 (not org-treat-S-cursor-todo-selection-as-state-change))
16293 (org-inhibit-blocking
16294 (not org-treat-S-cursor-todo-selection-as-state-change)))
16295 (org-call-with-arg 'org-todo 'left)))
16296 ((or (and org-support-shift-select
16297 (not (eq org-support-shift-select 'always))
16298 (org-at-item-bullet-p))
16299 (and (not org-support-shift-select) (org-at-item-p)))
16300 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16301 ((and (not (eq org-support-shift-select 'always))
16302 (org-at-property-p))
16303 (call-interactively 'org-property-previous-allowed-value))
16304 ((org-clocktable-try-shift 'left arg))
16305 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16306 (org-support-shift-select
16307 (org-call-for-shift-select 'backward-char))
16308 (t (org-shiftselect-error))))
16310 (defun org-shiftcontrolright ()
16311 "Switch to next TODO set."
16312 (interactive)
16313 (cond
16314 ((and org-support-shift-select (org-region-active-p))
16315 (org-call-for-shift-select 'forward-word))
16316 ((and (not (eq org-support-shift-select 'always))
16317 (org-on-heading-p))
16318 (org-call-with-arg 'org-todo 'nextset))
16319 (org-support-shift-select
16320 (org-call-for-shift-select 'forward-word))
16321 (t (org-shiftselect-error))))
16323 (defun org-shiftcontrolleft ()
16324 "Switch to previous TODO set."
16325 (interactive)
16326 (cond
16327 ((and org-support-shift-select (org-region-active-p))
16328 (org-call-for-shift-select 'backward-word))
16329 ((and (not (eq org-support-shift-select 'always))
16330 (org-on-heading-p))
16331 (org-call-with-arg 'org-todo 'previousset))
16332 (org-support-shift-select
16333 (org-call-for-shift-select 'backward-word))
16334 (t (org-shiftselect-error))))
16336 (defun org-ctrl-c-ret ()
16337 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16338 (interactive)
16339 (cond
16340 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16341 (t (call-interactively 'org-insert-heading))))
16343 (defun org-copy-special ()
16344 "Copy region in table or copy current subtree.
16345 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16346 See the individual commands for more information."
16347 (interactive)
16348 (call-interactively
16349 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16351 (defun org-cut-special ()
16352 "Cut region in table or cut current subtree.
16353 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16354 See the individual commands for more information."
16355 (interactive)
16356 (call-interactively
16357 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16359 (defun org-paste-special (arg)
16360 "Paste rectangular region into table, or past subtree relative to level.
16361 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16362 See the individual commands for more information."
16363 (interactive "P")
16364 (if (org-at-table-p)
16365 (org-table-paste-rectangle)
16366 (org-paste-subtree arg)))
16368 (defun org-edit-special ()
16369 "Call a special editor for the stuff at point.
16370 When at a table, call the formula editor with `org-table-edit-formulas'.
16371 When at the first line of an src example, call `org-edit-src-code'.
16372 When in an #+include line, visit the include file. Otherwise call
16373 `ffap' to visit the file at point."
16374 (interactive)
16375 (cond
16376 ((org-at-table.el-p)
16377 (org-edit-src-code))
16378 ((org-at-table-p)
16379 (call-interactively 'org-table-edit-formulas))
16380 ((save-excursion
16381 (beginning-of-line 1)
16382 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16383 (find-file (org-trim (match-string 1))))
16384 ((org-edit-src-code))
16385 ((org-edit-fixed-width-region))
16386 (t (call-interactively 'ffap))))
16389 (defun org-ctrl-c-ctrl-c (&optional arg)
16390 "Set tags in headline, or update according to changed information at point.
16392 This command does many different things, depending on context:
16394 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16395 this is what we do.
16397 - If the cursor is on a statistics cookie, update it.
16399 - If the cursor is in a headline, prompt for tags and insert them
16400 into the current line, aligned to `org-tags-column'. When called
16401 with prefix arg, realign all tags in the current buffer.
16403 - If the cursor is in one of the special #+KEYWORD lines, this
16404 triggers scanning the buffer for these lines and updating the
16405 information.
16407 - If the cursor is inside a table, realign the table. This command
16408 works even if the automatic table editor has been turned off.
16410 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16411 the entire table.
16413 - If the cursor is at a footnote reference or definition, jump to
16414 the corresponding definition or references, respectively.
16416 - If the cursor is a the beginning of a dynamic block, update it.
16418 - If the current buffer is a remember buffer, close note and file
16419 it. A prefix argument of 1 files to the default location
16420 without further interaction. A prefix argument of 2 files to
16421 the currently clocking task.
16423 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16424 links in this buffer.
16426 - If the cursor is on a numbered item in a plain list, renumber the
16427 ordered list.
16429 - If the cursor is on a checkbox, toggle it."
16430 (interactive "P")
16431 (let ((org-enable-table-editor t))
16432 (cond
16433 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16434 org-occur-highlights
16435 org-latex-fragment-image-overlays)
16436 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16437 (org-remove-occur-highlights)
16438 (org-remove-latex-fragment-image-overlays)
16439 (message "Temporary highlights/overlays removed from current buffer"))
16440 ((and (local-variable-p 'org-finish-function (current-buffer))
16441 (fboundp org-finish-function))
16442 (funcall org-finish-function))
16443 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16444 ((or (looking-at org-property-start-re)
16445 (org-at-property-p))
16446 (call-interactively 'org-property-action))
16447 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16448 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16449 (or (org-on-heading-p) (org-at-item-p)))
16450 (call-interactively 'org-update-statistics-cookies))
16451 ((org-on-heading-p) (call-interactively 'org-set-tags))
16452 ((org-at-table.el-p)
16453 (message "Use C-c ' to edit table.el tables"))
16454 ((org-at-table-p)
16455 (org-table-maybe-eval-formula)
16456 (if arg
16457 (call-interactively 'org-table-recalculate)
16458 (org-table-maybe-recalculate-line))
16459 (call-interactively 'org-table-align))
16460 ((or (org-footnote-at-reference-p)
16461 (org-footnote-at-definition-p))
16462 (call-interactively 'org-footnote-action))
16463 ((org-at-item-checkbox-p)
16464 (call-interactively 'org-toggle-checkbox))
16465 ((org-at-item-p)
16466 (if arg
16467 (call-interactively 'org-toggle-checkbox)
16468 (call-interactively 'org-maybe-renumber-ordered-list)))
16469 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16470 ;; Dynamic block
16471 (beginning-of-line 1)
16472 (save-excursion (org-update-dblock)))
16473 ((save-excursion
16474 (beginning-of-line 1)
16475 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16476 (cond
16477 ((equal (match-string 1) "TBLFM")
16478 ;; Recalculate the table before this line
16479 (save-excursion
16480 (beginning-of-line 1)
16481 (skip-chars-backward " \r\n\t")
16482 (if (org-at-table-p)
16483 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16485 (let ((org-inhibit-startup-visibility-stuff t)
16486 (org-startup-align-all-tables nil))
16487 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16488 (message "Local setup has been refreshed"))))
16489 ((org-clock-update-time-maybe))
16490 (t (error "C-c C-c can do nothing useful at this location")))))
16492 (defun org-mode-restart ()
16493 "Restart Org-mode, to scan again for special lines.
16494 Also updates the keyword regular expressions."
16495 (interactive)
16496 (org-mode)
16497 (message "Org-mode restarted"))
16499 (defun org-kill-note-or-show-branches ()
16500 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16501 (interactive)
16502 (if (not org-finish-function)
16503 (call-interactively 'show-branches)
16504 (let ((org-note-abort t))
16505 (funcall org-finish-function))))
16507 (defun org-return (&optional indent)
16508 "Goto next table row or insert a newline.
16509 Calls `org-table-next-row' or `newline', depending on context.
16510 See the individual commands for more information."
16511 (interactive)
16512 (cond
16513 ((bobp) (if indent (newline-and-indent) (newline)))
16514 ((org-at-table-p)
16515 (org-table-justify-field-maybe)
16516 (call-interactively 'org-table-next-row))
16517 ((and org-return-follows-link
16518 (eq (get-text-property (point) 'face) 'org-link))
16519 (call-interactively 'org-open-at-point))
16520 ((and (org-at-heading-p)
16521 (looking-at
16522 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16523 (org-show-entry)
16524 (end-of-line 1)
16525 (newline))
16526 (t (if indent (newline-and-indent) (newline)))))
16528 (defun org-return-indent ()
16529 "Goto next table row or insert a newline and indent.
16530 Calls `org-table-next-row' or `newline-and-indent', depending on
16531 context. See the individual commands for more information."
16532 (interactive)
16533 (org-return t))
16535 (defun org-ctrl-c-star ()
16536 "Compute table, or change heading status of lines.
16537 Calls `org-table-recalculate' or `org-toggle-heading',
16538 depending on context."
16539 (interactive)
16540 (cond
16541 ((org-at-table-p)
16542 (call-interactively 'org-table-recalculate))
16544 ;; Convert all lines in region to list items
16545 (call-interactively 'org-toggle-heading))))
16547 (defun org-ctrl-c-minus ()
16548 "Insert separator line in table or modify bullet status of line.
16549 Also turns a plain line or a region of lines into list items.
16550 Calls `org-table-insert-hline', `org-toggle-item', or
16551 `org-cycle-list-bullet', depending on context."
16552 (interactive)
16553 (cond
16554 ((org-at-table-p)
16555 (call-interactively 'org-table-insert-hline))
16556 ((org-region-active-p)
16557 (call-interactively 'org-toggle-item))
16558 ((org-in-item-p)
16559 (call-interactively 'org-cycle-list-bullet))
16561 (call-interactively 'org-toggle-item))))
16563 (defun org-toggle-item ()
16564 "Convert headings or normal lines to items, items to normal lines.
16565 If there is no active region, only the current line is considered.
16567 If the first line in the region is a headline, convert all headlines to items.
16569 If the first line in the region is an item, convert all items to normal lines.
16571 If the first line is normal text, add an item bullet to each line."
16572 (interactive)
16573 (let (l2 l beg end)
16574 (if (org-region-active-p)
16575 (setq beg (region-beginning) end (region-end))
16576 (setq beg (point-at-bol)
16577 end (min (1+ (point-at-eol)) (point-max))))
16578 (save-excursion
16579 (goto-char end)
16580 (setq l2 (org-current-line))
16581 (goto-char beg)
16582 (beginning-of-line 1)
16583 (setq l (1- (org-current-line)))
16584 (if (org-at-item-p)
16585 ;; We already have items, de-itemize
16586 (while (< (setq l (1+ l)) l2)
16587 (when (org-at-item-p)
16588 (goto-char (match-beginning 2))
16589 (delete-region (match-beginning 2) (match-end 2))
16590 (and (looking-at "[ \t]+") (replace-match "")))
16591 (beginning-of-line 2))
16592 (if (org-on-heading-p)
16593 ;; Headings, convert to items
16594 (while (< (setq l (1+ l)) l2)
16595 (if (looking-at org-outline-regexp)
16596 (replace-match "- " t t))
16597 (beginning-of-line 2))
16598 ;; normal lines, turn them into items
16599 (while (< (setq l (1+ l)) l2)
16600 (unless (org-at-item-p)
16601 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16602 (replace-match "\\1- \\2")))
16603 (beginning-of-line 2)))))))
16605 (defun org-toggle-heading (&optional nstars)
16606 "Convert headings to normal text, or items or text to headings.
16607 If there is no active region, only the current line is considered.
16609 If the first line is a heading, remove the stars from all headlines
16610 in the region.
16612 If the first line is a plain list item, turn all plain list items
16613 into headings.
16615 If the first line is a normal line, turn each and every line in the
16616 region into a heading.
16618 When converting a line into a heading, the number of stars is chosen
16619 such that the lines become children of the current entry. However,
16620 when a prefix argument is given, its value determines the number of
16621 stars to add."
16622 (interactive "P")
16623 (let (l2 l itemp beg end)
16624 (if (org-region-active-p)
16625 (setq beg (region-beginning) end (region-end))
16626 (setq beg (point-at-bol)
16627 end (min (1+ (point-at-eol)) (point-max))))
16628 (save-excursion
16629 (goto-char end)
16630 (setq l2 (org-current-line))
16631 (goto-char beg)
16632 (beginning-of-line 1)
16633 (setq l (1- (org-current-line)))
16634 (if (org-on-heading-p)
16635 ;; We already have headlines, de-star them
16636 (while (< (setq l (1+ l)) l2)
16637 (when (org-on-heading-p t)
16638 (and (looking-at outline-regexp) (replace-match "")))
16639 (beginning-of-line 2))
16640 (setq itemp (org-at-item-p))
16641 (let* ((stars
16642 (if nstars
16643 (make-string (prefix-numeric-value current-prefix-arg)
16645 (save-excursion
16646 (if (re-search-backward org-complex-heading-regexp nil t)
16647 (match-string 1) ""))))
16648 (add-stars (cond (nstars "")
16649 ((equal stars "") "*")
16650 (org-odd-levels-only "**")
16651 (t "*")))
16652 (rpl (concat stars add-stars " ")))
16653 (while (< (setq l (1+ l)) l2)
16654 (if itemp
16655 (and (org-at-item-p) (replace-match rpl t t))
16656 (unless (org-on-heading-p)
16657 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16658 (replace-match (concat rpl (match-string 2))))))
16659 (beginning-of-line 2)))))))
16661 (defun org-meta-return (&optional arg)
16662 "Insert a new heading or wrap a region in a table.
16663 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16664 See the individual commands for more information."
16665 (interactive "P")
16666 (cond
16667 ((run-hook-with-args-until-success 'org-metareturn-hook))
16668 ((org-at-table-p)
16669 (call-interactively 'org-table-wrap-region))
16670 (t (call-interactively 'org-insert-heading))))
16672 ;;; Menu entries
16674 ;; Define the Org-mode menus
16675 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16676 '("Tbl"
16677 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16678 ["Next Field" org-cycle (org-at-table-p)]
16679 ["Previous Field" org-shifttab (org-at-table-p)]
16680 ["Next Row" org-return (org-at-table-p)]
16681 "--"
16682 ["Blank Field" org-table-blank-field (org-at-table-p)]
16683 ["Edit Field" org-table-edit-field (org-at-table-p)]
16684 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16685 "--"
16686 ("Column"
16687 ["Move Column Left" org-metaleft (org-at-table-p)]
16688 ["Move Column Right" org-metaright (org-at-table-p)]
16689 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16690 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16691 ("Row"
16692 ["Move Row Up" org-metaup (org-at-table-p)]
16693 ["Move Row Down" org-metadown (org-at-table-p)]
16694 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16695 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16696 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16697 "--"
16698 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16699 ("Rectangle"
16700 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16701 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16702 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16703 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16704 "--"
16705 ("Calculate"
16706 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16707 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16708 ["Edit Formulas" org-edit-special (org-at-table-p)]
16709 "--"
16710 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16711 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16712 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16713 "--"
16714 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16715 "--"
16716 ["Sum Column/Rectangle" org-table-sum
16717 (or (org-at-table-p) (org-region-active-p))]
16718 ["Which Column?" org-table-current-column (org-at-table-p)])
16719 ["Debug Formulas"
16720 org-table-toggle-formula-debugger
16721 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16722 ["Show Col/Row Numbers"
16723 org-table-toggle-coordinate-overlays
16724 :style toggle
16725 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16726 "--"
16727 ["Create" org-table-create (and (not (org-at-table-p))
16728 org-enable-table-editor)]
16729 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16730 ["Import from File" org-table-import (not (org-at-table-p))]
16731 ["Export to File" org-table-export (org-at-table-p)]
16732 "--"
16733 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16735 (easy-menu-define org-org-menu org-mode-map "Org menu"
16736 '("Org"
16737 ("Show/Hide"
16738 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16739 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16740 ["Sparse Tree..." org-sparse-tree t]
16741 ["Reveal Context" org-reveal t]
16742 ["Show All" show-all t]
16743 "--"
16744 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16745 "--"
16746 ["New Heading" org-insert-heading t]
16747 ("Navigate Headings"
16748 ["Up" outline-up-heading t]
16749 ["Next" outline-next-visible-heading t]
16750 ["Previous" outline-previous-visible-heading t]
16751 ["Next Same Level" outline-forward-same-level t]
16752 ["Previous Same Level" outline-backward-same-level t]
16753 "--"
16754 ["Jump" org-goto t])
16755 ("Edit Structure"
16756 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16757 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16758 "--"
16759 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16760 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16761 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16762 "--"
16763 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16764 "--"
16765 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16766 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16767 ["Demote Heading" org-metaright (not (org-at-table-p))]
16768 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16769 "--"
16770 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16771 "--"
16772 ["Convert to odd levels" org-convert-to-odd-levels t]
16773 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16774 ("Editing"
16775 ["Emphasis..." org-emphasize t]
16776 ["Edit Source Example" org-edit-special t]
16777 "--"
16778 ["Footnote new/jump" org-footnote-action t]
16779 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16780 ("Archive"
16781 ["Archive (default method)" org-archive-subtree-default t]
16782 "--"
16783 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16784 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16785 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16787 "--"
16788 ("Hyperlinks"
16789 ["Store Link (Global)" org-store-link t]
16790 ["Find existing link to here" org-occur-link-in-agenda-files t]
16791 ["Insert Link" org-insert-link t]
16792 ["Follow Link" org-open-at-point t]
16793 "--"
16794 ["Next link" org-next-link t]
16795 ["Previous link" org-previous-link t]
16796 "--"
16797 ["Descriptive Links"
16798 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16799 :style radio
16800 :selected (member '(org-link) buffer-invisibility-spec)]
16801 ["Literal Links"
16802 (progn
16803 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16804 :style radio
16805 :selected (not (member '(org-link) buffer-invisibility-spec))])
16806 "--"
16807 ("TODO Lists"
16808 ["TODO/DONE/-" org-todo t]
16809 ("Select keyword"
16810 ["Next keyword" org-shiftright (org-on-heading-p)]
16811 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16812 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16813 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16814 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16815 ["Show TODO Tree" org-show-todo-tree t]
16816 ["Global TODO list" org-todo-list t]
16817 "--"
16818 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16819 :selected org-enforce-todo-dependencies :style toggle :active t]
16820 "Settings for tree at point"
16821 ["Do Children sequentially" org-toggle-ordered-property :style radio
16822 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16823 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16824 ["Do Children parallel" org-toggle-ordered-property :style radio
16825 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16826 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16827 "--"
16828 ["Set Priority" org-priority t]
16829 ["Priority Up" org-shiftup t]
16830 ["Priority Down" org-shiftdown t]
16831 "--"
16832 ["Get news from all feeds" org-feed-update-all t]
16833 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16834 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16835 ("TAGS and Properties"
16836 ["Set Tags" org-set-tags-command t]
16837 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16838 "--"
16839 ["Set property" org-set-property t]
16840 ["Column view of properties" org-columns t]
16841 ["Insert Column View DBlock" org-insert-columns-dblock t])
16842 ("Dates and Scheduling"
16843 ["Timestamp" org-time-stamp t]
16844 ["Timestamp (inactive)" org-time-stamp-inactive t]
16845 ("Change Date"
16846 ["1 Day Later" org-shiftright t]
16847 ["1 Day Earlier" org-shiftleft t]
16848 ["1 ... Later" org-shiftup t]
16849 ["1 ... Earlier" org-shiftdown t])
16850 ["Compute Time Range" org-evaluate-time-range t]
16851 ["Schedule Item" org-schedule t]
16852 ["Deadline" org-deadline t]
16853 "--"
16854 ["Custom time format" org-toggle-time-stamp-overlays
16855 :style radio :selected org-display-custom-times]
16856 "--"
16857 ["Goto Calendar" org-goto-calendar t]
16858 ["Date from Calendar" org-date-from-calendar t]
16859 "--"
16860 ["Start/Restart Timer" org-timer-start t]
16861 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16862 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16863 ["Insert Timer String" org-timer t]
16864 ["Insert Timer Item" org-timer-item t])
16865 ("Logging work"
16866 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16867 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16868 ["Clock out" org-clock-out t]
16869 ["Clock cancel" org-clock-cancel t]
16870 "--"
16871 ["Mark as default task" org-clock-mark-default-task t]
16872 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16873 ["Goto running clock" org-clock-goto t]
16874 "--"
16875 ["Display times" org-clock-display t]
16876 ["Create clock table" org-clock-report t]
16877 "--"
16878 ["Record DONE time"
16879 (progn (setq org-log-done (not org-log-done))
16880 (message "Switching to %s will %s record a timestamp"
16881 (car org-done-keywords)
16882 (if org-log-done "automatically" "not")))
16883 :style toggle :selected org-log-done])
16884 "--"
16885 ["Agenda Command..." org-agenda t]
16886 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16887 ("File List for Agenda")
16888 ("Special views current file"
16889 ["TODO Tree" org-show-todo-tree t]
16890 ["Check Deadlines" org-check-deadlines t]
16891 ["Timeline" org-timeline t]
16892 ["Tags/Property tree" org-match-sparse-tree t])
16893 "--"
16894 ["Export/Publish..." org-export t]
16895 ("LaTeX"
16896 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16897 :selected org-cdlatex-mode]
16898 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16899 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16900 ["Modify math symbol" org-cdlatex-math-modify
16901 (org-inside-LaTeX-fragment-p)]
16902 ["Insert citation" org-reftex-citation t]
16903 "--"
16904 ["Export LaTeX fragments as images"
16905 (if (featurep 'org-exp)
16906 (setq org-export-with-LaTeX-fragments
16907 (not org-export-with-LaTeX-fragments))
16908 (require 'org-exp))
16909 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16910 org-export-with-LaTeX-fragments)]
16911 "--"
16912 ["Template for BEAMER" org-beamer-settings-template t])
16913 "--"
16914 ("MobileOrg"
16915 ["Push Files and Views" org-mobile-push t]
16916 ["Get Captured and Flagged" org-mobile-pull t]
16917 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16918 "--"
16919 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16920 "--"
16921 ("Documentation"
16922 ["Show Version" org-version t]
16923 ["Info Documentation" org-info t])
16924 ("Customize"
16925 ["Browse Org Group" org-customize t]
16926 "--"
16927 ["Expand This Menu" org-create-customize-menu
16928 (fboundp 'customize-menu-create)])
16929 ["Send bug report" org-submit-bug-report t]
16930 "--"
16931 ("Refresh/Reload"
16932 ["Refresh setup current buffer" org-mode-restart t]
16933 ["Reload Org (after update)" org-reload t]
16934 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16937 (defun org-info (&optional node)
16938 "Read documentation for Org-mode in the info system.
16939 With optional NODE, go directly to that node."
16940 (interactive)
16941 (info (format "(org)%s" (or node ""))))
16943 ;;;###autoload
16944 (defun org-submit-bug-report ()
16945 "Submit a bug report on Org-mode via mail.
16947 Don't hesitate to report any problems or inaccurate documentation.
16949 If you don't have setup sending mail from (X)Emacs, please copy the
16950 output buffer into your mail program, as it gives us important
16951 information about your Org-mode version and configuration."
16952 (interactive)
16953 (require 'reporter)
16954 (org-load-modules-maybe)
16955 (org-require-autoloaded-modules)
16956 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16957 (reporter-submit-bug-report
16958 "emacs-orgmode@gnu.org"
16959 (org-version)
16960 (let (list)
16961 (save-window-excursion
16962 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16963 (delete-other-windows)
16964 (erase-buffer)
16965 (insert "You are about to submit a bug report to the Org-mode mailing list.
16967 We would like to add your full Org-mode and Outline configuration to the
16968 bug report. This greatly simplifies the work of the maintainer and
16969 other experts on the mailing list.
16971 HOWEVER, some variables you have customized may contain private
16972 information. The names of customers, colleagues, or friends, might
16973 appear in the form of file names, tags, todo states, or search strings.
16974 If you answer yes to the prompt, you might want to check and remove
16975 such private information before sending the email.")
16976 (add-text-properties (point-min) (point-max) '(face org-warning))
16977 (when (yes-or-no-p "Include your Org-mode configuration ")
16978 (mapatoms
16979 (lambda (v)
16980 (and (boundp v)
16981 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16982 (or (and (symbol-value v)
16983 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16984 (and
16985 (get v 'custom-type) (get v 'standard-value)
16986 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16987 (push v list)))))
16988 (kill-buffer (get-buffer "*Warn about privacy*"))
16989 list))
16990 nil nil
16991 "Remember to cover the basics, that is, what you expected to happen and
16992 what in fact did happen. You don't know how to make a good report? See
16994 http://orgmode.org/manual/Feedback.html#Feedback
16996 Your bug report will be posted to the Org-mode mailing list.
16997 ------------------------------------------------------------------------")
16998 (save-excursion
16999 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17000 (replace-match "\\1Bug: \\3 [\\2]")))))
17003 (defun org-install-agenda-files-menu ()
17004 (let ((bl (buffer-list)))
17005 (save-excursion
17006 (while bl
17007 (set-buffer (pop bl))
17008 (if (org-mode-p) (setq bl nil)))
17009 (when (org-mode-p)
17010 (easy-menu-change
17011 '("Org") "File List for Agenda"
17012 (append
17013 (list
17014 ["Edit File List" (org-edit-agenda-file-list) t]
17015 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17016 ["Remove Current File from List" org-remove-file t]
17017 ["Cycle through agenda files" org-cycle-agenda-files t]
17018 ["Occur in all agenda files" org-occur-in-agenda-files t]
17019 "--")
17020 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17022 ;;;; Documentation
17024 ;;;###autoload
17025 (defun org-require-autoloaded-modules ()
17026 (interactive)
17027 (mapc 'require
17028 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17029 org-docbook org-exp org-html org-icalendar
17030 org-id org-latex
17031 org-publish org-remember org-table
17032 org-timer org-xoxo)))
17034 ;;;###autoload
17035 (defun org-reload (&optional uncompiled)
17036 "Reload all org lisp files.
17037 With prefix arg UNCOMPILED, load the uncompiled versions."
17038 (interactive "P")
17039 (require 'find-func)
17040 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17041 (dir-org (file-name-directory (org-find-library-name "org")))
17042 (dir-org-contrib (ignore-errors
17043 (file-name-directory
17044 (org-find-library-name "org-contribdir"))))
17045 (files
17046 (append (directory-files dir-org t file-re)
17047 (and dir-org-contrib
17048 (directory-files dir-org-contrib t file-re))))
17049 (remove-re (concat (if (featurep 'xemacs)
17050 "org-colview" "org-colview-xemacs")
17051 "\\'")))
17052 (setq files (mapcar 'file-name-sans-extension files))
17053 (setq files (mapcar
17054 (lambda (x) (if (string-match remove-re x) nil x))
17055 files))
17056 (setq files (delq nil files))
17057 (mapc
17058 (lambda (f)
17059 (when (featurep (intern (file-name-nondirectory f)))
17060 (if (and (not uncompiled)
17061 (file-exists-p (concat f ".elc")))
17062 (load (concat f ".elc") nil nil t)
17063 (load (concat f ".el") nil nil t))))
17064 files))
17065 (org-version))
17067 ;;;###autoload
17068 (defun org-customize ()
17069 "Call the customize function with org as argument."
17070 (interactive)
17071 (org-load-modules-maybe)
17072 (org-require-autoloaded-modules)
17073 (customize-browse 'org))
17075 (defun org-create-customize-menu ()
17076 "Create a full customization menu for Org-mode, insert it into the menu."
17077 (interactive)
17078 (org-load-modules-maybe)
17079 (org-require-autoloaded-modules)
17080 (if (fboundp 'customize-menu-create)
17081 (progn
17082 (easy-menu-change
17083 '("Org") "Customize"
17084 `(["Browse Org group" org-customize t]
17085 "--"
17086 ,(customize-menu-create 'org)
17087 ["Set" Custom-set t]
17088 ["Save" Custom-save t]
17089 ["Reset to Current" Custom-reset-current t]
17090 ["Reset to Saved" Custom-reset-saved t]
17091 ["Reset to Standard Settings" Custom-reset-standard t]))
17092 (message "\"Org\"-menu now contains full customization menu"))
17093 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17095 ;;;; Miscellaneous stuff
17097 ;;; Generally useful functions
17099 (defun org-get-at-bol (property)
17100 "Get text property PROPERTY at beginning of line."
17101 (get-text-property (point-at-bol) property))
17103 (defun org-find-text-property-in-string (prop s)
17104 "Return the first non-nil value of property PROP in string S."
17105 (or (get-text-property 0 prop s)
17106 (get-text-property (or (next-single-property-change 0 prop s) 0)
17107 prop s)))
17109 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17110 "Display the given MESSAGE as a warning."
17111 (if (fboundp 'display-warning)
17112 (display-warning 'org message
17113 (if (featurep 'xemacs) 'warning :warning))
17114 (let ((buf (get-buffer-create "*Org warnings*")))
17115 (with-current-buffer buf
17116 (goto-char (point-max))
17117 (insert "Warning (Org): " message)
17118 (unless (bolp)
17119 (newline)))
17120 (display-buffer buf)
17121 (sit-for 0))))
17123 (defun org-in-commented-line ()
17124 "Is point in a line starting with `#'?"
17125 (equal (char-after (point-at-bol)) ?#))
17127 (defun org-in-verbatim-emphasis ()
17128 (save-match-data
17129 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17131 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17132 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17133 (if (and marker (marker-buffer marker)
17134 (buffer-live-p (marker-buffer marker)))
17135 (progn
17136 (switch-to-buffer (marker-buffer marker))
17137 (if (or (> marker (point-max)) (< marker (point-min)))
17138 (widen))
17139 (goto-char marker)
17140 (org-show-context 'org-goto))
17141 (if bookmark
17142 (bookmark-jump bookmark)
17143 (error "Cannot find location"))))
17145 (defun org-quote-csv-field (s)
17146 "Quote field for inclusion in CSV material."
17147 (if (string-match "[\",]" s)
17148 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17151 (defun org-plist-delete (plist property)
17152 "Delete PROPERTY from PLIST.
17153 This is in contrast to merely setting it to 0."
17154 (let (p)
17155 (while plist
17156 (if (not (eq property (car plist)))
17157 (setq p (plist-put p (car plist) (nth 1 plist))))
17158 (setq plist (cddr plist)))
17161 (defun org-force-self-insert (N)
17162 "Needed to enforce self-insert under remapping."
17163 (interactive "p")
17164 (self-insert-command N))
17166 (defun org-string-width (s)
17167 "Compute width of string, ignoring invisible characters.
17168 This ignores character with invisibility property `org-link', and also
17169 characters with property `org-cwidth', because these will become invisible
17170 upon the next fontification round."
17171 (let (b l)
17172 (when (or (eq t buffer-invisibility-spec)
17173 (assq 'org-link buffer-invisibility-spec))
17174 (while (setq b (text-property-any 0 (length s)
17175 'invisible 'org-link s))
17176 (setq s (concat (substring s 0 b)
17177 (substring s (or (next-single-property-change
17178 b 'invisible s) (length s)))))))
17179 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17180 (setq s (concat (substring s 0 b)
17181 (substring s (or (next-single-property-change
17182 b 'org-cwidth s) (length s))))))
17183 (setq l (string-width s) b -1)
17184 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17185 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17188 (defun org-get-indentation (&optional line)
17189 "Get the indentation of the current line, interpreting tabs.
17190 When LINE is given, assume it represents a line and compute its indentation."
17191 (if line
17192 (if (string-match "^ *" (org-remove-tabs line))
17193 (match-end 0))
17194 (save-excursion
17195 (beginning-of-line 1)
17196 (skip-chars-forward " \t")
17197 (current-column))))
17199 (defun org-remove-tabs (s &optional width)
17200 "Replace tabulators in S with spaces.
17201 Assumes that s is a single line, starting in column 0."
17202 (setq width (or width tab-width))
17203 (while (string-match "\t" s)
17204 (setq s (replace-match
17205 (make-string
17206 (- (* width (/ (+ (match-beginning 0) width) width))
17207 (match-beginning 0)) ?\ )
17208 t t s)))
17211 (defun org-fix-indentation (line ind)
17212 "Fix indentation in LINE.
17213 IND is a cons cell with target and minimum indentation.
17214 If the current indentation in LINE is smaller than the minimum,
17215 leave it alone. If it is larger than ind, set it to the target."
17216 (let* ((l (org-remove-tabs line))
17217 (i (org-get-indentation l))
17218 (i1 (car ind)) (i2 (cdr ind)))
17219 (if (>= i i2) (setq l (substring line i2)))
17220 (if (> i1 0)
17221 (concat (make-string i1 ?\ ) l)
17222 l)))
17224 (defun org-remove-indentation (code &optional n)
17225 "Remove the maximum common indentation from the lines in CODE.
17226 N may optionally be the number of spaces to remove."
17227 (with-temp-buffer
17228 (insert code)
17229 (org-do-remove-indentation n)
17230 (buffer-string)))
17232 (defun org-do-remove-indentation (&optional n)
17233 "Remove the maximum common indentation from the buffer."
17234 (untabify (point-min) (point-max))
17235 (let ((min 10000) re)
17236 (if n
17237 (setq min n)
17238 (goto-char (point-min))
17239 (while (re-search-forward "^ *[^ \n]" nil t)
17240 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17241 (unless (or (= min 0) (= min 10000))
17242 (setq re (format "^ \\{%d\\}" min))
17243 (goto-char (point-min))
17244 (while (re-search-forward re nil t)
17245 (replace-match "")
17246 (end-of-line 1))
17247 min)))
17249 (defun org-fill-template (template alist)
17250 "Find each %key of ALIST in TEMPLATE and replace it."
17251 (let ((case-fold-search nil)
17252 entry key value)
17253 (setq alist (sort (copy-sequence alist)
17254 (lambda (a b) (< (length (car a)) (length (car b))))))
17255 (while (setq entry (pop alist))
17256 (setq template
17257 (replace-regexp-in-string
17258 (concat "%" (regexp-quote (car entry)))
17259 (cdr entry) template t t)))
17260 template))
17262 (defun org-base-buffer (buffer)
17263 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17264 (if (not buffer)
17265 buffer
17266 (or (buffer-base-buffer buffer)
17267 buffer)))
17269 (defun org-trim (s)
17270 "Remove whitespace at beginning and end of string."
17271 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17272 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17275 (defun org-wrap (string &optional width lines)
17276 "Wrap string to either a number of lines, or a width in characters.
17277 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17278 that costs. If there is a word longer than WIDTH, the text is actually
17279 wrapped to the length of that word.
17280 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17281 many lines, whatever width that takes.
17282 The return value is a list of lines, without newlines at the end."
17283 (let* ((words (org-split-string string "[ \t\n]+"))
17284 (maxword (apply 'max (mapcar 'org-string-width words)))
17285 w ll)
17286 (cond (width
17287 (org-do-wrap words (max maxword width)))
17288 (lines
17289 (setq w maxword)
17290 (setq ll (org-do-wrap words maxword))
17291 (if (<= (length ll) lines)
17293 (setq ll words)
17294 (while (> (length ll) lines)
17295 (setq w (1+ w))
17296 (setq ll (org-do-wrap words w)))
17297 ll))
17298 (t (error "Cannot wrap this")))))
17300 (defun org-do-wrap (words width)
17301 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17302 (let (lines line)
17303 (while words
17304 (setq line (pop words))
17305 (while (and words (< (+ (length line) (length (car words))) width))
17306 (setq line (concat line " " (pop words))))
17307 (setq lines (push line lines)))
17308 (nreverse lines)))
17310 (defun org-split-string (string &optional separators)
17311 "Splits STRING into substrings at SEPARATORS.
17312 No empty strings are returned if there are matches at the beginning
17313 and end of string."
17314 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17315 (start 0)
17316 notfirst
17317 (list nil))
17318 (while (and (string-match rexp string
17319 (if (and notfirst
17320 (= start (match-beginning 0))
17321 (< start (length string)))
17322 (1+ start) start))
17323 (< (match-beginning 0) (length string)))
17324 (setq notfirst t)
17325 (or (eq (match-beginning 0) 0)
17326 (and (eq (match-beginning 0) (match-end 0))
17327 (eq (match-beginning 0) start))
17328 (setq list
17329 (cons (substring string start (match-beginning 0))
17330 list)))
17331 (setq start (match-end 0)))
17332 (or (eq start (length string))
17333 (setq list
17334 (cons (substring string start)
17335 list)))
17336 (nreverse list)))
17338 (defun org-quote-vert (s)
17339 "Replace \"|\" with \"\\vert\"."
17340 (while (string-match "|" s)
17341 (setq s (replace-match "\\vert" t t s)))
17344 (defun org-uuidgen-p (s)
17345 "Is S an ID created by UUIDGEN?"
17346 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17348 (defun org-context ()
17349 "Return a list of contexts of the current cursor position.
17350 If several contexts apply, all are returned.
17351 Each context entry is a list with a symbol naming the context, and
17352 two positions indicating start and end of the context. Possible
17353 contexts are:
17355 :headline anywhere in a headline
17356 :headline-stars on the leading stars in a headline
17357 :todo-keyword on a TODO keyword (including DONE) in a headline
17358 :tags on the TAGS in a headline
17359 :priority on the priority cookie in a headline
17360 :item on the first line of a plain list item
17361 :item-bullet on the bullet/number of a plain list item
17362 :checkbox on the checkbox in a plain list item
17363 :table in an org-mode table
17364 :table-special on a special filed in a table
17365 :table-table in a table.el table
17366 :link on a hyperlink
17367 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17368 :target on a <<target>>
17369 :radio-target on a <<<radio-target>>>
17370 :latex-fragment on a LaTeX fragment
17371 :latex-preview on a LaTeX fragment with overlayed preview image
17373 This function expects the position to be visible because it uses font-lock
17374 faces as a help to recognize the following contexts: :table-special, :link,
17375 and :keyword."
17376 (let* ((f (get-text-property (point) 'face))
17377 (faces (if (listp f) f (list f)))
17378 (p (point)) clist o)
17379 ;; First the large context
17380 (cond
17381 ((org-on-heading-p t)
17382 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17383 (when (progn
17384 (beginning-of-line 1)
17385 (looking-at org-todo-line-tags-regexp))
17386 (push (org-point-in-group p 1 :headline-stars) clist)
17387 (push (org-point-in-group p 2 :todo-keyword) clist)
17388 (push (org-point-in-group p 4 :tags) clist))
17389 (goto-char p)
17390 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17391 (if (looking-at "\\[#[A-Z0-9]\\]")
17392 (push (org-point-in-group p 0 :priority) clist)))
17394 ((org-at-item-p)
17395 (push (org-point-in-group p 2 :item-bullet) clist)
17396 (push (list :item (point-at-bol)
17397 (save-excursion (org-end-of-item) (point)))
17398 clist)
17399 (and (org-at-item-checkbox-p)
17400 (push (org-point-in-group p 0 :checkbox) clist)))
17402 ((org-at-table-p)
17403 (push (list :table (org-table-begin) (org-table-end)) clist)
17404 (if (memq 'org-formula faces)
17405 (push (list :table-special
17406 (previous-single-property-change p 'face)
17407 (next-single-property-change p 'face)) clist)))
17408 ((org-at-table-p 'any)
17409 (push (list :table-table) clist)))
17410 (goto-char p)
17412 ;; Now the small context
17413 (cond
17414 ((org-at-timestamp-p)
17415 (push (org-point-in-group p 0 :timestamp) clist))
17416 ((memq 'org-link faces)
17417 (push (list :link
17418 (previous-single-property-change p 'face)
17419 (next-single-property-change p 'face)) clist))
17420 ((memq 'org-special-keyword faces)
17421 (push (list :keyword
17422 (previous-single-property-change p 'face)
17423 (next-single-property-change p 'face)) clist))
17424 ((org-on-target-p)
17425 (push (org-point-in-group p 0 :target) clist)
17426 (goto-char (1- (match-beginning 0)))
17427 (if (looking-at org-radio-target-regexp)
17428 (push (org-point-in-group p 0 :radio-target) clist))
17429 (goto-char p))
17430 ((setq o (car (delq nil
17431 (mapcar
17432 (lambda (x)
17433 (if (memq x org-latex-fragment-image-overlays) x))
17434 (overlays-at (point))))))
17435 (push (list :latex-fragment
17436 (overlay-start o) (overlay-end o)) clist)
17437 (push (list :latex-preview
17438 (overlay-start o) (overlay-end o)) clist))
17439 ((org-inside-LaTeX-fragment-p)
17440 ;; FIXME: positions wrong.
17441 (push (list :latex-fragment (point) (point)) clist)))
17443 (setq clist (nreverse (delq nil clist)))
17444 clist))
17446 ;; FIXME: Compare with at-regexp-p Do we need both?
17447 (defun org-in-regexp (re &optional nlines visually)
17448 "Check if point is inside a match of regexp.
17449 Normally only the current line is checked, but you can include NLINES extra
17450 lines both before and after point into the search.
17451 If VISUALLY is set, require that the cursor is not after the match but
17452 really on, so that the block visually is on the match."
17453 (catch 'exit
17454 (let ((pos (point))
17455 (eol (point-at-eol (+ 1 (or nlines 0))))
17456 (inc (if visually 1 0)))
17457 (save-excursion
17458 (beginning-of-line (- 1 (or nlines 0)))
17459 (while (re-search-forward re eol t)
17460 (if (and (<= (match-beginning 0) pos)
17461 (>= (+ inc (match-end 0)) pos))
17462 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17464 (defun org-at-regexp-p (regexp)
17465 "Is point inside a match of REGEXP in the current line?"
17466 (catch 'exit
17467 (save-excursion
17468 (let ((pos (point)) (end (point-at-eol)))
17469 (beginning-of-line 1)
17470 (while (re-search-forward regexp end t)
17471 (if (and (<= (match-beginning 0) pos)
17472 (>= (match-end 0) pos))
17473 (throw 'exit t)))
17474 nil))))
17476 (defun org-in-regexps-block-p (start-re end-re)
17477 "Returns t if the current point is between matches of START-RE and END-RE.
17478 This will also return to if point is on one of the two matches."
17479 (interactive)
17480 (let ((p (point)))
17481 (save-excursion
17482 (and (or (org-at-regexp-p start-re)
17483 (re-search-backward start-re nil t))
17484 (re-search-forward end-re nil t)
17485 (>= (point) p)))))
17487 (defun org-occur-in-agenda-files (regexp &optional nlines)
17488 "Call `multi-occur' with buffers for all agenda files."
17489 (interactive "sOrg-files matching: \np")
17490 (let* ((files (org-agenda-files))
17491 (tnames (mapcar 'file-truename files))
17492 (extra org-agenda-text-search-extra-files)
17494 (when (eq (car extra) 'agenda-archives)
17495 (setq extra (cdr extra))
17496 (setq files (org-add-archive-files files)))
17497 (while (setq f (pop extra))
17498 (unless (member (file-truename f) tnames)
17499 (add-to-list 'files f 'append)
17500 (add-to-list 'tnames (file-truename f) 'append)))
17501 (multi-occur
17502 (mapcar (lambda (x)
17503 (with-current-buffer
17504 (or (get-file-buffer x) (find-file-noselect x))
17505 (widen)
17506 (current-buffer)))
17507 files)
17508 regexp)))
17510 (if (boundp 'occur-mode-find-occurrence-hook)
17511 ;; Emacs 23
17512 (add-hook 'occur-mode-find-occurrence-hook
17513 (lambda ()
17514 (when (org-mode-p)
17515 (org-reveal))))
17516 ;; Emacs 22
17517 (defadvice occur-mode-goto-occurrence
17518 (after org-occur-reveal activate)
17519 (and (org-mode-p) (org-reveal)))
17520 (defadvice occur-mode-goto-occurrence-other-window
17521 (after org-occur-reveal activate)
17522 (and (org-mode-p) (org-reveal)))
17523 (defadvice occur-mode-display-occurrence
17524 (after org-occur-reveal activate)
17525 (when (org-mode-p)
17526 (let ((pos (occur-mode-find-occurrence)))
17527 (with-current-buffer (marker-buffer pos)
17528 (save-excursion
17529 (goto-char pos)
17530 (org-reveal)))))))
17532 (defun org-occur-link-in-agenda-files ()
17533 "Create a link and search for it in the agendas.
17534 The link is not stored in `org-stored-links', it is just created
17535 for the search purpose."
17536 (interactive)
17537 (let ((link (condition-case nil
17538 (org-store-link nil)
17539 (error "Unable to create a link to here"))))
17540 (org-occur-in-agenda-files (regexp-quote link))))
17542 (defun org-uniquify (list)
17543 "Remove duplicate elements from LIST."
17544 (let (res)
17545 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17546 res))
17548 (defun org-delete-all (elts list)
17549 "Remove all elements in ELTS from LIST."
17550 (while elts
17551 (setq list (delete (pop elts) list)))
17552 list)
17554 (defun org-remove-if (predicate seq)
17555 "Remove everything from SEQ that fulfills PREDICATE."
17556 (let (res e)
17557 (while seq
17558 (setq e (pop seq))
17559 (if (not (funcall predicate e)) (push e res)))
17560 (nreverse res)))
17562 (defun org-remove-if-not (predicate seq)
17563 "Remove everything from SEQ that does not fulfill PREDICATE."
17564 (let (res e)
17565 (while seq
17566 (setq e (pop seq))
17567 (if (funcall predicate e) (push e res)))
17568 (nreverse res)))
17570 (defun org-back-over-empty-lines ()
17571 "Move backwards over whitespace, to the beginning of the first empty line.
17572 Returns the number of empty lines passed."
17573 (let ((pos (point)))
17574 (skip-chars-backward " \t\n\r")
17575 (beginning-of-line 2)
17576 (goto-char (min (point) pos))
17577 (count-lines (point) pos)))
17579 (defun org-skip-whitespace ()
17580 (skip-chars-forward " \t\n\r"))
17582 (defun org-point-in-group (point group &optional context)
17583 "Check if POINT is in match-group GROUP.
17584 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17585 match. If the match group does ot exist or point is not inside it,
17586 return nil."
17587 (and (match-beginning group)
17588 (>= point (match-beginning group))
17589 (<= point (match-end group))
17590 (if context
17591 (list context (match-beginning group) (match-end group))
17592 t)))
17594 (defun org-switch-to-buffer-other-window (&rest args)
17595 "Switch to buffer in a second window on the current frame.
17596 In particular, do not allow pop-up frames."
17597 (let (pop-up-frames special-display-buffer-names special-display-regexps
17598 special-display-function)
17599 (apply 'switch-to-buffer-other-window args)))
17601 (defun org-combine-plists (&rest plists)
17602 "Create a single property list from all plists in PLISTS.
17603 The process starts by copying the first list, and then setting properties
17604 from the other lists. Settings in the last list are the most significant
17605 ones and overrule settings in the other lists."
17606 (let ((rtn (copy-sequence (pop plists)))
17607 p v ls)
17608 (while plists
17609 (setq ls (pop plists))
17610 (while ls
17611 (setq p (pop ls) v (pop ls))
17612 (setq rtn (plist-put rtn p v))))
17613 rtn))
17615 (defun org-move-line-down (arg)
17616 "Move the current line down. With prefix argument, move it past ARG lines."
17617 (interactive "p")
17618 (let ((col (current-column))
17619 beg end pos)
17620 (beginning-of-line 1) (setq beg (point))
17621 (beginning-of-line 2) (setq end (point))
17622 (beginning-of-line (+ 1 arg))
17623 (setq pos (move-marker (make-marker) (point)))
17624 (insert (delete-and-extract-region beg end))
17625 (goto-char pos)
17626 (org-move-to-column col)))
17628 (defun org-move-line-up (arg)
17629 "Move the current line up. With prefix argument, move it past ARG lines."
17630 (interactive "p")
17631 (let ((col (current-column))
17632 beg end pos)
17633 (beginning-of-line 1) (setq beg (point))
17634 (beginning-of-line 2) (setq end (point))
17635 (beginning-of-line (- arg))
17636 (setq pos (move-marker (make-marker) (point)))
17637 (insert (delete-and-extract-region beg end))
17638 (goto-char pos)
17639 (org-move-to-column col)))
17641 (defun org-replace-escapes (string table)
17642 "Replace %-escapes in STRING with values in TABLE.
17643 TABLE is an association list with keys like \"%a\" and string values.
17644 The sequences in STRING may contain normal field width and padding information,
17645 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17646 so values can contain further %-escapes if they are define later in TABLE."
17647 (let ((case-fold-search nil)
17648 e re rpl)
17649 (while (setq e (pop table))
17650 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17651 (while (string-match re string)
17652 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17653 (cdr e)))
17654 (setq string (replace-match rpl t t string))))
17655 string))
17658 (defun org-sublist (list start end)
17659 "Return a section of LIST, from START to END.
17660 Counting starts at 1."
17661 (let (rtn (c start))
17662 (setq list (nthcdr (1- start) list))
17663 (while (and list (<= c end))
17664 (push (pop list) rtn)
17665 (setq c (1+ c)))
17666 (nreverse rtn)))
17668 (defun org-find-base-buffer-visiting (file)
17669 "Like `find-buffer-visiting' but always return the base buffer and
17670 not an indirect buffer."
17671 (let ((buf (or (get-file-buffer file)
17672 (find-buffer-visiting file))))
17673 (if buf
17674 (or (buffer-base-buffer buf) buf)
17675 nil)))
17677 (defun org-image-file-name-regexp (&optional extensions)
17678 "Return regexp matching the file names of images.
17679 If EXTENSIONS is given, only match these."
17680 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17681 (image-file-name-regexp)
17682 (let ((image-file-name-extensions
17683 (or extensions
17684 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17685 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17686 (concat "\\."
17687 (regexp-opt (nconc (mapcar 'upcase
17688 image-file-name-extensions)
17689 image-file-name-extensions)
17691 "\\'"))))
17693 (defun org-file-image-p (file &optional extensions)
17694 "Return non-nil if FILE is an image."
17695 (save-match-data
17696 (string-match (org-image-file-name-regexp extensions) file)))
17698 (defun org-get-cursor-date ()
17699 "Return the date at cursor in as a time.
17700 This works in the calendar and in the agenda, anywhere else it just
17701 returns the current time."
17702 (let (date day defd)
17703 (cond
17704 ((eq major-mode 'calendar-mode)
17705 (setq date (calendar-cursor-to-date)
17706 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17707 ((eq major-mode 'org-agenda-mode)
17708 (setq day (get-text-property (point) 'day))
17709 (if day
17710 (setq date (calendar-gregorian-from-absolute day)
17711 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17712 (nth 2 date))))))
17713 (or defd (current-time))))
17715 (defvar org-agenda-action-marker (make-marker)
17716 "Marker pointing to the entry for the next agenda action.")
17718 (defun org-mark-entry-for-agenda-action ()
17719 "Mark the current entry as target of an agenda action.
17720 Agenda actions are actions executed from the agenda with the key `k',
17721 which make use of the date at the cursor."
17722 (interactive)
17723 (move-marker org-agenda-action-marker
17724 (save-excursion (org-back-to-heading t) (point))
17725 (current-buffer))
17726 (message
17727 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17729 ;;; Paragraph filling stuff.
17730 ;; We want this to be just right, so use the full arsenal.
17732 (defun org-indent-line-function ()
17733 "Indent line like previous, but further if previous was headline or item."
17734 (interactive)
17735 (let* ((pos (point))
17736 (itemp (org-at-item-p))
17737 (case-fold-search t)
17738 (org-drawer-regexp (or org-drawer-regexp "\000"))
17739 column bpos bcol tpos tcol bullet btype bullet-type)
17740 ;; Find the previous relevant line
17741 (beginning-of-line 1)
17742 (cond
17743 ((looking-at "#") (setq column 0))
17744 ((looking-at "\\*+ ") (setq column 0))
17745 ((and (looking-at "[ \t]*:END:")
17746 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17747 (save-excursion
17748 (goto-char (1- (match-beginning 1)))
17749 (setq column (current-column))))
17750 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17751 (save-excursion
17752 (re-search-backward
17753 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17754 (setq column (org-get-indentation (match-string 0))))
17756 (beginning-of-line 0)
17757 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17758 (not (looking-at "[ \t]*:END:"))
17759 (not (looking-at org-drawer-regexp)))
17760 (beginning-of-line 0))
17761 (cond
17762 ((looking-at "\\*+[ \t]+")
17763 (if (not org-adapt-indentation)
17764 (setq column 0)
17765 (goto-char (match-end 0))
17766 (setq column (current-column))))
17767 ((looking-at org-drawer-regexp)
17768 (goto-char (1- (match-beginning 1)))
17769 (setq column (current-column)))
17770 ((looking-at "\\([ \t]*\\):END:")
17771 (goto-char (match-end 1))
17772 (setq column (current-column)))
17773 ((org-in-item-p)
17774 (org-beginning-of-item)
17775 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17776 (setq bpos (match-beginning 1) tpos (match-end 0)
17777 bcol (progn (goto-char bpos) (current-column))
17778 tcol (progn (goto-char tpos) (current-column))
17779 bullet (match-string 1)
17780 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17781 (if (> tcol (+ bcol org-description-max-indent))
17782 (setq tcol (+ bcol 5)))
17783 (if (not itemp)
17784 (setq column tcol)
17785 (goto-char pos)
17786 (beginning-of-line 1)
17787 (if (looking-at "\\S-")
17788 (progn
17789 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17790 (setq bullet (match-string 1)
17791 btype (if (string-match "[0-9]" bullet) "n" bullet))
17792 (setq column (if (equal btype bullet-type) bcol tcol)))
17793 (setq column (org-get-indentation)))))
17794 (t (setq column (org-get-indentation))))))
17795 (goto-char pos)
17796 (if (<= (current-column) (current-indentation))
17797 (org-indent-line-to column)
17798 (save-excursion (org-indent-line-to column)))
17799 (setq column (current-column))
17800 (beginning-of-line 1)
17801 (if (looking-at
17802 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17803 (replace-match (concat (match-string 1)
17804 (format org-property-format
17805 (match-string 2) (match-string 3)))
17806 t t))
17807 (org-move-to-column column)))
17809 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17810 "Variable to store copy of `adaptive-fill-regexp'.
17811 Since `adaptive-fill-regexp' is set to never match, we need to
17812 store a backup of its value before entering `org-mode' so that
17813 the functionality can be provided as a fall-back.")
17815 (defun org-set-autofill-regexps ()
17816 (interactive)
17817 ;; In the paragraph separator we include headlines, because filling
17818 ;; text in a line directly attached to a headline would otherwise
17819 ;; fill the headline as well.
17820 (org-set-local 'comment-start-skip "^#+[ \t]*")
17821 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17822 ;; The paragraph starter includes hand-formatted lists.
17823 (org-set-local
17824 'paragraph-start
17825 (concat
17826 "\f" "\\|"
17827 "[ ]*$" "\\|"
17828 "\\*+ " "\\|"
17829 "[ \t]*#" "\\|"
17830 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17831 "[ \t]*[:|]" "\\|"
17832 "\\$\\$" "\\|"
17833 "\\\\\\(begin\\|end\\|[][]\\)"))
17834 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17835 ;; But only if the user has not turned off tables or fixed-width regions
17836 (org-set-local
17837 'auto-fill-inhibit-regexp
17838 (concat "\\*+ \\|#\\+"
17839 "\\|[ \t]*" org-keyword-time-regexp
17840 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17841 (concat
17842 "\\|[ \t]*["
17843 (if org-enable-table-editor "|" "")
17844 (if org-enable-fixed-width-editor ":" "")
17845 "]"))))
17846 ;; We use our own fill-paragraph function, to make sure that tables
17847 ;; and fixed-width regions are not wrapped. That function will pass
17848 ;; through to `fill-paragraph' when appropriate.
17849 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17850 ;; Adaptive filling: To get full control, first make sure that
17851 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17852 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
17853 (org-set-local 'org-adaptive-fill-regexp-backup
17854 adaptive-fill-regexp))
17855 (org-set-local 'adaptive-fill-regexp "\000")
17856 (org-set-local 'adaptive-fill-function
17857 'org-adaptive-fill-function)
17858 (org-set-local
17859 'align-mode-rules-list
17860 '((org-in-buffer-settings
17861 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17862 (modes . '(org-mode))))))
17864 (defun org-fill-paragraph (&optional justify)
17865 "Re-align a table, pass through to fill-paragraph if no table."
17866 (let ((table-p (org-at-table-p))
17867 (table.el-p (org-at-table.el-p)))
17868 (cond ((and (equal (char-after (point-at-bol)) ?*)
17869 (save-excursion (goto-char (point-at-bol))
17870 (looking-at outline-regexp)))
17871 t) ; skip headlines
17872 (table.el-p t) ; skip table.el tables
17873 (table-p (org-table-align) t) ; align org-mode tables
17874 (t nil)))) ; call paragraph-fill
17876 ;; For reference, this is the default value of adaptive-fill-regexp
17877 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17879 (defun org-adaptive-fill-function ()
17880 "Return a fill prefix for org-mode files.
17881 In particular, this makes sure hanging paragraphs for hand-formatted lists
17882 work correctly."
17883 (cond
17884 ;; Comment line
17885 ((looking-at "#[ \t]+")
17886 (match-string-no-properties 0))
17887 ;; Description list
17888 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17889 (save-excursion
17890 (if (> (match-end 1) (+ (match-beginning 1)
17891 org-description-max-indent))
17892 (goto-char (+ (match-beginning 1) 5))
17893 (goto-char (match-end 0)))
17894 (make-string (current-column) ?\ )))
17895 ;; Ordered or unordered list
17896 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17897 (save-excursion
17898 (goto-char (match-end 0))
17899 (make-string (current-column) ?\ )))
17900 ;; Other text
17901 ((looking-at org-adaptive-fill-regexp-backup)
17902 (match-string-no-properties 0))))
17904 ;;; Other stuff.
17906 (defun org-toggle-fixed-width-section (arg)
17907 "Toggle the fixed-width export.
17908 If there is no active region, the QUOTE keyword at the current headline is
17909 inserted or removed. When present, it causes the text between this headline
17910 and the next to be exported as fixed-width text, and unmodified.
17911 If there is an active region, this command adds or removes a colon as the
17912 first character of this line. If the first character of a line is a colon,
17913 this line is also exported in fixed-width font."
17914 (interactive "P")
17915 (let* ((cc 0)
17916 (regionp (org-region-active-p))
17917 (beg (if regionp (region-beginning) (point)))
17918 (end (if regionp (region-end)))
17919 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17920 (case-fold-search nil)
17921 (re "[ \t]*\\(: \\)")
17922 off)
17923 (if regionp
17924 (save-excursion
17925 (goto-char beg)
17926 (setq cc (current-column))
17927 (beginning-of-line 1)
17928 (setq off (looking-at re))
17929 (while (> nlines 0)
17930 (setq nlines (1- nlines))
17931 (beginning-of-line 1)
17932 (cond
17933 (arg
17934 (org-move-to-column cc t)
17935 (insert ": \n")
17936 (forward-line -1))
17937 ((and off (looking-at re))
17938 (replace-match "" t t nil 1))
17939 ((not off) (org-move-to-column cc t) (insert ": ")))
17940 (forward-line 1)))
17941 (save-excursion
17942 (org-back-to-heading)
17943 (if (looking-at (concat outline-regexp
17944 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17945 (replace-match "" t t nil 1)
17946 (if (looking-at outline-regexp)
17947 (progn
17948 (goto-char (match-end 0))
17949 (insert org-quote-string " "))))))))
17951 (defun org-reftex-citation ()
17952 "Use reftex-citation to insert a citation into the buffer.
17953 This looks for a line like
17955 #+BIBLIOGRAPHY: foo plain option:-d
17957 and derives from it that foo.bib is the bibliography file relevant
17958 for this document. It then installs the necessary environment for RefTeX
17959 to work in this buffer and calls `reftex-citation' to insert a citation
17960 into the buffer.
17962 Export of such citations to both LaTeX and HTML is handled by the contributed
17963 package org-exp-bibtex by Taru Karttunen."
17964 (interactive)
17965 (let ((reftex-docstruct-symbol 'rds)
17966 (reftex-cite-format "\\cite{%l}")
17967 rds bib)
17968 (save-excursion
17969 (save-restriction
17970 (widen)
17971 (let ((case-fold-search t)
17972 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17973 (if (not (save-excursion
17974 (or (re-search-forward re nil t)
17975 (re-search-backward re nil t))))
17976 (error "No bibliography defined in file")
17977 (setq bib (concat (match-string 1) ".bib")
17978 rds (list (list 'bib bib)))))))
17979 (call-interactively 'reftex-citation)))
17981 ;;;; Functions extending outline functionality
17983 (defun org-beginning-of-line (&optional arg)
17984 "Go to the beginning of the current line. If that is invisible, continue
17985 to a visible line beginning. This makes the function of C-a more intuitive.
17986 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17987 first attempt, and only move to after the tags when the cursor is already
17988 beyond the end of the headline."
17989 (interactive "P")
17990 (let ((pos (point))
17991 (special (if (consp org-special-ctrl-a/e)
17992 (car org-special-ctrl-a/e)
17993 org-special-ctrl-a/e))
17994 refpos)
17995 (if (org-bound-and-true-p line-move-visual)
17996 (beginning-of-visual-line 1)
17997 (beginning-of-line 1))
17998 (if (and arg (fboundp 'move-beginning-of-line))
17999 (call-interactively 'move-beginning-of-line)
18000 (if (bobp)
18002 (backward-char 1)
18003 (if (org-invisible-p)
18004 (while (and (not (bobp)) (org-invisible-p))
18005 (backward-char 1)
18006 (beginning-of-line 1))
18007 (forward-char 1))))
18008 (when special
18009 (cond
18010 ((and (looking-at org-complex-heading-regexp)
18011 (= (char-after (match-end 1)) ?\ ))
18012 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18013 (point-at-eol)))
18014 (goto-char
18015 (if (eq special t)
18016 (cond ((> pos refpos) refpos)
18017 ((= pos (point)) refpos)
18018 (t (point)))
18019 (cond ((> pos (point)) (point))
18020 ((not (eq last-command this-command)) (point))
18021 (t refpos)))))
18022 ((org-at-item-p)
18023 (goto-char
18024 (if (eq special t)
18025 (cond ((> pos (match-end 4)) (match-end 4))
18026 ((= pos (point)) (match-end 4))
18027 (t (point)))
18028 (cond ((> pos (point)) (point))
18029 ((not (eq last-command this-command)) (point))
18030 (t (match-end 4))))))))
18031 (org-no-warnings
18032 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18034 (defun org-end-of-line (&optional arg)
18035 "Go to the end of the line.
18036 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18037 first attempt, and only move to after the tags when the cursor is already
18038 beyond the end of the headline."
18039 (interactive "P")
18040 (let ((special (if (consp org-special-ctrl-a/e)
18041 (cdr org-special-ctrl-a/e)
18042 org-special-ctrl-a/e)))
18043 (if (or (not special)
18044 (not (org-on-heading-p))
18045 arg)
18046 (call-interactively
18047 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18048 ((fboundp 'move-end-of-line) 'move-end-of-line)
18049 (t 'end-of-line)))
18050 (let ((pos (point)))
18051 (beginning-of-line 1)
18052 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18053 (if (eq special t)
18054 (if (or (< pos (match-beginning 1))
18055 (= pos (match-end 0)))
18056 (goto-char (match-beginning 1))
18057 (goto-char (match-end 0)))
18058 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18059 (goto-char (match-end 0))
18060 (goto-char (match-beginning 1))))
18061 (call-interactively (if (fboundp 'move-end-of-line)
18062 'move-end-of-line
18063 'end-of-line)))))
18064 (org-no-warnings
18065 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18067 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18068 (define-key org-mode-map "\C-e" 'org-end-of-line)
18069 (define-key org-mode-map [home] 'org-beginning-of-line)
18070 (define-key org-mode-map [end] 'org-end-of-line)
18072 (defun org-backward-sentence (&optional arg)
18073 "Go to beginning of sentence, or beginning of table field.
18074 This will call `backward-sentence' or `org-table-beginning-of-field',
18075 depending on context."
18076 (interactive "P")
18077 (cond
18078 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18079 (t (call-interactively 'backward-sentence))))
18081 (defun org-forward-sentence (&optional arg)
18082 "Go to end of sentence, or end of table field.
18083 This will call `forward-sentence' or `org-table-end-of-field',
18084 depending on context."
18085 (interactive "P")
18086 (cond
18087 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18088 (t (call-interactively 'forward-sentence))))
18090 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18091 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18093 (defun org-kill-line (&optional arg)
18094 "Kill line, to tags or end of line."
18095 (interactive "P")
18096 (cond
18097 ((or (not org-special-ctrl-k)
18098 (bolp)
18099 (not (org-on-heading-p)))
18100 (call-interactively 'kill-line))
18101 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18102 (kill-region (point) (match-beginning 1))
18103 (org-set-tags nil t))
18104 (t (kill-region (point) (point-at-eol)))))
18106 (define-key org-mode-map "\C-k" 'org-kill-line)
18108 (defun org-yank (&optional arg)
18109 "Yank. If the kill is a subtree, treat it specially.
18110 This command will look at the current kill and check if is a single
18111 subtree, or a series of subtrees[1]. If it passes the test, and if the
18112 cursor is at the beginning of a line or after the stars of a currently
18113 empty headline, then the yank is handled specially. How exactly depends
18114 on the value of the following variables, both set by default.
18116 org-yank-folded-subtrees
18117 When set, the subtree(s) will be folded after insertion, but only
18118 if doing so would now swallow text after the yanked text.
18120 org-yank-adjusted-subtrees
18121 When set, the subtree will be promoted or demoted in order to
18122 fit into the local outline tree structure, which means that the level
18123 will be adjusted so that it becomes the smaller one of the two
18124 *visible* surrounding headings.
18126 Any prefix to this command will cause `yank' to be called directly with
18127 no special treatment. In particular, a simple `C-u' prefix will just
18128 plainly yank the text as it is.
18130 \[1] The test checks if the first non-white line is a heading
18131 and if there are no other headings with fewer stars."
18132 (interactive "P")
18133 (org-yank-generic 'yank arg))
18135 (defun org-yank-generic (command arg)
18136 "Perform some yank-like command.
18138 This function implements the behavior described in the `org-yank'
18139 documentation. However, it has been generalized to work for any
18140 interactive command with similar behavior."
18142 ;; pretend to be command COMMAND
18143 (setq this-command command)
18145 (if arg
18146 (call-interactively command)
18148 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18149 (and (org-kill-is-subtree-p)
18150 (or (bolp)
18151 (and (looking-at "[ \t]*$")
18152 (string-match
18153 "\\`\\*+\\'"
18154 (buffer-substring (point-at-bol) (point)))))))
18155 swallowp)
18156 (cond
18157 ((and subtreep org-yank-folded-subtrees)
18158 (let ((beg (point))
18159 end)
18160 (if (and subtreep org-yank-adjusted-subtrees)
18161 (org-paste-subtree nil nil 'for-yank)
18162 (call-interactively command))
18164 (setq end (point))
18165 (goto-char beg)
18166 (when (and (bolp) subtreep
18167 (not (setq swallowp
18168 (org-yank-folding-would-swallow-text beg end))))
18169 (or (looking-at outline-regexp)
18170 (re-search-forward (concat "^" outline-regexp) end t))
18171 (while (and (< (point) end) (looking-at outline-regexp))
18172 (hide-subtree)
18173 (org-cycle-show-empty-lines 'folded)
18174 (condition-case nil
18175 (outline-forward-same-level 1)
18176 (error (goto-char end)))))
18177 (when swallowp
18178 (message
18179 "Inserted text not folded because that would swallow text"))
18181 (goto-char end)
18182 (skip-chars-forward " \t\n\r")
18183 (beginning-of-line 1)
18184 (push-mark beg 'nomsg)))
18185 ((and subtreep org-yank-adjusted-subtrees)
18186 (let ((beg (point-at-bol)))
18187 (org-paste-subtree nil nil 'for-yank)
18188 (push-mark beg 'nomsg)))
18190 (call-interactively command))))))
18192 (defun org-yank-folding-would-swallow-text (beg end)
18193 "Would hide-subtree at BEG swallow any text after END?"
18194 (let (level)
18195 (save-excursion
18196 (goto-char beg)
18197 (when (or (looking-at outline-regexp)
18198 (re-search-forward (concat "^" outline-regexp) end t))
18199 (setq level (org-outline-level)))
18200 (goto-char end)
18201 (skip-chars-forward " \t\r\n\v\f")
18202 (if (or (eobp)
18203 (and (bolp) (looking-at org-outline-regexp)
18204 (<= (org-outline-level) level)))
18205 nil ; Nothing would be swallowed
18206 t)))) ; something would swallow
18208 (define-key org-mode-map "\C-y" 'org-yank)
18210 (defun org-invisible-p ()
18211 "Check if point is at a character currently not visible."
18212 ;; Early versions of noutline don't have `outline-invisible-p'.
18213 (if (fboundp 'outline-invisible-p)
18214 (outline-invisible-p)
18215 (get-char-property (point) 'invisible)))
18217 (defun org-invisible-p2 ()
18218 "Check if point is at a character currently not visible."
18219 (save-excursion
18220 (if (and (eolp) (not (bobp))) (backward-char 1))
18221 ;; Early versions of noutline don't have `outline-invisible-p'.
18222 (if (fboundp 'outline-invisible-p)
18223 (outline-invisible-p)
18224 (get-char-property (point) 'invisible))))
18226 (defun org-back-to-heading (&optional invisible-ok)
18227 "Call `outline-back-to-heading', but provide a better error message."
18228 (condition-case nil
18229 (outline-back-to-heading invisible-ok)
18230 (error (error "Before first headline at position %d in buffer %s"
18231 (point) (current-buffer)))))
18233 (defun org-before-first-heading-p ()
18234 "Before first heading?"
18235 (save-excursion
18236 (null (re-search-backward "^\\*+ " nil t))))
18238 (defun org-on-heading-p (&optional ignored)
18239 (outline-on-heading-p t))
18240 (defun org-at-heading-p (&optional ignored)
18241 (outline-on-heading-p t))
18243 (defun org-point-at-end-of-empty-headline ()
18244 "If point is at the end of an empty headline, return t, else nil.
18245 If the heading only contains a TODO keyword, it is still still considered
18246 empty."
18247 (and (looking-at "[ \t]*$")
18248 (save-excursion
18249 (beginning-of-line 1)
18250 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18251 "\\)?[ \t]*$")))))
18252 (defun org-at-heading-or-item-p ()
18253 (or (org-on-heading-p) (org-at-item-p)))
18255 (defun org-on-target-p ()
18256 (or (org-in-regexp org-radio-target-regexp)
18257 (org-in-regexp org-target-regexp)))
18259 (defun org-up-heading-all (arg)
18260 "Move to the heading line of which the present line is a subheading.
18261 This function considers both visible and invisible heading lines.
18262 With argument, move up ARG levels."
18263 (if (fboundp 'outline-up-heading-all)
18264 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18265 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18267 (defun org-up-heading-safe ()
18268 "Move to the heading line of which the present line is a subheading.
18269 This version will not throw an error. It will return the level of the
18270 headline found, or nil if no higher level is found.
18272 Also, this function will be a lot faster than `outline-up-heading',
18273 because it relies on stars being the outline starters. This can really
18274 make a significant difference in outlines with very many siblings."
18275 (let (start-level re)
18276 (org-back-to-heading t)
18277 (setq start-level (funcall outline-level))
18278 (if (equal start-level 1)
18280 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18281 (if (re-search-backward re nil t)
18282 (funcall outline-level)))))
18284 (defun org-first-sibling-p ()
18285 "Is this heading the first child of its parents?"
18286 (interactive)
18287 (let ((re (concat "^" outline-regexp))
18288 level l)
18289 (unless (org-at-heading-p t)
18290 (error "Not at a heading"))
18291 (setq level (funcall outline-level))
18292 (save-excursion
18293 (if (not (re-search-backward re nil t))
18295 (setq l (funcall outline-level))
18296 (< l level)))))
18298 (defun org-goto-sibling (&optional previous)
18299 "Goto the next sibling, even if it is invisible.
18300 When PREVIOUS is set, go to the previous sibling instead. Returns t
18301 when a sibling was found. When none is found, return nil and don't
18302 move point."
18303 (let ((fun (if previous 're-search-backward 're-search-forward))
18304 (pos (point))
18305 (re (concat "^" outline-regexp))
18306 level l)
18307 (when (condition-case nil (org-back-to-heading t) (error nil))
18308 (setq level (funcall outline-level))
18309 (catch 'exit
18310 (or previous (forward-char 1))
18311 (while (funcall fun re nil t)
18312 (setq l (funcall outline-level))
18313 (when (< l level) (goto-char pos) (throw 'exit nil))
18314 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18315 (goto-char pos)
18316 nil))))
18318 (defun org-show-siblings ()
18319 "Show all siblings of the current headline."
18320 (save-excursion
18321 (while (org-goto-sibling) (org-flag-heading nil)))
18322 (save-excursion
18323 (while (org-goto-sibling 'previous)
18324 (org-flag-heading nil))))
18326 (defun org-show-hidden-entry ()
18327 "Show an entry where even the heading is hidden."
18328 (save-excursion
18329 (org-show-entry)))
18331 (defun org-flag-heading (flag &optional entry)
18332 "Flag the current heading. FLAG non-nil means make invisible.
18333 When ENTRY is non-nil, show the entire entry."
18334 (save-excursion
18335 (org-back-to-heading t)
18336 ;; Check if we should show the entire entry
18337 (if entry
18338 (progn
18339 (org-show-entry)
18340 (save-excursion
18341 (and (outline-next-heading)
18342 (org-flag-heading nil))))
18343 (outline-flag-region (max (point-min) (1- (point)))
18344 (save-excursion (outline-end-of-heading) (point))
18345 flag))))
18347 (defun org-get-next-sibling ()
18348 "Move to next heading of the same level, and return point.
18349 If there is no such heading, return nil.
18350 This is like outline-next-sibling, but invisible headings are ok."
18351 (let ((level (funcall outline-level)))
18352 (outline-next-heading)
18353 (while (and (not (eobp)) (> (funcall outline-level) level))
18354 (outline-next-heading))
18355 (if (or (eobp) (< (funcall outline-level) level))
18357 (point))))
18359 (defun org-get-last-sibling ()
18360 "Move to previous heading of the same level, and return point.
18361 If there is no such heading, return nil."
18362 (let ((opoint (point))
18363 (level (funcall outline-level)))
18364 (outline-previous-heading)
18365 (when (and (/= (point) opoint) (outline-on-heading-p t))
18366 (while (and (> (funcall outline-level) level)
18367 (not (bobp)))
18368 (outline-previous-heading))
18369 (if (< (funcall outline-level) level)
18371 (point)))))
18373 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18374 ;; This contains an exact copy of the original function, but it uses
18375 ;; `org-back-to-heading', to make it work also in invisible
18376 ;; trees. And is uses an invisible-OK argument.
18377 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18378 ;; Furthermore, when used inside Org, finding the end of a large subtree
18379 ;; with many children and grandchildren etc, this can be much faster
18380 ;; than the outline version.
18381 (org-back-to-heading invisible-OK)
18382 (let ((first t)
18383 (level (funcall outline-level)))
18384 (if (and (org-mode-p) (< level 1000))
18385 ;; A true heading (not a plain list item), in Org-mode
18386 ;; This means we can easily find the end by looking
18387 ;; only for the right number of stars. Using a regexp to do
18388 ;; this is so much faster than using a Lisp loop.
18389 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18390 (forward-char 1)
18391 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18392 ;; something else, do it the slow way
18393 (while (and (not (eobp))
18394 (or first (> (funcall outline-level) level)))
18395 (setq first nil)
18396 (outline-next-heading)))
18397 (unless to-heading
18398 (if (memq (preceding-char) '(?\n ?\^M))
18399 (progn
18400 ;; Go to end of line before heading
18401 (forward-char -1)
18402 (if (memq (preceding-char) '(?\n ?\^M))
18403 ;; leave blank line before heading
18404 (forward-char -1))))))
18405 (point))
18407 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18408 "Use Org version in org-mode, for dramatic speed-up."
18409 (if (eq major-mode 'org-mode)
18410 (progn
18411 (org-end-of-subtree nil t)
18412 (unless (eobp) (backward-char 1)))
18413 ad-do-it))
18415 (defun org-forward-same-level (arg &optional invisible-ok)
18416 "Move forward to the arg'th subheading at same level as this one.
18417 Stop at the first and last subheadings of a superior heading."
18418 (interactive "p")
18419 (org-back-to-heading invisible-ok)
18420 (org-on-heading-p)
18421 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18422 (re (format "^\\*\\{1,%d\\} " level))
18424 (forward-char 1)
18425 (while (> arg 0)
18426 (while (and (re-search-forward re nil 'move)
18427 (setq l (- (match-end 0) (match-beginning 0) 1))
18428 (= l level)
18429 (not invisible-ok)
18430 (progn (backward-char 1) (org-invisible-p)))
18431 (if (< l level) (setq arg 1)))
18432 (setq arg (1- arg)))
18433 (beginning-of-line 1)))
18435 (defun org-backward-same-level (arg &optional invisible-ok)
18436 "Move backward to the arg'th subheading at same level as this one.
18437 Stop at the first and last subheadings of a superior heading."
18438 (interactive "p")
18439 (org-back-to-heading)
18440 (org-on-heading-p)
18441 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18442 (re (format "^\\*\\{1,%d\\} " level))
18444 (while (> arg 0)
18445 (while (and (re-search-backward re nil 'move)
18446 (setq l (- (match-end 0) (match-beginning 0) 1))
18447 (= l level)
18448 (not invisible-ok)
18449 (org-invisible-p))
18450 (if (< l level) (setq arg 1)))
18451 (setq arg (1- arg)))))
18453 (defun org-show-subtree ()
18454 "Show everything after this heading at deeper levels."
18455 (outline-flag-region
18456 (point)
18457 (save-excursion
18458 (org-end-of-subtree t t))
18459 nil))
18461 (defun org-show-entry ()
18462 "Show the body directly following this heading.
18463 Show the heading too, if it is currently invisible."
18464 (interactive)
18465 (save-excursion
18466 (condition-case nil
18467 (progn
18468 (org-back-to-heading t)
18469 (outline-flag-region
18470 (max (point-min) (1- (point)))
18471 (save-excursion
18472 (if (re-search-forward
18473 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18474 (match-beginning 1)
18475 (point-max)))
18476 nil)
18477 (org-cycle-hide-drawers 'children))
18478 (error nil))))
18480 (defun org-make-options-regexp (kwds &optional extra)
18481 "Make a regular expression for keyword lines."
18482 (concat
18484 "#?[ \t]*\\+\\("
18485 (mapconcat 'regexp-quote kwds "\\|")
18486 (if extra (concat "\\|" extra))
18487 "\\):[ \t]*"
18488 "\\(.*\\)"))
18490 ;; Make isearch reveal the necessary context
18491 (defun org-isearch-end ()
18492 "Reveal context after isearch exits."
18493 (when isearch-success ; only if search was successful
18494 (if (featurep 'xemacs)
18495 ;; Under XEmacs, the hook is run in the correct place,
18496 ;; we directly show the context.
18497 (org-show-context 'isearch)
18498 ;; In Emacs the hook runs *before* restoring the overlays.
18499 ;; So we have to use a one-time post-command-hook to do this.
18500 ;; (Emacs 22 has a special variable, see function `org-mode')
18501 (unless (and (boundp 'isearch-mode-end-hook-quit)
18502 isearch-mode-end-hook-quit)
18503 ;; Only when the isearch was not quitted.
18504 (org-add-hook 'post-command-hook 'org-isearch-post-command
18505 'append 'local)))))
18507 (defun org-isearch-post-command ()
18508 "Remove self from hook, and show context."
18509 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18510 (org-show-context 'isearch))
18513 ;;;; Integration with and fixes for other packages
18515 ;;; Imenu support
18517 (defvar org-imenu-markers nil
18518 "All markers currently used by Imenu.")
18519 (make-variable-buffer-local 'org-imenu-markers)
18521 (defun org-imenu-new-marker (&optional pos)
18522 "Return a new marker for use by Imenu, and remember the marker."
18523 (let ((m (make-marker)))
18524 (move-marker m (or pos (point)))
18525 (push m org-imenu-markers)
18528 (defun org-imenu-get-tree ()
18529 "Produce the index for Imenu."
18530 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18531 (setq org-imenu-markers nil)
18532 (let* ((n org-imenu-depth)
18533 (re (concat "^" outline-regexp))
18534 (subs (make-vector (1+ n) nil))
18535 (last-level 0)
18536 m level head)
18537 (save-excursion
18538 (save-restriction
18539 (widen)
18540 (goto-char (point-max))
18541 (while (re-search-backward re nil t)
18542 (setq level (org-reduced-level (funcall outline-level)))
18543 (when (<= level n)
18544 (looking-at org-complex-heading-regexp)
18545 (setq head (org-link-display-format
18546 (org-match-string-no-properties 4))
18547 m (org-imenu-new-marker))
18548 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18549 (if (>= level last-level)
18550 (push (cons head m) (aref subs level))
18551 (push (cons head (aref subs (1+ level))) (aref subs level))
18552 (loop for i from (1+ level) to n do (aset subs i nil)))
18553 (setq last-level level)))))
18554 (aref subs 1)))
18556 (eval-after-load "imenu"
18557 '(progn
18558 (add-hook 'imenu-after-jump-hook
18559 (lambda ()
18560 (if (eq major-mode 'org-mode)
18561 (org-show-context 'org-goto))))))
18563 (defun org-link-display-format (link)
18564 "Replace a link with either the description, or the link target
18565 if no description is present"
18566 (save-match-data
18567 (if (string-match org-bracket-link-analytic-regexp link)
18568 (replace-match (if (match-end 5)
18569 (match-string 5 link)
18570 (concat (match-string 1 link)
18571 (match-string 3 link)))
18572 nil t link)
18573 link)))
18575 ;; Speedbar support
18577 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
18578 "Overlay marking the agenda restriction line in speedbar.")
18579 (overlay-put org-speedbar-restriction-lock-overlay
18580 'face 'org-agenda-restriction-lock)
18581 (overlay-put org-speedbar-restriction-lock-overlay
18582 'help-echo "Agendas are currently limited to this item.")
18583 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18585 (defun org-speedbar-set-agenda-restriction ()
18586 "Restrict future agenda commands to the location at point in speedbar.
18587 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18588 (interactive)
18589 (require 'org-agenda)
18590 (let (p m tp np dir txt)
18591 (cond
18592 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18593 'org-imenu t))
18594 (setq m (get-text-property p 'org-imenu-marker))
18595 (with-current-buffer (marker-buffer m)
18596 (goto-char m)
18597 (org-agenda-set-restriction-lock 'subtree)))
18598 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18599 'speedbar-function 'speedbar-find-file))
18600 (setq tp (previous-single-property-change
18601 (1+ p) 'speedbar-function)
18602 np (next-single-property-change
18603 tp 'speedbar-function)
18604 dir (speedbar-line-directory)
18605 txt (buffer-substring-no-properties (or tp (point-min))
18606 (or np (point-max))))
18607 (with-current-buffer (find-file-noselect
18608 (let ((default-directory dir))
18609 (expand-file-name txt)))
18610 (unless (org-mode-p)
18611 (error "Cannot restrict to non-Org-mode file"))
18612 (org-agenda-set-restriction-lock 'file)))
18613 (t (error "Don't know how to restrict Org-mode's agenda")))
18614 (move-overlay org-speedbar-restriction-lock-overlay
18615 (point-at-bol) (point-at-eol))
18616 (setq current-prefix-arg nil)
18617 (org-agenda-maybe-redo)))
18619 (eval-after-load "speedbar"
18620 '(progn
18621 (speedbar-add-supported-extension ".org")
18622 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18623 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18624 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18625 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18626 (add-hook 'speedbar-visiting-tag-hook
18627 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18630 ;;; Fixes and Hacks for problems with other packages
18632 ;; Make flyspell not check words in links, to not mess up our keymap
18633 (defun org-mode-flyspell-verify ()
18634 "Don't let flyspell put overlays at active buttons."
18635 (and (not (get-text-property (point) 'keymap))
18636 (not (get-text-property (point) 'org-no-flyspell))))
18638 (defun org-remove-flyspell-overlays-in (beg end)
18639 "Remove flyspell overlays in region."
18640 (and (org-bound-and-true-p flyspell-mode)
18641 (fboundp 'flyspell-delete-region-overlays)
18642 (flyspell-delete-region-overlays beg end))
18643 (add-text-properties beg end '(org-no-flyspell t)))
18645 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18646 (eval-after-load "bookmark"
18647 '(if (boundp 'bookmark-after-jump-hook)
18648 ;; We can use the hook
18649 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18650 ;; Hook not available, use advice
18651 (defadvice bookmark-jump (after org-make-visible activate)
18652 "Make the position visible."
18653 (org-bookmark-jump-unhide))))
18655 ;; Make sure saveplace shows the location if it was hidden
18656 (eval-after-load "saveplace"
18657 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18658 "Make the position visible."
18659 (org-bookmark-jump-unhide)))
18661 ;; Make sure ecb shows the location if it was hidden
18662 (eval-after-load "ecb"
18663 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18664 "Make hierarchy visible when jumping into location from ECB tree buffer."
18665 (if (eq major-mode 'org-mode)
18666 (org-show-context))))
18668 (defun org-bookmark-jump-unhide ()
18669 "Unhide the current position, to show the bookmark location."
18670 (and (org-mode-p)
18671 (or (org-invisible-p)
18672 (save-excursion (goto-char (max (point-min) (1- (point))))
18673 (org-invisible-p)))
18674 (org-show-context 'bookmark-jump)))
18676 ;; Make session.el ignore our circular variable
18677 (eval-after-load "session"
18678 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18680 ;;;; Experimental code
18682 (defun org-closed-in-range ()
18683 "Sparse tree of items closed in a certain time range.
18684 Still experimental, may disappear in the future."
18685 (interactive)
18686 ;; Get the time interval from the user.
18687 (let* ((time1 (org-float-time
18688 (org-read-date nil 'to-time nil "Starting date: ")))
18689 (time2 (org-float-time
18690 (org-read-date nil 'to-time nil "End date:")))
18691 ;; callback function
18692 (callback (lambda ()
18693 (let ((time
18694 (org-float-time
18695 (apply 'encode-time
18696 (org-parse-time-string
18697 (match-string 1))))))
18698 ;; check if time in interval
18699 (and (>= time time1) (<= time time2))))))
18700 ;; make tree, check each match with the callback
18701 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18703 ;;;; Finish up
18705 (provide 'org)
18707 (run-hooks 'org-load-hook)
18709 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18711 ;;; org.el ends here