Fix typo in `org-splice-latex-header'.
[org-mode.git] / lisp / org.el
blobdbe0f6a55e767c204e739a4f2d0bf07c928ed126
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.34trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-entities)
89 (require 'org-compat)
90 (require 'org-faces)
91 (require 'org-list)
92 (require 'org-src)
93 (require 'org-footnote)
95 ;;;; Customization variables
97 ;;; Version
99 (defconst org-version "6.34trans"
100 "The version number of the file org.el.")
102 (defun org-version (&optional here)
103 "Show the org-mode version in the echo area.
104 With prefix arg HERE, insert it at point."
105 (interactive "P")
106 (let* ((origin default-directory)
107 (version org-version)
108 (git-version)
109 (dir (concat (file-name-directory (locate-library "org")) "../" )))
110 (when (and (file-exists-p (expand-file-name ".git" dir))
111 (executable-find "git"))
112 (unwind-protect
113 (progn
114 (cd dir)
115 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
116 (with-current-buffer "*Shell Command Output*"
117 (goto-char (point-min))
118 (setq git-version (buffer-substring (point) (point-at-eol))))
119 (subst-char-in-string ?- ?. git-version t)
120 (when (string-match "\\S-"
121 (shell-command-to-string
122 "git diff-index --name-only HEAD --"))
123 (setq git-version (concat git-version ".dirty")))
124 (setq version (concat version " (" git-version ")"))))
125 (cd origin)))
126 (setq version (format "Org-mode version %s" version))
127 (if here (insert version))
128 (message version)))
130 ;;; Compatibility constants
132 ;;; The custom variables
134 (defgroup org nil
135 "Outline-based notes management and organizer."
136 :tag "Org"
137 :group 'outlines
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
193 (const :tag " docview: Links to doc-view buffers" org-docview)
194 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
195 (const :tag " id: Global IDs for identifying entries" org-id)
196 (const :tag " info: Links to Info nodes" org-info)
197 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
198 (const :tag " habit: Track your consistency with habits" org-habit)
199 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
200 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
201 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
202 (const :tag " mew Links to Mew folders/messages" org-mew)
203 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
204 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
205 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
206 (const :tag " vm: Links to VM folders/messages" org-vm)
207 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
208 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
209 (const :tag " mouse: Additional mouse support" org-mouse)
211 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
212 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
225 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
227 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
229 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
230 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
231 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
232 (const :tag "C mtags: Support for muse-like tags" org-mtags)
233 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C secretary: Team management with org-mode" org-secretary)
238 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
239 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
240 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
241 (const :tag "C track: Keep up with Org-mode development" org-track)
242 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
244 (defcustom org-support-shift-select nil
245 "Non-nil means make shift-cursor commands select text when possible.
247 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
248 selecting a region, or enlarge thusly regions started in this way.
249 In Org-mode, in special contexts, these same keys are used for other
250 purposes, important enough to compete with shift selection. Org tries
251 to balance these needs by supporting `shift-select-mode' outside these
252 special contexts, under control of this variable.
254 The default of this variable is nil, to avoid confusing behavior. Shifted
255 cursor keys will then execute Org commands in the following contexts:
256 - on a headline, changing TODO state (left/right) and priority (up/down)
257 - on a time stamp, changing the time
258 - in a plain list item, changing the bullet type
259 - in a property definition line, switching between allowed values
260 - in the BEGIN line of a clock table (changing the time block).
261 Outside these contexts, the commands will throw an error.
263 When this variable is t and the cursor is not in a special context,
264 Org-mode will support shift-selection for making and enlarging regions.
265 To make this more effective, the bullet cycling will no longer happen
266 anywhere in an item line, but only if the cursor is exactly on the bullet.
268 If you set this variable to the symbol `always', then the keys
269 will not be special in headlines, property lines, and item lines, to make
270 shift selection work there as well. If this is what you want, you can
271 use the following alternative commands: `C-c C-t' and `C-c ,' to
272 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
273 TODO sets, `C-c -' to cycle item bullet types, and properties can be
274 edited by hand or in column view.
276 However, when the cursor is on a timestamp, shift-cursor commands
277 will still edit the time stamp - this is just too good to give up.
279 XEmacs user should have this variable set to nil, because shift-select-mode
280 is Emacs 23 only."
281 :group 'org
282 :type '(choice
283 (const :tag "Never" nil)
284 (const :tag "When outside special context" t)
285 (const :tag "Everywhere except timestamps" always)))
287 (defgroup org-startup nil
288 "Options concerning startup of Org-mode."
289 :tag "Org Startup"
290 :group 'org)
292 (defcustom org-startup-folded t
293 "Non-nil means entering Org-mode will switch to OVERVIEW.
294 This can also be configured on a per-file basis by adding one of
295 the following lines anywhere in the buffer:
297 #+STARTUP: fold (or `overview', this is equivalent)
298 #+STARTUP: nofold (or `showall', this is equivalent)
299 #+STARTUP: content
300 #+STARTUP: showeverything"
301 :group 'org-startup
302 :type '(choice
303 (const :tag "nofold: show all" nil)
304 (const :tag "fold: overview" t)
305 (const :tag "content: all headlines" content)
306 (const :tag "show everything, even drawers" showeverything)))
308 (defcustom org-startup-truncated t
309 "Non-nil means entering Org-mode will set `truncate-lines'.
310 This is useful since some lines containing links can be very long and
311 uninteresting. Also tables look terrible when wrapped."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-startup-indented nil
316 "Non-nil means turn on `org-indent-mode' on startup.
317 This can also be configured on a per-file basis by adding one of
318 the following lines anywhere in the buffer:
320 #+STARTUP: indent
321 #+STARTUP: noindent"
322 :group 'org-structure
323 :type '(choice
324 (const :tag "Not" nil)
325 (const :tag "Globally (slow on startup in large files)" t)))
327 (defcustom org-startup-with-beamer-mode nil
328 "Non-nil means turn on `org-beamer-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: beamer"
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-startup-align-all-tables nil
337 "Non-nil means align all tables when visiting a file.
338 This is useful when the column width in tables is forced with <N> cookies
339 in table fields. Such tables will look correct only after the first re-align.
340 This can also be configured on a per-file basis by adding one of
341 the following lines anywhere in the buffer:
342 #+STARTUP: align
343 #+STARTUP: noalign"
344 :group 'org-startup
345 :type 'boolean)
347 (defcustom org-insert-mode-line-in-empty-file nil
348 "Non-nil means insert the first line setting Org-mode in empty files.
349 When the function `org-mode' is called interactively in an empty file, this
350 normally means that the file name does not automatically trigger Org-mode.
351 To ensure that the file will always be in Org-mode in the future, a
352 line enforcing Org-mode will be inserted into the buffer, if this option
353 has been set."
354 :group 'org-startup
355 :type 'boolean)
357 (defcustom org-replace-disputed-keys nil
358 "Non-nil means use alternative key bindings for some keys.
359 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
360 These keys are also used by other packages like shift-selection-mode'
361 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
362 If you want to use Org-mode together with one of these other modes,
363 or more generally if you would like to move some Org-mode commands to
364 other keys, set this variable and configure the keys with the variable
365 `org-disputed-keys'.
367 This option is only relevant at load-time of Org-mode, and must be set
368 *before* org.el is loaded. Changing it requires a restart of Emacs to
369 become effective."
370 :group 'org-startup
371 :type 'boolean)
373 (defcustom org-use-extra-keys nil
374 "Non-nil means use extra key sequence definitions for certain
375 commands. This happens automatically if you run XEmacs or if
376 window-system is nil. This variable lets you do the same
377 manually. You must set it before loading org.
379 Example: on Carbon Emacs 22 running graphically, with an external
380 keyboard on a Powerbook, the default way of setting M-left might
381 not work for either Alt or ESC. Setting this variable will make
382 it work for ESC."
383 :group 'org-startup
384 :type 'boolean)
386 (if (fboundp 'defvaralias)
387 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
389 (defcustom org-disputed-keys
390 '(([(shift up)] . [(meta p)])
391 ([(shift down)] . [(meta n)])
392 ([(shift left)] . [(meta -)])
393 ([(shift right)] . [(meta +)])
394 ([(control shift right)] . [(meta shift +)])
395 ([(control shift left)] . [(meta shift -)]))
396 "Keys for which Org-mode and other modes compete.
397 This is an alist, cars are the default keys, second element specifies
398 the alternative to use when `org-replace-disputed-keys' is t.
400 Keys can be specified in any syntax supported by `define-key'.
401 The value of this option takes effect only at Org-mode's startup,
402 therefore you'll have to restart Emacs to apply it after changing."
403 :group 'org-startup
404 :type 'alist)
406 (defun org-key (key)
407 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
408 Or return the original if not disputed."
409 (if org-replace-disputed-keys
410 (let* ((nkey (key-description key))
411 (x (org-find-if (lambda (x)
412 (equal (key-description (car x)) nkey))
413 org-disputed-keys)))
414 (if x (cdr x) key))
415 key))
417 (defun org-find-if (predicate seq)
418 (catch 'exit
419 (while seq
420 (if (funcall predicate (car seq))
421 (throw 'exit (car seq))
422 (pop seq)))))
424 (defun org-defkey (keymap key def)
425 "Define a key, possibly translated, as returned by `org-key'."
426 (define-key keymap (org-key key) def))
428 (defcustom org-ellipsis nil
429 "The ellipsis to use in the Org-mode outline.
430 When nil, just use the standard three dots. When a string, use that instead,
431 When a face, use the standard 3 dots, but with the specified face.
432 The change affects only Org-mode (which will then use its own display table).
433 Changing this requires executing `M-x org-mode' in a buffer to become
434 effective."
435 :group 'org-startup
436 :type '(choice (const :tag "Default" nil)
437 (face :tag "Face" :value org-warning)
438 (string :tag "String" :value "...#")))
440 (defvar org-display-table nil
441 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
443 (defgroup org-keywords nil
444 "Keywords in Org-mode."
445 :tag "Org Keywords"
446 :group 'org)
448 (defcustom org-deadline-string "DEADLINE:"
449 "String to mark deadline entries.
450 A deadline is this string, followed by a time stamp. Should be a word,
451 terminated by a colon. You can insert a schedule keyword and
452 a timestamp with \\[org-deadline].
453 Changes become only effective after restarting Emacs."
454 :group 'org-keywords
455 :type 'string)
457 (defcustom org-scheduled-string "SCHEDULED:"
458 "String to mark scheduled TODO entries.
459 A schedule is this string, followed by a time stamp. Should be a word,
460 terminated by a colon. You can insert a schedule keyword and
461 a timestamp with \\[org-schedule].
462 Changes become only effective after restarting Emacs."
463 :group 'org-keywords
464 :type 'string)
466 (defcustom org-closed-string "CLOSED:"
467 "String used as the prefix for timestamps logging closing a TODO entry."
468 :group 'org-keywords
469 :type 'string)
471 (defcustom org-clock-string "CLOCK:"
472 "String used as prefix for timestamps clocking work hours on an item."
473 :group 'org-keywords
474 :type 'string)
476 (defcustom org-comment-string "COMMENT"
477 "Entries starting with this keyword will never be exported.
478 An entry can be toggled between COMMENT and normal with
479 \\[org-toggle-comment].
480 Changes become only effective after restarting Emacs."
481 :group 'org-keywords
482 :type 'string)
484 (defcustom org-quote-string "QUOTE"
485 "Entries starting with this keyword will be exported in fixed-width font.
486 Quoting applies only to the text in the entry following the headline, and does
487 not extend beyond the next headline, even if that is lower level.
488 An entry can be toggled between QUOTE and normal with
489 \\[org-toggle-fixed-width-section]."
490 :group 'org-keywords
491 :type 'string)
493 (defconst org-repeat-re
494 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
495 "Regular expression for specifying repeated events.
496 After a match, group 1 contains the repeat expression.")
498 (defgroup org-structure nil
499 "Options concerning the general structure of Org-mode files."
500 :tag "Org Structure"
501 :group 'org)
503 (defgroup org-reveal-location nil
504 "Options about how to make context of a location visible."
505 :tag "Org Reveal Location"
506 :group 'org-structure)
508 (defconst org-context-choice
509 '(choice
510 (const :tag "Always" t)
511 (const :tag "Never" nil)
512 (repeat :greedy t :tag "Individual contexts"
513 (cons
514 (choice :tag "Context"
515 (const agenda)
516 (const org-goto)
517 (const occur-tree)
518 (const tags-tree)
519 (const link-search)
520 (const mark-goto)
521 (const bookmark-jump)
522 (const isearch)
523 (const default))
524 (boolean))))
525 "Contexts for the reveal options.")
527 (defcustom org-show-hierarchy-above '((default . t))
528 "Non-nil means show full hierarchy when revealing a location.
529 Org-mode often shows locations in an org-mode file which might have
530 been invisible before. When this is set, the hierarchy of headings
531 above the exposed location is shown.
532 Turning this off for example for sparse trees makes them very compact.
533 Instead of t, this can also be an alist specifying this option for different
534 contexts. Valid contexts are
535 agenda when exposing an entry from the agenda
536 org-goto when using the command `org-goto' on key C-c C-j
537 occur-tree when using the command `org-occur' on key C-c /
538 tags-tree when constructing a sparse tree based on tags matches
539 link-search when exposing search matches associated with a link
540 mark-goto when exposing the jump goal of a mark
541 bookmark-jump when exposing a bookmark location
542 isearch when exiting from an incremental search
543 default default for all contexts not set explicitly"
544 :group 'org-reveal-location
545 :type org-context-choice)
547 (defcustom org-show-following-heading '((default . nil))
548 "Non-nil means show following heading when revealing a location.
549 Org-mode often shows locations in an org-mode file which might have
550 been invisible before. When this is set, the heading following the
551 match is shown.
552 Turning this off for example for sparse trees makes them very compact,
553 but makes it harder to edit the location of the match. In such a case,
554 use the command \\[org-reveal] to show more context.
555 Instead of t, this can also be an alist specifying this option for different
556 contexts. See `org-show-hierarchy-above' for valid contexts."
557 :group 'org-reveal-location
558 :type org-context-choice)
560 (defcustom org-show-siblings '((default . nil) (isearch t))
561 "Non-nil means show all sibling heading when revealing a location.
562 Org-mode often shows locations in an org-mode file which might have
563 been invisible before. When this is set, the sibling of the current entry
564 heading are all made visible. If `org-show-hierarchy-above' is t,
565 the same happens on each level of the hierarchy above the current entry.
567 By default this is on for the isearch context, off for all other contexts.
568 Turning this off for example for sparse trees makes them very compact,
569 but makes it harder to edit the location of the match. In such a case,
570 use the command \\[org-reveal] to show more context.
571 Instead of t, this can also be an alist specifying this option for different
572 contexts. See `org-show-hierarchy-above' for valid contexts."
573 :group 'org-reveal-location
574 :type org-context-choice)
576 (defcustom org-show-entry-below '((default . nil))
577 "Non-nil means show the entry below a headline when revealing a location.
578 Org-mode often shows locations in an org-mode file which might have
579 been invisible before. When this is set, the text below the headline that is
580 exposed is also shown.
582 By default this is off for all contexts.
583 Instead of t, this can also be an alist specifying this option for different
584 contexts. See `org-show-hierarchy-above' for valid contexts."
585 :group 'org-reveal-location
586 :type org-context-choice)
588 (defcustom org-indirect-buffer-display 'other-window
589 "How should indirect tree buffers be displayed?
590 This applies to indirect buffers created with the commands
591 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
592 Valid values are:
593 current-window Display in the current window
594 other-window Just display in another window.
595 dedicated-frame Create one new frame, and re-use it each time.
596 new-frame Make a new frame each time. Note that in this case
597 previously-made indirect buffers are kept, and you need to
598 kill these buffers yourself."
599 :group 'org-structure
600 :group 'org-agenda-windows
601 :type '(choice
602 (const :tag "In current window" current-window)
603 (const :tag "In current frame, other window" other-window)
604 (const :tag "Each time a new frame" new-frame)
605 (const :tag "One dedicated frame" dedicated-frame)))
607 (defcustom org-use-speed-commands nil
608 "Non-nil means activate single letter commands at beginning of a headline.
609 This may also be a function to test for appropriate locations where speed
610 commands should be active."
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Never" nil)
614 (const :tag "At beginning of headline stars" t)
615 (function)))
617 (defcustom org-speed-commands-user nil
618 "Alist of additional speed commands.
619 This list will be checked before `org-speed-commands-default'
620 when the variable `org-use-speed-commands' is non-nil
621 and when the cursor is at the beginning of a headline.
622 The car if each entry is a string with a single letter, which must
623 be assigned to `self-insert-command' in the global map.
624 The cdr is either a command to be called interactively, a function
625 to be called, or a form to be evaluated.
626 An entry that is just a list with a single string will be interpreted
627 as a descriptive headline that will be added when listing the speed
628 copmmands in the Help buffer using the `?' speed command."
629 :group 'org-structure
630 :type '(repeat :value ("k" . ignore)
631 (choice :value ("k" . ignore)
632 (list :tag "Descriptive Headline" (string :tag "Headline"))
633 (cons :tag "Letter and Command"
634 (string :tag "Command letter")
635 (choice
636 (function)
637 (sexp))))))
639 (defgroup org-cycle nil
640 "Options concerning visibility cycling in Org-mode."
641 :tag "Org Cycle"
642 :group 'org-structure)
644 (defcustom org-cycle-skip-children-state-if-no-children t
645 "Non-nil means skip CHILDREN state in entries that don't have any."
646 :group 'org-cycle
647 :type 'boolean)
649 (defcustom org-cycle-max-level nil
650 "Maximum level which should still be subject to visibility cycling.
651 Levels higher than this will, for cycling, be treated as text, not a headline.
652 When `org-odd-levels-only' is set, a value of N in this variable actually
653 means 2N-1 stars as the limiting headline.
654 When nil, cycle all levels.
655 Note that the limiting level of cycling is also influenced by
656 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
657 `org-inlinetask-min-level' is, cycling will be limited to levels one less
658 than its value."
659 :group 'org-cycle
660 :type '(choice
661 (const :tag "No limit" nil)
662 (integer :tag "Maximum level")))
664 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
665 "Names of drawers. Drawers are not opened by cycling on the headline above.
666 Drawers only open with a TAB on the drawer line itself. A drawer looks like
667 this:
668 :DRAWERNAME:
669 .....
670 :END:
671 The drawer \"PROPERTIES\" is special for capturing properties through
672 the property API.
674 Drawers can be defined on the per-file basis with a line like:
676 #+DRAWERS: HIDDEN STATE PROPERTIES"
677 :group 'org-structure
678 :group 'org-cycle
679 :type '(repeat (string :tag "Drawer Name")))
681 (defcustom org-hide-block-startup nil
682 "Non-nil means entering Org-mode will fold all blocks.
683 This can also be set in on a per-file basis with
685 #+STARTUP: hideblocks
686 #+STARTUP: showblocks"
687 :group 'org-startup
688 :group 'org-cycle
689 :type 'boolean)
691 (defcustom org-cycle-global-at-bob nil
692 "Cycle globally if cursor is at beginning of buffer and not at a headline.
693 This makes it possible to do global cycling without having to use S-TAB or
694 C-u TAB. For this special case to work, the first line of the buffer
695 must not be a headline - it may be empty or some other text. When used in
696 this way, `org-cycle-hook' is disables temporarily, to make sure the
697 cursor stays at the beginning of the buffer.
698 When this option is nil, don't do anything special at the beginning
699 of the buffer."
700 :group 'org-cycle
701 :type 'boolean)
703 (defcustom org-cycle-level-after-item/entry-creation t
704 "Non-nil means cycle entry level or item indentation in new empty entries.
706 When the cursor is at the end of an empty headline, i.e with only stars
707 and maybe a TODO keyword, TAB will then switch the entry to become a child,
708 and then all possible anchestor states, before returning to the original state.
709 This makes data entry extremely fast: M-RET to create a new headline,
710 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
712 When the cursor is at the end of an empty plain list item, one TAB will
713 make it a subitem, two or more tabs will back up to make this an item
714 higher up in the item hierarchy."
715 :group 'org-cycle
716 :type 'boolean)
718 (defcustom org-cycle-emulate-tab t
719 "Where should `org-cycle' emulate TAB.
720 nil Never
721 white Only in completely white lines
722 whitestart Only at the beginning of lines, before the first non-white char
723 t Everywhere except in headlines
724 exc-hl-bol Everywhere except at the start of a headline
725 If TAB is used in a place where it does not emulate TAB, the current subtree
726 visibility is cycled."
727 :group 'org-cycle
728 :type '(choice (const :tag "Never" nil)
729 (const :tag "Only in completely white lines" white)
730 (const :tag "Before first char in a line" whitestart)
731 (const :tag "Everywhere except in headlines" t)
732 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
735 (defcustom org-cycle-separator-lines 2
736 "Number of empty lines needed to keep an empty line between collapsed trees.
737 If you leave an empty line between the end of a subtree and the following
738 headline, this empty line is hidden when the subtree is folded.
739 Org-mode will leave (exactly) one empty line visible if the number of
740 empty lines is equal or larger to the number given in this variable.
741 So the default 2 means at least 2 empty lines after the end of a subtree
742 are needed to produce free space between a collapsed subtree and the
743 following headline.
745 If the number is negative, and the number of empty lines is at least -N,
746 all empty lines are shown.
748 Special case: when 0, never leave empty lines in collapsed view."
749 :group 'org-cycle
750 :type 'integer)
751 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
753 (defcustom org-pre-cycle-hook nil
754 "Hook that is run before visibility cycling is happening.
755 The function(s) in this hook must accept a single argument which indicates
756 the new state that will be set right after running this hook. The
757 argument is a symbol. Before a global state change, it can have the values
758 `overview', `content', or `all'. Before a local state change, it can have
759 the values `folded', `children', or `subtree'."
760 :group 'org-cycle
761 :type 'hook)
763 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
764 org-cycle-hide-drawers
765 org-cycle-show-empty-lines
766 org-optimize-window-after-visibility-change)
767 "Hook that is run after `org-cycle' has changed the buffer visibility.
768 The function(s) in this hook must accept a single argument which indicates
769 the new state that was set by the most recent `org-cycle' command. The
770 argument is a symbol. After a global state change, it can have the values
771 `overview', `content', or `all'. After a local state change, it can have
772 the values `folded', `children', or `subtree'."
773 :group 'org-cycle
774 :type 'hook)
776 (defgroup org-edit-structure nil
777 "Options concerning structure editing in Org-mode."
778 :tag "Org Edit Structure"
779 :group 'org-structure)
781 (defcustom org-odd-levels-only nil
782 "Non-nil means skip even levels and only use odd levels for the outline.
783 This has the effect that two stars are being added/taken away in
784 promotion/demotion commands. It also influences how levels are
785 handled by the exporters.
786 Changing it requires restart of `font-lock-mode' to become effective
787 for fontification also in regions already fontified.
788 You may also set this on a per-file basis by adding one of the following
789 lines to the buffer:
791 #+STARTUP: odd
792 #+STARTUP: oddeven"
793 :group 'org-edit-structure
794 :group 'org-appearance
795 :type 'boolean)
797 (defcustom org-adapt-indentation t
798 "Non-nil means adapt indentation to outline node level.
800 When this variable is set, Org assumes that you write outlines by
801 indenting text in each node to align with the headline (after the stars).
802 The following issues are influenced by this variable:
804 - When this is set and the *entire* text in an entry is indented, the
805 indentation is increased by one space in a demotion command, and
806 decreased by one in a promotion command. If any line in the entry
807 body starts with text at column 0, indentation is not changed at all.
809 - Property drawers and planning information is inserted indented when
810 this variable s set. When nil, they will not be indented.
812 - TAB indents a line relative to context. The lines below a headline
813 will be indented when this variable is set.
815 Note that this is all about true indentation, by adding and removing
816 space characters. See also `org-indent.el' which does level-dependent
817 indentation in a virtual way, i.e. at display time in Emacs."
818 :group 'org-edit-structure
819 :type 'boolean)
821 (defcustom org-special-ctrl-a/e nil
822 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
824 When t, `C-a' will bring back the cursor to the beginning of the
825 headline text, i.e. after the stars and after a possible TODO keyword.
826 In an item, this will be the position after the bullet.
827 When the cursor is already at that position, another `C-a' will bring
828 it to the beginning of the line.
830 `C-e' will jump to the end of the headline, ignoring the presence of tags
831 in the headline. A second `C-e' will then jump to the true end of the
832 line, after any tags. This also means that, when this variable is
833 non-nil, `C-e' also will never jump beyond the end of the heading of a
834 folded section, i.e. not after the ellipses.
836 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
837 going to the true line boundary first. Only a directly following, identical
838 keypress will bring the cursor to the special positions.
840 This may also be a cons cell where the behavior for `C-a' and `C-e' is
841 set separately."
842 :group 'org-edit-structure
843 :type '(choice
844 (const :tag "off" nil)
845 (const :tag "on: after stars/bullet and before tags first" t)
846 (const :tag "reversed: true line boundary first" reversed)
847 (cons :tag "Set C-a and C-e separately"
848 (choice :tag "Special C-a"
849 (const :tag "off" nil)
850 (const :tag "on: after stars/bullet first" t)
851 (const :tag "reversed: before stars/bullet first" reversed))
852 (choice :tag "Special C-e"
853 (const :tag "off" nil)
854 (const :tag "on: before tags first" t)
855 (const :tag "reversed: after tags first" reversed)))))
856 (if (fboundp 'defvaralias)
857 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
859 (defcustom org-special-ctrl-k nil
860 "Non-nil means `C-k' will behave specially in headlines.
861 When nil, `C-k' will call the default `kill-line' command.
862 When t, the following will happen while the cursor is in the headline:
864 - When the cursor is at the beginning of a headline, kill the entire
865 line and possible the folded subtree below the line.
866 - When in the middle of the headline text, kill the headline up to the tags.
867 - When after the headline text, kill the tags."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defcustom org-yank-folded-subtrees t
872 "Non-nil means when yanking subtrees, fold them.
873 If the kill is a single subtree, or a sequence of subtrees, i.e. if
874 it starts with a heading and all other headings in it are either children
875 or siblings, then fold all the subtrees. However, do this only if no
876 text after the yank would be swallowed into a folded tree by this action."
877 :group 'org-edit-structure
878 :type 'boolean)
880 (defcustom org-yank-adjusted-subtrees nil
881 "Non-nil means when yanking subtrees, adjust the level.
882 With this setting, `org-paste-subtree' is used to insert the subtree, see
883 this function for details."
884 :group 'org-edit-structure
885 :type 'boolean)
887 (defcustom org-M-RET-may-split-line '((default . t))
888 "Non-nil means M-RET will split the line at the cursor position.
889 When nil, it will go to the end of the line before making a
890 new line.
891 You may also set this option in a different way for different
892 contexts. Valid contexts are:
894 headline when creating a new headline
895 item when creating a new item
896 table in a table field
897 default the value to be used for all contexts not explicitly
898 customized"
899 :group 'org-structure
900 :group 'org-table
901 :type '(choice
902 (const :tag "Always" t)
903 (const :tag "Never" nil)
904 (repeat :greedy t :tag "Individual contexts"
905 (cons
906 (choice :tag "Context"
907 (const headline)
908 (const item)
909 (const table)
910 (const default))
911 (boolean)))))
914 (defcustom org-insert-heading-respect-content nil
915 "Non-nil means insert new headings after the current subtree.
916 When nil, the new heading is created directly after the current line.
917 The commands \\[org-insert-heading-respect-content] and
918 \\[org-insert-todo-heading-respect-content] turn this variable on
919 for the duration of the command."
920 :group 'org-structure
921 :type 'boolean)
923 (defcustom org-blank-before-new-entry '((heading . auto)
924 (plain-list-item . auto))
925 "Should `org-insert-heading' leave a blank line before new heading/item?
926 The value is an alist, with `heading' and `plain-list-item' as car,
927 and a boolean flag as cdr. For plain lists, if the variable
928 `org-empty-line-terminates-plain-lists' is set, the setting here
929 is ignored and no empty line is inserted, to keep the list in tact."
930 :group 'org-edit-structure
931 :type '(list
932 (cons (const heading)
933 (choice (const :tag "Never" nil)
934 (const :tag "Always" t)
935 (const :tag "Auto" auto)))
936 (cons (const plain-list-item)
937 (choice (const :tag "Never" nil)
938 (const :tag "Always" t)
939 (const :tag "Auto" auto)))))
941 (defcustom org-insert-heading-hook nil
942 "Hook being run after inserting a new heading."
943 :group 'org-edit-structure
944 :type 'hook)
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means lines starting with \":\" are treated as fixed-width.
948 This currently only means they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-edit-structure
952 :type 'boolean)
955 (defcustom org-goto-auto-isearch t
956 "Non-nil means typing characters in org-goto starts incremental search."
957 :group 'org-edit-structure
958 :type 'boolean)
960 (defgroup org-sparse-trees nil
961 "Options concerning sparse trees in Org-mode."
962 :tag "Org Sparse Trees"
963 :group 'org-structure)
965 (defcustom org-highlight-sparse-tree-matches t
966 "Non-nil means highlight all matches that define a sparse tree.
967 The highlights will automatically disappear the next time the buffer is
968 changed by an edit command."
969 :group 'org-sparse-trees
970 :type 'boolean)
972 (defcustom org-remove-highlights-with-change t
973 "Non-nil means any change to the buffer will remove temporary highlights.
974 Such highlights are created by `org-occur' and `org-clock-display'.
975 When nil, `C-c C-c needs to be used to get rid of the highlights.
976 The highlights created by `org-preview-latex-fragment' always need
977 `C-c C-c' to be removed."
978 :group 'org-sparse-trees
979 :group 'org-time
980 :type 'boolean)
983 (defcustom org-occur-hook '(org-first-headline-recenter)
984 "Hook that is run after `org-occur' has constructed a sparse tree.
985 This can be used to recenter the window to show as much of the structure
986 as possible."
987 :group 'org-sparse-trees
988 :type 'hook)
990 (defgroup org-imenu-and-speedbar nil
991 "Options concerning imenu and speedbar in Org-mode."
992 :tag "Org Imenu and Speedbar"
993 :group 'org-structure)
995 (defcustom org-imenu-depth 2
996 "The maximum level for Imenu access to Org-mode headlines.
997 This also applied for speedbar access."
998 :group 'org-imenu-and-speedbar
999 :type 'integer)
1001 (defgroup org-table nil
1002 "Options concerning tables in Org-mode."
1003 :tag "Org Table"
1004 :group 'org)
1006 (defcustom org-enable-table-editor 'optimized
1007 "Non-nil means lines starting with \"|\" are handled by the table editor.
1008 When nil, such lines will be treated like ordinary lines.
1010 When equal to the symbol `optimized', the table editor will be optimized to
1011 do the following:
1012 - Automatic overwrite mode in front of whitespace in table fields.
1013 This makes the structure of the table stay in tact as long as the edited
1014 field does not exceed the column width.
1015 - Minimize the number of realigns. Normally, the table is aligned each time
1016 TAB or RET are pressed to move to another field. With optimization this
1017 happens only if changes to a field might have changed the column width.
1018 Optimization requires replacing the functions `self-insert-command',
1019 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1020 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1021 very good at guessing when a re-align will be necessary, but you can always
1022 force one with \\[org-ctrl-c-ctrl-c].
1024 If you would like to use the optimized version in Org-mode, but the
1025 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1027 This variable can be used to turn on and off the table editor during a session,
1028 but in order to toggle optimization, a restart is required.
1030 See also the variable `org-table-auto-blank-field'."
1031 :group 'org-table
1032 :type '(choice
1033 (const :tag "off" nil)
1034 (const :tag "on" t)
1035 (const :tag "on, optimized" optimized)))
1037 (defcustom org-self-insert-cluster-for-undo t
1038 "Non-nil means cluster self-insert commands for undo when possible.
1039 If this is set, then, like in the Emacs command loop, 20 consecutive
1040 characters will be undone together.
1041 This is configurable, because there is some impact on typing performance."
1042 :group 'org-table
1043 :type 'boolean)
1045 (defcustom org-table-tab-recognizes-table.el t
1046 "Non-nil means TAB will automatically notice a table.el table.
1047 When it sees such a table, it moves point into it and - if necessary -
1048 calls `table-recognize-table'."
1049 :group 'org-table-editing
1050 :type 'boolean)
1052 (defgroup org-link nil
1053 "Options concerning links in Org-mode."
1054 :tag "Org Link"
1055 :group 'org)
1057 (defvar org-link-abbrev-alist-local nil
1058 "Buffer-local version of `org-link-abbrev-alist', which see.
1059 The value of this is taken from the #+LINK lines.")
1060 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1062 (defcustom org-link-abbrev-alist nil
1063 "Alist of link abbreviations.
1064 The car of each element is a string, to be replaced at the start of a link.
1065 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1066 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1068 [[linkkey:tag][description]]
1070 The 'linkkey' must be a word word, starting with a letter, followed
1071 by letters, numbers, '-' or '_'.
1073 If REPLACE is a string, the tag will simply be appended to create the link.
1074 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1075 the placeholder \"%h\" will cause a url-encoded version of the tag to
1076 be inserted at that point (see the function `url-hexify-string').
1078 REPLACE may also be a function that will be called with the tag as the
1079 only argument to create the link, which should be returned as a string.
1081 See the manual for examples."
1082 :group 'org-link
1083 :type '(repeat
1084 (cons
1085 (string :tag "Protocol")
1086 (choice
1087 (string :tag "Format")
1088 (function)))))
1090 (defcustom org-descriptive-links t
1091 "Non-nil means hide link part and only show description of bracket links.
1092 Bracket links are like [[link][description]]. This variable sets the initial
1093 state in new org-mode buffers. The setting can then be toggled on a
1094 per-buffer basis from the Org->Hyperlinks menu."
1095 :group 'org-link
1096 :type 'boolean)
1098 (defcustom org-link-file-path-type 'adaptive
1099 "How the path name in file links should be stored.
1100 Valid values are:
1102 relative Relative to the current directory, i.e. the directory of the file
1103 into which the link is being inserted.
1104 absolute Absolute path, if possible with ~ for home directory.
1105 noabbrev Absolute path, no abbreviation of home directory.
1106 adaptive Use relative path for files in the current directory and sub-
1107 directories of it. For other files, use an absolute path."
1108 :group 'org-link
1109 :type '(choice
1110 (const relative)
1111 (const absolute)
1112 (const noabbrev)
1113 (const adaptive)))
1115 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1116 "Types of links that should be activated in Org-mode files.
1117 This is a list of symbols, each leading to the activation of a certain link
1118 type. In principle, it does not hurt to turn on most link types - there may
1119 be a small gain when turning off unused link types. The types are:
1121 bracket The recommended [[link][description]] or [[link]] links with hiding.
1122 angular Links in angular brackets that may contain whitespace like
1123 <bbdb:Carsten Dominik>.
1124 plain Plain links in normal text, no whitespace, like http://google.com.
1125 radio Text that is matched by a radio target, see manual for details.
1126 tag Tag settings in a headline (link to tag search).
1127 date Time stamps (link to calendar).
1128 footnote Footnote labels.
1130 Changing this variable requires a restart of Emacs to become effective."
1131 :group 'org-link
1132 :type '(set :greedy t
1133 (const :tag "Double bracket links (new style)" bracket)
1134 (const :tag "Angular bracket links (old style)" angular)
1135 (const :tag "Plain text links" plain)
1136 (const :tag "Radio target matches" radio)
1137 (const :tag "Tags" tag)
1138 (const :tag "Timestamps" date)
1139 (const :tag "Footnotes" footnote)))
1141 (defcustom org-make-link-description-function nil
1142 "Function to use to generate link descriptions from links. If
1143 nil the link location will be used. This function must take two
1144 parameters; the first is the link and the second the description
1145 org-insert-link has generated, and should return the description
1146 to use."
1147 :group 'org-link
1148 :type 'function)
1150 (defgroup org-link-store nil
1151 "Options concerning storing links in Org-mode."
1152 :tag "Org Store Link"
1153 :group 'org-link)
1155 (defcustom org-email-link-description-format "Email %c: %.30s"
1156 "Format of the description part of a link to an email or usenet message.
1157 The following %-escapes will be replaced by corresponding information:
1159 %F full \"From\" field
1160 %f name, taken from \"From\" field, address if no name
1161 %T full \"To\" field
1162 %t first name in \"To\" field, address if no name
1163 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1164 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1165 %s subject
1166 %m message-id.
1168 You may use normal field width specification between the % and the letter.
1169 This is for example useful to limit the length of the subject.
1171 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1172 :group 'org-link-store
1173 :type 'string)
1175 (defcustom org-from-is-user-regexp
1176 (let (r1 r2)
1177 (when (and user-mail-address (not (string= user-mail-address "")))
1178 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1179 (when (and user-full-name (not (string= user-full-name "")))
1180 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1181 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1182 "Regexp matched against the \"From:\" header of an email or usenet message.
1183 It should match if the message is from the user him/herself."
1184 :group 'org-link-store
1185 :type 'regexp)
1187 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1188 "Non-nil means storing a link to an Org file will use entry IDs.
1190 Note that before this variable is even considered, org-id must be loaded,
1191 so please customize `org-modules' and turn it on.
1193 The variable can have the following values:
1195 t Create an ID if needed to make a link to the current entry.
1197 create-if-interactive
1198 If `org-store-link' is called directly (interactively, as a user
1199 command), do create an ID to support the link. But when doing the
1200 job for remember, only use the ID if it already exists. The
1201 purpose of this setting is to avoid proliferation of unwanted
1202 IDs, just because you happen to be in an Org file when you
1203 call `org-remember' that automatically and preemptively
1204 creates a link. If you do want to get an ID link in a remember
1205 template to an entry not having an ID, create it first by
1206 explicitly creating a link to it, using `C-c C-l' first.
1208 create-if-interactive-and-no-custom-id
1209 Like create-if-interactive, but do not create an ID if there is
1210 a CUSTOM_ID property defined in the entry. This is the default.
1212 use-existing
1213 Use existing ID, do not create one.
1215 nil Never use an ID to make a link, instead link using a text search for
1216 the headline text."
1217 :group 'org-link-store
1218 :type '(choice
1219 (const :tag "Create ID to make link" t)
1220 (const :tag "Create if storing link interactively"
1221 create-if-interactive)
1222 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1223 create-if-interactive-and-no-custom-id)
1224 (const :tag "Only use existing" use-existing)
1225 (const :tag "Do not use ID to create link" nil)))
1227 (defcustom org-context-in-file-links t
1228 "Non-nil means file links from `org-store-link' contain context.
1229 A search string will be added to the file name with :: as separator and
1230 used to find the context when the link is activated by the command
1231 `org-open-at-point'.
1232 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1233 negates this setting for the duration of the command."
1234 :group 'org-link-store
1235 :type 'boolean)
1237 (defcustom org-keep-stored-link-after-insertion nil
1238 "Non-nil means keep link in list for entire session.
1240 The command `org-store-link' adds a link pointing to the current
1241 location to an internal list. These links accumulate during a session.
1242 The command `org-insert-link' can be used to insert links into any
1243 Org-mode file (offering completion for all stored links). When this
1244 option is nil, every link which has been inserted once using \\[org-insert-link]
1245 will be removed from the list, to make completing the unused links
1246 more efficient."
1247 :group 'org-link-store
1248 :type 'boolean)
1250 (defgroup org-link-follow nil
1251 "Options concerning following links in Org-mode."
1252 :tag "Org Follow Link"
1253 :group 'org-link)
1255 (defcustom org-link-translation-function nil
1256 "Function to translate links with different syntax to Org syntax.
1257 This can be used to translate links created for example by the Planner
1258 or emacs-wiki packages to Org syntax.
1259 The function must accept two parameters, a TYPE containing the link
1260 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1261 which is everything after the link protocol. It should return a cons
1262 with possibly modified values of type and path.
1263 Org contains a function for this, so if you set this variable to
1264 `org-translate-link-from-planner', you should be able follow many
1265 links created by planner."
1266 :group 'org-link-follow
1267 :type 'function)
1269 (defcustom org-follow-link-hook nil
1270 "Hook that is run after a link has been followed."
1271 :group 'org-link-follow
1272 :type 'hook)
1274 (defcustom org-tab-follows-link nil
1275 "Non-nil means on links TAB will follow the link.
1276 Needs to be set before org.el is loaded.
1277 This really should not be used, it does not make sense, and the
1278 implementation is bad."
1279 :group 'org-link-follow
1280 :type 'boolean)
1282 (defcustom org-return-follows-link nil
1283 "Non-nil means on links RET will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1288 (defcustom org-mouse-1-follows-link
1289 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1290 "Non-nil means mouse-1 on a link will follow the link.
1291 A longer mouse click will still set point. Does not work on XEmacs.
1292 Needs to be set before org.el is loaded."
1293 :group 'org-link-follow
1294 :type 'boolean)
1296 (defcustom org-mark-ring-length 4
1297 "Number of different positions to be recorded in the ring
1298 Changing this requires a restart of Emacs to work correctly."
1299 :group 'org-link-follow
1300 :type 'integer)
1302 (defcustom org-link-frame-setup
1303 '((vm . vm-visit-folder-other-frame)
1304 (gnus . gnus-other-frame)
1305 (file . find-file-other-window))
1306 "Setup the frame configuration for following links.
1307 When following a link with Emacs, it may often be useful to display
1308 this link in another window or frame. This variable can be used to
1309 set this up for the different types of links.
1310 For VM, use any of
1311 `vm-visit-folder'
1312 `vm-visit-folder-other-frame'
1313 For Gnus, use any of
1314 `gnus'
1315 `gnus-other-frame'
1316 `org-gnus-no-new-news'
1317 For FILE, use any of
1318 `find-file'
1319 `find-file-other-window'
1320 `find-file-other-frame'
1321 For the calendar, use the variable `calendar-setup'.
1322 For BBDB, it is currently only possible to display the matches in
1323 another window."
1324 :group 'org-link-follow
1325 :type '(list
1326 (cons (const vm)
1327 (choice
1328 (const vm-visit-folder)
1329 (const vm-visit-folder-other-window)
1330 (const vm-visit-folder-other-frame)))
1331 (cons (const gnus)
1332 (choice
1333 (const gnus)
1334 (const gnus-other-frame)
1335 (const org-gnus-no-new-news)))
1336 (cons (const file)
1337 (choice
1338 (const find-file)
1339 (const find-file-other-window)
1340 (const find-file-other-frame)))))
1342 (defcustom org-display-internal-link-with-indirect-buffer nil
1343 "Non-nil means use indirect buffer to display infile links.
1344 Activating internal links (from one location in a file to another location
1345 in the same file) normally just jumps to the location. When the link is
1346 activated with a C-u prefix (or with mouse-3), the link is displayed in
1347 another window. When this option is set, the other window actually displays
1348 an indirect buffer clone of the current buffer, to avoid any visibility
1349 changes to the current buffer."
1350 :group 'org-link-follow
1351 :type 'boolean)
1353 (defcustom org-open-non-existing-files nil
1354 "Non-nil means `org-open-file' will open non-existing files.
1355 When nil, an error will be generated.
1356 This variable applies only to external applications because they
1357 might choke on non-existing files. If the link is to a file that
1358 will be opened in Emacs, the variable is ignored."
1359 :group 'org-link-follow
1360 :type 'boolean)
1362 (defcustom org-open-directory-means-index-dot-org nil
1363 "Non-nil means a link to a directory really means to index.org.
1364 When nil, following a directory link will run dired or open a finder/explorer
1365 window on that directory."
1366 :group 'org-link-follow
1367 :type 'boolean)
1369 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1370 "Function and arguments to call for following mailto links.
1371 This is a list with the first element being a lisp function, and the
1372 remaining elements being arguments to the function. In string arguments,
1373 %a will be replaced by the address, and %s will be replaced by the subject
1374 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1378 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1379 (const :tag "message-mail" (message-mail "%a" "%s"))
1380 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1382 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1383 "Non-nil means ask for confirmation before executing shell links.
1384 Shell links can be dangerous: just think about a link
1386 [[shell:rm -rf ~/*][Google Search]]
1388 This link would show up in your Org-mode document as \"Google Search\",
1389 but really it would remove your entire home directory.
1390 Therefore we advise against setting this variable to nil.
1391 Just change it to `y-or-n-p' if you want to confirm with a
1392 single keystroke rather than having to type \"yes\"."
1393 :group 'org-link-follow
1394 :type '(choice
1395 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1396 (const :tag "with y-or-n (faster)" y-or-n-p)
1397 (const :tag "no confirmation (dangerous)" nil)))
1399 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1400 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1401 Elisp links can be dangerous: just think about a link
1403 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1405 This link would show up in your Org-mode document as \"Google Search\",
1406 but really it would remove your entire home directory.
1407 Therefore we advise against setting this variable to nil.
1408 Just change it to `y-or-n-p' if you want to confirm with a
1409 single keystroke rather than having to type \"yes\"."
1410 :group 'org-link-follow
1411 :type '(choice
1412 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1413 (const :tag "with y-or-n (faster)" y-or-n-p)
1414 (const :tag "no confirmation (dangerous)" nil)))
1416 (defconst org-file-apps-defaults-gnu
1417 '((remote . emacs)
1418 (system . mailcap)
1419 (t . mailcap))
1420 "Default file applications on a UNIX or GNU/Linux system.
1421 See `org-file-apps'.")
1423 (defconst org-file-apps-defaults-macosx
1424 '((remote . emacs)
1425 (t . "open %s")
1426 (system . "open %s")
1427 ("ps.gz" . "gv %s")
1428 ("eps.gz" . "gv %s")
1429 ("dvi" . "xdvi %s")
1430 ("fig" . "xfig %s"))
1431 "Default file applications on a MacOS X system.
1432 The system \"open\" is known as a default, but we use X11 applications
1433 for some files for which the OS does not have a good default.
1434 See `org-file-apps'.")
1436 (defconst org-file-apps-defaults-windowsnt
1437 (list
1438 '(remote . emacs)
1439 (cons t
1440 (list (if (featurep 'xemacs)
1441 'mswindows-shell-execute
1442 'w32-shell-execute)
1443 "open" 'file))
1444 (cons 'system
1445 (list (if (featurep 'xemacs)
1446 'mswindows-shell-execute
1447 'w32-shell-execute)
1448 "open" 'file)))
1449 "Default file applications on a Windows NT system.
1450 The system \"open\" is used for most files.
1451 See `org-file-apps'.")
1453 (defcustom org-file-apps
1455 (auto-mode . emacs)
1456 ("\\.mm\\'" . default)
1457 ("\\.x?html?\\'" . default)
1458 ("\\.pdf\\'" . default)
1460 "External applications for opening `file:path' items in a document.
1461 Org-mode uses system defaults for different file types, but
1462 you can use this variable to set the application for a given file
1463 extension. The entries in this list are cons cells where the car identifies
1464 files and the cdr the corresponding command. Possible values for the
1465 file identifier are
1466 \"regex\" Regular expression matched against the file: link. For
1467 backward compatibility, this can also be a string with only
1468 alphanumeric characters, which is then interpreted as an
1469 extension.
1470 `directory' Matches a directory
1471 `remote' Matches a remote file, accessible through tramp or efs.
1472 Remote files most likely should be visited through Emacs
1473 because external applications cannot handle such paths.
1474 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1475 so all files Emacs knows how to handle. Using this with
1476 command `emacs' will open most files in Emacs. Beware that this
1477 will also open html files inside Emacs, unless you add
1478 (\"html\" . default) to the list as well.
1479 t Default for files not matched by any of the other options.
1480 `system' The system command to open files, like `open' on Windows
1481 and Mac OS X, and mailcap under GNU/Linux. This is the command
1482 that will be selected if you call `C-c C-o' with a double
1483 `C-u C-u' prefix.
1485 Possible values for the command are:
1486 `emacs' The file will be visited by the current Emacs process.
1487 `default' Use the default application for this file type, which is the
1488 association for t in the list, most likely in the system-specific
1489 part.
1490 This can be used to overrule an unwanted setting in the
1491 system-specific variable.
1492 `system' Use the system command for opening files, like \"open\".
1493 This command is specified by the entry whose car is `system'.
1494 Most likely, the system-specific version of this variable
1495 does define this command, but you can overrule/replace it
1496 here.
1497 string A command to be executed by a shell; %s will be replaced
1498 by the path to the file. If the file identifier is a regex,
1499 %n will be replaced by the match of the nth match group.
1500 sexp A Lisp form which will be evaluated. The file path will
1501 be available in the Lisp variable `file', the link itself
1502 in the Lisp variable `link'. If the file identifier is a regex,
1503 the original match data will be restored, so subexpression
1504 matches are accessible using (match-string n link).
1505 For more examples, see the system specific constants
1506 `org-file-apps-defaults-macosx'
1507 `org-file-apps-defaults-windowsnt'
1508 `org-file-apps-defaults-gnu'."
1509 :group 'org-link-follow
1510 :type '(repeat
1511 (cons (choice :value ""
1512 (string :tag "Extension")
1513 (const :tag "System command to open files" system)
1514 (const :tag "Default for unrecognized files" t)
1515 (const :tag "Remote file" remote)
1516 (const :tag "Links to a directory" directory)
1517 (const :tag "Any files that have Emacs modes"
1518 auto-mode))
1519 (choice :value ""
1520 (const :tag "Visit with Emacs" emacs)
1521 (const :tag "Use default" default)
1522 (const :tag "Use the system command" system)
1523 (string :tag "Command")
1524 (sexp :tag "Lisp form")))))
1526 (defgroup org-refile nil
1527 "Options concerning refiling entries in Org-mode."
1528 :tag "Org Refile"
1529 :group 'org)
1531 (defcustom org-directory "~/org"
1532 "Directory with org files.
1533 This is just a default location to look for Org files. There is no need
1534 at all to put your files into this directory. It is only used in the
1535 following situations:
1537 1. When a remember template specifies a target file that is not an
1538 absolute path. The path will then be interpreted relative to
1539 `org-directory'
1540 2. When a remember note is filed away in an interactive way (when exiting the
1541 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1542 with `org-directory' as the default path."
1543 :group 'org-refile
1544 :group 'org-remember
1545 :type 'directory)
1547 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1548 "Default target for storing notes.
1549 Used by the hooks for remember.el. This can be a string, or nil to mean
1550 the value of `remember-data-file'.
1551 You can set this on a per-template basis with the variable
1552 `org-remember-templates'."
1553 :group 'org-refile
1554 :group 'org-remember
1555 :type '(choice
1556 (const :tag "Default from remember-data-file" nil)
1557 file))
1559 (defcustom org-goto-interface 'outline
1560 "The default interface to be used for `org-goto'.
1561 Allowed values are:
1562 outline The interface shows an outline of the relevant file
1563 and the correct heading is found by moving through
1564 the outline or by searching with incremental search.
1565 outline-path-completion Headlines in the current buffer are offered via
1566 completion. This is the interface also used by
1567 the refile command."
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Outline" outline)
1571 (const :tag "Outline-path-completion" outline-path-completion)))
1573 (defcustom org-goto-max-level 5
1574 "Maximum level to be considered when running org-goto with refile interface."
1575 :group 'org-refile
1576 :type 'integer)
1578 (defcustom org-reverse-note-order nil
1579 "Non-nil means store new notes at the beginning of a file or entry.
1580 When nil, new notes will be filed to the end of a file or entry.
1581 This can also be a list with cons cells of regular expressions that
1582 are matched against file names, and values."
1583 :group 'org-remember
1584 :group 'org-refile
1585 :type '(choice
1586 (const :tag "Reverse always" t)
1587 (const :tag "Reverse never" nil)
1588 (repeat :tag "By file name regexp"
1589 (cons regexp boolean))))
1591 (defcustom org-log-refile nil
1592 "Information to record when a task is refiled.
1594 Possible values are:
1596 nil Don't add anything
1597 time Add a time stamp to the task
1598 note Prompt for a note and add it with template `org-log-note-headings'
1600 This option can also be set with on a per-file-basis with
1602 #+STARTUP: nologrefile
1603 #+STARTUP: logrefile
1604 #+STARTUP: lognoterefile
1606 You can have local logging settings for a subtree by setting the LOGGING
1607 property to one or more of these keywords.
1609 When bulk-refiling from the agenda, the value `note' is forbidden and
1610 will temporarily be changed to `time'."
1611 :group 'org-refile
1612 :group 'org-progress
1613 :type '(choice
1614 (const :tag "No logging" nil)
1615 (const :tag "Record timestamp" time)
1616 (const :tag "Record timestamp with note." note)))
1618 (defcustom org-refile-targets nil
1619 "Targets for refiling entries with \\[org-refile].
1620 This is list of cons cells. Each cell contains:
1621 - a specification of the files to be considered, either a list of files,
1622 or a symbol whose function or variable value will be used to retrieve
1623 a file name or a list of file names. If you use `org-agenda-files' for
1624 that, all agenda files will be scanned for targets. Nil means consider
1625 headings in the current buffer.
1626 - A specification of how to find candidate refile targets. This may be
1627 any of:
1628 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1629 This tag has to be present in all target headlines, inheritance will
1630 not be considered.
1631 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1632 todo keyword.
1633 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1634 headlines that are refiling targets.
1635 - a cons cell (:level . N). Any headline of level N is considered a target.
1636 Note that, when `org-odd-levels-only' is set, level corresponds to
1637 order in hierarchy, not to the number of stars.
1638 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1639 Note that, when `org-odd-levels-only' is set, level corresponds to
1640 order in hierarchy, not to the number of stars.
1642 You can set the variable `org-refile-target-verify-function' to a function
1643 to verify each headline found by the simple critery above.
1645 When this variable is nil, all top-level headlines in the current buffer
1646 are used, equivalent to the value `((nil . (:level . 1))'."
1647 :group 'org-refile
1648 :type '(repeat
1649 (cons
1650 (choice :value org-agenda-files
1651 (const :tag "All agenda files" org-agenda-files)
1652 (const :tag "Current buffer" nil)
1653 (function) (variable) (file))
1654 (choice :tag "Identify target headline by"
1655 (cons :tag "Specific tag" (const :value :tag) (string))
1656 (cons :tag "TODO keyword" (const :value :todo) (string))
1657 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1658 (cons :tag "Level number" (const :value :level) (integer))
1659 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1661 (defcustom org-refile-target-verify-function nil
1662 "Function to verify if the headline at point should be a refile target.
1663 The function will be called without arguments, with point at the
1664 beginning of the headline. It should return t and leave point
1665 where it is if the headline is a valid target for refiling.
1667 If the target should not be selected, the function must return nil.
1668 In addition to this, it may move point to a place from where the search
1669 should be continued. For example, the function may decide that the entire
1670 subtree of the current entry should be excluded and move point to the end
1671 of the subtree."
1672 :group 'org-refile
1673 :type 'function)
1675 (defcustom org-refile-use-outline-path nil
1676 "Non-nil means provide refile targets as paths.
1677 So a level 3 headline will be available as level1/level2/level3.
1679 When the value is `file', also include the file name (without directory)
1680 into the path. In this case, you can also stop the completion after
1681 the file name, to get entries inserted as top level in the file.
1683 When `full-file-path', include the full file path."
1684 :group 'org-refile
1685 :type '(choice
1686 (const :tag "Not" nil)
1687 (const :tag "Yes" t)
1688 (const :tag "Start with file name" file)
1689 (const :tag "Start with full file path" full-file-path)))
1691 (defcustom org-outline-path-complete-in-steps t
1692 "Non-nil means complete the outline path in hierarchical steps.
1693 When Org-mode uses the refile interface to select an outline path
1694 \(see variable `org-refile-use-outline-path'), the completion of
1695 the path can be done is a single go, or if can be done in steps down
1696 the headline hierarchy. Going in steps is probably the best if you
1697 do not use a special completion package like `ido' or `icicles'.
1698 However, when using these packages, going in one step can be very
1699 fast, while still showing the whole path to the entry."
1700 :group 'org-refile
1701 :type 'boolean)
1703 (defcustom org-refile-allow-creating-parent-nodes nil
1704 "Non-nil means allow to create new nodes as refile targets.
1705 New nodes are then created by adding \"/new node name\" to the completion
1706 of an existing node. When the value of this variable is `confirm',
1707 new node creation must be confirmed by the user (recommended)
1708 When nil, the completion must match an existing entry.
1710 Note that, if the new heading is not seen by the criteria
1711 listed in `org-refile-targets', multiple instances of the same
1712 heading would be created by trying again to file under the new
1713 heading."
1714 :group 'org-refile
1715 :type '(choice
1716 (const :tag "Never" nil)
1717 (const :tag "Always" t)
1718 (const :tag "Prompt for confirmation" confirm)))
1720 (defgroup org-todo nil
1721 "Options concerning TODO items in Org-mode."
1722 :tag "Org TODO"
1723 :group 'org)
1725 (defgroup org-progress nil
1726 "Options concerning Progress logging in Org-mode."
1727 :tag "Org Progress"
1728 :group 'org-time)
1730 (defvar org-todo-interpretation-widgets
1732 (:tag "Sequence (cycling hits every state)" sequence)
1733 (:tag "Type (cycling directly to DONE)" type))
1734 "The available interpretation symbols for customizing
1735 `org-todo-keywords'.
1736 Interested libraries should add to this list.")
1738 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1739 "List of TODO entry keyword sequences and their interpretation.
1740 \\<org-mode-map>This is a list of sequences.
1742 Each sequence starts with a symbol, either `sequence' or `type',
1743 indicating if the keywords should be interpreted as a sequence of
1744 action steps, or as different types of TODO items. The first
1745 keywords are states requiring action - these states will select a headline
1746 for inclusion into the global TODO list Org-mode produces. If one of
1747 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1748 signify that no further action is necessary. If \"|\" is not found,
1749 the last keyword is treated as the only DONE state of the sequence.
1751 The command \\[org-todo] cycles an entry through these states, and one
1752 additional state where no keyword is present. For details about this
1753 cycling, see the manual.
1755 TODO keywords and interpretation can also be set on a per-file basis with
1756 the special #+SEQ_TODO and #+TYP_TODO lines.
1758 Each keyword can optionally specify a character for fast state selection
1759 \(in combination with the variable `org-use-fast-todo-selection')
1760 and specifiers for state change logging, using the same syntax
1761 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1762 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1763 indicates to record a time stamp each time this state is selected.
1765 Each keyword may also specify if a timestamp or a note should be
1766 recorded when entering or leaving the state, by adding additional
1767 characters in the parenthesis after the keyword. This looks like this:
1768 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1769 record only the time of the state change. With X and Y being either
1770 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1771 Y when leaving the state if and only if the *target* state does not
1772 define X. You may omit any of the fast-selection key or X or /Y,
1773 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1775 For backward compatibility, this variable may also be just a list
1776 of keywords - in this case the interpretation (sequence or type) will be
1777 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1778 :group 'org-todo
1779 :group 'org-keywords
1780 :type '(choice
1781 (repeat :tag "Old syntax, just keywords"
1782 (string :tag "Keyword"))
1783 (repeat :tag "New syntax"
1784 (cons
1785 (choice
1786 :tag "Interpretation"
1787 ;;Quick and dirty way to see
1788 ;;`org-todo-interpretations'. This takes the
1789 ;;place of item arguments
1790 :convert-widget
1791 (lambda (widget)
1792 (widget-put widget
1793 :args (mapcar
1794 #'(lambda (x)
1795 (widget-convert
1796 (cons 'const x)))
1797 org-todo-interpretation-widgets))
1798 widget))
1799 (repeat
1800 (string :tag "Keyword"))))))
1802 (defvar org-todo-keywords-1 nil
1803 "All TODO and DONE keywords active in a buffer.")
1804 (make-variable-buffer-local 'org-todo-keywords-1)
1805 (defvar org-todo-keywords-for-agenda nil)
1806 (defvar org-done-keywords-for-agenda nil)
1807 (defvar org-drawers-for-agenda nil)
1808 (defvar org-todo-keyword-alist-for-agenda nil)
1809 (defvar org-tag-alist-for-agenda nil)
1810 (defvar org-agenda-contributing-files nil)
1811 (defvar org-not-done-keywords nil)
1812 (make-variable-buffer-local 'org-not-done-keywords)
1813 (defvar org-done-keywords nil)
1814 (make-variable-buffer-local 'org-done-keywords)
1815 (defvar org-todo-heads nil)
1816 (make-variable-buffer-local 'org-todo-heads)
1817 (defvar org-todo-sets nil)
1818 (make-variable-buffer-local 'org-todo-sets)
1819 (defvar org-todo-log-states nil)
1820 (make-variable-buffer-local 'org-todo-log-states)
1821 (defvar org-todo-kwd-alist nil)
1822 (make-variable-buffer-local 'org-todo-kwd-alist)
1823 (defvar org-todo-key-alist nil)
1824 (make-variable-buffer-local 'org-todo-key-alist)
1825 (defvar org-todo-key-trigger nil)
1826 (make-variable-buffer-local 'org-todo-key-trigger)
1828 (defcustom org-todo-interpretation 'sequence
1829 "Controls how TODO keywords are interpreted.
1830 This variable is in principle obsolete and is only used for
1831 backward compatibility, if the interpretation of todo keywords is
1832 not given already in `org-todo-keywords'. See that variable for
1833 more information."
1834 :group 'org-todo
1835 :group 'org-keywords
1836 :type '(choice (const sequence)
1837 (const type)))
1839 (defcustom org-use-fast-todo-selection t
1840 "Non-nil means use the fast todo selection scheme with C-c C-t.
1841 This variable describes if and under what circumstances the cycling
1842 mechanism for TODO keywords will be replaced by a single-key, direct
1843 selection scheme.
1845 When nil, fast selection is never used.
1847 When the symbol `prefix', it will be used when `org-todo' is called with
1848 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1849 in an agenda buffer.
1851 When t, fast selection is used by default. In this case, the prefix
1852 argument forces cycling instead.
1854 In all cases, the special interface is only used if access keys have actually
1855 been assigned by the user, i.e. if keywords in the configuration are followed
1856 by a letter in parenthesis, like TODO(t)."
1857 :group 'org-todo
1858 :type '(choice
1859 (const :tag "Never" nil)
1860 (const :tag "By default" t)
1861 (const :tag "Only with C-u C-c C-t" prefix)))
1863 (defcustom org-provide-todo-statistics t
1864 "Non-nil means update todo statistics after insert and toggle.
1865 ALL-HEADLINES means update todo statistics by including headlines
1866 with no TODO keyword as well, counting them as not done.
1867 A list of TODO keywords means the same, but skip keywords that are
1868 not in this list.
1870 When this is set, todo statistics is updated in the parent of the
1871 current entry each time a todo state is changed."
1872 :group 'org-todo
1873 :type '(choice
1874 (const :tag "Yes, only for TODO entries" t)
1875 (const :tag "Yes, including all entries" 'all-headlines)
1876 (repeat :tag "Yes, for TODOs in this list"
1877 (string :tag "TODO keyword"))
1878 (other :tag "No TODO statistics" nil)))
1880 (defcustom org-hierarchical-todo-statistics t
1881 "Non-nil means TODO statistics covers just direct children.
1882 When nil, all entries in the subtree are considered.
1883 This has only an effect if `org-provide-todo-statistics' is set.
1884 To set this to nil for only a single subtree, use a COOKIE_DATA
1885 property and include the word \"recursive\" into the value."
1886 :group 'org-todo
1887 :type 'boolean)
1889 (defcustom org-after-todo-state-change-hook nil
1890 "Hook which is run after the state of a TODO item was changed.
1891 The new state (a string with a TODO keyword, or nil) is available in the
1892 Lisp variable `state'."
1893 :group 'org-todo
1894 :type 'hook)
1896 (defvar org-blocker-hook nil
1897 "Hook for functions that are allowed to block a state change.
1899 Each function gets as its single argument a property list, see
1900 `org-trigger-hook' for more information about this list.
1902 If any of the functions in this hook returns nil, the state change
1903 is blocked.")
1905 (defvar org-trigger-hook nil
1906 "Hook for functions that are triggered by a state change.
1908 Each function gets as its single argument a property list with at least
1909 the following elements:
1911 (:type type-of-change :position pos-at-entry-start
1912 :from old-state :to new-state)
1914 Depending on the type, more properties may be present.
1916 This mechanism is currently implemented for:
1918 TODO state changes
1919 ------------------
1920 :type todo-state-change
1921 :from previous state (keyword as a string), or nil, or a symbol
1922 'todo' or 'done', to indicate the general type of state.
1923 :to new state, like in :from")
1925 (defcustom org-enforce-todo-dependencies nil
1926 "Non-nil means undone TODO entries will block switching the parent to DONE.
1927 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1928 be blocked if any prior sibling is not yet done.
1929 Finally, if the parent is blocked because of ordered siblings of its own,
1930 the child will also be blocked.
1931 This variable needs to be set before org.el is loaded, and you need to
1932 restart Emacs after a change to make the change effective. The only way
1933 to change is while Emacs is running is through the customize interface."
1934 :set (lambda (var val)
1935 (set var val)
1936 (if val
1937 (add-hook 'org-blocker-hook
1938 'org-block-todo-from-children-or-siblings-or-parent)
1939 (remove-hook 'org-blocker-hook
1940 'org-block-todo-from-children-or-siblings-or-parent)))
1941 :group 'org-todo
1942 :type 'boolean)
1944 (defcustom org-enforce-todo-checkbox-dependencies nil
1945 "Non-nil means unchecked boxes will block switching the parent to DONE.
1946 When this is nil, checkboxes have no influence on switching TODO states.
1947 When non-nil, you first need to check off all check boxes before the TODO
1948 entry can be switched to DONE.
1949 This variable needs to be set before org.el is loaded, and you need to
1950 restart Emacs after a change to make the change effective. The only way
1951 to change is while Emacs is running is through the customize interface."
1952 :set (lambda (var val)
1953 (set var val)
1954 (if val
1955 (add-hook 'org-blocker-hook
1956 'org-block-todo-from-checkboxes)
1957 (remove-hook 'org-blocker-hook
1958 'org-block-todo-from-checkboxes)))
1959 :group 'org-todo
1960 :type 'boolean)
1962 (defcustom org-treat-insert-todo-heading-as-state-change nil
1963 "Non-nil means inserting a TODO heading is treated as state change.
1964 So when the command \\[org-insert-todo-heading] is used, state change
1965 logging will apply if appropriate. When nil, the new TODO item will
1966 be inserted directly, and no logging will take place."
1967 :group 'org-todo
1968 :type 'boolean)
1970 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1971 "Non-nil means switching TODO states with S-cursor counts as state change.
1972 This is the default behavior. However, setting this to nil allows a
1973 convenient way to select a TODO state and bypass any logging associated
1974 with that."
1975 :group 'org-todo
1976 :type 'boolean)
1978 (defcustom org-todo-state-tags-triggers nil
1979 "Tag changes that should be triggered by TODO state changes.
1980 This is a list. Each entry is
1982 (state-change (tag . flag) .......)
1984 State-change can be a string with a state, and empty string to indicate the
1985 state that has no TODO keyword, or it can be one of the symbols `todo'
1986 or `done', meaning any not-done or done state, respectively."
1987 :group 'org-todo
1988 :group 'org-tags
1989 :type '(repeat
1990 (cons (choice :tag "When changing to"
1991 (const :tag "Not-done state" todo)
1992 (const :tag "Done state" done)
1993 (string :tag "State"))
1994 (repeat
1995 (cons :tag "Tag action"
1996 (string :tag "Tag")
1997 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1999 (defcustom org-log-done nil
2000 "Information to record when a task moves to the DONE state.
2002 Possible values are:
2004 nil Don't add anything, just change the keyword
2005 time Add a time stamp to the task
2006 note Prompt for a note and add it with template `org-log-note-headings'
2008 This option can also be set with on a per-file-basis with
2010 #+STARTUP: nologdone
2011 #+STARTUP: logdone
2012 #+STARTUP: lognotedone
2014 You can have local logging settings for a subtree by setting the LOGGING
2015 property to one or more of these keywords."
2016 :group 'org-todo
2017 :group 'org-progress
2018 :type '(choice
2019 (const :tag "No logging" nil)
2020 (const :tag "Record CLOSED timestamp" time)
2021 (const :tag "Record CLOSED timestamp with note." note)))
2023 ;; Normalize old uses of org-log-done.
2024 (cond
2025 ((eq org-log-done t) (setq org-log-done 'time))
2026 ((and (listp org-log-done) (memq 'done org-log-done))
2027 (setq org-log-done 'note)))
2029 (defcustom org-log-reschedule nil
2030 "Information to record when the scheduling date of a tasks is modified.
2032 Possible values are:
2034 nil Don't add anything, just change the date
2035 time Add a time stamp to the task
2036 note Prompt for a note and add it with template `org-log-note-headings'
2038 This option can also be set with on a per-file-basis with
2040 #+STARTUP: nologreschedule
2041 #+STARTUP: logreschedule
2042 #+STARTUP: lognotereschedule"
2043 :group 'org-todo
2044 :group 'org-progress
2045 :type '(choice
2046 (const :tag "No logging" nil)
2047 (const :tag "Record timestamp" time)
2048 (const :tag "Record timestamp with note." note)))
2050 (defcustom org-log-redeadline nil
2051 "Information to record when the deadline date of a tasks is modified.
2053 Possible values are:
2055 nil Don't add anything, just change the date
2056 time Add a time stamp to the task
2057 note Prompt for a note and add it with template `org-log-note-headings'
2059 This option can also be set with on a per-file-basis with
2061 #+STARTUP: nologredeadline
2062 #+STARTUP: logredeadline
2063 #+STARTUP: lognoteredeadline
2065 You can have local logging settings for a subtree by setting the LOGGING
2066 property to one or more of these keywords."
2067 :group 'org-todo
2068 :group 'org-progress
2069 :type '(choice
2070 (const :tag "No logging" nil)
2071 (const :tag "Record timestamp" time)
2072 (const :tag "Record timestamp with note." note)))
2074 (defcustom org-log-note-clock-out nil
2075 "Non-nil means record a note when clocking out of an item.
2076 This can also be configured on a per-file basis by adding one of
2077 the following lines anywhere in the buffer:
2079 #+STARTUP: lognoteclock-out
2080 #+STARTUP: nolognoteclock-out"
2081 :group 'org-todo
2082 :group 'org-progress
2083 :type 'boolean)
2085 (defcustom org-log-done-with-time t
2086 "Non-nil means the CLOSED time stamp will contain date and time.
2087 When nil, only the date will be recorded."
2088 :group 'org-progress
2089 :type 'boolean)
2091 (defcustom org-log-note-headings
2092 '((done . "CLOSING NOTE %t")
2093 (state . "State %-12s from %-12S %t")
2094 (note . "Note taken on %t")
2095 (reschedule . "Rescheduled from %S on %t")
2096 (delschedule . "Not scheduled, was %S on %t")
2097 (redeadline . "New deadline from %S on %t")
2098 (deldeadline . "Removed deadline, was %S on %t")
2099 (refile . "Refiled on %t")
2100 (clock-out . ""))
2101 "Headings for notes added to entries.
2102 The value is an alist, with the car being a symbol indicating the note
2103 context, and the cdr is the heading to be used. The heading may also be the
2104 empty string.
2105 %t in the heading will be replaced by a time stamp.
2106 %s will be replaced by the new TODO state, in double quotes.
2107 %S will be replaced by the old TODO state, in double quotes.
2108 %u will be replaced by the user name.
2109 %U will be replaced by the full user name.
2111 In fact, it is not a good idea to change the `state' entry, because
2112 agenda log mode depends on the format of these entries."
2113 :group 'org-todo
2114 :group 'org-progress
2115 :type '(list :greedy t
2116 (cons (const :tag "Heading when closing an item" done) string)
2117 (cons (const :tag
2118 "Heading when changing todo state (todo sequence only)"
2119 state) string)
2120 (cons (const :tag "Heading when just taking a note" note) string)
2121 (cons (const :tag "Heading when clocking out" clock-out) string)
2122 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2123 (cons (const :tag "Heading when rescheduling" reschedule) string)
2124 (cons (const :tag "Heading when changing deadline" redeadline) string)
2125 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2126 (cons (const :tag "Heading when refiling" refile) string)))
2128 (unless (assq 'note org-log-note-headings)
2129 (push '(note . "%t") org-log-note-headings))
2131 (defcustom org-log-into-drawer nil
2132 "Non-nil means insert state change notes and time stamps into a drawer.
2133 When nil, state changes notes will be inserted after the headline and
2134 any scheduling and clock lines, but not inside a drawer.
2136 The value of this variable should be the name of the drawer to use.
2137 LOGBOOK is proposed at the default drawer for this purpose, you can
2138 also set this to a string to define the drawer of your choice.
2140 A value of t is also allowed, representing \"LOGBOOK\".
2142 If this variable is set, `org-log-state-notes-insert-after-drawers'
2143 will be ignored.
2145 You can set the property LOG_INTO_DRAWER to overrule this setting for
2146 a subtree."
2147 :group 'org-todo
2148 :group 'org-progress
2149 :type '(choice
2150 (const :tag "Not into a drawer" nil)
2151 (const :tag "LOGBOOK" t)
2152 (string :tag "Other")))
2154 (if (fboundp 'defvaralias)
2155 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2157 (defun org-log-into-drawer ()
2158 "Return the value of `org-log-into-drawer', but let properties overrule.
2159 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2160 used instead of the default value."
2161 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2162 (cond
2163 ((or (not p) (equal p "nil")) org-log-into-drawer)
2164 ((equal p "t") "LOGBOOK")
2165 (t p))))
2167 (defcustom org-log-state-notes-insert-after-drawers nil
2168 "Non-nil means insert state change notes after any drawers in entry.
2169 Only the drawers that *immediately* follow the headline and the
2170 deadline/scheduled line are skipped.
2171 When nil, insert notes right after the heading and perhaps the line
2172 with deadline/scheduling if present.
2174 This variable will have no effect if `org-log-into-drawer' is
2175 set."
2176 :group 'org-todo
2177 :group 'org-progress
2178 :type 'boolean)
2180 (defcustom org-log-states-order-reversed t
2181 "Non-nil means the latest state note will be directly after heading.
2182 When nil, the state change notes will be ordered according to time."
2183 :group 'org-todo
2184 :group 'org-progress
2185 :type 'boolean)
2187 (defcustom org-log-repeat 'time
2188 "Non-nil means record moving through the DONE state when triggering repeat.
2189 An auto-repeating task is immediately switched back to TODO when
2190 marked DONE. If you are not logging state changes (by adding \"@\"
2191 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2192 record a closing note, there will be no record of the task moving
2193 through DONE. This variable forces taking a note anyway.
2195 nil Don't force a record
2196 time Record a time stamp
2197 note Record a note
2199 This option can also be set with on a per-file-basis with
2201 #+STARTUP: logrepeat
2202 #+STARTUP: lognoterepeat
2203 #+STARTUP: nologrepeat
2205 You can have local logging settings for a subtree by setting the LOGGING
2206 property to one or more of these keywords."
2207 :group 'org-todo
2208 :group 'org-progress
2209 :type '(choice
2210 (const :tag "Don't force a record" nil)
2211 (const :tag "Force recording the DONE state" time)
2212 (const :tag "Force recording a note with the DONE state" note)))
2215 (defgroup org-priorities nil
2216 "Priorities in Org-mode."
2217 :tag "Org Priorities"
2218 :group 'org-todo)
2220 (defcustom org-enable-priority-commands t
2221 "Non-nil means priority commands are active.
2222 When nil, these commands will be disabled, so that you never accidentally
2223 set a priority."
2224 :group 'org-priorities
2225 :type 'boolean)
2227 (defcustom org-highest-priority ?A
2228 "The highest priority of TODO items. A character like ?A, ?B etc.
2229 Must have a smaller ASCII number than `org-lowest-priority'."
2230 :group 'org-priorities
2231 :type 'character)
2233 (defcustom org-lowest-priority ?C
2234 "The lowest priority of TODO items. A character like ?A, ?B etc.
2235 Must have a larger ASCII number than `org-highest-priority'."
2236 :group 'org-priorities
2237 :type 'character)
2239 (defcustom org-default-priority ?B
2240 "The default priority of TODO items.
2241 This is the priority an item get if no explicit priority is given."
2242 :group 'org-priorities
2243 :type 'character)
2245 (defcustom org-priority-start-cycle-with-default t
2246 "Non-nil means start with default priority when starting to cycle.
2247 When this is nil, the first step in the cycle will be (depending on the
2248 command used) one higher or lower that the default priority."
2249 :group 'org-priorities
2250 :type 'boolean)
2252 (defgroup org-time nil
2253 "Options concerning time stamps and deadlines in Org-mode."
2254 :tag "Org Time"
2255 :group 'org)
2257 (defcustom org-insert-labeled-timestamps-at-point nil
2258 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2259 When nil, these labeled time stamps are forces into the second line of an
2260 entry, just after the headline. When scheduling from the global TODO list,
2261 the time stamp will always be forced into the second line."
2262 :group 'org-time
2263 :type 'boolean)
2265 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2266 "Formats for `format-time-string' which are used for time stamps.
2267 It is not recommended to change this constant.")
2269 (defcustom org-time-stamp-rounding-minutes '(0 5)
2270 "Number of minutes to round time stamps to.
2271 These are two values, the first applies when first creating a time stamp.
2272 The second applies when changing it with the commands `S-up' and `S-down'.
2273 When changing the time stamp, this means that it will change in steps
2274 of N minutes, as given by the second value.
2276 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2277 numbers should be factors of 60, so for example 5, 10, 15.
2279 When this is larger than 1, you can still force an exact time-stamp by using
2280 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2281 and by using a prefix arg to `S-up/down' to specify the exact number
2282 of minutes to shift."
2283 :group 'org-time
2284 :get '(lambda (var) ; Make sure all entries have 5 elements
2285 (if (integerp (default-value var))
2286 (list (default-value var) 5)
2287 (default-value var)))
2288 :type '(list
2289 (integer :tag "when inserting times")
2290 (integer :tag "when modifying times")))
2292 ;; Normalize old customizations of this variable.
2293 (when (integerp org-time-stamp-rounding-minutes)
2294 (setq org-time-stamp-rounding-minutes
2295 (list org-time-stamp-rounding-minutes
2296 org-time-stamp-rounding-minutes)))
2298 (defcustom org-display-custom-times nil
2299 "Non-nil means overlay custom formats over all time stamps.
2300 The formats are defined through the variable `org-time-stamp-custom-formats'.
2301 To turn this on on a per-file basis, insert anywhere in the file:
2302 #+STARTUP: customtime"
2303 :group 'org-time
2304 :set 'set-default
2305 :type 'sexp)
2306 (make-variable-buffer-local 'org-display-custom-times)
2308 (defcustom org-time-stamp-custom-formats
2309 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2310 "Custom formats for time stamps. See `format-time-string' for the syntax.
2311 These are overlayed over the default ISO format if the variable
2312 `org-display-custom-times' is set. Time like %H:%M should be at the
2313 end of the second format. The custom formats are also honored by export
2314 commands, if custom time display is turned on at the time of export."
2315 :group 'org-time
2316 :type 'sexp)
2318 (defun org-time-stamp-format (&optional long inactive)
2319 "Get the right format for a time string."
2320 (let ((f (if long (cdr org-time-stamp-formats)
2321 (car org-time-stamp-formats))))
2322 (if inactive
2323 (concat "[" (substring f 1 -1) "]")
2324 f)))
2326 (defcustom org-time-clocksum-format "%d:%02d"
2327 "The format string used when creating CLOCKSUM lines, or when
2328 org-mode generates a time duration."
2329 :group 'org-time
2330 :type 'string)
2332 (defcustom org-time-clocksum-use-fractional nil
2333 "If non-nil, \\[org-clock-display] uses fractional times.
2334 org-mode generates a time duration."
2335 :group 'org-time
2336 :type 'boolean)
2338 (defcustom org-time-clocksum-fractional-format "%.2f"
2339 "The format string used when creating CLOCKSUM lines, or when
2340 org-mode generates a time duration."
2341 :group 'org-time
2342 :type 'string)
2344 (defcustom org-deadline-warning-days 14
2345 "No. of days before expiration during which a deadline becomes active.
2346 This variable governs the display in sparse trees and in the agenda.
2347 When 0 or negative, it means use this number (the absolute value of it)
2348 even if a deadline has a different individual lead time specified.
2350 Custom commands can set this variable in the options section."
2351 :group 'org-time
2352 :group 'org-agenda-daily/weekly
2353 :type 'integer)
2355 (defcustom org-read-date-prefer-future t
2356 "Non-nil means assume future for incomplete date input from user.
2357 This affects the following situations:
2358 1. The user gives a month but not a year.
2359 For example, if it is april and you enter \"feb 2\", this will be read
2360 as feb 2, *next* year. \"May 5\", however, will be this year.
2361 2. The user gives a day, but no month.
2362 For example, if today is the 15th, and you enter \"3\", Org-mode will
2363 read this as the third of *next* month. However, if you enter \"17\",
2364 it will be considered as *this* month.
2366 If you set this variable to the symbol `time', then also the following
2367 will work:
2369 3. If the user gives a time, but no day. If the time is before now,
2370 to will be interpreted as tomorrow.
2372 Currently none of this works for ISO week specifications.
2374 When this option is nil, the current day, month and year will always be
2375 used as defaults."
2376 :group 'org-time
2377 :type '(choice
2378 (const :tag "Never" nil)
2379 (const :tag "Check month and day" t)
2380 (const :tag "Check month, day, and time" time)))
2382 (defcustom org-read-date-display-live t
2383 "Non-nil means display current interpretation of date prompt live.
2384 This display will be in an overlay, in the minibuffer."
2385 :group 'org-time
2386 :type 'boolean)
2388 (defcustom org-read-date-popup-calendar t
2389 "Non-nil means pop up a calendar when prompting for a date.
2390 In the calendar, the date can be selected with mouse-1. However, the
2391 minibuffer will also be active, and you can simply enter the date as well.
2392 When nil, only the minibuffer will be available."
2393 :group 'org-time
2394 :type 'boolean)
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-popup-calendar-for-date-prompt
2397 'org-read-date-popup-calendar))
2399 (defcustom org-read-date-minibuffer-setup-hook nil
2400 "Hook to be used to set up keys for the date/time interface.
2401 Add key definitions to `minibuffer-local-map', which will be a temporary
2402 copy."
2403 :group 'org-time
2404 :type 'hook)
2406 (defcustom org-extend-today-until 0
2407 "The hour when your day really ends. Must be an integer.
2408 This has influence for the following applications:
2409 - When switching the agenda to \"today\". It it is still earlier than
2410 the time given here, the day recognized as TODAY is actually yesterday.
2411 - When a date is read from the user and it is still before the time given
2412 here, the current date and time will be assumed to be yesterday, 23:59.
2413 Also, timestamps inserted in remember templates follow this rule.
2415 IMPORTANT: This is a feature whose implementation is and likely will
2416 remain incomplete. Really, it is only here because past midnight seems to
2417 be the favorite working time of John Wiegley :-)"
2418 :group 'org-time
2419 :type 'integer)
2421 (defcustom org-edit-timestamp-down-means-later nil
2422 "Non-nil means S-down will increase the time in a time stamp.
2423 When nil, S-up will increase."
2424 :group 'org-time
2425 :type 'boolean)
2427 (defcustom org-calendar-follow-timestamp-change t
2428 "Non-nil means make the calendar window follow timestamp changes.
2429 When a timestamp is modified and the calendar window is visible, it will be
2430 moved to the new date."
2431 :group 'org-time
2432 :type 'boolean)
2434 (defgroup org-tags nil
2435 "Options concerning tags in Org-mode."
2436 :tag "Org Tags"
2437 :group 'org)
2439 (defcustom org-tag-alist nil
2440 "List of tags allowed in Org-mode files.
2441 When this list is nil, Org-mode will base TAG input on what is already in the
2442 buffer.
2443 The value of this variable is an alist, the car of each entry must be a
2444 keyword as a string, the cdr may be a character that is used to select
2445 that tag through the fast-tag-selection interface.
2446 See the manual for details."
2447 :group 'org-tags
2448 :type '(repeat
2449 (choice
2450 (cons (string :tag "Tag name")
2451 (character :tag "Access char"))
2452 (list :tag "Start radio group"
2453 (const :startgroup)
2454 (option (string :tag "Group description")))
2455 (list :tag "End radio group"
2456 (const :endgroup)
2457 (option (string :tag "Group description")))
2458 (const :tag "New line" (:newline)))))
2460 (defcustom org-tag-persistent-alist nil
2461 "List of tags that will always appear in all Org-mode files.
2462 This is in addition to any in buffer settings or customizations
2463 of `org-tag-alist'.
2464 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2465 The value of this variable is an alist, the car of each entry must be a
2466 keyword as a string, the cdr may be a character that is used to select
2467 that tag through the fast-tag-selection interface.
2468 See the manual for details.
2469 To disable these tags on a per-file basis, insert anywhere in the file:
2470 #+STARTUP: noptag"
2471 :group 'org-tags
2472 :type '(repeat
2473 (choice
2474 (cons (string :tag "Tag name")
2475 (character :tag "Access char"))
2476 (const :tag "Start radio group" (:startgroup))
2477 (const :tag "End radio group" (:endgroup))
2478 (const :tag "New line" (:newline)))))
2480 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2481 "If non-nil, always offer completion for all tags of all agenda files.
2482 Instead of customizing this variable directly, you might want to
2483 set it locally for remember buffers, because there no list of
2484 tags in that file can be created dynamically (there are none).
2486 (add-hook 'org-remember-mode-hook
2487 (lambda ()
2488 (set (make-local-variable
2489 'org-complete-tags-always-offer-all-agenda-tags)
2490 t)))"
2491 :group 'org-tags
2492 :type 'boolean)
2494 (defvar org-file-tags nil
2495 "List of tags that can be inherited by all entries in the file.
2496 The tags will be inherited if the variable `org-use-tag-inheritance'
2497 says they should be.
2498 This variable is populated from #+FILETAGS lines.")
2500 (defcustom org-use-fast-tag-selection 'auto
2501 "Non-nil means use fast tag selection scheme.
2502 This is a special interface to select and deselect tags with single keys.
2503 When nil, fast selection is never used.
2504 When the symbol `auto', fast selection is used if and only if selection
2505 characters for tags have been configured, either through the variable
2506 `org-tag-alist' or through a #+TAGS line in the buffer.
2507 When t, fast selection is always used and selection keys are assigned
2508 automatically if necessary."
2509 :group 'org-tags
2510 :type '(choice
2511 (const :tag "Always" t)
2512 (const :tag "Never" nil)
2513 (const :tag "When selection characters are configured" 'auto)))
2515 (defcustom org-fast-tag-selection-single-key nil
2516 "Non-nil means fast tag selection exits after first change.
2517 When nil, you have to press RET to exit it.
2518 During fast tag selection, you can toggle this flag with `C-c'.
2519 This variable can also have the value `expert'. In this case, the window
2520 displaying the tags menu is not even shown, until you press C-c again."
2521 :group 'org-tags
2522 :type '(choice
2523 (const :tag "No" nil)
2524 (const :tag "Yes" t)
2525 (const :tag "Expert" expert)))
2527 (defvar org-fast-tag-selection-include-todo nil
2528 "Non-nil means fast tags selection interface will also offer TODO states.
2529 This is an undocumented feature, you should not rely on it.")
2531 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2532 "The column to which tags should be indented in a headline.
2533 If this number is positive, it specifies the column. If it is negative,
2534 it means that the tags should be flushright to that column. For example,
2535 -80 works well for a normal 80 character screen."
2536 :group 'org-tags
2537 :type 'integer)
2539 (defcustom org-auto-align-tags t
2540 "Non-nil means realign tags after pro/demotion of TODO state change.
2541 These operations change the length of a headline and therefore shift
2542 the tags around. With this options turned on, after each such operation
2543 the tags are again aligned to `org-tags-column'."
2544 :group 'org-tags
2545 :type 'boolean)
2547 (defcustom org-use-tag-inheritance t
2548 "Non-nil means tags in levels apply also for sublevels.
2549 When nil, only the tags directly given in a specific line apply there.
2550 This may also be a list of tags that should be inherited, or a regexp that
2551 matches tags that should be inherited. Additional control is possible
2552 with the variable `org-tags-exclude-from-inheritance' which gives an
2553 explicit list of tags to be excluded from inheritance., even if the value of
2554 `org-use-tag-inheritance' would select it for inheritance.
2556 If this option is t, a match early-on in a tree can lead to a large
2557 number of matches in the subtree when constructing the agenda or creating
2558 a sparse tree. If you only want to see the first match in a tree during
2559 a search, check out the variable `org-tags-match-list-sublevels'."
2560 :group 'org-tags
2561 :type '(choice
2562 (const :tag "Not" nil)
2563 (const :tag "Always" t)
2564 (repeat :tag "Specific tags" (string :tag "Tag"))
2565 (regexp :tag "Tags matched by regexp")))
2567 (defcustom org-tags-exclude-from-inheritance nil
2568 "List of tags that should never be inherited.
2569 This is a way to exclude a few tags from inheritance. For way to do
2570 the opposite, to actively allow inheritance for selected tags,
2571 see the variable `org-use-tag-inheritance'."
2572 :group 'org-tags
2573 :type '(repeat (string :tag "Tag")))
2575 (defun org-tag-inherit-p (tag)
2576 "Check if TAG is one that should be inherited."
2577 (cond
2578 ((member tag org-tags-exclude-from-inheritance) nil)
2579 ((eq org-use-tag-inheritance t) t)
2580 ((not org-use-tag-inheritance) nil)
2581 ((stringp org-use-tag-inheritance)
2582 (string-match org-use-tag-inheritance tag))
2583 ((listp org-use-tag-inheritance)
2584 (member tag org-use-tag-inheritance))
2585 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2587 (defcustom org-tags-match-list-sublevels t
2588 "Non-nil means list also sublevels of headlines matching a search.
2589 This variable applies to tags/property searches, and also to stuck
2590 projects because this search is based on a tags match as well.
2592 When set to the symbol `indented', sublevels are indented with
2593 leading dots.
2595 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2596 the sublevels of a headline matching a tag search often also match
2597 the same search. Listing all of them can create very long lists.
2598 Setting this variable to nil causes subtrees of a match to be skipped.
2600 This variable is semi-obsolete and probably should always be true. It
2601 is better to limit inheritance to certain tags using the variables
2602 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2603 :group 'org-tags
2604 :type '(choice
2605 (const :tag "No, don't list them" nil)
2606 (const :tag "Yes, do list them" t)
2607 (const :tag "List them, indented with leading dots" indented)))
2609 (defcustom org-tags-sort-function nil
2610 "When set, tags are sorted using this function as a comparator"
2611 :group 'org-tags
2612 :type '(choice
2613 (const :tag "No sorting" nil)
2614 (const :tag "Alphabetical" string<)
2615 (const :tag "Reverse alphabetical" string>)
2616 (function :tag "Custom function" nil)))
2618 (defvar org-tags-history nil
2619 "History of minibuffer reads for tags.")
2620 (defvar org-last-tags-completion-table nil
2621 "The last used completion table for tags.")
2622 (defvar org-after-tags-change-hook nil
2623 "Hook that is run after the tags in a line have changed.")
2625 (defgroup org-properties nil
2626 "Options concerning properties in Org-mode."
2627 :tag "Org Properties"
2628 :group 'org)
2630 (defcustom org-property-format "%-10s %s"
2631 "How property key/value pairs should be formatted by `indent-line'.
2632 When `indent-line' hits a property definition, it will format the line
2633 according to this format, mainly to make sure that the values are
2634 lined-up with respect to each other."
2635 :group 'org-properties
2636 :type 'string)
2638 (defcustom org-use-property-inheritance nil
2639 "Non-nil means properties apply also for sublevels.
2641 This setting is chiefly used during property searches. Turning it on can
2642 cause significant overhead when doing a search, which is why it is not
2643 on by default.
2645 When nil, only the properties directly given in the current entry count.
2646 When t, every property is inherited. The value may also be a list of
2647 properties that should have inheritance, or a regular expression matching
2648 properties that should be inherited.
2650 However, note that some special properties use inheritance under special
2651 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2652 and the properties ending in \"_ALL\" when they are used as descriptor
2653 for valid values of a property.
2655 Note for programmers:
2656 When querying an entry with `org-entry-get', you can control if inheritance
2657 should be used. By default, `org-entry-get' looks only at the local
2658 properties. You can request inheritance by setting the inherit argument
2659 to t (to force inheritance) or to `selective' (to respect the setting
2660 in this variable)."
2661 :group 'org-properties
2662 :type '(choice
2663 (const :tag "Not" nil)
2664 (const :tag "Always" t)
2665 (repeat :tag "Specific properties" (string :tag "Property"))
2666 (regexp :tag "Properties matched by regexp")))
2668 (defun org-property-inherit-p (property)
2669 "Check if PROPERTY is one that should be inherited."
2670 (cond
2671 ((eq org-use-property-inheritance t) t)
2672 ((not org-use-property-inheritance) nil)
2673 ((stringp org-use-property-inheritance)
2674 (string-match org-use-property-inheritance property))
2675 ((listp org-use-property-inheritance)
2676 (member property org-use-property-inheritance))
2677 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2679 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2680 "The default column format, if no other format has been defined.
2681 This variable can be set on the per-file basis by inserting a line
2683 #+COLUMNS: %25ITEM ....."
2684 :group 'org-properties
2685 :type 'string)
2687 (defcustom org-columns-ellipses ".."
2688 "The ellipses to be used when a field in column view is truncated.
2689 When this is the empty string, as many characters as possible are shown,
2690 but then there will be no visual indication that the field has been truncated.
2691 When this is a string of length N, the last N characters of a truncated
2692 field are replaced by this string. If the column is narrower than the
2693 ellipses string, only part of the ellipses string will be shown."
2694 :group 'org-properties
2695 :type 'string)
2697 (defcustom org-columns-modify-value-for-display-function nil
2698 "Function that modifies values for display in column view.
2699 For example, it can be used to cut out a certain part from a time stamp.
2700 The function must take 2 arguments:
2702 column-title The title of the column (*not* the property name)
2703 value The value that should be modified.
2705 The function should return the value that should be displayed,
2706 or nil if the normal value should be used."
2707 :group 'org-properties
2708 :type 'function)
2710 (defcustom org-effort-property "Effort"
2711 "The property that is being used to keep track of effort estimates.
2712 Effort estimates given in this property need to have the format H:MM."
2713 :group 'org-properties
2714 :group 'org-progress
2715 :type '(string :tag "Property"))
2717 (defconst org-global-properties-fixed
2718 '(("VISIBILITY_ALL" . "folded children content all")
2719 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2720 "List of property/value pairs that can be inherited by any entry.
2722 These are fixed values, for the preset properties. The user variable
2723 that can be used to add to this list is `org-global-properties'.
2725 The entries in this list are cons cells where the car is a property
2726 name and cdr is a string with the value. If the value represents
2727 multiple items like an \"_ALL\" property, separate the items by
2728 spaces.")
2730 (defcustom org-global-properties nil
2731 "List of property/value pairs that can be inherited by any entry.
2733 This list will be combined with the constant `org-global-properties-fixed'.
2735 The entries in this list are cons cells where the car is a property
2736 name and cdr is a string with the value.
2738 You can set buffer-local values for the same purpose in the variable
2739 `org-file-properties' this by adding lines like
2741 #+PROPERTY: NAME VALUE"
2742 :group 'org-properties
2743 :type '(repeat
2744 (cons (string :tag "Property")
2745 (string :tag "Value"))))
2747 (defvar org-file-properties nil
2748 "List of property/value pairs that can be inherited by any entry.
2749 Valid for the current buffer.
2750 This variable is populated from #+PROPERTY lines.")
2751 (make-variable-buffer-local 'org-file-properties)
2753 (defgroup org-agenda nil
2754 "Options concerning agenda views in Org-mode."
2755 :tag "Org Agenda"
2756 :group 'org)
2758 (defvar org-category nil
2759 "Variable used by org files to set a category for agenda display.
2760 Such files should use a file variable to set it, for example
2762 # -*- mode: org; org-category: \"ELisp\"
2764 or contain a special line
2766 #+CATEGORY: ELisp
2768 If the file does not specify a category, then file's base name
2769 is used instead.")
2770 (make-variable-buffer-local 'org-category)
2771 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2773 (defcustom org-agenda-files nil
2774 "The files to be used for agenda display.
2775 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2776 \\[org-remove-file]. You can also use customize to edit the list.
2778 If an entry is a directory, all files in that directory that are matched by
2779 `org-agenda-file-regexp' will be part of the file list.
2781 If the value of the variable is not a list but a single file name, then
2782 the list of agenda files is actually stored and maintained in that file, one
2783 agenda file per line. In this file paths can be given relative to
2784 `org-directory'. Tilde expansion and environment variable substitution
2785 are also made."
2786 :group 'org-agenda
2787 :type '(choice
2788 (repeat :tag "List of files and directories" file)
2789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2792 "Regular expression to match files for `org-agenda-files'.
2793 If any element in the list in that variable contains a directory instead
2794 of a normal file, all files in that directory that are matched by this
2795 regular expression will be included."
2796 :group 'org-agenda
2797 :type 'regexp)
2799 (defcustom org-agenda-text-search-extra-files nil
2800 "List of extra files to be searched by text search commands.
2801 These files will be search in addition to the agenda files by the
2802 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2803 Note that these files will only be searched for text search commands,
2804 not for the other agenda views like todo lists, tag searches or the weekly
2805 agenda. This variable is intended to list notes and possibly archive files
2806 that should also be searched by these two commands.
2807 In fact, if the first element in the list is the symbol `agenda-archives',
2808 than all archive files of all agenda files will be added to the search
2809 scope."
2810 :group 'org-agenda
2811 :type '(set :greedy t
2812 (const :tag "Agenda Archives" agenda-archives)
2813 (repeat :inline t (file))))
2815 (if (fboundp 'defvaralias)
2816 (defvaralias 'org-agenda-multi-occur-extra-files
2817 'org-agenda-text-search-extra-files))
2819 (defcustom org-agenda-skip-unavailable-files nil
2820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2821 A nil value means to remove them, after a query, from the list."
2822 :group 'org-agenda
2823 :type 'boolean)
2825 (defcustom org-calendar-to-agenda-key [?c]
2826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2827 The command `org-calendar-goto-agenda' will be bound to this key. The
2828 default is the character `c' because then `c' can be used to switch back and
2829 forth between agenda and calendar."
2830 :group 'org-agenda
2831 :type 'sexp)
2833 (defcustom org-calendar-agenda-action-key [?k]
2834 "The key to be installed in `calendar-mode-map' for agenda-action.
2835 The command `org-agenda-action' will be bound to this key. The
2836 default is the character `k' because we use the same key in the agenda."
2837 :group 'org-agenda
2838 :type 'sexp)
2840 (defcustom org-calendar-insert-diary-entry-key [?i]
2841 "The key to be installed in `calendar-mode-map' for adding diary entries.
2842 This option is irrelevant until `org-agenda-diary-file' has been configured
2843 to point to an Org-mode file. When that is the case, the command
2844 `org-agenda-diary-entry' will be bound to the key given here, by default
2845 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2846 if you want to continue doing this, you need to change this to a different
2847 key."
2848 :group 'org-agenda
2849 :type 'sexp)
2851 (defcustom org-agenda-diary-file 'diary-file
2852 "File to which to add new entries with the `i' key in agenda and calendar.
2853 When this is the symbol `diary-file', the functionality in the Emacs
2854 calendar will be used to add entries to the `diary-file'. But when this
2855 points to a file, `org-agenda-diary-entry' will be used instead."
2856 :group 'org-agenda
2857 :type '(choice
2858 (const :tag "The standard Emacs diary file" diary-file)
2859 (file :tag "Special Org file diary entries")))
2861 (eval-after-load "calendar"
2862 '(progn
2863 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2864 'org-calendar-goto-agenda)
2865 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2866 'org-agenda-action)
2867 (add-hook 'calendar-mode-hook
2868 (lambda ()
2869 (unless (eq org-agenda-diary-file 'diary-file)
2870 (define-key calendar-mode-map
2871 org-calendar-insert-diary-entry-key
2872 'org-agenda-diary-entry))))))
2874 (defgroup org-latex nil
2875 "Options for embedding LaTeX code into Org-mode."
2876 :tag "Org LaTeX"
2877 :group 'org)
2879 (defcustom org-format-latex-options
2880 '(:foreground default :background default :scale 1.0
2881 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2882 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2883 "Options for creating images from LaTeX fragments.
2884 This is a property list with the following properties:
2885 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2886 `default' means use the foreground of the default face.
2887 :background the background color, or \"Transparent\".
2888 `default' means use the background of the default face.
2889 :scale a scaling factor for the size of the images.
2890 :html-foreground, :html-background, :html-scale
2891 the same numbers for HTML export.
2892 :matchers a list indicating which matchers should be used to
2893 find LaTeX fragments. Valid members of this list are:
2894 \"begin\" find environments
2895 \"$1\" find single characters surrounded by $.$
2896 \"$\" find math expressions surrounded by $...$
2897 \"$$\" find math expressions surrounded by $$....$$
2898 \"\\(\" find math expressions surrounded by \\(...\\)
2899 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2900 :group 'org-latex
2901 :type 'plist)
2903 (defcustom org-format-latex-signal-error t
2904 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2905 When nil, just push out a message."
2906 :group 'org-latex
2907 :type 'boolean)
2909 (defcustom org-format-latex-header "\\documentclass{article}
2910 \\usepackage[usenames]{color}
2911 \\usepackage{amsmath}
2912 \\usepackage[mathscr]{eucal}
2913 \\pagestyle{empty} % do not remove
2914 % The settings below are copied from fullpage.sty
2915 \\setlength{\\textwidth}{\\paperwidth}
2916 \\addtolength{\\textwidth}{-3cm}
2917 \\setlength{\\oddsidemargin}{1.5cm}
2918 \\addtolength{\\oddsidemargin}{-2.54cm}
2919 \\setlength{\\evensidemargin}{\\oddsidemargin}
2920 \\setlength{\\textheight}{\\paperheight}
2921 \\addtolength{\\textheight}{-\\headheight}
2922 \\addtolength{\\textheight}{-\\headsep}
2923 \\addtolength{\\textheight}{-\\footskip}
2924 \\addtolength{\\textheight}{-3cm}
2925 \\setlength{\\topmargin}{1.5cm}
2926 \\addtolength{\\topmargin}{-2.54cm}"
2927 "The document header used for processing LaTeX fragments.
2928 It is imperative that this header make sure that no page number
2929 appears on the page. The package defined in the variables
2930 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
2931 will either replace the placeholder \"[PACKAGES]\" in this header, or they
2932 will be appended."
2933 :group 'org-latex
2934 :type 'string)
2936 (defvar org-format-latex-header-extra nil)
2938 ;; The following variables are defined here because is it also used
2939 ;; when formatting latex fragments. Originally it was part of the
2940 ;; LaTeX exporter, which is why the name includes "export".
2941 (defcustom org-export-latex-default-packages-alist
2942 '(("AUTO" "inputenc")
2943 ("T1" "fontenc")
2944 ("" "graphicx")
2945 ("" "longtable")
2946 ("" "float")
2947 ("" "wrapfig")
2948 ("" "soul")
2949 ("" "t1enc")
2950 ("" "textcomp")
2951 ("" "marvosym")
2952 ("" "wasysym")
2953 ("" "latexsym")
2954 ("" "amssymb")
2955 ("" "hyperref"))
2956 "Alist of default packages to be inserted in the header.
2957 Change this only if one of the packages here causes an incompatibility
2958 with another package you are using.
2959 The packages in this list are needed by one part or another of Org-mode
2960 to function properly.
2962 - inputenc, fontenc, t1enc: for basic font and character selection
2963 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
2964 for interpreting the entities in `org-entities'. You can skip some of these
2965 packages if you don't use any of the symbols in it.
2966 - graphicx: for including images
2967 - float, wrapfig: for figure placement
2968 - longtable: for long tables
2969 - hyperref: for cross references
2971 Therefore you should not modify this variable unless you know what you
2972 are doing. The one reason to change it anyway is that you might be loading
2973 some other package that conflicts with one of the default packages.
2974 Each cell is of the format \( \"options\" \"package\" \)."
2975 :group 'org-export-latex
2976 :type '(repeat
2977 (list
2978 (string :tag "options")
2979 (string :tag "package"))))
2981 (defcustom org-export-latex-packages-alist nil
2982 "Alist of packages to be inserted in every LaTeX the header.
2983 These will be inserted after `org-export-latex-default-packages-alist'.
2984 Each cell is of the format \( \"options\" \"package\" \).
2985 Make sure that you only lis packages here which:
2986 - you want in every file
2987 - do not conflict with the default packages in
2988 `org-export-latex-default-packages-alist'
2989 - do not conflict with the setup in `org-format-latex-header'."
2990 :group 'org-export-latex
2991 :type '(repeat
2992 (list
2993 (string :tag "options")
2994 (string :tag "package"))))
2996 (defgroup org-appearance nil
2997 "Settings for Org-mode appearance."
2998 :tag "Org Appearance"
2999 :group 'org)
3001 (defcustom org-level-color-stars-only nil
3002 "Non-nil means fontify only the stars in each headline.
3003 When nil, the entire headline is fontified.
3004 Changing it requires restart of `font-lock-mode' to become effective
3005 also in regions already fontified."
3006 :group 'org-appearance
3007 :type 'boolean)
3009 (defcustom org-hide-leading-stars nil
3010 "Non-nil means hide the first N-1 stars in a headline.
3011 This works by using the face `org-hide' for these stars. This
3012 face is white for a light background, and black for a dark
3013 background. You may have to customize the face `org-hide' to
3014 make this work.
3015 Changing it requires restart of `font-lock-mode' to become effective
3016 also in regions already fontified.
3017 You may also set this on a per-file basis by adding one of the following
3018 lines to the buffer:
3020 #+STARTUP: hidestars
3021 #+STARTUP: showstars"
3022 :group 'org-appearance
3023 :type 'boolean)
3025 (defcustom org-hidden-keywords nil
3026 "List of keywords that should be hidden when typed in the org buffer.
3027 For example, add #+TITLE to this list in order to make the
3028 document title appear in the buffer without the initial #+TITLE:
3029 keyword."
3030 :group 'org-appearance
3031 :type '(set (const :tag "#+AUTHOR" author)
3032 (const :tag "#+DATE" date)
3033 (const :tag "#+EMAIL" email)
3034 (const :tag "#+TITLE" title)))
3036 (defcustom org-fontify-done-headline nil
3037 "Non-nil means change the face of a headline if it is marked DONE.
3038 Normally, only the TODO/DONE keyword indicates the state of a headline.
3039 When this is non-nil, the headline after the keyword is set to the
3040 `org-headline-done' as an additional indication."
3041 :group 'org-appearance
3042 :type 'boolean)
3044 (defcustom org-fontify-emphasized-text t
3045 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3046 Changing this variable requires a restart of Emacs to take effect."
3047 :group 'org-appearance
3048 :type 'boolean)
3050 (defcustom org-fontify-whole-heading-line nil
3051 "Non-nil means fontify the whole line for headings.
3052 This is useful when setting a background color for the
3053 org-level-* faces."
3054 :group 'org-appearance
3055 :type 'boolean)
3057 (defcustom org-highlight-latex-fragments-and-specials nil
3058 "Non-nil means fontify what is treated specially by the exporters."
3059 :group 'org-appearance
3060 :type 'boolean)
3062 (defcustom org-hide-emphasis-markers nil
3063 "Non-nil mean font-lock should hide the emphasis marker characters."
3064 :group 'org-appearance
3065 :type 'boolean)
3067 (defvar org-emph-re nil
3068 "Regular expression for matching emphasis.")
3069 (defvar org-verbatim-re nil
3070 "Regular expression for matching verbatim text.")
3071 (defvar org-emphasis-regexp-components) ; defined just below
3072 (defvar org-emphasis-alist) ; defined just below
3073 (defun org-set-emph-re (var val)
3074 "Set variable and compute the emphasis regular expression."
3075 (set var val)
3076 (when (and (boundp 'org-emphasis-alist)
3077 (boundp 'org-emphasis-regexp-components)
3078 org-emphasis-alist org-emphasis-regexp-components)
3079 (let* ((e org-emphasis-regexp-components)
3080 (pre (car e))
3081 (post (nth 1 e))
3082 (border (nth 2 e))
3083 (body (nth 3 e))
3084 (nl (nth 4 e))
3085 (body1 (concat body "*?"))
3086 (markers (mapconcat 'car org-emphasis-alist ""))
3087 (vmarkers (mapconcat
3088 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3089 org-emphasis-alist "")))
3090 ;; make sure special characters appear at the right position in the class
3091 (if (string-match "\\^" markers)
3092 (setq markers (concat (replace-match "" t t markers) "^")))
3093 (if (string-match "-" markers)
3094 (setq markers (concat (replace-match "" t t markers) "-")))
3095 (if (string-match "\\^" vmarkers)
3096 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3097 (if (string-match "-" vmarkers)
3098 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3099 (if (> nl 0)
3100 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3101 (int-to-string nl) "\\}")))
3102 ;; Make the regexp
3103 (setq org-emph-re
3104 (concat "\\([" pre "]\\|^\\)"
3105 "\\("
3106 "\\([" markers "]\\)"
3107 "\\("
3108 "[^" border "]\\|"
3109 "[^" border "]"
3110 body1
3111 "[^" border "]"
3112 "\\)"
3113 "\\3\\)"
3114 "\\([" post "]\\|$\\)"))
3115 (setq org-verbatim-re
3116 (concat "\\([" pre "]\\|^\\)"
3117 "\\("
3118 "\\([" vmarkers "]\\)"
3119 "\\("
3120 "[^" border "]\\|"
3121 "[^" border "]"
3122 body1
3123 "[^" border "]"
3124 "\\)"
3125 "\\3\\)"
3126 "\\([" post "]\\|$\\)")))))
3128 (defcustom org-emphasis-regexp-components
3129 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3130 "Components used to build the regular expression for emphasis.
3131 This is a list with 6 entries. Terminology: In an emphasis string
3132 like \" *strong word* \", we call the initial space PREMATCH, the final
3133 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3134 and \"trong wor\" is the body. The different components in this variable
3135 specify what is allowed/forbidden in each part:
3137 pre Chars allowed as prematch. Beginning of line will be allowed too.
3138 post Chars allowed as postmatch. End of line will be allowed too.
3139 border The chars *forbidden* as border characters.
3140 body-regexp A regexp like \".\" to match a body character. Don't use
3141 non-shy groups here, and don't allow newline here.
3142 newline The maximum number of newlines allowed in an emphasis exp.
3144 Use customize to modify this, or restart Emacs after changing it."
3145 :group 'org-appearance
3146 :set 'org-set-emph-re
3147 :type '(list
3148 (sexp :tag "Allowed chars in pre ")
3149 (sexp :tag "Allowed chars in post ")
3150 (sexp :tag "Forbidden chars in border ")
3151 (sexp :tag "Regexp for body ")
3152 (integer :tag "number of newlines allowed")
3153 (option (boolean :tag "Please ignore this button"))))
3155 (defcustom org-emphasis-alist
3156 `(("*" bold "<b>" "</b>")
3157 ("/" italic "<i>" "</i>")
3158 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3159 ("=" org-code "<code>" "</code>" verbatim)
3160 ("~" org-verbatim "<code>" "</code>" verbatim)
3161 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3162 "<del>" "</del>")
3164 "Special syntax for emphasized text.
3165 Text starting and ending with a special character will be emphasized, for
3166 example *bold*, _underlined_ and /italic/. This variable sets the marker
3167 characters, the face to be used by font-lock for highlighting in Org-mode
3168 Emacs buffers, and the HTML tags to be used for this.
3169 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3170 Use customize to modify this, or restart Emacs after changing it."
3171 :group 'org-appearance
3172 :set 'org-set-emph-re
3173 :type '(repeat
3174 (list
3175 (string :tag "Marker character")
3176 (choice
3177 (face :tag "Font-lock-face")
3178 (plist :tag "Face property list"))
3179 (string :tag "HTML start tag")
3180 (string :tag "HTML end tag")
3181 (option (const verbatim)))))
3183 (defvar org-protecting-blocks
3184 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3185 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3186 This is needed for font-lock setup.")
3188 ;;; Miscellaneous options
3190 (defgroup org-completion nil
3191 "Completion in Org-mode."
3192 :tag "Org Completion"
3193 :group 'org)
3195 (defcustom org-completion-use-ido nil
3196 "Non-nil means use ido completion wherever possible.
3197 Note that `ido-mode' must be active for this variable to be relevant.
3198 If you decide to turn this variable on, you might well want to turn off
3199 `org-outline-path-complete-in-steps'.
3200 See also `org-completion-use-iswitchb'."
3201 :group 'org-completion
3202 :type 'boolean)
3204 (defcustom org-completion-use-iswitchb nil
3205 "Non-nil means use iswitchb completion wherever possible.
3206 Note that `iswitchb-mode' must be active for this variable to be relevant.
3207 If you decide to turn this variable on, you might well want to turn off
3208 `org-outline-path-complete-in-steps'.
3209 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3210 :group 'org-completion
3211 :type 'boolean)
3213 (defcustom org-completion-fallback-command 'hippie-expand
3214 "The expansion command called by \\[org-complete] in normal context.
3215 Normal means no org-mode-specific context."
3216 :group 'org-completion
3217 :type 'function)
3219 ;;; Functions and variables from their packages
3220 ;; Declared here to avoid compiler warnings
3222 ;; XEmacs only
3223 (defvar outline-mode-menu-heading)
3224 (defvar outline-mode-menu-show)
3225 (defvar outline-mode-menu-hide)
3226 (defvar zmacs-regions) ; XEmacs regions
3228 ;; Emacs only
3229 (defvar mark-active)
3231 ;; Various packages
3232 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3233 (declare-function calendar-forward-day "cal-move" (arg))
3234 (declare-function calendar-goto-date "cal-move" (date))
3235 (declare-function calendar-goto-today "cal-move" ())
3236 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3237 (defvar calc-embedded-close-formula)
3238 (defvar calc-embedded-open-formula)
3239 (declare-function cdlatex-tab "ext:cdlatex" ())
3240 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3241 (defvar font-lock-unfontify-region-function)
3242 (declare-function iswitchb-read-buffer "iswitchb"
3243 (prompt &optional default require-match start matches-set))
3244 (defvar iswitchb-temp-buflist)
3245 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3246 (defvar org-agenda-tags-todo-honor-ignore-options)
3247 (declare-function org-agenda-skip "org-agenda" ())
3248 (declare-function
3249 org-format-agenda-item "org-agenda"
3250 (extra txt &optional category tags dotime noprefix remove-re habitp))
3251 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3252 (declare-function org-agenda-change-all-lines "org-agenda"
3253 (newhead hdmarker &optional fixface just-this))
3254 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3255 (declare-function org-agenda-maybe-redo "org-agenda" ())
3256 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3257 (beg end))
3258 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3259 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3260 "org-agenda" (&optional end))
3261 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3262 (declare-function org-indent-mode "org-indent" (&optional arg))
3263 (declare-function parse-time-string "parse-time" (string))
3264 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3265 (defvar remember-data-file)
3266 (defvar texmathp-why)
3267 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3268 (declare-function table--at-cell-p "table" (position &optional object at-column))
3270 (defvar w3m-current-url)
3271 (defvar w3m-current-title)
3273 (defvar org-latex-regexps)
3275 ;;; Autoload and prepare some org modules
3277 ;; Some table stuff that needs to be defined here, because it is used
3278 ;; by the functions setting up org-mode or checking for table context.
3280 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3281 "Detects an org-type or table-type table.")
3282 (defconst org-table-line-regexp "^[ \t]*|"
3283 "Detects an org-type table line.")
3284 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3285 "Detects an org-type table line.")
3286 (defconst org-table-hline-regexp "^[ \t]*|-"
3287 "Detects an org-type table hline.")
3288 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3289 "Detects a table-type table hline.")
3290 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3291 "Searching from within a table (any type) this finds the first line
3292 outside the table.")
3294 ;; Autoload the functions in org-table.el that are needed by functions here.
3296 (eval-and-compile
3297 (org-autoload "org-table"
3298 '(org-table-align org-table-begin org-table-blank-field
3299 org-table-convert org-table-convert-region org-table-copy-down
3300 org-table-copy-region org-table-create
3301 org-table-create-or-convert-from-region
3302 org-table-create-with-table.el org-table-current-dline
3303 org-table-cut-region org-table-delete-column org-table-edit-field
3304 org-table-edit-formulas org-table-end org-table-eval-formula
3305 org-table-export org-table-field-info
3306 org-table-get-stored-formulas org-table-goto-column
3307 org-table-hline-and-move org-table-import org-table-insert-column
3308 org-table-insert-hline org-table-insert-row org-table-iterate
3309 org-table-justify-field-maybe org-table-kill-row
3310 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3311 org-table-move-column org-table-move-column-left
3312 org-table-move-column-right org-table-move-row
3313 org-table-move-row-down org-table-move-row-up
3314 org-table-next-field org-table-next-row org-table-paste-rectangle
3315 org-table-previous-field org-table-recalculate
3316 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3317 org-table-toggle-coordinate-overlays
3318 org-table-toggle-formula-debugger org-table-wrap-region
3319 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3321 (defun org-at-table-p (&optional table-type)
3322 "Return t if the cursor is inside an org-type table.
3323 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3324 (if org-enable-table-editor
3325 (save-excursion
3326 (beginning-of-line 1)
3327 (looking-at (if table-type org-table-any-line-regexp
3328 org-table-line-regexp)))
3329 nil))
3330 (defsubst org-table-p () (org-at-table-p))
3332 (defun org-at-table.el-p ()
3333 "Return t if and only if we are at a table.el table."
3334 (and (org-at-table-p 'any)
3335 (save-excursion
3336 (goto-char (org-table-begin 'any))
3337 (looking-at org-table1-hline-regexp))))
3338 (defun org-table-recognize-table.el ()
3339 "If there is a table.el table nearby, recognize it and move into it."
3340 (if org-table-tab-recognizes-table.el
3341 (if (org-at-table.el-p)
3342 (progn
3343 (beginning-of-line 1)
3344 (if (looking-at org-table-dataline-regexp)
3346 (if (looking-at org-table1-hline-regexp)
3347 (progn
3348 (beginning-of-line 2)
3349 (if (looking-at org-table-any-border-regexp)
3350 (beginning-of-line -1)))))
3351 (if (re-search-forward "|" (org-table-end t) t)
3352 (progn
3353 (require 'table)
3354 (if (table--at-cell-p (point))
3356 (message "recognizing table.el table...")
3357 (table-recognize-table)
3358 (message "recognizing table.el table...done")))
3359 (error "This should not happen..."))
3361 nil)
3362 nil))
3364 (defun org-at-table-hline-p ()
3365 "Return t if the cursor is inside a hline in a table."
3366 (if org-enable-table-editor
3367 (save-excursion
3368 (beginning-of-line 1)
3369 (looking-at org-table-hline-regexp))
3370 nil))
3372 (defvar org-table-clean-did-remove-column nil)
3374 (defun org-table-map-tables (function)
3375 "Apply FUNCTION to the start of all tables in the buffer."
3376 (save-excursion
3377 (save-restriction
3378 (widen)
3379 (goto-char (point-min))
3380 (while (re-search-forward org-table-any-line-regexp nil t)
3381 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3382 (beginning-of-line 1)
3383 (when (looking-at org-table-line-regexp)
3384 (save-excursion (funcall function))
3385 (or (looking-at org-table-line-regexp)
3386 (forward-char 1)))
3387 (re-search-forward org-table-any-border-regexp nil 1))))
3388 (message "Mapping tables: done"))
3390 ;; Declare and autoload functions from org-exp.el & Co
3392 (declare-function org-default-export-plist "org-exp")
3393 (declare-function org-infile-export-plist "org-exp")
3394 (declare-function org-get-current-options "org-exp")
3395 (eval-and-compile
3396 (org-autoload "org-exp"
3397 '(org-export org-export-visible
3398 org-insert-export-options-template
3399 org-table-clean-before-export))
3400 (org-autoload "org-ascii"
3401 '(org-export-as-ascii org-export-ascii-preprocess
3402 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3403 org-export-region-as-ascii))
3404 (org-autoload "org-latex"
3405 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3406 org-replace-region-by-latex org-export-region-as-latex
3407 org-export-as-latex org-export-as-pdf
3408 org-export-as-pdf-and-open))
3409 (org-autoload "org-html"
3410 '(org-export-as-html-and-open
3411 org-export-as-html-batch org-export-as-html-to-buffer
3412 org-replace-region-by-html org-export-region-as-html
3413 org-export-as-html))
3414 (org-autoload "org-docbook"
3415 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3416 org-replace-region-by-docbook org-export-region-as-docbook
3417 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3418 org-export-as-docbook))
3419 (org-autoload "org-icalendar"
3420 '(org-export-icalendar-this-file
3421 org-export-icalendar-all-agenda-files
3422 org-export-icalendar-combine-agenda-files))
3423 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3424 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3426 ;; Declare and autoload functions from org-agenda.el
3428 (eval-and-compile
3429 (org-autoload "org-agenda"
3430 '(org-agenda org-agenda-list org-search-view
3431 org-todo-list org-tags-view org-agenda-list-stuck-projects
3432 org-diary org-agenda-to-appt
3433 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3435 ;; Autoload org-remember
3437 (eval-and-compile
3438 (org-autoload "org-remember"
3439 '(org-remember-insinuate org-remember-annotation
3440 org-remember-apply-template org-remember org-remember-handler)))
3442 ;; Autoload org-clock.el
3445 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3446 (beg end))
3447 (declare-function org-clock-update-mode-line "org-clock" ())
3448 (declare-function org-resolve-clocks "org-clock"
3449 (&optional also-non-dangling-p prompt last-valid))
3450 (defvar org-clock-start-time)
3451 (defvar org-clock-marker (make-marker)
3452 "Marker recording the last clock-in.")
3453 (defvar org-clock-hd-marker (make-marker)
3454 "Marker recording the last clock-in, but the headline position.")
3455 (defvar org-clock-heading ""
3456 "The heading of the current clock entry.")
3457 (defun org-clock-is-active ()
3458 "Return non-nil if clock is currently running.
3459 The return value is actually the clock marker."
3460 (marker-buffer org-clock-marker))
3462 (eval-and-compile
3463 (org-autoload
3464 "org-clock"
3465 '(org-clock-in org-clock-out org-clock-cancel
3466 org-clock-goto org-clock-sum org-clock-display
3467 org-clock-remove-overlays org-clock-report
3468 org-clocktable-shift org-dblock-write:clocktable
3469 org-get-clocktable org-resolve-clocks)))
3471 (defun org-clock-update-time-maybe ()
3472 "If this is a CLOCK line, update it and return t.
3473 Otherwise, return nil."
3474 (interactive)
3475 (save-excursion
3476 (beginning-of-line 1)
3477 (skip-chars-forward " \t")
3478 (when (looking-at org-clock-string)
3479 (let ((re (concat "[ \t]*" org-clock-string
3480 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3481 "\\([ \t]*=>.*\\)?\\)?"))
3482 ts te h m s neg)
3483 (cond
3484 ((not (looking-at re))
3485 nil)
3486 ((not (match-end 2))
3487 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3488 (> org-clock-marker (point))
3489 (<= org-clock-marker (point-at-eol)))
3490 ;; The clock is running here
3491 (setq org-clock-start-time
3492 (apply 'encode-time
3493 (org-parse-time-string (match-string 1))))
3494 (org-clock-update-mode-line)))
3496 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3497 (end-of-line 1)
3498 (setq ts (match-string 1)
3499 te (match-string 3))
3500 (setq s (- (org-float-time
3501 (apply 'encode-time (org-parse-time-string te)))
3502 (org-float-time
3503 (apply 'encode-time (org-parse-time-string ts))))
3504 neg (< s 0)
3505 s (abs s)
3506 h (floor (/ s 3600))
3507 s (- s (* 3600 h))
3508 m (floor (/ s 60))
3509 s (- s (* 60 s)))
3510 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3511 t))))))
3513 (defun org-check-running-clock ()
3514 "Check if the current buffer contains the running clock.
3515 If yes, offer to stop it and to save the buffer with the changes."
3516 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3517 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3518 (buffer-name))))
3519 (org-clock-out)
3520 (when (y-or-n-p "Save changed buffer?")
3521 (save-buffer))))
3523 (defun org-clocktable-try-shift (dir n)
3524 "Check if this line starts a clock table, if yes, shift the time block."
3525 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3526 (org-clocktable-shift dir n)))
3528 ;; Autoload org-timer.el
3530 (eval-and-compile
3531 (org-autoload
3532 "org-timer"
3533 '(org-timer-start org-timer org-timer-item
3534 org-timer-change-times-in-region
3535 org-timer-set-timer
3536 org-timer-reset-timers
3537 org-timer-show-remaining-time)))
3539 ;; Autoload org-feed.el
3541 (eval-and-compile
3542 (org-autoload
3543 "org-feed"
3544 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3547 ;; Autoload org-indent.el
3549 ;; Define the variable already here, to make sure we have it.
3550 (defvar org-indent-mode nil
3551 "Non-nil if Org-Indent mode is enabled.
3552 Use the command `org-indent-mode' to change this variable.")
3554 (eval-and-compile
3555 (org-autoload
3556 "org-indent"
3557 '(org-indent-mode)))
3559 ;; Autoload org-mobile.el
3561 (eval-and-compile
3562 (org-autoload
3563 "org-mobile"
3564 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3566 ;; Autoload archiving code
3567 ;; The stuff that is needed for cycling and tags has to be defined here.
3569 (defgroup org-archive nil
3570 "Options concerning archiving in Org-mode."
3571 :tag "Org Archive"
3572 :group 'org-structure)
3574 (defcustom org-archive-location "%s_archive::"
3575 "The location where subtrees should be archived.
3577 The value of this variable is a string, consisting of two parts,
3578 separated by a double-colon. The first part is a filename and
3579 the second part is a headline.
3581 When the filename is omitted, archiving happens in the same file.
3582 %s in the filename will be replaced by the current file
3583 name (without the directory part). Archiving to a different file
3584 is useful to keep archived entries from contributing to the
3585 Org-mode Agenda.
3587 The archived entries will be filed as subtrees of the specified
3588 headline. When the headline is omitted, the subtrees are simply
3589 filed away at the end of the file, as top-level entries. Also in
3590 the heading you can use %s to represent the file name, this can be
3591 useful when using the same archive for a number of different files.
3593 Here are a few examples:
3594 \"%s_archive::\"
3595 If the current file is Projects.org, archive in file
3596 Projects.org_archive, as top-level trees. This is the default.
3598 \"::* Archived Tasks\"
3599 Archive in the current file, under the top-level headline
3600 \"* Archived Tasks\".
3602 \"~/org/archive.org::\"
3603 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3605 \"~/org/archive.org::From %s\"
3606 Archive in file ~/org/archive.org (absolute path), under headlines
3607 \"From FILENAME\" where file name is the current file name.
3609 \"basement::** Finished Tasks\"
3610 Archive in file ./basement (relative path), as level 3 trees
3611 below the level 2 heading \"** Finished Tasks\".
3613 You may set this option on a per-file basis by adding to the buffer a
3614 line like
3616 #+ARCHIVE: basement::** Finished Tasks
3618 You may also define it locally for a subtree by setting an ARCHIVE property
3619 in the entry. If such a property is found in an entry, or anywhere up
3620 the hierarchy, it will be used."
3621 :group 'org-archive
3622 :type 'string)
3624 (defcustom org-archive-tag "ARCHIVE"
3625 "The tag that marks a subtree as archived.
3626 An archived subtree does not open during visibility cycling, and does
3627 not contribute to the agenda listings.
3628 After changing this, font-lock must be restarted in the relevant buffers to
3629 get the proper fontification."
3630 :group 'org-archive
3631 :group 'org-keywords
3632 :type 'string)
3634 (defcustom org-agenda-skip-archived-trees t
3635 "Non-nil means the agenda will skip any items located in archived trees.
3636 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3637 variable is no longer recommended, you should leave it at the value t.
3638 Instead, use the key `v' to cycle the archives-mode in the agenda."
3639 :group 'org-archive
3640 :group 'org-agenda-skip
3641 :type 'boolean)
3643 (defcustom org-columns-skip-archived-trees t
3644 "Non-nil means ignore archived trees when creating column view."
3645 :group 'org-archive
3646 :group 'org-properties
3647 :type 'boolean)
3649 (defcustom org-cycle-open-archived-trees nil
3650 "Non-nil means `org-cycle' will open archived trees.
3651 An archived tree is a tree marked with the tag ARCHIVE.
3652 When nil, archived trees will stay folded. You can still open them with
3653 normal outline commands like `show-all', but not with the cycling commands."
3654 :group 'org-archive
3655 :group 'org-cycle
3656 :type 'boolean)
3658 (defcustom org-sparse-tree-open-archived-trees nil
3659 "Non-nil means sparse tree construction shows matches in archived trees.
3660 When nil, matches in these trees are highlighted, but the trees are kept in
3661 collapsed state."
3662 :group 'org-archive
3663 :group 'org-sparse-trees
3664 :type 'boolean)
3666 (defun org-cycle-hide-archived-subtrees (state)
3667 "Re-hide all archived subtrees after a visibility state change."
3668 (when (and (not org-cycle-open-archived-trees)
3669 (not (memq state '(overview folded))))
3670 (save-excursion
3671 (let* ((globalp (memq state '(contents all)))
3672 (beg (if globalp (point-min) (point)))
3673 (end (if globalp (point-max) (org-end-of-subtree t))))
3674 (org-hide-archived-subtrees beg end)
3675 (goto-char beg)
3676 (if (looking-at (concat ".*:" org-archive-tag ":"))
3677 (message "%s" (substitute-command-keys
3678 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3680 (defun org-force-cycle-archived ()
3681 "Cycle subtree even if it is archived."
3682 (interactive)
3683 (setq this-command 'org-cycle)
3684 (let ((org-cycle-open-archived-trees t))
3685 (call-interactively 'org-cycle)))
3687 (defun org-hide-archived-subtrees (beg end)
3688 "Re-hide all archived subtrees after a visibility state change."
3689 (save-excursion
3690 (let* ((re (concat ":" org-archive-tag ":")))
3691 (goto-char beg)
3692 (while (re-search-forward re end t)
3693 (when (org-on-heading-p)
3694 (org-flag-subtree t)
3695 (org-end-of-subtree t))))))
3697 (defun org-flag-subtree (flag)
3698 (save-excursion
3699 (org-back-to-heading t)
3700 (outline-end-of-heading)
3701 (outline-flag-region (point)
3702 (progn (org-end-of-subtree t) (point))
3703 flag)))
3705 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3707 (eval-and-compile
3708 (org-autoload "org-archive"
3709 '(org-add-archive-files org-archive-subtree
3710 org-archive-to-archive-sibling org-toggle-archive-tag
3711 org-archive-subtree-default
3712 org-archive-subtree-default-with-confirmation)))
3714 ;; Autoload Column View Code
3716 (declare-function org-columns-number-to-string "org-colview")
3717 (declare-function org-columns-get-format-and-top-level "org-colview")
3718 (declare-function org-columns-compute "org-colview")
3720 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3721 '(org-columns-number-to-string org-columns-get-format-and-top-level
3722 org-columns-compute org-agenda-columns org-columns-remove-overlays
3723 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3725 ;; Autoload ID code
3727 (declare-function org-id-store-link "org-id")
3728 (declare-function org-id-locations-load "org-id")
3729 (declare-function org-id-locations-save "org-id")
3730 (defvar org-id-track-globally)
3731 (org-autoload "org-id"
3732 '(org-id-get-create org-id-new org-id-copy org-id-get
3733 org-id-get-with-outline-path-completion
3734 org-id-get-with-outline-drilling
3735 org-id-goto org-id-find org-id-store-link))
3737 ;; Autoload Plotting Code
3739 (org-autoload "org-plot"
3740 '(org-plot/gnuplot))
3742 ;;; Variables for pre-computed regular expressions, all buffer local
3744 (defvar org-drawer-regexp nil
3745 "Matches first line of a hidden block.")
3746 (make-variable-buffer-local 'org-drawer-regexp)
3747 (defvar org-todo-regexp nil
3748 "Matches any of the TODO state keywords.")
3749 (make-variable-buffer-local 'org-todo-regexp)
3750 (defvar org-not-done-regexp nil
3751 "Matches any of the TODO state keywords except the last one.")
3752 (make-variable-buffer-local 'org-not-done-regexp)
3753 (defvar org-not-done-heading-regexp nil
3754 "Matches a TODO headline that is not done.")
3755 (make-variable-buffer-local 'org-not-done-regexp)
3756 (defvar org-todo-line-regexp nil
3757 "Matches a headline and puts TODO state into group 2 if present.")
3758 (make-variable-buffer-local 'org-todo-line-regexp)
3759 (defvar org-complex-heading-regexp nil
3760 "Matches a headline and puts everything into groups:
3761 group 1: the stars
3762 group 2: The todo keyword, maybe
3763 group 3: Priority cookie
3764 group 4: True headline
3765 group 5: Tags")
3766 (make-variable-buffer-local 'org-complex-heading-regexp)
3767 (defvar org-complex-heading-regexp-format nil)
3768 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3769 (defvar org-todo-line-tags-regexp nil
3770 "Matches a headline and puts TODO state into group 2 if present.
3771 Also put tags into group 4 if tags are present.")
3772 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3773 (defvar org-nl-done-regexp nil
3774 "Matches newline followed by a headline with the DONE keyword.")
3775 (make-variable-buffer-local 'org-nl-done-regexp)
3776 (defvar org-looking-at-done-regexp nil
3777 "Matches the DONE keyword a point.")
3778 (make-variable-buffer-local 'org-looking-at-done-regexp)
3779 (defvar org-ds-keyword-length 12
3780 "Maximum length of the Deadline and SCHEDULED keywords.")
3781 (make-variable-buffer-local 'org-ds-keyword-length)
3782 (defvar org-deadline-regexp nil
3783 "Matches the DEADLINE keyword.")
3784 (make-variable-buffer-local 'org-deadline-regexp)
3785 (defvar org-deadline-time-regexp nil
3786 "Matches the DEADLINE keyword together with a time stamp.")
3787 (make-variable-buffer-local 'org-deadline-time-regexp)
3788 (defvar org-deadline-line-regexp nil
3789 "Matches the DEADLINE keyword and the rest of the line.")
3790 (make-variable-buffer-local 'org-deadline-line-regexp)
3791 (defvar org-scheduled-regexp nil
3792 "Matches the SCHEDULED keyword.")
3793 (make-variable-buffer-local 'org-scheduled-regexp)
3794 (defvar org-scheduled-time-regexp nil
3795 "Matches the SCHEDULED keyword together with a time stamp.")
3796 (make-variable-buffer-local 'org-scheduled-time-regexp)
3797 (defvar org-closed-time-regexp nil
3798 "Matches the CLOSED keyword together with a time stamp.")
3799 (make-variable-buffer-local 'org-closed-time-regexp)
3801 (defvar org-keyword-time-regexp nil
3802 "Matches any of the 4 keywords, together with the time stamp.")
3803 (make-variable-buffer-local 'org-keyword-time-regexp)
3804 (defvar org-keyword-time-not-clock-regexp nil
3805 "Matches any of the 3 keywords, together with the time stamp.")
3806 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3807 (defvar org-maybe-keyword-time-regexp nil
3808 "Matches a timestamp, possibly preceeded by a keyword.")
3809 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3810 (defvar org-planning-or-clock-line-re nil
3811 "Matches a line with planning or clock info.")
3812 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3813 (defvar org-all-time-keywords nil
3814 "List of time keywords.")
3815 (make-variable-buffer-local 'org-all-time-keywords)
3817 (defconst org-plain-time-of-day-regexp
3818 (concat
3819 "\\(\\<[012]?[0-9]"
3820 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3821 "\\(--?"
3822 "\\(\\<[012]?[0-9]"
3823 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3824 "\\)?")
3825 "Regular expression to match a plain time or time range.
3826 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3827 groups carry important information:
3828 0 the full match
3829 1 the first time, range or not
3830 8 the second time, if it is a range.")
3832 (defconst org-plain-time-extension-regexp
3833 (concat
3834 "\\(\\<[012]?[0-9]"
3835 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3836 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3837 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3838 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3839 groups carry important information:
3840 0 the full match
3841 7 hours of duration
3842 9 minutes of duration")
3844 (defconst org-stamp-time-of-day-regexp
3845 (concat
3846 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3847 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3848 "\\(--?"
3849 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3850 "Regular expression to match a timestamp time or time range.
3851 After a match, the following groups carry important information:
3852 0 the full match
3853 1 date plus weekday, for back referencing to make sure both times are on the same day
3854 2 the first time, range or not
3855 4 the second time, if it is a range.")
3857 (defconst org-startup-options
3858 '(("fold" org-startup-folded t)
3859 ("overview" org-startup-folded t)
3860 ("nofold" org-startup-folded nil)
3861 ("showall" org-startup-folded nil)
3862 ("showeverything" org-startup-folded showeverything)
3863 ("content" org-startup-folded content)
3864 ("indent" org-startup-indented t)
3865 ("noindent" org-startup-indented nil)
3866 ("hidestars" org-hide-leading-stars t)
3867 ("showstars" org-hide-leading-stars nil)
3868 ("odd" org-odd-levels-only t)
3869 ("oddeven" org-odd-levels-only nil)
3870 ("align" org-startup-align-all-tables t)
3871 ("noalign" org-startup-align-all-tables nil)
3872 ("customtime" org-display-custom-times t)
3873 ("logdone" org-log-done time)
3874 ("lognotedone" org-log-done note)
3875 ("nologdone" org-log-done nil)
3876 ("lognoteclock-out" org-log-note-clock-out t)
3877 ("nolognoteclock-out" org-log-note-clock-out nil)
3878 ("logrepeat" org-log-repeat state)
3879 ("lognoterepeat" org-log-repeat note)
3880 ("nologrepeat" org-log-repeat nil)
3881 ("logreschedule" org-log-reschedule time)
3882 ("lognotereschedule" org-log-reschedule note)
3883 ("nologreschedule" org-log-reschedule nil)
3884 ("logredeadline" org-log-redeadline time)
3885 ("lognoteredeadline" org-log-redeadline note)
3886 ("nologredeadline" org-log-redeadline nil)
3887 ("logrefile" org-log-refile time)
3888 ("lognoterefile" org-log-refile note)
3889 ("nologrefile" org-log-refile nil)
3890 ("fninline" org-footnote-define-inline t)
3891 ("nofninline" org-footnote-define-inline nil)
3892 ("fnlocal" org-footnote-section nil)
3893 ("fnauto" org-footnote-auto-label t)
3894 ("fnprompt" org-footnote-auto-label nil)
3895 ("fnconfirm" org-footnote-auto-label confirm)
3896 ("fnplain" org-footnote-auto-label plain)
3897 ("fnadjust" org-footnote-auto-adjust t)
3898 ("nofnadjust" org-footnote-auto-adjust nil)
3899 ("constcgs" constants-unit-system cgs)
3900 ("constSI" constants-unit-system SI)
3901 ("noptag" org-tag-persistent-alist nil)
3902 ("hideblocks" org-hide-block-startup t)
3903 ("nohideblocks" org-hide-block-startup nil)
3904 ("beamer" org-startup-with-beamer-mode t))
3905 "Variable associated with STARTUP options for org-mode.
3906 Each element is a list of three items: The startup options as written
3907 in the #+STARTUP line, the corresponding variable, and the value to
3908 set this variable to if the option is found. An optional forth element PUSH
3909 means to push this value onto the list in the variable.")
3911 (defun org-set-regexps-and-options ()
3912 "Precompute regular expressions for current buffer."
3913 (when (org-mode-p)
3914 (org-set-local 'org-todo-kwd-alist nil)
3915 (org-set-local 'org-todo-key-alist nil)
3916 (org-set-local 'org-todo-key-trigger nil)
3917 (org-set-local 'org-todo-keywords-1 nil)
3918 (org-set-local 'org-done-keywords nil)
3919 (org-set-local 'org-todo-heads nil)
3920 (org-set-local 'org-todo-sets nil)
3921 (org-set-local 'org-todo-log-states nil)
3922 (org-set-local 'org-file-properties nil)
3923 (org-set-local 'org-file-tags nil)
3924 (let ((re (org-make-options-regexp
3925 '("CATEGORY" "TODO" "COLUMNS"
3926 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3927 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3928 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3929 (splitre "[ \t]+")
3930 kwds kws0 kwsa key log value cat arch tags const links hw dws
3931 tail sep kws1 prio props ftags drawers beamer-p
3932 ext-setup-or-nil setup-contents (start 0))
3933 (save-excursion
3934 (save-restriction
3935 (widen)
3936 (goto-char (point-min))
3937 (while (or (and ext-setup-or-nil
3938 (string-match re ext-setup-or-nil start)
3939 (setq start (match-end 0)))
3940 (and (setq ext-setup-or-nil nil start 0)
3941 (re-search-forward re nil t)))
3942 (setq key (upcase (match-string 1 ext-setup-or-nil))
3943 value (org-match-string-no-properties 2 ext-setup-or-nil))
3944 (cond
3945 ((equal key "CATEGORY")
3946 (if (string-match "[ \t]+$" value)
3947 (setq value (replace-match "" t t value)))
3948 (setq cat value))
3949 ((member key '("SEQ_TODO" "TODO"))
3950 (push (cons 'sequence (org-split-string value splitre)) kwds))
3951 ((equal key "TYP_TODO")
3952 (push (cons 'type (org-split-string value splitre)) kwds))
3953 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3954 ;; general TODO-like setup
3955 (push (cons (intern (downcase (match-string 1 key)))
3956 (org-split-string value splitre)) kwds))
3957 ((equal key "TAGS")
3958 (setq tags (append tags (if tags '("\\n") nil)
3959 (org-split-string value splitre))))
3960 ((equal key "COLUMNS")
3961 (org-set-local 'org-columns-default-format value))
3962 ((equal key "LINK")
3963 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3964 (push (cons (match-string 1 value)
3965 (org-trim (match-string 2 value)))
3966 links)))
3967 ((equal key "PRIORITIES")
3968 (setq prio (org-split-string value " +")))
3969 ((equal key "PROPERTY")
3970 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3971 (push (cons (match-string 1 value) (match-string 2 value))
3972 props)))
3973 ((equal key "FILETAGS")
3974 (when (string-match "\\S-" value)
3975 (setq ftags
3976 (append
3977 ftags
3978 (apply 'append
3979 (mapcar (lambda (x) (org-split-string x ":"))
3980 (org-split-string value)))))))
3981 ((equal key "DRAWERS")
3982 (setq drawers (org-split-string value splitre)))
3983 ((equal key "CONSTANTS")
3984 (setq const (append const (org-split-string value splitre))))
3985 ((equal key "STARTUP")
3986 (let ((opts (org-split-string value splitre))
3987 l var val)
3988 (while (setq l (pop opts))
3989 (when (setq l (assoc l org-startup-options))
3990 (setq var (nth 1 l) val (nth 2 l))
3991 (if (not (nth 3 l))
3992 (set (make-local-variable var) val)
3993 (if (not (listp (symbol-value var)))
3994 (set (make-local-variable var) nil))
3995 (set (make-local-variable var) (symbol-value var))
3996 (add-to-list var val))))))
3997 ((equal key "ARCHIVE")
3998 (string-match " *$" value)
3999 (setq arch (replace-match "" t t value))
4000 (remove-text-properties 0 (length arch)
4001 '(face t fontified t) arch))
4002 ((equal key "LATEX_CLASS")
4003 (setq beamer-p (equal value "beamer")))
4004 ((equal key "SETUPFILE")
4005 (setq setup-contents (org-file-contents
4006 (expand-file-name
4007 (org-remove-double-quotes value))
4008 'noerror))
4009 (if (not ext-setup-or-nil)
4010 (setq ext-setup-or-nil setup-contents start 0)
4011 (setq ext-setup-or-nil
4012 (concat (substring ext-setup-or-nil 0 start)
4013 "\n" setup-contents "\n"
4014 (substring ext-setup-or-nil start)))))
4015 ))))
4016 (when cat
4017 (org-set-local 'org-category (intern cat))
4018 (push (cons "CATEGORY" cat) props))
4019 (when prio
4020 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4021 (setq prio (mapcar 'string-to-char prio))
4022 (org-set-local 'org-highest-priority (nth 0 prio))
4023 (org-set-local 'org-lowest-priority (nth 1 prio))
4024 (org-set-local 'org-default-priority (nth 2 prio)))
4025 (and props (org-set-local 'org-file-properties (nreverse props)))
4026 (and ftags (org-set-local 'org-file-tags
4027 (mapcar 'org-add-prop-inherited ftags)))
4028 (and drawers (org-set-local 'org-drawers drawers))
4029 (and arch (org-set-local 'org-archive-location arch))
4030 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4031 ;; Process the TODO keywords
4032 (unless kwds
4033 ;; Use the global values as if they had been given locally.
4034 (setq kwds (default-value 'org-todo-keywords))
4035 (if (stringp (car kwds))
4036 (setq kwds (list (cons org-todo-interpretation
4037 (default-value 'org-todo-keywords)))))
4038 (setq kwds (reverse kwds)))
4039 (setq kwds (nreverse kwds))
4040 (let (inter kws kw)
4041 (while (setq kws (pop kwds))
4042 (let ((kws (or
4043 (run-hook-with-args-until-success
4044 'org-todo-setup-filter-hook kws)
4045 kws)))
4046 (setq inter (pop kws) sep (member "|" kws)
4047 kws0 (delete "|" (copy-sequence kws))
4048 kwsa nil
4049 kws1 (mapcar
4050 (lambda (x)
4051 ;; 1 2
4052 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4053 (progn
4054 (setq kw (match-string 1 x)
4055 key (and (match-end 2) (match-string 2 x))
4056 log (org-extract-log-state-settings x))
4057 (push (cons kw (and key (string-to-char key))) kwsa)
4058 (and log (push log org-todo-log-states))
4060 (error "Invalid TODO keyword %s" x)))
4061 kws0)
4062 kwsa (if kwsa (append '((:startgroup))
4063 (nreverse kwsa)
4064 '((:endgroup))))
4065 hw (car kws1)
4066 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4067 tail (list inter hw (car dws) (org-last dws))))
4068 (add-to-list 'org-todo-heads hw 'append)
4069 (push kws1 org-todo-sets)
4070 (setq org-done-keywords (append org-done-keywords dws nil))
4071 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4072 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4073 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4074 (setq org-todo-sets (nreverse org-todo-sets)
4075 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4076 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4077 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4078 ;; Process the constants
4079 (when const
4080 (let (e cst)
4081 (while (setq e (pop const))
4082 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4083 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4084 (setq org-table-formula-constants-local cst)))
4086 ;; Process the tags.
4087 (when tags
4088 (let (e tgs)
4089 (while (setq e (pop tags))
4090 (cond
4091 ((equal e "{") (push '(:startgroup) tgs))
4092 ((equal e "}") (push '(:endgroup) tgs))
4093 ((equal e "\\n") (push '(:newline) tgs))
4094 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4095 (push (cons (match-string 1 e)
4096 (string-to-char (match-string 2 e)))
4097 tgs))
4098 (t (push (list e) tgs))))
4099 (org-set-local 'org-tag-alist nil)
4100 (while (setq e (pop tgs))
4101 (or (and (stringp (car e))
4102 (assoc (car e) org-tag-alist))
4103 (push e org-tag-alist)))))
4105 ;; Compute the regular expressions and other local variables
4106 (if (not org-done-keywords)
4107 (setq org-done-keywords (and org-todo-keywords-1
4108 (list (org-last org-todo-keywords-1)))))
4109 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4110 (length org-scheduled-string)
4111 (length org-clock-string)
4112 (length org-closed-string)))
4113 org-drawer-regexp
4114 (concat "^[ \t]*:\\("
4115 (mapconcat 'regexp-quote org-drawers "\\|")
4116 "\\):[ \t]*$")
4117 org-not-done-keywords
4118 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4119 org-todo-regexp
4120 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4121 "\\|") "\\)\\>")
4122 org-not-done-regexp
4123 (concat "\\<\\("
4124 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4125 "\\)\\>")
4126 org-not-done-heading-regexp
4127 (concat "^\\(\\*+\\)[ \t]+\\("
4128 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4129 "\\)\\>")
4130 org-todo-line-regexp
4131 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4132 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4133 "\\)\\>\\)?[ \t]*\\(.*\\)")
4134 org-complex-heading-regexp
4135 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4136 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4137 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4138 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4139 org-complex-heading-regexp-format
4140 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4141 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4142 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4143 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4144 org-nl-done-regexp
4145 (concat "\n\\*+[ \t]+"
4146 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4147 "\\)" "\\>")
4148 org-todo-line-tags-regexp
4149 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4150 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4151 (org-re
4152 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4153 org-looking-at-done-regexp
4154 (concat "^" "\\(?:"
4155 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4156 "\\>")
4157 org-deadline-regexp (concat "\\<" org-deadline-string)
4158 org-deadline-time-regexp
4159 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4160 org-deadline-line-regexp
4161 (concat "\\<\\(" org-deadline-string "\\).*")
4162 org-scheduled-regexp
4163 (concat "\\<" org-scheduled-string)
4164 org-scheduled-time-regexp
4165 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4166 org-closed-time-regexp
4167 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4168 org-keyword-time-regexp
4169 (concat "\\<\\(" org-scheduled-string
4170 "\\|" org-deadline-string
4171 "\\|" org-closed-string
4172 "\\|" org-clock-string "\\)"
4173 " *[[<]\\([^]>]+\\)[]>]")
4174 org-keyword-time-not-clock-regexp
4175 (concat "\\<\\(" org-scheduled-string
4176 "\\|" org-deadline-string
4177 "\\|" org-closed-string
4178 "\\)"
4179 " *[[<]\\([^]>]+\\)[]>]")
4180 org-maybe-keyword-time-regexp
4181 (concat "\\(\\<\\(" org-scheduled-string
4182 "\\|" org-deadline-string
4183 "\\|" org-closed-string
4184 "\\|" org-clock-string "\\)\\)?"
4185 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4186 org-planning-or-clock-line-re
4187 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4188 "\\|" org-deadline-string
4189 "\\|" org-closed-string "\\|" org-clock-string
4190 "\\)\\>\\)")
4191 org-all-time-keywords
4192 (mapcar (lambda (w) (substring w 0 -1))
4193 (list org-scheduled-string org-deadline-string
4194 org-clock-string org-closed-string))
4196 (org-compute-latex-and-specials-regexp)
4197 (org-set-font-lock-defaults))))
4199 (defun org-file-contents (file &optional noerror)
4200 "Return the contents of FILE, as a string."
4201 (if (or (not file)
4202 (not (file-readable-p file)))
4203 (if noerror
4204 (progn
4205 (message "Cannot read file %s" file)
4206 (ding) (sit-for 2)
4208 (error "Cannot read file %s" file))
4209 (with-temp-buffer
4210 (insert-file-contents file)
4211 (buffer-string))))
4213 (defun org-extract-log-state-settings (x)
4214 "Extract the log state setting from a TODO keyword string.
4215 This will extract info from a string like \"WAIT(w@/!)\"."
4216 (let (kw key log1 log2)
4217 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4218 (setq kw (match-string 1 x)
4219 key (and (match-end 2) (match-string 2 x))
4220 log1 (and (match-end 3) (match-string 3 x))
4221 log2 (and (match-end 4) (match-string 4 x)))
4222 (and (or log1 log2)
4223 (list kw
4224 (and log1 (if (equal log1 "!") 'time 'note))
4225 (and log2 (if (equal log2 "!") 'time 'note)))))))
4227 (defun org-remove-keyword-keys (list)
4228 "Remove a pair of parenthesis at the end of each string in LIST."
4229 (mapcar (lambda (x)
4230 (if (string-match "(.*)$" x)
4231 (substring x 0 (match-beginning 0))
4233 list))
4235 (defun org-assign-fast-keys (alist)
4236 "Assign fast keys to a keyword-key alist.
4237 Respect keys that are already there."
4238 (let (new e (alt ?0))
4239 (while (setq e (pop alist))
4240 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4241 (cdr e)) ;; Key already assigned.
4242 (push e new)
4243 (let ((clist (string-to-list (downcase (car e))))
4244 (used (append new alist)))
4245 (when (= (car clist) ?@)
4246 (pop clist))
4247 (while (and clist (rassoc (car clist) used))
4248 (pop clist))
4249 (unless clist
4250 (while (rassoc alt used)
4251 (incf alt)))
4252 (push (cons (car e) (or (car clist) alt)) new))))
4253 (nreverse new)))
4255 ;;; Some variables used in various places
4257 (defvar org-window-configuration nil
4258 "Used in various places to store a window configuration.")
4259 (defvar org-selected-window nil
4260 "Used in various places to store a window configuration.")
4261 (defvar org-finish-function nil
4262 "Function to be called when `C-c C-c' is used.
4263 This is for getting out of special buffers like remember.")
4266 ;; FIXME: Occasionally check by commenting these, to make sure
4267 ;; no other functions uses these, forgetting to let-bind them.
4268 (defvar entry)
4269 (defvar last-state)
4270 (defvar date)
4272 ;; Defined somewhere in this file, but used before definition.
4273 (defvar org-entities) ;; defined in org-entities.el
4274 (defvar org-struct-menu)
4275 (defvar org-org-menu)
4276 (defvar org-tbl-menu)
4278 ;;;; Define the Org-mode
4280 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4281 (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."))
4284 ;; We use a before-change function to check if a table might need
4285 ;; an update.
4286 (defvar org-table-may-need-update t
4287 "Indicates that a table might need an update.
4288 This variable is set by `org-before-change-function'.
4289 `org-table-align' sets it back to nil.")
4290 (defun org-before-change-function (beg end)
4291 "Every change indicates that a table might need an update."
4292 (setq org-table-may-need-update t))
4293 (defvar org-mode-map)
4294 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4295 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4296 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4297 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4298 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4299 (defvar org-table-buffer-is-an nil)
4300 (defconst org-outline-regexp "\\*+ ")
4302 ;;;###autoload
4303 (define-derived-mode org-mode outline-mode "Org"
4304 "Outline-based notes management and organizer, alias
4305 \"Carsten's outline-mode for keeping track of everything.\"
4307 Org-mode develops organizational tasks around a NOTES file which
4308 contains information about projects as plain text. Org-mode is
4309 implemented on top of outline-mode, which is ideal to keep the content
4310 of large files well structured. It supports ToDo items, deadlines and
4311 time stamps, which magically appear in the diary listing of the Emacs
4312 calendar. Tables are easily created with a built-in table editor.
4313 Plain text URL-like links connect to websites, emails (VM), Usenet
4314 messages (Gnus), BBDB entries, and any files related to the project.
4315 For printing and sharing of notes, an Org-mode file (or a part of it)
4316 can be exported as a structured ASCII or HTML file.
4318 The following commands are available:
4320 \\{org-mode-map}"
4322 ;; Get rid of Outline menus, they are not needed
4323 ;; Need to do this here because define-derived-mode sets up
4324 ;; the keymap so late. Still, it is a waste to call this each time
4325 ;; we switch another buffer into org-mode.
4326 (if (featurep 'xemacs)
4327 (when (boundp 'outline-mode-menu-heading)
4328 ;; Assume this is Greg's port, it used easymenu
4329 (easy-menu-remove outline-mode-menu-heading)
4330 (easy-menu-remove outline-mode-menu-show)
4331 (easy-menu-remove outline-mode-menu-hide))
4332 (define-key org-mode-map [menu-bar headings] 'undefined)
4333 (define-key org-mode-map [menu-bar hide] 'undefined)
4334 (define-key org-mode-map [menu-bar show] 'undefined))
4336 (org-load-modules-maybe)
4337 (easy-menu-add org-org-menu)
4338 (easy-menu-add org-tbl-menu)
4339 (org-install-agenda-files-menu)
4340 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4341 (org-add-to-invisibility-spec '(org-cwidth))
4342 (org-add-to-invisibility-spec '(org-hide-block . t))
4343 (when (featurep 'xemacs)
4344 (org-set-local 'line-move-ignore-invisible t))
4345 (org-set-local 'outline-regexp org-outline-regexp)
4346 (org-set-local 'outline-level 'org-outline-level)
4347 (when (and org-ellipsis
4348 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4349 (fboundp 'make-glyph-code))
4350 (unless org-display-table
4351 (setq org-display-table (make-display-table)))
4352 (set-display-table-slot
4353 org-display-table 4
4354 (vconcat (mapcar
4355 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4356 org-ellipsis)))
4357 (if (stringp org-ellipsis) org-ellipsis "..."))))
4358 (setq buffer-display-table org-display-table))
4359 (org-set-regexps-and-options)
4360 (when (and org-tag-faces (not org-tags-special-faces-re))
4361 ;; tag faces set outside customize.... force initialization.
4362 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4363 ;; Calc embedded
4364 (org-set-local 'calc-embedded-open-mode "# ")
4365 (modify-syntax-entry ?# "<")
4366 (modify-syntax-entry ?@ "w")
4367 (if org-startup-truncated (setq truncate-lines t))
4368 (org-set-local 'font-lock-unfontify-region-function
4369 'org-unfontify-region)
4370 ;; Activate before-change-function
4371 (org-set-local 'org-table-may-need-update t)
4372 (org-add-hook 'before-change-functions 'org-before-change-function nil
4373 'local)
4374 ;; Check for running clock before killing a buffer
4375 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4376 ;; Paragraphs and auto-filling
4377 (org-set-autofill-regexps)
4378 (setq indent-line-function 'org-indent-line-function)
4379 (org-update-radio-target-regexp)
4380 ;; Make sure dependence stuff works reliably, even for users who set it
4381 ;; too late :-(
4382 (if org-enforce-todo-dependencies
4383 (add-hook 'org-blocker-hook
4384 'org-block-todo-from-children-or-siblings-or-parent)
4385 (remove-hook 'org-blocker-hook
4386 'org-block-todo-from-children-or-siblings-or-parent))
4387 (if org-enforce-todo-checkbox-dependencies
4388 (add-hook 'org-blocker-hook
4389 'org-block-todo-from-checkboxes)
4390 (remove-hook 'org-blocker-hook
4391 'org-block-todo-from-checkboxes))
4393 ;; Comment characters
4394 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4395 (org-set-local 'comment-padding " ")
4397 ;; Align options lines
4398 (org-set-local
4399 'align-mode-rules-list
4400 '((org-in-buffer-settings
4401 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4402 (modes . '(org-mode)))))
4404 ;; Imenu
4405 (org-set-local 'imenu-create-index-function
4406 'org-imenu-get-tree)
4408 ;; Make isearch reveal context
4409 (if (or (featurep 'xemacs)
4410 (not (boundp 'outline-isearch-open-invisible-function)))
4411 ;; Emacs 21 and XEmacs make use of the hook
4412 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4413 ;; Emacs 22 deals with this through a special variable
4414 (org-set-local 'outline-isearch-open-invisible-function
4415 (lambda (&rest ignore) (org-show-context 'isearch))))
4417 ;; Turn on org-beamer-mode?
4418 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4420 ;; If empty file that did not turn on org-mode automatically, make it to.
4421 (if (and org-insert-mode-line-in-empty-file
4422 (interactive-p)
4423 (= (point-min) (point-max)))
4424 (insert "# -*- mode: org -*-\n\n"))
4425 (unless org-inhibit-startup
4426 (when org-startup-align-all-tables
4427 (let ((bmp (buffer-modified-p)))
4428 (org-table-map-tables 'org-table-align)
4429 (set-buffer-modified-p bmp)))
4430 (when org-startup-indented
4431 (require 'org-indent)
4432 (org-indent-mode 1))
4433 (unless org-inhibit-startup-visibility-stuff
4434 (org-set-startup-visibility))))
4436 (when (fboundp 'abbrev-table-put)
4437 (abbrev-table-put org-mode-abbrev-table
4438 :parents (list text-mode-abbrev-table)))
4440 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4442 (defun org-current-time ()
4443 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4444 (if (> (car org-time-stamp-rounding-minutes) 1)
4445 (let ((r (car org-time-stamp-rounding-minutes))
4446 (time (decode-time)))
4447 (apply 'encode-time
4448 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4449 (nthcdr 2 time))))
4450 (current-time)))
4452 ;;;; Font-Lock stuff, including the activators
4454 (defvar org-mouse-map (make-sparse-keymap))
4455 (org-defkey org-mouse-map
4456 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4457 (org-defkey org-mouse-map
4458 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4459 (when org-mouse-1-follows-link
4460 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4461 (when org-tab-follows-link
4462 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4463 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4465 (require 'font-lock)
4467 (defconst org-non-link-chars "]\t\n\r<>")
4468 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4469 "shell" "elisp"))
4470 (defvar org-link-types-re nil
4471 "Matches a link that has a url-like prefix like \"http:\"")
4472 (defvar org-link-re-with-space nil
4473 "Matches a link with spaces, optional angular brackets around it.")
4474 (defvar org-link-re-with-space2 nil
4475 "Matches a link with spaces, optional angular brackets around it.")
4476 (defvar org-link-re-with-space3 nil
4477 "Matches a link with spaces, only for internal part in bracket links.")
4478 (defvar org-angle-link-re nil
4479 "Matches link with angular brackets, spaces are allowed.")
4480 (defvar org-plain-link-re nil
4481 "Matches plain link, without spaces.")
4482 (defvar org-bracket-link-regexp nil
4483 "Matches a link in double brackets.")
4484 (defvar org-bracket-link-analytic-regexp nil
4485 "Regular expression used to analyze links.
4486 Here is what the match groups contain after a match:
4487 1: http:
4488 2: http
4489 3: path
4490 4: [desc]
4491 5: desc")
4492 (defvar org-bracket-link-analytic-regexp++ nil
4493 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4494 (defvar org-any-link-re nil
4495 "Regular expression matching any link.")
4497 (defun org-make-link-regexps ()
4498 "Update the link regular expressions.
4499 This should be called after the variable `org-link-types' has changed."
4500 (setq org-link-types-re
4501 (concat
4502 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4503 org-link-re-with-space
4504 (concat
4505 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4506 "\\([^" org-non-link-chars " ]"
4507 "[^" org-non-link-chars "]*"
4508 "[^" org-non-link-chars " ]\\)>?")
4509 org-link-re-with-space2
4510 (concat
4511 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4512 "\\([^" org-non-link-chars " ]"
4513 "[^\t\n\r]*"
4514 "[^" org-non-link-chars " ]\\)>?")
4515 org-link-re-with-space3
4516 (concat
4517 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4518 "\\([^" org-non-link-chars " ]"
4519 "[^\t\n\r]*\\)")
4520 org-angle-link-re
4521 (concat
4522 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4523 "\\([^" org-non-link-chars " ]"
4524 "[^" org-non-link-chars "]*"
4525 "\\)>")
4526 org-plain-link-re
4527 (concat
4528 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4529 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4530 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4531 org-bracket-link-regexp
4532 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4533 org-bracket-link-analytic-regexp
4534 (concat
4535 "\\[\\["
4536 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4537 "\\([^]]+\\)"
4538 "\\]"
4539 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4540 "\\]")
4541 org-bracket-link-analytic-regexp++
4542 (concat
4543 "\\[\\["
4544 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4545 "\\([^]]+\\)"
4546 "\\]"
4547 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4548 "\\]")
4549 org-any-link-re
4550 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4551 org-angle-link-re "\\)\\|\\("
4552 org-plain-link-re "\\)")))
4554 (org-make-link-regexps)
4556 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4557 "Regular expression for fast time stamp matching.")
4558 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4559 "Regular expression for fast time stamp matching.")
4560 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4561 "Regular expression matching time strings for analysis.
4562 This one does not require the space after the date, so it can be used
4563 on a string that terminates immediately after the date.")
4564 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4565 "Regular expression matching time strings for analysis.")
4566 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4567 "Regular expression matching time stamps, with groups.")
4568 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4569 "Regular expression matching time stamps (also [..]), with groups.")
4570 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4571 "Regular expression matching a time stamp range.")
4572 (defconst org-tr-regexp-both
4573 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4574 "Regular expression matching a time stamp range.")
4575 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4576 org-ts-regexp "\\)?")
4577 "Regular expression matching a time stamp or time stamp range.")
4578 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4579 org-ts-regexp-both "\\)?")
4580 "Regular expression matching a time stamp or time stamp range.
4581 The time stamps may be either active or inactive.")
4583 (defvar org-emph-face nil)
4585 (defun org-do-emphasis-faces (limit)
4586 "Run through the buffer and add overlays to links."
4587 (let (rtn a)
4588 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4589 (if (not (= (char-after (match-beginning 3))
4590 (char-after (match-beginning 4))))
4591 (progn
4592 (setq rtn t)
4593 (setq a (assoc (match-string 3) org-emphasis-alist))
4594 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4595 'face
4596 (nth 1 a))
4597 (and (nth 4 a)
4598 (org-remove-flyspell-overlays-in
4599 (match-beginning 0) (match-end 0)))
4600 (add-text-properties (match-beginning 2) (match-end 2)
4601 '(font-lock-multiline t))
4602 (when org-hide-emphasis-markers
4603 (add-text-properties (match-end 4) (match-beginning 5)
4604 '(invisible org-link))
4605 (add-text-properties (match-beginning 3) (match-end 3)
4606 '(invisible org-link)))))
4607 (backward-char 1))
4608 rtn))
4610 (defun org-emphasize (&optional char)
4611 "Insert or change an emphasis, i.e. a font like bold or italic.
4612 If there is an active region, change that region to a new emphasis.
4613 If there is no region, just insert the marker characters and position
4614 the cursor between them.
4615 CHAR should be either the marker character, or the first character of the
4616 HTML tag associated with that emphasis. If CHAR is a space, the means
4617 to remove the emphasis of the selected region.
4618 If char is not given (for example in an interactive call) it
4619 will be prompted for."
4620 (interactive)
4621 (let ((eal org-emphasis-alist) e det
4622 (erc org-emphasis-regexp-components)
4623 (prompt "")
4624 (string "") beg end move tag c s)
4625 (if (org-region-active-p)
4626 (setq beg (region-beginning) end (region-end)
4627 string (buffer-substring beg end))
4628 (setq move t))
4630 (while (setq e (pop eal))
4631 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4632 c (aref tag 0))
4633 (push (cons c (string-to-char (car e))) det)
4634 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4635 (substring tag 1)))))
4636 (setq det (nreverse det))
4637 (unless char
4638 (message "%s" (concat "Emphasis marker or tag:" prompt))
4639 (setq char (read-char-exclusive)))
4640 (setq char (or (cdr (assoc char det)) char))
4641 (if (equal char ?\ )
4642 (setq s "" move nil)
4643 (unless (assoc (char-to-string char) org-emphasis-alist)
4644 (error "No such emphasis marker: \"%c\"" char))
4645 (setq s (char-to-string char)))
4646 (while (and (> (length string) 1)
4647 (equal (substring string 0 1) (substring string -1))
4648 (assoc (substring string 0 1) org-emphasis-alist))
4649 (setq string (substring string 1 -1)))
4650 (setq string (concat s string s))
4651 (if beg (delete-region beg end))
4652 (unless (or (bolp)
4653 (string-match (concat "[" (nth 0 erc) "\n]")
4654 (char-to-string (char-before (point)))))
4655 (insert " "))
4656 (unless (or (eobp)
4657 (string-match (concat "[" (nth 1 erc) "\n]")
4658 (char-to-string (char-after (point)))))
4659 (insert " ") (backward-char 1))
4660 (insert string)
4661 (and move (backward-char 1))))
4663 (defconst org-nonsticky-props
4664 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4666 (defsubst org-rear-nonsticky-at (pos)
4667 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4669 (defun org-activate-plain-links (limit)
4670 "Run through the buffer and add overlays to links."
4671 (catch 'exit
4672 (let (f)
4673 (if (re-search-forward org-plain-link-re limit t)
4674 (progn
4675 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4676 (setq f (get-text-property (match-beginning 0) 'face))
4677 (if (or (eq f 'org-tag)
4678 (and (listp f) (memq 'org-tag f)))
4680 (add-text-properties (match-beginning 0) (match-end 0)
4681 (list 'mouse-face 'highlight
4682 'face 'org-link
4683 'keymap org-mouse-map))
4684 (org-rear-nonsticky-at (match-end 0)))
4685 t)))))
4687 (defun org-activate-code (limit)
4688 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4689 (progn
4690 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4691 (remove-text-properties (match-beginning 0) (match-end 0)
4692 '(display t invisible t intangible t))
4693 t)))
4695 (defun org-fontify-meta-lines-and-blocks (limit)
4696 "Fontify #+ lines and blocks, in the correct ways."
4697 (let ((case-fold-search t))
4698 (if (re-search-forward
4699 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4700 limit t)
4701 (let ((beg (match-beginning 0))
4702 (beg1 (line-beginning-position 2))
4703 (dc1 (downcase (match-string 2)))
4704 (dc3 (downcase (match-string 3)))
4705 end end1 quoting block-type)
4706 (cond
4707 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4708 ;; a single line of backend-specific content
4709 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4710 (remove-text-properties (match-beginning 0) (match-end 0)
4711 '(display t invisible t intangible t))
4712 (add-text-properties (match-beginning 1) (match-end 3)
4713 '(font-lock-fontified t face org-meta-line))
4714 (add-text-properties (match-beginning 6) (match-end 6)
4715 '(font-lock-fontified t face org-block))
4717 ((and (match-end 4) (equal dc3 "begin"))
4718 ;; Truely a block
4719 (setq block-type (downcase (match-string 5))
4720 quoting (member block-type org-protecting-blocks))
4721 (when (re-search-forward
4722 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4723 nil t) ;; on purpose, we look further than LIMIT
4724 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4725 (when quoting
4726 (remove-text-properties beg end
4727 '(display t invisible t intangible t)))
4728 (add-text-properties
4729 beg end
4730 '(font-lock-fontified t font-lock-multiline t))
4731 (add-text-properties beg beg1 '(face org-meta-line))
4732 (add-text-properties end1 end '(face org-meta-line))
4733 (cond
4734 (quoting
4735 (add-text-properties beg1 end1 '(face org-block)))
4736 ((not org-fontify-quote-and-verse-blocks))
4737 ((string= block-type "quote")
4738 (add-text-properties beg1 end1 '(face org-quote)))
4739 ((string= block-type "verse")
4740 (add-text-properties beg1 end1 '(face org-verse))))
4742 ((member dc1 '("title:" "author:" "email:" "date:"))
4743 (add-text-properties
4744 beg (match-end 3)
4745 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4746 '(font-lock-fontified t invisible t)
4747 '(font-lock-fontified t face org-document-info-keyword)))
4748 (add-text-properties
4749 (match-beginning 6) (match-end 6)
4750 (if (string-equal dc1 "title:")
4751 '(font-lock-fontified t face org-document-title)
4752 '(font-lock-fontified t face org-document-info))))
4753 ((not (member (char-after beg) '(?\ ?\t)))
4754 ;; just any other in-buffer setting, but not indented
4755 (add-text-properties
4756 beg (match-end 0)
4757 '(font-lock-fontified t face org-meta-line))
4759 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4760 "orgtbl:" "tblfm:" "tblname:"))
4761 (and (match-end 4) (equal dc3 "attr")))
4762 (add-text-properties
4763 beg (match-end 0)
4764 '(font-lock-fontified t face org-meta-line))
4766 ((member dc3 '(" " ""))
4767 (add-text-properties
4768 beg (match-end 0)
4769 '(font-lock-fontified t face font-lock-comment-face)))
4770 (t nil))))))
4772 (defun org-activate-angle-links (limit)
4773 "Run through the buffer and add overlays to links."
4774 (if (re-search-forward org-angle-link-re limit t)
4775 (progn
4776 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4777 (add-text-properties (match-beginning 0) (match-end 0)
4778 (list 'mouse-face 'highlight
4779 'keymap org-mouse-map))
4780 (org-rear-nonsticky-at (match-end 0))
4781 t)))
4783 (defun org-activate-footnote-links (limit)
4784 "Run through the buffer and add overlays to links."
4785 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4786 limit t)
4787 (progn
4788 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4789 (add-text-properties (match-beginning 2) (match-end 2)
4790 (list 'mouse-face 'highlight
4791 'keymap org-mouse-map
4792 'help-echo
4793 (if (= (point-at-bol) (match-beginning 2))
4794 "Footnote definition"
4795 "Footnote reference")
4797 (org-rear-nonsticky-at (match-end 2))
4798 t)))
4800 (defun org-activate-bracket-links (limit)
4801 "Run through the buffer and add overlays to bracketed links."
4802 (if (re-search-forward org-bracket-link-regexp limit t)
4803 (let* ((help (concat "LINK: "
4804 (org-match-string-no-properties 1)))
4805 ;; FIXME: above we should remove the escapes.
4806 ;; but that requires another match, protecting match data,
4807 ;; a lot of overhead for font-lock.
4808 (ip (org-maybe-intangible
4809 (list 'invisible 'org-link
4810 'keymap org-mouse-map 'mouse-face 'highlight
4811 'font-lock-multiline t 'help-echo help)))
4812 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4813 'font-lock-multiline t 'help-echo help)))
4814 ;; We need to remove the invisible property here. Table narrowing
4815 ;; may have made some of this invisible.
4816 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4817 (remove-text-properties (match-beginning 0) (match-end 0)
4818 '(invisible nil))
4819 (if (match-end 3)
4820 (progn
4821 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4822 (org-rear-nonsticky-at (match-beginning 3))
4823 (add-text-properties (match-beginning 3) (match-end 3) vp)
4824 (org-rear-nonsticky-at (match-end 3))
4825 (add-text-properties (match-end 3) (match-end 0) ip)
4826 (org-rear-nonsticky-at (match-end 0)))
4827 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4828 (org-rear-nonsticky-at (match-beginning 1))
4829 (add-text-properties (match-beginning 1) (match-end 1) vp)
4830 (org-rear-nonsticky-at (match-end 1))
4831 (add-text-properties (match-end 1) (match-end 0) ip)
4832 (org-rear-nonsticky-at (match-end 0)))
4833 t)))
4835 (defun org-activate-dates (limit)
4836 "Run through the buffer and add overlays to dates."
4837 (if (re-search-forward org-tsr-regexp-both limit t)
4838 (progn
4839 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4840 (add-text-properties (match-beginning 0) (match-end 0)
4841 (list 'mouse-face 'highlight
4842 'keymap org-mouse-map))
4843 (org-rear-nonsticky-at (match-end 0))
4844 (when org-display-custom-times
4845 (if (match-end 3)
4846 (org-display-custom-time (match-beginning 3) (match-end 3)))
4847 (org-display-custom-time (match-beginning 1) (match-end 1)))
4848 t)))
4850 (defvar org-target-link-regexp nil
4851 "Regular expression matching radio targets in plain text.")
4852 (make-variable-buffer-local 'org-target-link-regexp)
4853 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4854 "Regular expression matching a link target.")
4855 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4856 "Regular expression matching a radio target.")
4857 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4858 "Regular expression matching any target.")
4860 (defun org-activate-target-links (limit)
4861 "Run through the buffer and add overlays to target matches."
4862 (when org-target-link-regexp
4863 (let ((case-fold-search t))
4864 (if (re-search-forward org-target-link-regexp limit t)
4865 (progn
4866 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4867 (add-text-properties (match-beginning 0) (match-end 0)
4868 (list 'mouse-face 'highlight
4869 'keymap org-mouse-map
4870 'help-echo "Radio target link"
4871 'org-linked-text t))
4872 (org-rear-nonsticky-at (match-end 0))
4873 t)))))
4875 (defun org-update-radio-target-regexp ()
4876 "Find all radio targets in this file and update the regular expression."
4877 (interactive)
4878 (when (memq 'radio org-activate-links)
4879 (setq org-target-link-regexp
4880 (org-make-target-link-regexp (org-all-targets 'radio)))
4881 (org-restart-font-lock)))
4883 (defun org-hide-wide-columns (limit)
4884 (let (s e)
4885 (setq s (text-property-any (point) (or limit (point-max))
4886 'org-cwidth t))
4887 (when s
4888 (setq e (next-single-property-change s 'org-cwidth))
4889 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4890 (goto-char e)
4891 t)))
4893 (defvar org-latex-and-specials-regexp nil
4894 "Regular expression for highlighting export special stuff.")
4895 (defvar org-match-substring-regexp)
4896 (defvar org-match-substring-with-braces-regexp)
4898 ;; This should be with the exporter code, but we also use if for font-locking
4899 (defconst org-export-html-special-string-regexps
4900 '(("\\\\-" . "&shy;")
4901 ("---\\([^-]\\)" . "&mdash;\\1")
4902 ("--\\([^-]\\)" . "&ndash;\\1")
4903 ("\\.\\.\\." . "&hellip;"))
4904 "Regular expressions for special string conversion.")
4907 (defun org-compute-latex-and-specials-regexp ()
4908 "Compute regular expression for stuff treated specially by exporters."
4909 (if (not org-highlight-latex-fragments-and-specials)
4910 (org-set-local 'org-latex-and-specials-regexp nil)
4911 (require 'org-exp)
4912 (let*
4913 ((matchers (plist-get org-format-latex-options :matchers))
4914 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4915 org-latex-regexps)))
4916 (org-export-allow-BIND nil)
4917 (options (org-combine-plists (org-default-export-plist)
4918 (org-infile-export-plist)))
4919 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4920 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4921 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4922 (org-export-html-expand (plist-get options :expand-quoted-html))
4923 (org-export-with-special-strings (plist-get options :special-strings))
4924 (re-sub
4925 (cond
4926 ((equal org-export-with-sub-superscripts '{})
4927 (list org-match-substring-with-braces-regexp))
4928 (org-export-with-sub-superscripts
4929 (list org-match-substring-regexp))
4930 (t nil)))
4931 (re-latex
4932 (if org-export-with-LaTeX-fragments
4933 (mapcar (lambda (x) (nth 1 x)) latexs)))
4934 (re-macros
4935 (if org-export-with-TeX-macros
4936 (list (concat "\\\\"
4937 (regexp-opt
4938 (append (mapcar 'car (append org-entities-user
4939 org-entities))
4940 (if (boundp 'org-latex-entities)
4941 (mapcar (lambda (x)
4942 (or (car-safe x) x))
4943 org-latex-entities)
4944 nil))
4945 'words))) ; FIXME
4947 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4948 (re-special (if org-export-with-special-strings
4949 (mapcar (lambda (x) (car x))
4950 org-export-html-special-string-regexps)))
4951 (re-rest
4952 (delq nil
4953 (list
4954 (if org-export-html-expand "@<[^>\n]+>")
4955 ))))
4956 (org-set-local
4957 'org-latex-and-specials-regexp
4958 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4959 re-rest) "\\|")))))
4961 (defun org-do-latex-and-special-faces (limit)
4962 "Run through the buffer and add overlays to links."
4963 (when org-latex-and-specials-regexp
4964 (let (rtn d)
4965 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4966 limit t))
4967 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4968 'face))
4969 '(org-code org-verbatim underline)))
4970 (progn
4971 (setq rtn t
4972 d (cond ((member (char-after (1+ (match-beginning 0)))
4973 '(?_ ?^)) 1)
4974 (t 0)))
4975 (font-lock-prepend-text-property
4976 (+ d (match-beginning 0)) (match-end 0)
4977 'face 'org-latex-and-export-specials)
4978 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4979 '(font-lock-multiline t)))))
4980 rtn)))
4982 (defun org-restart-font-lock ()
4983 "Restart font-lock-mode, to force refontification."
4984 (when (and (boundp 'font-lock-mode) font-lock-mode)
4985 (font-lock-mode -1)
4986 (font-lock-mode 1)))
4988 (defun org-all-targets (&optional radio)
4989 "Return a list of all targets in this file.
4990 With optional argument RADIO, only find radio targets."
4991 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4992 rtn)
4993 (save-excursion
4994 (goto-char (point-min))
4995 (while (re-search-forward re nil t)
4996 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4997 rtn)))
4999 (defun org-make-target-link-regexp (targets)
5000 "Make regular expression matching all strings in TARGETS.
5001 The regular expression finds the targets also if there is a line break
5002 between words."
5003 (and targets
5004 (concat
5005 "\\<\\("
5006 (mapconcat
5007 (lambda (x)
5008 (while (string-match " +" x)
5009 (setq x (replace-match "\\s-+" t t x)))
5011 targets
5012 "\\|")
5013 "\\)\\>")))
5015 (defun org-activate-tags (limit)
5016 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5017 (progn
5018 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5019 (add-text-properties (match-beginning 1) (match-end 1)
5020 (list 'mouse-face 'highlight
5021 'keymap org-mouse-map))
5022 (org-rear-nonsticky-at (match-end 1))
5023 t)))
5025 (defun org-outline-level ()
5026 "Compute the outline level of the heading at point.
5027 This function assumes that the cursor is at the beginning of a line matched
5028 by outline-regexp. Otherwise it returns garbage.
5029 If this is called at a normal headline, the level is the number of stars.
5030 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5031 For plain list items, if they are matched by `outline-regexp', this returns
5032 1000 plus the line indentation."
5033 (save-excursion
5034 (looking-at outline-regexp)
5035 (if (match-beginning 1)
5036 (+ (org-get-string-indentation (match-string 1)) 1000)
5037 (1- (- (match-end 0) (match-beginning 0))))))
5039 (defvar org-font-lock-keywords nil)
5041 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5042 "Regular expression matching a property line.")
5044 (defvar org-font-lock-hook nil
5045 "Functions to be called for special font lock stuff.")
5047 (defun org-font-lock-hook (limit)
5048 (run-hook-with-args 'org-font-lock-hook limit))
5050 (defun org-set-font-lock-defaults ()
5051 (let* ((em org-fontify-emphasized-text)
5052 (lk org-activate-links)
5053 (org-font-lock-extra-keywords
5054 (list
5055 ;; Call the hook
5056 '(org-font-lock-hook)
5057 ;; Headlines
5058 `(,(if org-fontify-whole-heading-line
5059 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5060 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5061 (1 (org-get-level-face 1))
5062 (2 (org-get-level-face 2))
5063 (3 (org-get-level-face 3)))
5064 ;; Table lines
5065 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5066 (1 'org-table t))
5067 ;; Table internals
5068 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5069 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5070 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5071 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5072 ;; Drawers
5073 (list org-drawer-regexp '(0 'org-special-keyword t))
5074 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5075 ;; Properties
5076 (list org-property-re
5077 '(1 'org-special-keyword t)
5078 '(3 'org-property-value t))
5079 ;; Links
5080 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5081 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5082 (if (memq 'plain lk) '(org-activate-plain-links))
5083 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5084 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5085 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5086 (if (memq 'footnote lk) '(org-activate-footnote-links
5087 (2 'org-footnote t)))
5088 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5089 '(org-hide-wide-columns (0 nil append))
5090 ;; TODO lines
5091 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5092 '(1 (org-get-todo-face 1) t))
5093 ;; DONE
5094 (if org-fontify-done-headline
5095 (list (concat "^[*]+ +\\<\\("
5096 (mapconcat 'regexp-quote org-done-keywords "\\|")
5097 "\\)\\(.*\\)")
5098 '(2 'org-headline-done t))
5099 nil)
5100 ;; Priorities
5101 '(org-font-lock-add-priority-faces)
5102 ;; Tags
5103 '(org-font-lock-add-tag-faces)
5104 ;; Special keywords
5105 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5106 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5107 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5108 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5109 ;; Emphasis
5110 (if em
5111 (if (featurep 'xemacs)
5112 '(org-do-emphasis-faces (0 nil append))
5113 '(org-do-emphasis-faces)))
5114 ;; Checkboxes
5115 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5116 2 'org-checkbox prepend)
5117 (if org-provide-checkbox-statistics
5118 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5119 (0 (org-get-checkbox-statistics-face) t)))
5120 ;; Description list items
5121 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5122 2 'bold prepend)
5123 ;; ARCHIVEd headings
5124 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5125 '(1 'org-archived prepend))
5126 ;; Specials
5127 '(org-do-latex-and-special-faces)
5128 ;; Code
5129 '(org-activate-code (1 'org-code t))
5130 ;; COMMENT
5131 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5132 "\\|" org-quote-string "\\)\\>")
5133 '(1 'org-special-keyword t))
5134 '("^#.*" (0 'font-lock-comment-face t))
5135 ;; Blocks and meta lines
5136 '(org-fontify-meta-lines-and-blocks)
5138 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5139 ;; Now set the full font-lock-keywords
5140 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5141 (org-set-local 'font-lock-defaults
5142 '(org-font-lock-keywords t nil nil backward-paragraph))
5143 (kill-local-variable 'font-lock-keywords) nil))
5145 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5146 "Fontify string S like in Org-mode"
5147 (with-temp-buffer
5148 (insert s)
5149 (let ((org-odd-levels-only odd-levels))
5150 (org-mode)
5151 (font-lock-fontify-buffer)
5152 (buffer-string))))
5154 (defvar org-m nil)
5155 (defvar org-l nil)
5156 (defvar org-f nil)
5157 (defun org-get-level-face (n)
5158 "Get the right face for match N in font-lock matching of headlines."
5159 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5160 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5161 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5162 (cond
5163 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5164 ((eq n 2) org-f)
5165 (t (if org-level-color-stars-only nil org-f))))
5167 (defun org-get-todo-face (kwd)
5168 "Get the right face for a TODO keyword KWD.
5169 If KWD is a number, get the corresponding match group."
5170 (if (numberp kwd) (setq kwd (match-string kwd)))
5171 (or (org-face-from-face-or-color
5172 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5173 (and (member kwd org-done-keywords) 'org-done)
5174 'org-todo))
5176 (defun org-face-from-face-or-color (context inherit face-or-color)
5177 "Create a face list that inherits INHERIT, but sets the foreground color.
5178 When FACE-OR-COLOR is not a string, just return it."
5179 (if (stringp face-or-color)
5180 (list :inherit inherit
5181 (cdr (assoc context org-faces-easy-properties))
5182 face-or-color)
5183 face-or-color))
5185 (defun org-font-lock-add-tag-faces (limit)
5186 "Add the special tag faces."
5187 (when (and org-tag-faces org-tags-special-faces-re)
5188 (while (re-search-forward org-tags-special-faces-re limit t)
5189 (add-text-properties (match-beginning 1) (match-end 1)
5190 (list 'face (org-get-tag-face 1)
5191 'font-lock-fontified t))
5192 (backward-char 1))))
5194 (defun org-font-lock-add-priority-faces (limit)
5195 "Add the special priority faces."
5196 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5197 (add-text-properties
5198 (match-beginning 0) (match-end 0)
5199 (list 'face (or (org-face-from-face-or-color
5200 'priority 'org-special-keyword
5201 (cdr (assoc (char-after (match-beginning 1))
5202 org-priority-faces)))
5203 'org-special-keyword)
5204 'font-lock-fontified t))))
5206 (defun org-get-tag-face (kwd)
5207 "Get the right face for a TODO keyword KWD.
5208 If KWD is a number, get the corresponding match group."
5209 (if (numberp kwd) (setq kwd (match-string kwd)))
5210 (or (org-face-from-face-or-color
5211 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5212 'org-tag))
5214 (defun org-unfontify-region (beg end &optional maybe_loudly)
5215 "Remove fontification and activation overlays from links."
5216 (font-lock-default-unfontify-region beg end)
5217 (let* ((buffer-undo-list t)
5218 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5219 (inhibit-modification-hooks t)
5220 deactivate-mark buffer-file-name buffer-file-truename)
5221 (remove-text-properties
5222 beg end
5223 (if org-indent-mode
5224 ;; also remove line-prefix and wrap-prefix properties
5225 '(mouse-face t keymap t org-linked-text t
5226 invisible t intangible t
5227 line-prefix t wrap-prefix t
5228 org-no-flyspell t)
5229 '(mouse-face t keymap t org-linked-text t
5230 invisible t intangible t
5231 org-no-flyspell t)))))
5233 ;;;; Visibility cycling, including org-goto and indirect buffer
5235 ;;; Cycling
5237 (defvar org-cycle-global-status nil)
5238 (make-variable-buffer-local 'org-cycle-global-status)
5239 (defvar org-cycle-subtree-status nil)
5240 (make-variable-buffer-local 'org-cycle-subtree-status)
5242 ;;;###autoload
5244 (defvar org-inlinetask-min-level)
5246 (defun org-cycle (&optional arg)
5247 "TAB-action and visibility cycling for Org-mode.
5249 This is the command invoked in Org-mode by the TAB key. Its main purpose
5250 is outline visibility cycling, but it also invokes other actions
5251 in special contexts.
5253 - When this function is called with a prefix argument, rotate the entire
5254 buffer through 3 states (global cycling)
5255 1. OVERVIEW: Show only top-level headlines.
5256 2. CONTENTS: Show all headlines of all levels, but no body text.
5257 3. SHOW ALL: Show everything.
5258 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5259 determined by the variable `org-startup-folded', and by any VISIBILITY
5260 properties in the buffer.
5261 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5262 including any drawers.
5264 - When inside a table, re-align the table and move to the next field.
5266 - When point is at the beginning of a headline, rotate the subtree started
5267 by this line through 3 different states (local cycling)
5268 1. FOLDED: Only the main headline is shown.
5269 2. CHILDREN: The main headline and the direct children are shown.
5270 From this state, you can move to one of the children
5271 and zoom in further.
5272 3. SUBTREE: Show the entire subtree, including body text.
5273 If there is no subtree, switch directly from CHILDREN to FOLDED.
5275 - When point is at the beginning of an empty headline and the variable
5276 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5277 of the headline by demoting and promoting it to likely levels. This
5278 speeds up creation document structure by presing TAB once or several
5279 times right after creating a new headline.
5281 - When there is a numeric prefix, go up to a heading with level ARG, do
5282 a `show-subtree' and return to the previous cursor position. If ARG
5283 is negative, go up that many levels.
5285 - When point is not at the beginning of a headline, execute the global
5286 binding for TAB, which is re-indenting the line. See the option
5287 `org-cycle-emulate-tab' for details.
5289 - Special case: if point is at the beginning of the buffer and there is
5290 no headline in line 1, this function will act as if called with prefix arg.
5291 But only if also the variable `org-cycle-global-at-bob' is t."
5292 (interactive "P")
5293 (org-load-modules-maybe)
5294 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5295 (and org-cycle-level-after-item/entry-creation
5296 (or (org-cycle-level)
5297 (org-cycle-item-indentation))))
5298 (let* ((limit-level
5299 (or org-cycle-max-level
5300 (and (boundp 'org-inlinetask-min-level)
5301 org-inlinetask-min-level
5302 (1- org-inlinetask-min-level))))
5303 (nstars (and limit-level
5304 (if org-odd-levels-only
5305 (and limit-level (1- (* limit-level 2)))
5306 limit-level)))
5307 (outline-regexp
5308 (cond
5309 ((not (org-mode-p)) outline-regexp)
5310 ((or (eq org-cycle-include-plain-lists 'integrate)
5311 (and org-cycle-include-plain-lists (org-at-item-p)))
5312 (concat "\\(?:\\*"
5313 (if nstars (format "\\{1,%d\\}" nstars) "+")
5314 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5315 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5316 (bob-special (and org-cycle-global-at-bob (bobp)
5317 (not (looking-at outline-regexp))))
5318 (org-cycle-hook
5319 (if bob-special
5320 (delq 'org-optimize-window-after-visibility-change
5321 (copy-sequence org-cycle-hook))
5322 org-cycle-hook))
5323 (pos (point)))
5325 (if (or bob-special (equal arg '(4)))
5326 ;; special case: use global cycling
5327 (setq arg t))
5329 (cond
5331 ((equal arg '(16))
5332 (org-set-startup-visibility)
5333 (message "Startup visibility, plus VISIBILITY properties"))
5335 ((equal arg '(64))
5336 (show-all)
5337 (message "Entire buffer visible, including drawers"))
5339 ((org-at-table-p 'any)
5340 ;; Enter the table or move to the next field in the table
5341 (if (org-at-table.el-p)
5342 (message "Use C-c ' to edit table.el tables")
5343 (if arg (org-table-edit-field t)
5344 (org-table-justify-field-maybe)
5345 (call-interactively 'org-table-next-field))))
5347 ((run-hook-with-args-until-success
5348 'org-tab-after-check-for-table-hook))
5350 ((eq arg t) ;; Global cycling
5351 (org-cycle-internal-global))
5353 ((and org-drawers org-drawer-regexp
5354 (save-excursion
5355 (beginning-of-line 1)
5356 (looking-at org-drawer-regexp)))
5357 ;; Toggle block visibility
5358 (org-flag-drawer
5359 (not (get-char-property (match-end 0) 'invisible))))
5361 ((integerp arg)
5362 ;; Show-subtree, ARG levels up from here.
5363 (save-excursion
5364 (org-back-to-heading)
5365 (outline-up-heading (if (< arg 0) (- arg)
5366 (- (funcall outline-level) arg)))
5367 (org-show-subtree)))
5369 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5370 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5372 (org-cycle-internal-local))
5374 ;; TAB emulation and template completion
5375 (buffer-read-only (org-back-to-heading))
5377 ((run-hook-with-args-until-success
5378 'org-tab-after-check-for-cycling-hook))
5380 ((org-try-structure-completion))
5382 ((org-try-cdlatex-tab))
5384 ((run-hook-with-args-until-success
5385 'org-tab-before-tab-emulation-hook))
5387 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5388 (or (not (bolp))
5389 (not (looking-at outline-regexp))))
5390 (call-interactively (global-key-binding "\t")))
5392 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5393 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5394 (or (and (eq org-cycle-emulate-tab 'white)
5395 (= (match-end 0) (point-at-eol)))
5396 (and (eq org-cycle-emulate-tab 'whitestart)
5397 (>= (match-end 0) pos))))
5399 (eq org-cycle-emulate-tab t))
5400 (call-interactively (global-key-binding "\t")))
5402 (t (save-excursion
5403 (org-back-to-heading)
5404 (org-cycle)))))))
5406 (defun org-cycle-internal-global ()
5407 "Do the global cycling action."
5408 (cond
5409 ((and (eq last-command this-command)
5410 (eq org-cycle-global-status 'overview))
5411 ;; We just created the overview - now do table of contents
5412 ;; This can be slow in very large buffers, so indicate action
5413 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5414 (message "CONTENTS...")
5415 (org-content)
5416 (message "CONTENTS...done")
5417 (setq org-cycle-global-status 'contents)
5418 (run-hook-with-args 'org-cycle-hook 'contents))
5420 ((and (eq last-command this-command)
5421 (eq org-cycle-global-status 'contents))
5422 ;; We just showed the table of contents - now show everything
5423 (run-hook-with-args 'org-pre-cycle-hook 'all)
5424 (show-all)
5425 (message "SHOW ALL")
5426 (setq org-cycle-global-status 'all)
5427 (run-hook-with-args 'org-cycle-hook 'all))
5430 ;; Default action: go to overview
5431 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5432 (org-overview)
5433 (message "OVERVIEW")
5434 (setq org-cycle-global-status 'overview)
5435 (run-hook-with-args 'org-cycle-hook 'overview))))
5437 (defun org-cycle-internal-local ()
5438 "Do the local cycling action."
5439 (org-back-to-heading)
5440 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5441 ;; First, some boundaries
5442 (save-excursion
5443 (org-back-to-heading)
5444 (setq level (funcall outline-level))
5445 (save-excursion
5446 (beginning-of-line 2)
5447 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5448 ; XEmacs does not have `next-single-char-property-change'
5449 ; I'm not sure about Emacs 21.
5450 (while (and (not (eobp)) ;; this is like `next-line'
5451 (get-char-property (1- (point)) 'invisible))
5452 (beginning-of-line 2))
5453 (while (and (not (eobp)) ;; this is like `next-line'
5454 (get-char-property (1- (point)) 'invisible))
5455 (goto-char (next-single-char-property-change (point) 'invisible))
5456 ;;;??? (or (bolp) (beginning-of-line 2))))
5457 (and (eolp) (beginning-of-line 2))))
5458 (setq eol (point)))
5459 (outline-end-of-heading) (setq eoh (point))
5460 (save-excursion
5461 (outline-next-heading)
5462 (setq has-children (and (org-at-heading-p t)
5463 (> (funcall outline-level) level))))
5464 (org-end-of-subtree t)
5465 (unless (eobp)
5466 (skip-chars-forward " \t\n")
5467 (beginning-of-line 1) ; in case this is an item
5469 (setq eos (if (eobp) (point) (1- (point)))))
5470 ;; Find out what to do next and set `this-command'
5471 (cond
5472 ((= eos eoh)
5473 ;; Nothing is hidden behind this heading
5474 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5475 (message "EMPTY ENTRY")
5476 (setq org-cycle-subtree-status nil)
5477 (save-excursion
5478 (goto-char eos)
5479 (outline-next-heading)
5480 (if (org-invisible-p) (org-flag-heading nil))))
5481 ((and (or (>= eol eos)
5482 (not (string-match "\\S-" (buffer-substring eol eos))))
5483 (or has-children
5484 (not (setq children-skipped
5485 org-cycle-skip-children-state-if-no-children))))
5486 ;; Entire subtree is hidden in one line: children view
5487 (run-hook-with-args 'org-pre-cycle-hook 'children)
5488 (org-show-entry)
5489 (show-children)
5490 (message "CHILDREN")
5491 (save-excursion
5492 (goto-char eos)
5493 (outline-next-heading)
5494 (if (org-invisible-p) (org-flag-heading nil)))
5495 (setq org-cycle-subtree-status 'children)
5496 (run-hook-with-args 'org-cycle-hook 'children))
5497 ((or children-skipped
5498 (and (eq last-command this-command)
5499 (eq org-cycle-subtree-status 'children)))
5500 ;; We just showed the children, or no children are there,
5501 ;; now show everything.
5502 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5503 (org-show-subtree)
5504 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5505 (setq org-cycle-subtree-status 'subtree)
5506 (run-hook-with-args 'org-cycle-hook 'subtree))
5508 ;; Default action: hide the subtree.
5509 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5510 (hide-subtree)
5511 (message "FOLDED")
5512 (setq org-cycle-subtree-status 'folded)
5513 (run-hook-with-args 'org-cycle-hook 'folded)))))
5515 ;;;###autoload
5516 (defun org-global-cycle (&optional arg)
5517 "Cycle the global visibility. For details see `org-cycle'.
5518 With C-u prefix arg, switch to startup visibility.
5519 With a numeric prefix, show all headlines up to that level."
5520 (interactive "P")
5521 (let ((org-cycle-include-plain-lists
5522 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5523 (cond
5524 ((integerp arg)
5525 (show-all)
5526 (hide-sublevels arg)
5527 (setq org-cycle-global-status 'contents))
5528 ((equal arg '(4))
5529 (org-set-startup-visibility)
5530 (message "Startup visibility, plus VISIBILITY properties."))
5532 (org-cycle '(4))))))
5534 (defun org-set-startup-visibility ()
5535 "Set the visibility required by startup options and properties."
5536 (cond
5537 ((eq org-startup-folded t)
5538 (org-cycle '(4)))
5539 ((eq org-startup-folded 'content)
5540 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5541 (org-cycle '(4)) (org-cycle '(4)))))
5542 (unless (eq org-startup-folded 'showeverything)
5543 (if org-hide-block-startup (org-hide-block-all))
5544 (org-set-visibility-according-to-property 'no-cleanup)
5545 (org-cycle-hide-archived-subtrees 'all)
5546 (org-cycle-hide-drawers 'all)
5547 (org-cycle-show-empty-lines 'all)))
5549 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5550 "Switch subtree visibilities according to :VISIBILITY: property."
5551 (interactive)
5552 (let (org-show-entry-below state)
5553 (save-excursion
5554 (goto-char (point-min))
5555 (while (re-search-forward
5556 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5557 nil t)
5558 (setq state (match-string 1))
5559 (save-excursion
5560 (org-back-to-heading t)
5561 (hide-subtree)
5562 (org-reveal)
5563 (cond
5564 ((equal state '("fold" "folded"))
5565 (hide-subtree))
5566 ((equal state "children")
5567 (org-show-hidden-entry)
5568 (show-children))
5569 ((equal state "content")
5570 (save-excursion
5571 (save-restriction
5572 (org-narrow-to-subtree)
5573 (org-content))))
5574 ((member state '("all" "showall"))
5575 (show-subtree)))))
5576 (unless no-cleanup
5577 (org-cycle-hide-archived-subtrees 'all)
5578 (org-cycle-hide-drawers 'all)
5579 (org-cycle-show-empty-lines 'all)))))
5581 (defun org-overview ()
5582 "Switch to overview mode, showing only top-level headlines.
5583 Really, this shows all headlines with level equal or greater than the level
5584 of the first headline in the buffer. This is important, because if the
5585 first headline is not level one, then (hide-sublevels 1) gives confusing
5586 results."
5587 (interactive)
5588 (let ((level (save-excursion
5589 (goto-char (point-min))
5590 (if (re-search-forward (concat "^" outline-regexp) nil t)
5591 (progn
5592 (goto-char (match-beginning 0))
5593 (funcall outline-level))))))
5594 (and level (hide-sublevels level))))
5596 (defun org-content (&optional arg)
5597 "Show all headlines in the buffer, like a table of contents.
5598 With numerical argument N, show content up to level N."
5599 (interactive "P")
5600 (save-excursion
5601 ;; Visit all headings and show their offspring
5602 (and (integerp arg) (org-overview))
5603 (goto-char (point-max))
5604 (catch 'exit
5605 (while (and (progn (condition-case nil
5606 (outline-previous-visible-heading 1)
5607 (error (goto-char (point-min))))
5609 (looking-at outline-regexp))
5610 (if (integerp arg)
5611 (show-children (1- arg))
5612 (show-branches))
5613 (if (bobp) (throw 'exit nil))))))
5616 (defun org-optimize-window-after-visibility-change (state)
5617 "Adjust the window after a change in outline visibility.
5618 This function is the default value of the hook `org-cycle-hook'."
5619 (when (get-buffer-window (current-buffer))
5620 (cond
5621 ((eq state 'content) nil)
5622 ((eq state 'all) nil)
5623 ((eq state 'folded) nil)
5624 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5625 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5627 (defun org-remove-empty-overlays-at (pos)
5628 "Remove outline overlays that do not contain non-white stuff."
5629 (mapc
5630 (lambda (o)
5631 (and (eq 'outline (org-overlay-get o 'invisible))
5632 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5633 (org-overlay-end o))))
5634 (org-delete-overlay o)))
5635 (org-overlays-at pos)))
5637 (defun org-clean-visibility-after-subtree-move ()
5638 "Fix visibility issues after moving a subtree."
5639 ;; First, find a reasonable region to look at:
5640 ;; Start two siblings above, end three below
5641 (let* ((beg (save-excursion
5642 (and (org-get-last-sibling)
5643 (org-get-last-sibling))
5644 (point)))
5645 (end (save-excursion
5646 (and (org-get-next-sibling)
5647 (org-get-next-sibling)
5648 (org-get-next-sibling))
5649 (if (org-at-heading-p)
5650 (point-at-eol)
5651 (point))))
5652 (level (looking-at "\\*+"))
5653 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5654 (save-excursion
5655 (save-restriction
5656 (narrow-to-region beg end)
5657 (when re
5658 ;; Properly fold already folded siblings
5659 (goto-char (point-min))
5660 (while (re-search-forward re nil t)
5661 (if (and (not (org-invisible-p))
5662 (save-excursion
5663 (goto-char (point-at-eol)) (org-invisible-p)))
5664 (hide-entry))))
5665 (org-cycle-show-empty-lines 'overview)
5666 (org-cycle-hide-drawers 'overview)))))
5668 (defun org-cycle-show-empty-lines (state)
5669 "Show empty lines above all visible headlines.
5670 The region to be covered depends on STATE when called through
5671 `org-cycle-hook'. Lisp program can use t for STATE to get the
5672 entire buffer covered. Note that an empty line is only shown if there
5673 are at least `org-cycle-separator-lines' empty lines before the headline."
5674 (when (not (= org-cycle-separator-lines 0))
5675 (save-excursion
5676 (let* ((n (abs org-cycle-separator-lines))
5677 (re (cond
5678 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5679 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5680 (t (let ((ns (number-to-string (- n 2))))
5681 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5682 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5683 beg end b e)
5684 (cond
5685 ((memq state '(overview contents t))
5686 (setq beg (point-min) end (point-max)))
5687 ((memq state '(children folded))
5688 (setq beg (point) end (progn (org-end-of-subtree t t)
5689 (beginning-of-line 2)
5690 (point)))))
5691 (when beg
5692 (goto-char beg)
5693 (while (re-search-forward re end t)
5694 (unless (get-char-property (match-end 1) 'invisible)
5695 (setq e (match-end 1))
5696 (if (< org-cycle-separator-lines 0)
5697 (setq b (save-excursion
5698 (goto-char (match-beginning 0))
5699 (org-back-over-empty-lines)
5700 (if (save-excursion
5701 (goto-char (max (point-min) (1- (point))))
5702 (org-on-heading-p))
5703 (1- (point))
5704 (point))))
5705 (setq b (match-beginning 1)))
5706 (outline-flag-region b e nil)))))))
5707 ;; Never hide empty lines at the end of the file.
5708 (save-excursion
5709 (goto-char (point-max))
5710 (outline-previous-heading)
5711 (outline-end-of-heading)
5712 (if (and (looking-at "[ \t\n]+")
5713 (= (match-end 0) (point-max)))
5714 (outline-flag-region (point) (match-end 0) nil))))
5716 (defun org-show-empty-lines-in-parent ()
5717 "Move to the parent and re-show empty lines before visible headlines."
5718 (save-excursion
5719 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5720 (org-cycle-show-empty-lines context))))
5722 (defun org-files-list ()
5723 "Return `org-agenda-files' list, plus all open org-mode files.
5724 This is useful for operations that need to scan all of a user's
5725 open and agenda-wise Org files."
5726 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5727 (dolist (buf (buffer-list))
5728 (with-current-buffer buf
5729 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5730 (let ((file (expand-file-name (buffer-file-name))))
5731 (unless (member file files)
5732 (push file files))))))
5733 files))
5735 (defsubst org-entry-beginning-position ()
5736 "Return the beginning position of the current entry."
5737 (save-excursion (outline-back-to-heading t) (point)))
5739 (defsubst org-entry-end-position ()
5740 "Return the end position of the current entry."
5741 (save-excursion (outline-next-heading) (point)))
5743 (defun org-cycle-hide-drawers (state)
5744 "Re-hide all drawers after a visibility state change."
5745 (when (and (org-mode-p)
5746 (not (memq state '(overview folded contents))))
5747 (save-excursion
5748 (let* ((globalp (memq state '(contents all)))
5749 (beg (if globalp (point-min) (point)))
5750 (end (if globalp (point-max)
5751 (if (eq state 'children)
5752 (save-excursion (outline-next-heading) (point))
5753 (org-end-of-subtree t)))))
5754 (goto-char beg)
5755 (while (re-search-forward org-drawer-regexp end t)
5756 (org-flag-drawer t))))))
5758 (defun org-flag-drawer (flag)
5759 (save-excursion
5760 (beginning-of-line 1)
5761 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5762 (let ((b (match-end 0))
5763 (outline-regexp org-outline-regexp))
5764 (if (re-search-forward
5765 "^[ \t]*:END:"
5766 (save-excursion (outline-next-heading) (point)) t)
5767 (outline-flag-region b (point-at-eol) flag)
5768 (error ":END: line missing at position %s" b))))))
5770 (defun org-subtree-end-visible-p ()
5771 "Is the end of the current subtree visible?"
5772 (pos-visible-in-window-p
5773 (save-excursion (org-end-of-subtree t) (point))))
5775 (defun org-first-headline-recenter (&optional N)
5776 "Move cursor to the first headline and recenter the headline.
5777 Optional argument N means put the headline into the Nth line of the window."
5778 (goto-char (point-min))
5779 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5780 (beginning-of-line)
5781 (recenter (prefix-numeric-value N))))
5783 ;;; Saving and restoring visibility
5785 (defun org-outline-overlay-data (&optional use-markers)
5786 "Return a list of the locations of all outline overlays.
5787 The are overlays with the `invisible' property value `outline'.
5788 The return valus is a list of cons cells, with start and stop
5789 positions for each overlay.
5790 If USE-MARKERS is set, return the positions as markers."
5791 (let (beg end)
5792 (save-excursion
5793 (save-restriction
5794 (widen)
5795 (delq nil
5796 (mapcar (lambda (o)
5797 (when (eq (org-overlay-get o 'invisible) 'outline)
5798 (setq beg (org-overlay-start o)
5799 end (org-overlay-end o))
5800 (and beg end (> end beg)
5801 (if use-markers
5802 (cons (move-marker (make-marker) beg)
5803 (move-marker (make-marker) end))
5804 (cons beg end)))))
5805 (org-overlays-in (point-min) (point-max))))))))
5807 (defun org-set-outline-overlay-data (data)
5808 "Create visibility overlays for all positions in DATA.
5809 DATA should have been made by `org-outline-overlay-data'."
5810 (let (o)
5811 (save-excursion
5812 (save-restriction
5813 (widen)
5814 (show-all)
5815 (mapc (lambda (c)
5816 (setq o (org-make-overlay (car c) (cdr c)))
5817 (org-overlay-put o 'invisible 'outline))
5818 data)))))
5820 (defmacro org-save-outline-visibility (use-markers &rest body)
5821 "Save and restore outline visibility around BODY.
5822 If USE-MARKERS is non-nil, use markers for the positions.
5823 This means that the buffer may change while running BODY,
5824 but it also means that the buffer should stay alive
5825 during the operation, because otherwise all these markers will
5826 point nowhere."
5827 `(let ((data (org-outline-overlay-data ,use-markers)))
5828 (unwind-protect
5829 (progn
5830 ,@body
5831 (org-set-outline-overlay-data data))
5832 (when ,use-markers
5833 (mapc (lambda (c)
5834 (and (markerp (car c)) (move-marker (car c) nil))
5835 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5836 data)))))
5839 ;;; Folding of blocks
5841 (defconst org-block-regexp
5843 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5844 "Regular expression for hiding blocks.")
5846 (defvar org-hide-block-overlays nil
5847 "Overlays hiding blocks.")
5848 (make-variable-buffer-local 'org-hide-block-overlays)
5850 (defun org-block-map (function &optional start end)
5851 "Call func at the head of all source blocks in the current
5852 buffer. Optional arguments START and END can be used to limit
5853 the range."
5854 (let ((start (or start (point-min)))
5855 (end (or end (point-max))))
5856 (save-excursion
5857 (goto-char start)
5858 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5859 (save-excursion
5860 (save-match-data
5861 (goto-char (match-beginning 0))
5862 (funcall function)))))))
5864 (defun org-hide-block-toggle-all ()
5865 "Toggle the visibility of all blocks in the current buffer."
5866 (org-block-map #'org-hide-block-toggle))
5868 (defun org-hide-block-all ()
5869 "Fold all blocks in the current buffer."
5870 (interactive)
5871 (org-show-block-all)
5872 (org-block-map #'org-hide-block-toggle-maybe))
5874 (defun org-show-block-all ()
5875 "Unfold all blocks in the current buffer."
5876 (mapc 'org-delete-overlay org-hide-block-overlays)
5877 (setq org-hide-block-overlays nil))
5879 (defun org-hide-block-toggle-maybe ()
5880 "Toggle visibility of block at point."
5881 (interactive)
5882 (let ((case-fold-search t))
5883 (if (save-excursion
5884 (beginning-of-line 1)
5885 (looking-at org-block-regexp))
5886 (progn (org-hide-block-toggle)
5887 t) ;; to signal that we took action
5888 nil))) ;; to signal that we did not
5890 (defun org-hide-block-toggle (&optional force)
5891 "Toggle the visibility of the current block."
5892 (interactive)
5893 (save-excursion
5894 (beginning-of-line)
5895 (if (re-search-forward org-block-regexp nil t)
5896 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5897 (end (match-end 0)) ;; end of entire body
5899 (if (memq t (mapcar (lambda (overlay)
5900 (eq (org-overlay-get overlay 'invisible)
5901 'org-hide-block))
5902 (org-overlays-at start)))
5903 (if (or (not force) (eq force 'off))
5904 (mapc (lambda (ov)
5905 (when (member ov org-hide-block-overlays)
5906 (setq org-hide-block-overlays
5907 (delq ov org-hide-block-overlays)))
5908 (when (eq (org-overlay-get ov 'invisible)
5909 'org-hide-block)
5910 (org-delete-overlay ov)))
5911 (org-overlays-at start)))
5912 (setq ov (org-make-overlay start end))
5913 (org-overlay-put ov 'invisible 'org-hide-block)
5914 ;; make the block accessible to isearch
5915 (org-overlay-put
5916 ov 'isearch-open-invisible
5917 (lambda (ov)
5918 (when (member ov org-hide-block-overlays)
5919 (setq org-hide-block-overlays
5920 (delq ov org-hide-block-overlays)))
5921 (when (eq (org-overlay-get ov 'invisible)
5922 'org-hide-block)
5923 (org-delete-overlay ov))))
5924 (push ov org-hide-block-overlays)))
5925 (error "Not looking at a source block"))))
5927 ;; org-tab-after-check-for-cycling-hook
5928 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5929 ;; Remove overlays when changing major mode
5930 (add-hook 'org-mode-hook
5931 (lambda () (org-add-hook 'change-major-mode-hook
5932 'org-show-block-all 'append 'local)))
5934 ;;; Org-goto
5936 (defvar org-goto-window-configuration nil)
5937 (defvar org-goto-marker nil)
5938 (defvar org-goto-map
5939 (let ((map (make-sparse-keymap)))
5940 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5941 (while (setq cmd (pop cmds))
5942 (substitute-key-definition cmd cmd map global-map)))
5943 (suppress-keymap map)
5944 (org-defkey map "\C-m" 'org-goto-ret)
5945 (org-defkey map [(return)] 'org-goto-ret)
5946 (org-defkey map [(left)] 'org-goto-left)
5947 (org-defkey map [(right)] 'org-goto-right)
5948 (org-defkey map [(control ?g)] 'org-goto-quit)
5949 (org-defkey map "\C-i" 'org-cycle)
5950 (org-defkey map [(tab)] 'org-cycle)
5951 (org-defkey map [(down)] 'outline-next-visible-heading)
5952 (org-defkey map [(up)] 'outline-previous-visible-heading)
5953 (if org-goto-auto-isearch
5954 (if (fboundp 'define-key-after)
5955 (define-key-after map [t] 'org-goto-local-auto-isearch)
5956 nil)
5957 (org-defkey map "q" 'org-goto-quit)
5958 (org-defkey map "n" 'outline-next-visible-heading)
5959 (org-defkey map "p" 'outline-previous-visible-heading)
5960 (org-defkey map "f" 'outline-forward-same-level)
5961 (org-defkey map "b" 'outline-backward-same-level)
5962 (org-defkey map "u" 'outline-up-heading))
5963 (org-defkey map "/" 'org-occur)
5964 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5965 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5966 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5967 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5968 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5969 map))
5971 (defconst org-goto-help
5972 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5973 RET=jump to location [Q]uit and return to previous location
5974 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5976 (defvar org-goto-start-pos) ; dynamically scoped parameter
5978 ;; FIXME: Docstring does not mention both interfaces
5979 (defun org-goto (&optional alternative-interface)
5980 "Look up a different location in the current file, keeping current visibility.
5982 When you want look-up or go to a different location in a document, the
5983 fastest way is often to fold the entire buffer and then dive into the tree.
5984 This method has the disadvantage, that the previous location will be folded,
5985 which may not be what you want.
5987 This command works around this by showing a copy of the current buffer
5988 in an indirect buffer, in overview mode. You can dive into the tree in
5989 that copy, use org-occur and incremental search to find a location.
5990 When pressing RET or `Q', the command returns to the original buffer in
5991 which the visibility is still unchanged. After RET is will also jump to
5992 the location selected in the indirect buffer and expose the
5993 the headline hierarchy above."
5994 (interactive "P")
5995 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5996 (org-refile-use-outline-path t)
5997 (org-refile-target-verify-function nil)
5998 (interface
5999 (if (not alternative-interface)
6000 org-goto-interface
6001 (if (eq org-goto-interface 'outline)
6002 'outline-path-completion
6003 'outline)))
6004 (org-goto-start-pos (point))
6005 (selected-point
6006 (if (eq interface 'outline)
6007 (car (org-get-location (current-buffer) org-goto-help))
6008 (nth 3 (org-refile-get-location "Goto: ")))))
6009 (if selected-point
6010 (progn
6011 (org-mark-ring-push org-goto-start-pos)
6012 (goto-char selected-point)
6013 (if (or (org-invisible-p) (org-invisible-p2))
6014 (org-show-context 'org-goto)))
6015 (message "Quit"))))
6017 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6018 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6019 (defvar org-goto-local-auto-isearch-map) ; defined below
6021 (defun org-get-location (buf help)
6022 "Let the user select a location in the Org-mode buffer BUF.
6023 This function uses a recursive edit. It returns the selected position
6024 or nil."
6025 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6026 (isearch-hide-immediately nil)
6027 (isearch-search-fun-function
6028 (lambda () 'org-goto-local-search-headings))
6029 (org-goto-selected-point org-goto-exit-command)
6030 (pop-up-frames nil)
6031 (special-display-buffer-names nil)
6032 (special-display-regexps nil)
6033 (special-display-function nil))
6034 (save-excursion
6035 (save-window-excursion
6036 (delete-other-windows)
6037 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6038 (switch-to-buffer
6039 (condition-case nil
6040 (make-indirect-buffer (current-buffer) "*org-goto*")
6041 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6042 (with-output-to-temp-buffer "*Help*"
6043 (princ help))
6044 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6045 (setq buffer-read-only nil)
6046 (let ((org-startup-truncated t)
6047 (org-startup-folded nil)
6048 (org-startup-align-all-tables nil))
6049 (org-mode)
6050 (org-overview))
6051 (setq buffer-read-only t)
6052 (if (and (boundp 'org-goto-start-pos)
6053 (integer-or-marker-p org-goto-start-pos))
6054 (let ((org-show-hierarchy-above t)
6055 (org-show-siblings t)
6056 (org-show-following-heading t))
6057 (goto-char org-goto-start-pos)
6058 (and (org-invisible-p) (org-show-context)))
6059 (goto-char (point-min)))
6060 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6061 (message "Select location and press RET")
6062 (use-local-map org-goto-map)
6063 (recursive-edit)
6065 (kill-buffer "*org-goto*")
6066 (cons org-goto-selected-point org-goto-exit-command)))
6068 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6069 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6070 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6071 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6073 (defun org-goto-local-search-headings (string bound noerror)
6074 "Search and make sure that any matches are in headlines."
6075 (catch 'return
6076 (while (if isearch-forward
6077 (search-forward string bound noerror)
6078 (search-backward string bound noerror))
6079 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6080 (and (member :headline context)
6081 (not (member :tags context))))
6082 (throw 'return (point))))))
6084 (defun org-goto-local-auto-isearch ()
6085 "Start isearch."
6086 (interactive)
6087 (goto-char (point-min))
6088 (let ((keys (this-command-keys)))
6089 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6090 (isearch-mode t)
6091 (isearch-process-search-char (string-to-char keys)))))
6093 (defun org-goto-ret (&optional arg)
6094 "Finish `org-goto' by going to the new location."
6095 (interactive "P")
6096 (setq org-goto-selected-point (point)
6097 org-goto-exit-command 'return)
6098 (throw 'exit nil))
6100 (defun org-goto-left ()
6101 "Finish `org-goto' by going to the new location."
6102 (interactive)
6103 (if (org-on-heading-p)
6104 (progn
6105 (beginning-of-line 1)
6106 (setq org-goto-selected-point (point)
6107 org-goto-exit-command 'left)
6108 (throw 'exit nil))
6109 (error "Not on a heading")))
6111 (defun org-goto-right ()
6112 "Finish `org-goto' by going to the new location."
6113 (interactive)
6114 (if (org-on-heading-p)
6115 (progn
6116 (setq org-goto-selected-point (point)
6117 org-goto-exit-command 'right)
6118 (throw 'exit nil))
6119 (error "Not on a heading")))
6121 (defun org-goto-quit ()
6122 "Finish `org-goto' without cursor motion."
6123 (interactive)
6124 (setq org-goto-selected-point nil)
6125 (setq org-goto-exit-command 'quit)
6126 (throw 'exit nil))
6128 ;;; Indirect buffer display of subtrees
6130 (defvar org-indirect-dedicated-frame nil
6131 "This is the frame being used for indirect tree display.")
6132 (defvar org-last-indirect-buffer nil)
6134 (defun org-tree-to-indirect-buffer (&optional arg)
6135 "Create indirect buffer and narrow it to current subtree.
6136 With numerical prefix ARG, go up to this level and then take that tree.
6137 If ARG is negative, go up that many levels.
6138 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6139 indirect buffer previously made with this command, to avoid proliferation of
6140 indirect buffers. However, when you call the command with a `C-u' prefix, or
6141 when `org-indirect-buffer-display' is `new-frame', the last buffer
6142 is kept so that you can work with several indirect buffers at the same time.
6143 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6144 requests that a new frame be made for the new buffer, so that the dedicated
6145 frame is not changed."
6146 (interactive "P")
6147 (let ((cbuf (current-buffer))
6148 (cwin (selected-window))
6149 (pos (point))
6150 beg end level heading ibuf)
6151 (save-excursion
6152 (org-back-to-heading t)
6153 (when (numberp arg)
6154 (setq level (org-outline-level))
6155 (if (< arg 0) (setq arg (+ level arg)))
6156 (while (> (setq level (org-outline-level)) arg)
6157 (outline-up-heading 1 t)))
6158 (setq beg (point)
6159 heading (org-get-heading))
6160 (org-end-of-subtree t t)
6161 (if (org-on-heading-p) (backward-char 1))
6162 (setq end (point)))
6163 (if (and (buffer-live-p org-last-indirect-buffer)
6164 (not (eq org-indirect-buffer-display 'new-frame))
6165 (not arg))
6166 (kill-buffer org-last-indirect-buffer))
6167 (setq ibuf (org-get-indirect-buffer cbuf)
6168 org-last-indirect-buffer ibuf)
6169 (cond
6170 ((or (eq org-indirect-buffer-display 'new-frame)
6171 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6172 (select-frame (make-frame))
6173 (delete-other-windows)
6174 (switch-to-buffer ibuf)
6175 (org-set-frame-title heading))
6176 ((eq org-indirect-buffer-display 'dedicated-frame)
6177 (raise-frame
6178 (select-frame (or (and org-indirect-dedicated-frame
6179 (frame-live-p org-indirect-dedicated-frame)
6180 org-indirect-dedicated-frame)
6181 (setq org-indirect-dedicated-frame (make-frame)))))
6182 (delete-other-windows)
6183 (switch-to-buffer ibuf)
6184 (org-set-frame-title (concat "Indirect: " heading)))
6185 ((eq org-indirect-buffer-display 'current-window)
6186 (switch-to-buffer ibuf))
6187 ((eq org-indirect-buffer-display 'other-window)
6188 (pop-to-buffer ibuf))
6189 (t (error "Invalid value")))
6190 (if (featurep 'xemacs)
6191 (save-excursion (org-mode) (turn-on-font-lock)))
6192 (narrow-to-region beg end)
6193 (show-all)
6194 (goto-char pos)
6195 (and (window-live-p cwin) (select-window cwin))))
6197 (defun org-get-indirect-buffer (&optional buffer)
6198 (setq buffer (or buffer (current-buffer)))
6199 (let ((n 1) (base (buffer-name buffer)) bname)
6200 (while (buffer-live-p
6201 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6202 (setq n (1+ n)))
6203 (condition-case nil
6204 (make-indirect-buffer buffer bname 'clone)
6205 (error (make-indirect-buffer buffer bname)))))
6207 (defun org-set-frame-title (title)
6208 "Set the title of the current frame to the string TITLE."
6209 ;; FIXME: how to name a single frame in XEmacs???
6210 (unless (featurep 'xemacs)
6211 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6213 ;;;; Structure editing
6215 ;;; Inserting headlines
6217 (defun org-previous-line-empty-p ()
6218 (save-excursion
6219 (and (not (bobp))
6220 (or (beginning-of-line 0) t)
6221 (save-match-data
6222 (looking-at "[ \t]*$")))))
6224 (defun org-insert-heading (&optional force-heading invisible-ok)
6225 "Insert a new heading or item with same depth at point.
6226 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6227 If point is at the beginning of a headline, insert a sibling before the
6228 current headline. If point is not at the beginning, do not split the line,
6229 but create the new headline after the current line.
6230 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6231 This is important for non-interactive uses of the command."
6232 (interactive "P")
6233 (if (or (= (buffer-size) 0)
6234 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6235 (org-on-heading-p))))
6236 (not (org-in-item-p))))
6237 (insert "\n* ")
6238 (when (or force-heading (not (org-insert-item)))
6239 (let* ((empty-line-p nil)
6240 (head (save-excursion
6241 (condition-case nil
6242 (progn
6243 (org-back-to-heading invisible-ok)
6244 (setq empty-line-p (org-previous-line-empty-p))
6245 (match-string 0))
6246 (error "*"))))
6247 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6248 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6249 pos hide-previous previous-pos)
6250 (cond
6251 ((and (org-on-heading-p) (bolp)
6252 (or (bobp)
6253 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6254 ;; insert before the current line
6255 (open-line (if blank 2 1)))
6256 ((and (bolp)
6257 (not org-insert-heading-respect-content)
6258 (or (bobp)
6259 (save-excursion
6260 (backward-char 1) (not (org-invisible-p)))))
6261 ;; insert right here
6262 nil)
6264 ;; somewhere in the line
6265 (save-excursion
6266 (setq previous-pos (point-at-bol))
6267 (end-of-line)
6268 (setq hide-previous (org-invisible-p)))
6269 (and org-insert-heading-respect-content (org-show-subtree))
6270 (let ((split
6271 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6272 (save-excursion
6273 (let ((p (point)))
6274 (goto-char (point-at-bol))
6275 (and (looking-at org-complex-heading-regexp)
6276 (> p (match-beginning 4)))))))
6277 tags pos)
6278 (cond
6279 (org-insert-heading-respect-content
6280 (org-end-of-subtree nil t)
6281 (or (bolp) (newline))
6282 (or (org-previous-line-empty-p)
6283 (and blank (newline)))
6284 (open-line 1))
6285 ((org-on-heading-p)
6286 (when hide-previous
6287 (show-children)
6288 (org-show-entry))
6289 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6290 (setq tags (and (match-end 2) (match-string 2)))
6291 (and (match-end 1)
6292 (delete-region (match-beginning 1) (match-end 1)))
6293 (setq pos (point-at-bol))
6294 (or split (end-of-line 1))
6295 (delete-horizontal-space)
6296 (if (string-match "\\`\\*+\\'"
6297 (buffer-substring (point-at-bol) (point)))
6298 (insert " "))
6299 (newline (if blank 2 1))
6300 (when tags
6301 (save-excursion
6302 (goto-char pos)
6303 (end-of-line 1)
6304 (insert " " tags)
6305 (org-set-tags nil 'align))))
6307 (or split (end-of-line 1))
6308 (newline (if blank 2 1)))))))
6309 (insert head) (just-one-space)
6310 (setq pos (point))
6311 (end-of-line 1)
6312 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6313 (when (and org-insert-heading-respect-content hide-previous)
6314 (save-excursion
6315 (goto-char previous-pos)
6316 (hide-subtree)))
6317 (run-hooks 'org-insert-heading-hook)))))
6319 (defun org-get-heading (&optional no-tags)
6320 "Return the heading of the current entry, without the stars."
6321 (save-excursion
6322 (org-back-to-heading t)
6323 (if (looking-at
6324 (if no-tags
6325 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6326 "\\*+[ \t]+\\([^\r\n]*\\)"))
6327 (match-string 1) "")))
6329 (defun org-heading-components ()
6330 "Return the components of the current heading.
6331 This is a list with the following elements:
6332 - the level as an integer
6333 - the reduced level, different if `org-odd-levels-only' is set.
6334 - the TODO keyword, or nil
6335 - the priority character, like ?A, or nil if no priority is given
6336 - the headline text itself, or the tags string if no headline text
6337 - the tags string, or nil."
6338 (save-excursion
6339 (org-back-to-heading t)
6340 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6341 (list (length (match-string 1))
6342 (org-reduced-level (length (match-string 1)))
6343 (org-match-string-no-properties 2)
6344 (and (match-end 3) (aref (match-string 3) 2))
6345 (org-match-string-no-properties 4)
6346 (org-match-string-no-properties 5)))))
6348 (defun org-get-entry ()
6349 "Get the entry text, after heading, entire subtree."
6350 (save-excursion
6351 (org-back-to-heading t)
6352 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6354 (defun org-insert-heading-after-current ()
6355 "Insert a new heading with same level as current, after current subtree."
6356 (interactive)
6357 (org-back-to-heading)
6358 (org-insert-heading)
6359 (org-move-subtree-down)
6360 (end-of-line 1))
6362 (defun org-insert-heading-respect-content ()
6363 (interactive)
6364 (let ((org-insert-heading-respect-content t))
6365 (org-insert-heading t)))
6367 (defun org-insert-todo-heading-respect-content (&optional force-state)
6368 (interactive "P")
6369 (let ((org-insert-heading-respect-content t))
6370 (org-insert-todo-heading force-state t)))
6372 (defun org-insert-todo-heading (arg &optional force-heading)
6373 "Insert a new heading with the same level and TODO state as current heading.
6374 If the heading has no TODO state, or if the state is DONE, use the first
6375 state (TODO by default). Also with prefix arg, force first state."
6376 (interactive "P")
6377 (when (or force-heading (not (org-insert-item 'checkbox)))
6378 (org-insert-heading force-heading)
6379 (save-excursion
6380 (org-back-to-heading)
6381 (outline-previous-heading)
6382 (looking-at org-todo-line-regexp))
6383 (let*
6384 ((new-mark-x
6385 (if (or arg
6386 (not (match-beginning 2))
6387 (member (match-string 2) org-done-keywords))
6388 (car org-todo-keywords-1)
6389 (match-string 2)))
6390 (new-mark
6392 (run-hook-with-args-until-success
6393 'org-todo-get-default-hook new-mark-x nil)
6394 new-mark-x)))
6395 (beginning-of-line 1)
6396 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6397 (if org-treat-insert-todo-heading-as-state-change
6398 (org-todo new-mark)
6399 (insert new-mark " "))))
6400 (when org-provide-todo-statistics
6401 (org-update-parent-todo-statistics))))
6403 (defun org-insert-subheading (arg)
6404 "Insert a new subheading and demote it.
6405 Works for outline headings and for plain lists alike."
6406 (interactive "P")
6407 (org-insert-heading arg)
6408 (cond
6409 ((org-on-heading-p) (org-do-demote))
6410 ((org-at-item-p) (org-indent-item 1))))
6412 (defun org-insert-todo-subheading (arg)
6413 "Insert a new subheading with TODO keyword or checkbox and demote it.
6414 Works for outline headings and for plain lists alike."
6415 (interactive "P")
6416 (org-insert-todo-heading arg)
6417 (cond
6418 ((org-on-heading-p) (org-do-demote))
6419 ((org-at-item-p) (org-indent-item 1))))
6421 ;;; Promotion and Demotion
6423 (defvar org-after-demote-entry-hook nil
6424 "Hook run after an entry has been demoted.
6425 The cursor will be at the beginning of the entry.
6426 When a subtree is being demoted, the hook will be called for each node.")
6428 (defvar org-after-promote-entry-hook nil
6429 "Hook run after an entry has been promoted.
6430 The cursor will be at the beginning of the entry.
6431 When a subtree is being promoted, the hook will be called for each node.")
6433 (defun org-promote-subtree ()
6434 "Promote the entire subtree.
6435 See also `org-promote'."
6436 (interactive)
6437 (save-excursion
6438 (org-map-tree 'org-promote))
6439 (org-fix-position-after-promote))
6441 (defun org-demote-subtree ()
6442 "Demote the entire subtree. See `org-demote'.
6443 See also `org-promote'."
6444 (interactive)
6445 (save-excursion
6446 (org-map-tree 'org-demote))
6447 (org-fix-position-after-promote))
6450 (defun org-do-promote ()
6451 "Promote the current heading higher up the tree.
6452 If the region is active in `transient-mark-mode', promote all headings
6453 in the region."
6454 (interactive)
6455 (save-excursion
6456 (if (org-region-active-p)
6457 (org-map-region 'org-promote (region-beginning) (region-end))
6458 (org-promote)))
6459 (org-fix-position-after-promote))
6461 (defun org-do-demote ()
6462 "Demote the current heading lower down the tree.
6463 If the region is active in `transient-mark-mode', demote all headings
6464 in the region."
6465 (interactive)
6466 (save-excursion
6467 (if (org-region-active-p)
6468 (org-map-region 'org-demote (region-beginning) (region-end))
6469 (org-demote)))
6470 (org-fix-position-after-promote))
6472 (defun org-fix-position-after-promote ()
6473 "Make sure that after pro/demotion cursor position is right."
6474 (let ((pos (point)))
6475 (when (save-excursion
6476 (beginning-of-line 1)
6477 (looking-at org-todo-line-regexp)
6478 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6479 (cond ((eobp) (insert " "))
6480 ((eolp) (insert " "))
6481 ((equal (char-after) ?\ ) (forward-char 1))))))
6483 (defun org-current-level ()
6484 "Return the level of the current entry, or nil if before the first headline.
6485 The level is the number of stars at the beginning of the headline."
6486 (save-excursion
6487 (condition-case nil
6488 (progn
6489 (org-back-to-heading t)
6490 (funcall outline-level))
6491 (error nil))))
6493 (defun org-get-previous-line-level ()
6494 "Return the outline depth of the last headline before the current line.
6495 Returns 0 for the first headline in the buffer, and nil if before the
6496 first headline."
6497 (let ((current-level (org-current-level))
6498 (prev-level (when (> (line-number-at-pos) 1)
6499 (save-excursion
6500 (beginning-of-line 0)
6501 (org-current-level)))))
6502 (cond ((null current-level) nil) ; Before first headline
6503 ((null prev-level) 0) ; At first headline
6504 (prev-level))))
6506 (defun org-reduced-level (l)
6507 "Compute the effective level of a heading.
6508 This takes into account the setting of `org-odd-levels-only'."
6509 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6511 (defun org-level-increment ()
6512 "Return the number of stars that will be added or removed at a
6513 time to headlines when structure editing, based on the value of
6514 `org-odd-levels-only'."
6515 (if org-odd-levels-only 2 1))
6517 (defun org-get-valid-level (level &optional change)
6518 "Rectify a level change under the influence of `org-odd-levels-only'
6519 LEVEL is a current level, CHANGE is by how much the level should be
6520 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6521 even level numbers will become the next higher odd number."
6522 (if org-odd-levels-only
6523 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6524 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6525 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6526 (max 1 (+ level (or change 0)))))
6528 (if (boundp 'define-obsolete-function-alias)
6529 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6530 (define-obsolete-function-alias 'org-get-legal-level
6531 'org-get-valid-level)
6532 (define-obsolete-function-alias 'org-get-legal-level
6533 'org-get-valid-level "23.1")))
6535 (defun org-promote ()
6536 "Promote the current heading higher up the tree.
6537 If the region is active in `transient-mark-mode', promote all headings
6538 in the region."
6539 (org-back-to-heading t)
6540 (let* ((level (save-match-data (funcall outline-level)))
6541 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6542 (diff (abs (- level (length up-head) -1))))
6543 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6544 (replace-match up-head nil t)
6545 ;; Fixup tag positioning
6546 (and org-auto-align-tags (org-set-tags nil t))
6547 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6548 (run-hooks 'org-after-promote-entry-hook)))
6550 (defun org-demote ()
6551 "Demote the current heading lower down the tree.
6552 If the region is active in `transient-mark-mode', demote all headings
6553 in the region."
6554 (org-back-to-heading t)
6555 (let* ((level (save-match-data (funcall outline-level)))
6556 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6557 (diff (abs (- level (length down-head) -1))))
6558 (replace-match down-head nil t)
6559 ;; Fixup tag positioning
6560 (and org-auto-align-tags (org-set-tags nil t))
6561 (if org-adapt-indentation (org-fixup-indentation diff))
6562 (run-hooks 'org-after-demote-entry-hook)))
6564 (defun org-cycle-level ()
6565 "Cycle the level of an empty headline through possible states.
6566 This goes first to child, then to parent, level, then up the hierarchy.
6567 After top level, it switches back to sibling level."
6568 (interactive)
6569 (let ((org-adapt-indentation nil))
6570 (when (org-point-at-end-of-empty-headline)
6571 (setq this-command 'org-cycle-level) ; Only needed for caching
6572 (let ((cur-level (org-current-level))
6573 (prev-level (org-get-previous-line-level)))
6574 (cond
6575 ;; If first headline in file, promote to top-level.
6576 ((= prev-level 0)
6577 (loop repeat (/ (- cur-level 1) (org-level-increment))
6578 do (org-do-promote)))
6579 ;; If same level as prev, demote one.
6580 ((= prev-level cur-level)
6581 (org-do-demote))
6582 ;; If parent is top-level, promote to top level if not already.
6583 ((= prev-level 1)
6584 (loop repeat (/ (- cur-level 1) (org-level-increment))
6585 do (org-do-promote)))
6586 ;; If top-level, return to prev-level.
6587 ((= cur-level 1)
6588 (loop repeat (/ (- prev-level 1) (org-level-increment))
6589 do (org-do-demote)))
6590 ;; If less than prev-level, promote one.
6591 ((< cur-level prev-level)
6592 (org-do-promote))
6593 ;; If deeper than prev-level, promote until higher than
6594 ;; prev-level.
6595 ((> cur-level prev-level)
6596 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6597 do (org-do-promote))))
6598 t))))
6600 (defun org-map-tree (fun)
6601 "Call FUN for every heading underneath the current one."
6602 (org-back-to-heading)
6603 (let ((level (funcall outline-level)))
6604 (save-excursion
6605 (funcall fun)
6606 (while (and (progn
6607 (outline-next-heading)
6608 (> (funcall outline-level) level))
6609 (not (eobp)))
6610 (funcall fun)))))
6612 (defun org-map-region (fun beg end)
6613 "Call FUN for every heading between BEG and END."
6614 (let ((org-ignore-region t))
6615 (save-excursion
6616 (setq end (copy-marker end))
6617 (goto-char beg)
6618 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6619 (< (point) end))
6620 (funcall fun))
6621 (while (and (progn
6622 (outline-next-heading)
6623 (< (point) end))
6624 (not (eobp)))
6625 (funcall fun)))))
6627 (defun org-fixup-indentation (diff)
6628 "Change the indentation in the current entry by DIFF
6629 However, if any line in the current entry has no indentation, or if it
6630 would end up with no indentation after the change, nothing at all is done."
6631 (save-excursion
6632 (let ((end (save-excursion (outline-next-heading)
6633 (point-marker)))
6634 (prohibit (if (> diff 0)
6635 "^\\S-"
6636 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6637 col)
6638 (unless (save-excursion (end-of-line 1)
6639 (re-search-forward prohibit end t))
6640 (while (and (< (point) end)
6641 (re-search-forward "^[ \t]+" end t))
6642 (goto-char (match-end 0))
6643 (setq col (current-column))
6644 (if (< diff 0) (replace-match ""))
6645 (org-indent-to-column (+ diff col))))
6646 (move-marker end nil))))
6648 (defun org-convert-to-odd-levels ()
6649 "Convert an org-mode file with all levels allowed to one with odd levels.
6650 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6651 level 5 etc."
6652 (interactive)
6653 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6654 (let ((outline-regexp org-outline-regexp)
6655 (outline-level 'org-outline-level)
6656 (org-odd-levels-only nil) n)
6657 (save-excursion
6658 (goto-char (point-min))
6659 (while (re-search-forward "^\\*\\*+ " nil t)
6660 (setq n (- (length (match-string 0)) 2))
6661 (while (>= (setq n (1- n)) 0)
6662 (org-demote))
6663 (end-of-line 1))))))
6665 (defun org-convert-to-oddeven-levels ()
6666 "Convert an org-mode file with only odd levels to one with odd and even levels.
6667 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6668 section with an even level, conversion would destroy the structure of the file. An error
6669 is signaled in this case."
6670 (interactive)
6671 (goto-char (point-min))
6672 ;; First check if there are no even levels
6673 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6674 (org-show-context t)
6675 (error "Not all levels are odd in this file. Conversion not possible"))
6676 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6677 (let ((outline-regexp org-outline-regexp)
6678 (outline-level 'org-outline-level)
6679 (org-odd-levels-only nil) n)
6680 (save-excursion
6681 (goto-char (point-min))
6682 (while (re-search-forward "^\\*\\*+ " nil t)
6683 (setq n (/ (1- (length (match-string 0))) 2))
6684 (while (>= (setq n (1- n)) 0)
6685 (org-promote))
6686 (end-of-line 1))))))
6688 (defun org-tr-level (n)
6689 "Make N odd if required."
6690 (if org-odd-levels-only (1+ (/ n 2)) n))
6692 ;;; Vertical tree motion, cutting and pasting of subtrees
6694 (defun org-move-subtree-up (&optional arg)
6695 "Move the current subtree up past ARG headlines of the same level."
6696 (interactive "p")
6697 (org-move-subtree-down (- (prefix-numeric-value arg))))
6699 (defun org-move-subtree-down (&optional arg)
6700 "Move the current subtree down past ARG headlines of the same level."
6701 (interactive "p")
6702 (setq arg (prefix-numeric-value arg))
6703 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6704 'org-get-last-sibling))
6705 (ins-point (make-marker))
6706 (cnt (abs arg))
6707 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6708 ;; Select the tree
6709 (org-back-to-heading)
6710 (setq beg0 (point))
6711 (save-excursion
6712 (setq ne-beg (org-back-over-empty-lines))
6713 (setq beg (point)))
6714 (save-match-data
6715 (save-excursion (outline-end-of-heading)
6716 (setq folded (org-invisible-p)))
6717 (outline-end-of-subtree))
6718 (outline-next-heading)
6719 (setq ne-end (org-back-over-empty-lines))
6720 (setq end (point))
6721 (goto-char beg0)
6722 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6723 ;; include less whitespace
6724 (save-excursion
6725 (goto-char beg)
6726 (forward-line (- ne-beg ne-end))
6727 (setq beg (point))))
6728 ;; Find insertion point, with error handling
6729 (while (> cnt 0)
6730 (or (and (funcall movfunc) (looking-at outline-regexp))
6731 (progn (goto-char beg0)
6732 (error "Cannot move past superior level or buffer limit")))
6733 (setq cnt (1- cnt)))
6734 (if (> arg 0)
6735 ;; Moving forward - still need to move over subtree
6736 (progn (org-end-of-subtree t t)
6737 (save-excursion
6738 (org-back-over-empty-lines)
6739 (or (bolp) (newline)))))
6740 (setq ne-ins (org-back-over-empty-lines))
6741 (move-marker ins-point (point))
6742 (setq txt (buffer-substring beg end))
6743 (org-save-markers-in-region beg end)
6744 (delete-region beg end)
6745 (org-remove-empty-overlays-at beg)
6746 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6747 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6748 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6749 (let ((bbb (point)))
6750 (insert-before-markers txt)
6751 (org-reinstall-markers-in-region bbb)
6752 (move-marker ins-point bbb))
6753 (or (bolp) (insert "\n"))
6754 (setq ins-end (point))
6755 (goto-char ins-point)
6756 (org-skip-whitespace)
6757 (when (and (< arg 0)
6758 (org-first-sibling-p)
6759 (> ne-ins ne-beg))
6760 ;; Move whitespace back to beginning
6761 (save-excursion
6762 (goto-char ins-end)
6763 (let ((kill-whole-line t))
6764 (kill-line (- ne-ins ne-beg)) (point)))
6765 (insert (make-string (- ne-ins ne-beg) ?\n)))
6766 (move-marker ins-point nil)
6767 (if folded
6768 (hide-subtree)
6769 (org-show-entry)
6770 (show-children)
6771 (org-cycle-hide-drawers 'children))
6772 (org-clean-visibility-after-subtree-move)))
6774 (defvar org-subtree-clip ""
6775 "Clipboard for cut and paste of subtrees.
6776 This is actually only a copy of the kill, because we use the normal kill
6777 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6779 (defvar org-subtree-clip-folded nil
6780 "Was the last copied subtree folded?
6781 This is used to fold the tree back after pasting.")
6783 (defun org-cut-subtree (&optional n)
6784 "Cut the current subtree into the clipboard.
6785 With prefix arg N, cut this many sequential subtrees.
6786 This is a short-hand for marking the subtree and then cutting it."
6787 (interactive "p")
6788 (org-copy-subtree n 'cut))
6790 (defun org-copy-subtree (&optional n cut force-store-markers)
6791 "Cut the current subtree into the clipboard.
6792 With prefix arg N, cut this many sequential subtrees.
6793 This is a short-hand for marking the subtree and then copying it.
6794 If CUT is non-nil, actually cut the subtree.
6795 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6796 of some markers in the region, even if CUT is non-nil. This is
6797 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6798 (interactive "p")
6799 (let (beg end folded (beg0 (point)))
6800 (if (interactive-p)
6801 (org-back-to-heading nil) ; take what looks like a subtree
6802 (org-back-to-heading t)) ; take what is really there
6803 (org-back-over-empty-lines)
6804 (setq beg (point))
6805 (skip-chars-forward " \t\r\n")
6806 (save-match-data
6807 (save-excursion (outline-end-of-heading)
6808 (setq folded (org-invisible-p)))
6809 (condition-case nil
6810 (org-forward-same-level (1- n) t)
6811 (error nil))
6812 (org-end-of-subtree t t))
6813 (org-back-over-empty-lines)
6814 (setq end (point))
6815 (goto-char beg0)
6816 (when (> end beg)
6817 (setq org-subtree-clip-folded folded)
6818 (when (or cut force-store-markers)
6819 (org-save-markers-in-region beg end))
6820 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6821 (setq org-subtree-clip (current-kill 0))
6822 (message "%s: Subtree(s) with %d characters"
6823 (if cut "Cut" "Copied")
6824 (length org-subtree-clip)))))
6826 (defun org-paste-subtree (&optional level tree for-yank)
6827 "Paste the clipboard as a subtree, with modification of headline level.
6828 The entire subtree is promoted or demoted in order to match a new headline
6829 level.
6831 If the cursor is at the beginning of a headline, the same level as
6832 that headline is used to paste the tree
6834 If not, the new level is derived from the *visible* headings
6835 before and after the insertion point, and taken to be the inferior headline
6836 level of the two. So if the previous visible heading is level 3 and the
6837 next is level 4 (or vice versa), level 4 will be used for insertion.
6838 This makes sure that the subtree remains an independent subtree and does
6839 not swallow low level entries.
6841 You can also force a different level, either by using a numeric prefix
6842 argument, or by inserting the heading marker by hand. For example, if the
6843 cursor is after \"*****\", then the tree will be shifted to level 5.
6845 If optional TREE is given, use this text instead of the kill ring.
6847 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6848 move back over whitespace before inserting, and move point to the end of
6849 the inserted text when done."
6850 (interactive "P")
6851 (setq tree (or tree (and kill-ring (current-kill 0))))
6852 (unless (org-kill-is-subtree-p tree)
6853 (error "%s"
6854 (substitute-command-keys
6855 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6856 (let* ((visp (not (org-invisible-p)))
6857 (txt tree)
6858 (^re (concat "^\\(" outline-regexp "\\)"))
6859 (re (concat "\\(" outline-regexp "\\)"))
6860 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6862 (old-level (if (string-match ^re txt)
6863 (- (match-end 0) (match-beginning 0) 1)
6864 -1))
6865 (force-level (cond (level (prefix-numeric-value level))
6866 ((and (looking-at "[ \t]*$")
6867 (string-match
6868 ^re_ (buffer-substring
6869 (point-at-bol) (point))))
6870 (- (match-end 1) (match-beginning 1)))
6871 ((and (bolp)
6872 (looking-at org-outline-regexp))
6873 (- (match-end 0) (point) 1))
6874 (t nil)))
6875 (previous-level (save-excursion
6876 (condition-case nil
6877 (progn
6878 (outline-previous-visible-heading 1)
6879 (if (looking-at re)
6880 (- (match-end 0) (match-beginning 0) 1)
6882 (error 1))))
6883 (next-level (save-excursion
6884 (condition-case nil
6885 (progn
6886 (or (looking-at outline-regexp)
6887 (outline-next-visible-heading 1))
6888 (if (looking-at re)
6889 (- (match-end 0) (match-beginning 0) 1)
6891 (error 1))))
6892 (new-level (or force-level (max previous-level next-level)))
6893 (shift (if (or (= old-level -1)
6894 (= new-level -1)
6895 (= old-level new-level))
6897 (- new-level old-level)))
6898 (delta (if (> shift 0) -1 1))
6899 (func (if (> shift 0) 'org-demote 'org-promote))
6900 (org-odd-levels-only nil)
6901 beg end newend)
6902 ;; Remove the forced level indicator
6903 (if force-level
6904 (delete-region (point-at-bol) (point)))
6905 ;; Paste
6906 (beginning-of-line 1)
6907 (unless for-yank (org-back-over-empty-lines))
6908 (setq beg (point))
6909 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6910 (insert-before-markers txt)
6911 (unless (string-match "\n\\'" txt) (insert "\n"))
6912 (setq newend (point))
6913 (org-reinstall-markers-in-region beg)
6914 (setq end (point))
6915 (goto-char beg)
6916 (skip-chars-forward " \t\n\r")
6917 (setq beg (point))
6918 (if (and (org-invisible-p) visp)
6919 (save-excursion (outline-show-heading)))
6920 ;; Shift if necessary
6921 (unless (= shift 0)
6922 (save-restriction
6923 (narrow-to-region beg end)
6924 (while (not (= shift 0))
6925 (org-map-region func (point-min) (point-max))
6926 (setq shift (+ delta shift)))
6927 (goto-char (point-min))
6928 (setq newend (point-max))))
6929 (when (or (interactive-p) for-yank)
6930 (message "Clipboard pasted as level %d subtree" new-level))
6931 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6932 kill-ring
6933 (eq org-subtree-clip (current-kill 0))
6934 org-subtree-clip-folded)
6935 ;; The tree was folded before it was killed/copied
6936 (hide-subtree))
6937 (and for-yank (goto-char newend))))
6939 (defun org-kill-is-subtree-p (&optional txt)
6940 "Check if the current kill is an outline subtree, or a set of trees.
6941 Returns nil if kill does not start with a headline, or if the first
6942 headline level is not the largest headline level in the tree.
6943 So this will actually accept several entries of equal levels as well,
6944 which is OK for `org-paste-subtree'.
6945 If optional TXT is given, check this string instead of the current kill."
6946 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6947 (start-level (and kill
6948 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6949 org-outline-regexp "\\)")
6950 kill)
6951 (- (match-end 2) (match-beginning 2) 1)))
6952 (re (concat "^" org-outline-regexp))
6953 (start (1+ (or (match-beginning 2) -1))))
6954 (if (not start-level)
6955 (progn
6956 nil) ;; does not even start with a heading
6957 (catch 'exit
6958 (while (setq start (string-match re kill (1+ start)))
6959 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6960 (throw 'exit nil)))
6961 t))))
6963 (defvar org-markers-to-move nil
6964 "Markers that should be moved with a cut-and-paste operation.
6965 Those markers are stored together with their positions relative to
6966 the start of the region.")
6968 (defun org-save-markers-in-region (beg end)
6969 "Check markers in region.
6970 If these markers are between BEG and END, record their position relative
6971 to BEG, so that after moving the block of text, we can put the markers back
6972 into place.
6973 This function gets called just before an entry or tree gets cut from the
6974 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6975 called immediately, to move the markers with the entries."
6976 (setq org-markers-to-move nil)
6977 (when (featurep 'org-clock)
6978 (org-clock-save-markers-for-cut-and-paste beg end))
6979 (when (featurep 'org-agenda)
6980 (org-agenda-save-markers-for-cut-and-paste beg end)))
6982 (defun org-check-and-save-marker (marker beg end)
6983 "Check if MARKER is between BEG and END.
6984 If yes, remember the marker and the distance to BEG."
6985 (when (and (marker-buffer marker)
6986 (equal (marker-buffer marker) (current-buffer)))
6987 (if (and (>= marker beg) (< marker end))
6988 (push (cons marker (- marker beg)) org-markers-to-move))))
6990 (defun org-reinstall-markers-in-region (beg)
6991 "Move all remembered markers to their position relative to BEG."
6992 (mapc (lambda (x)
6993 (move-marker (car x) (+ beg (cdr x))))
6994 org-markers-to-move)
6995 (setq org-markers-to-move nil))
6997 (defun org-narrow-to-subtree ()
6998 "Narrow buffer to the current subtree."
6999 (interactive)
7000 (save-excursion
7001 (save-match-data
7002 (narrow-to-region
7003 (progn (org-back-to-heading t) (point))
7004 (progn (org-end-of-subtree t t)
7005 (if (org-on-heading-p) (backward-char 1))
7006 (point))))))
7008 (defun org-clone-subtree-with-time-shift (n &optional shift)
7009 "Clone the task (subtree) at point N times.
7010 The clones will be inserted as siblings.
7012 In interactive use, the user will be prompted for the number of clones
7013 to be produced, and for a time SHIFT, which may be a repeater as used
7014 in time stamps, for example `+3d'.
7016 When a valid repeater is given and the entry contains any time stamps,
7017 the clones will become a sequence in time, with time stamps in the
7018 subtree shifted for each clone produced. If SHIFT is nil or the
7019 empty string, time stamps will be left alone.
7021 If the original subtree did contain time stamps with a repeater,
7022 the following will happen:
7023 - the repeater will be removed in each clone
7024 - an additional clone will be produced, with the current, unshifted
7025 date(s) in the entry.
7026 - the original entry will be placed *after* all the clones, with
7027 repeater intact.
7028 - the start days in the repeater in the original entry will be shifted
7029 to past the last clone.
7030 I this way you can spell out a number of instances of a repeating task,
7031 and still retain the repeater to cover future instances of the task."
7032 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7033 (let (beg end template task
7034 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7035 (if (not (and (integerp n) (> n 0)))
7036 (error "Invalid number of replications %s" n))
7037 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7038 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7039 shift)))
7040 (error "Invalid shift specification %s" shift))
7041 (when doshift
7042 (setq shift-n (string-to-number (match-string 1 shift))
7043 shift-what (cdr (assoc (match-string 2 shift)
7044 '(("d" . day) ("w" . week)
7045 ("m" . month) ("y" . year))))))
7046 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7047 (setq nmin 1 nmax n)
7048 (org-back-to-heading t)
7049 (setq beg (point))
7050 (org-end-of-subtree t t)
7051 (or (bolp) (insert "\n"))
7052 (setq end (point))
7053 (setq template (buffer-substring beg end))
7054 (when (and doshift
7055 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7056 (delete-region beg end)
7057 (setq end beg)
7058 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7059 (goto-char end)
7060 (loop for n from nmin to nmax do
7061 (if (not doshift)
7062 (setq task template)
7063 (with-temp-buffer
7064 (insert template)
7065 (org-mode)
7066 (goto-char (point-min))
7067 (while (re-search-forward org-ts-regexp-both nil t)
7068 (org-timestamp-change (* n shift-n) shift-what))
7069 (unless (= n n-no-remove)
7070 (goto-char (point-min))
7071 (while (re-search-forward org-ts-regexp nil t)
7072 (save-excursion
7073 (goto-char (match-beginning 0))
7074 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7075 (delete-region (match-beginning 1) (match-end 1))))))
7076 (setq task (buffer-string))))
7077 (insert task))
7078 (goto-char beg)))
7080 ;;; Outline Sorting
7082 (defun org-sort (with-case)
7083 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7084 Optional argument WITH-CASE means sort case-sensitively.
7085 With a double prefix argument, also remove duplicate entries."
7086 (interactive "P")
7087 (if (org-at-table-p)
7088 (org-call-with-arg 'org-table-sort-lines with-case)
7089 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7091 (defun org-sort-remove-invisible (s)
7092 (remove-text-properties 0 (length s) org-rm-props s)
7093 (while (string-match org-bracket-link-regexp s)
7094 (setq s (replace-match (if (match-end 2)
7095 (match-string 3 s)
7096 (match-string 1 s)) t t s)))
7099 (defvar org-priority-regexp) ; defined later in the file
7101 (defvar org-after-sorting-entries-or-items-hook nil
7102 "Hook that is run after a bunch of entries or items have been sorted.
7103 When children are sorted, the cursor is in the parent line when this
7104 hook gets called. When a region or a plain list is sorted, the cursor
7105 will be in the first entry of the sorted region/list.")
7107 (defun org-sort-entries-or-items
7108 (&optional with-case sorting-type getkey-func compare-func property)
7109 "Sort entries on a certain level of an outline tree, or plain list items.
7110 If there is an active region, the entries in the region are sorted.
7111 Else, if the cursor is before the first entry, sort the top-level items.
7112 Else, the children of the entry at point are sorted.
7113 If the cursor is at the first item in a plain list, the list items will be
7114 sorted.
7116 Sorting can be alphabetically, numerically, by date/time as given by
7117 a time stamp, by a property or by priority.
7119 The command prompts for the sorting type unless it has been given to the
7120 function through the SORTING-TYPE argument, which needs to a character,
7121 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7122 precise meaning of each character:
7124 n Numerically, by converting the beginning of the entry/item to a number.
7125 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7126 t By date/time, either the first active time stamp in the entry, or, if
7127 none exist, by the first inactive one.
7128 In items, only the first line will be checked.
7129 s By the scheduled date/time.
7130 d By deadline date/time.
7131 c By creation time, which is assumed to be the first inactive time stamp
7132 at the beginning of a line.
7133 p By priority according to the cookie.
7134 r By the value of a property.
7136 Capital letters will reverse the sort order.
7138 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7139 called with point at the beginning of the record. It must return either
7140 a string or a number that should serve as the sorting key for that record.
7142 Comparing entries ignores case by default. However, with an optional argument
7143 WITH-CASE, the sorting considers case as well."
7144 (interactive "P")
7145 (let ((case-func (if with-case 'identity 'downcase))
7146 start beg end stars re re2
7147 txt what tmp plain-list-p)
7148 ;; Find beginning and end of region to sort
7149 (cond
7150 ((org-region-active-p)
7151 ;; we will sort the region
7152 (setq end (region-end)
7153 what "region")
7154 (goto-char (region-beginning))
7155 (if (not (org-on-heading-p)) (outline-next-heading))
7156 (setq start (point)))
7157 ((org-at-item-p)
7158 ;; we will sort this plain list
7159 (org-beginning-of-item-list) (setq start (point))
7160 (org-end-of-item-list)
7161 (or (bolp) (insert "\n"))
7162 (setq end (point))
7163 (goto-char start)
7164 (setq plain-list-p t
7165 what "plain list"))
7166 ((or (org-on-heading-p)
7167 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7168 ;; we will sort the children of the current headline
7169 (org-back-to-heading)
7170 (setq start (point)
7171 end (progn (org-end-of-subtree t t)
7172 (or (bolp) (insert "\n"))
7173 (org-back-over-empty-lines)
7174 (point))
7175 what "children")
7176 (goto-char start)
7177 (show-subtree)
7178 (outline-next-heading))
7180 ;; we will sort the top-level entries in this file
7181 (goto-char (point-min))
7182 (or (org-on-heading-p) (outline-next-heading))
7183 (setq start (point))
7184 (goto-char (point-max))
7185 (beginning-of-line 1)
7186 (when (looking-at ".*?\\S-")
7187 ;; File ends in a non-white line
7188 (end-of-line 1)
7189 (insert "\n"))
7190 (setq end (point-max))
7191 (setq what "top-level")
7192 (goto-char start)
7193 (show-all)))
7195 (setq beg (point))
7196 (if (>= beg end) (error "Nothing to sort"))
7198 (unless plain-list-p
7199 (looking-at "\\(\\*+\\)")
7200 (setq stars (match-string 1)
7201 re (concat "^" (regexp-quote stars) " +")
7202 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7203 txt (buffer-substring beg end))
7204 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7205 (if (and (not (equal stars "*")) (string-match re2 txt))
7206 (error "Region to sort contains a level above the first entry")))
7208 (unless sorting-type
7209 (message
7210 (if plain-list-p
7211 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7212 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7213 [t]ime [s]cheduled [d]eadline [c]reated
7214 A/N/T/S/D/C/P/O/F means reversed:")
7215 what)
7216 (setq sorting-type (read-char-exclusive))
7218 (and (= (downcase sorting-type) ?f)
7219 (setq getkey-func
7220 (org-icompleting-read "Sort using function: "
7221 obarray 'fboundp t nil nil))
7222 (setq getkey-func (intern getkey-func)))
7224 (and (= (downcase sorting-type) ?r)
7225 (setq property
7226 (org-icompleting-read "Property: "
7227 (mapcar 'list (org-buffer-property-keys t))
7228 nil t))))
7230 (message "Sorting entries...")
7232 (save-restriction
7233 (narrow-to-region start end)
7235 (let ((dcst (downcase sorting-type))
7236 (case-fold-search nil)
7237 (now (current-time)))
7238 (sort-subr
7239 (/= dcst sorting-type)
7240 ;; This function moves to the beginning character of the "record" to
7241 ;; be sorted.
7242 (if plain-list-p
7243 (lambda nil
7244 (if (org-at-item-p) t (goto-char (point-max))))
7245 (lambda nil
7246 (if (re-search-forward re nil t)
7247 (goto-char (match-beginning 0))
7248 (goto-char (point-max)))))
7249 ;; This function moves to the last character of the "record" being
7250 ;; sorted.
7251 (if plain-list-p
7252 'org-end-of-item
7253 (lambda nil
7254 (save-match-data
7255 (condition-case nil
7256 (outline-forward-same-level 1)
7257 (error
7258 (goto-char (point-max)))))))
7260 ;; This function returns the value that gets sorted against.
7261 (if plain-list-p
7262 (lambda nil
7263 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7264 (cond
7265 ((= dcst ?n)
7266 (string-to-number (buffer-substring (match-end 0)
7267 (point-at-eol))))
7268 ((= dcst ?a)
7269 (buffer-substring (match-end 0) (point-at-eol)))
7270 ((= dcst ?t)
7271 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7272 (re-search-forward org-ts-regexp-both
7273 (point-at-eol) t))
7274 (org-time-string-to-seconds (match-string 0))
7275 (org-float-time now)))
7276 ((= dcst ?f)
7277 (if getkey-func
7278 (progn
7279 (setq tmp (funcall getkey-func))
7280 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7281 tmp)
7282 (error "Invalid key function `%s'" getkey-func)))
7283 (t (error "Invalid sorting type `%c'" sorting-type)))))
7284 (lambda nil
7285 (cond
7286 ((= dcst ?n)
7287 (if (looking-at org-complex-heading-regexp)
7288 (string-to-number (match-string 4))
7289 nil))
7290 ((= dcst ?a)
7291 (if (looking-at org-complex-heading-regexp)
7292 (funcall case-func (match-string 4))
7293 nil))
7294 ((= dcst ?t)
7295 (let ((end (save-excursion (outline-next-heading) (point))))
7296 (if (or (re-search-forward org-ts-regexp end t)
7297 (re-search-forward org-ts-regexp-both end t))
7298 (org-time-string-to-seconds (match-string 0))
7299 (org-float-time now))))
7300 ((= dcst ?c)
7301 (let ((end (save-excursion (outline-next-heading) (point))))
7302 (if (re-search-forward
7303 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7304 end t)
7305 (org-time-string-to-seconds (match-string 0))
7306 (org-float-time now))))
7307 ((= dcst ?s)
7308 (let ((end (save-excursion (outline-next-heading) (point))))
7309 (if (re-search-forward org-scheduled-time-regexp end t)
7310 (org-time-string-to-seconds (match-string 1))
7311 (org-float-time now))))
7312 ((= dcst ?d)
7313 (let ((end (save-excursion (outline-next-heading) (point))))
7314 (if (re-search-forward org-deadline-time-regexp end t)
7315 (org-time-string-to-seconds (match-string 1))
7316 (org-float-time now))))
7317 ((= dcst ?p)
7318 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7319 (string-to-char (match-string 2))
7320 org-default-priority))
7321 ((= dcst ?r)
7322 (or (org-entry-get nil property) ""))
7323 ((= dcst ?o)
7324 (if (looking-at org-complex-heading-regexp)
7325 (- 9999 (length (member (match-string 2)
7326 org-todo-keywords-1)))))
7327 ((= dcst ?f)
7328 (if getkey-func
7329 (progn
7330 (setq tmp (funcall getkey-func))
7331 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7332 tmp)
7333 (error "Invalid key function `%s'" getkey-func)))
7334 (t (error "Invalid sorting type `%c'" sorting-type)))))
7336 (cond
7337 ((= dcst ?a) 'string<)
7338 ((= dcst ?f) compare-func)
7339 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7340 (t nil)))))
7341 (run-hooks 'org-after-sorting-entries-or-items-hook)
7342 (message "Sorting entries...done")))
7344 (defun org-do-sort (table what &optional with-case sorting-type)
7345 "Sort TABLE of WHAT according to SORTING-TYPE.
7346 The user will be prompted for the SORTING-TYPE if the call to this
7347 function does not specify it. WHAT is only for the prompt, to indicate
7348 what is being sorted. The sorting key will be extracted from
7349 the car of the elements of the table.
7350 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7351 (unless sorting-type
7352 (message
7353 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7354 what)
7355 (setq sorting-type (read-char-exclusive)))
7356 (let ((dcst (downcase sorting-type))
7357 extractfun comparefun)
7358 ;; Define the appropriate functions
7359 (cond
7360 ((= dcst ?n)
7361 (setq extractfun 'string-to-number
7362 comparefun (if (= dcst sorting-type) '< '>)))
7363 ((= dcst ?a)
7364 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7365 (lambda(x) (downcase (org-sort-remove-invisible x))))
7366 comparefun (if (= dcst sorting-type)
7367 'string<
7368 (lambda (a b) (and (not (string< a b))
7369 (not (string= a b)))))))
7370 ((= dcst ?t)
7371 (setq extractfun
7372 (lambda (x)
7373 (if (or (string-match org-ts-regexp x)
7374 (string-match org-ts-regexp-both x))
7375 (org-float-time
7376 (org-time-string-to-time (match-string 0 x)))
7378 comparefun (if (= dcst sorting-type) '< '>)))
7379 (t (error "Invalid sorting type `%c'" sorting-type)))
7381 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7382 table)
7383 (lambda (a b) (funcall comparefun (car a) (car b))))))
7386 ;;; The orgstruct minor mode
7388 ;; Define a minor mode which can be used in other modes in order to
7389 ;; integrate the org-mode structure editing commands.
7391 ;; This is really a hack, because the org-mode structure commands use
7392 ;; keys which normally belong to the major mode. Here is how it
7393 ;; works: The minor mode defines all the keys necessary to operate the
7394 ;; structure commands, but wraps the commands into a function which
7395 ;; tests if the cursor is currently at a headline or a plain list
7396 ;; item. If that is the case, the structure command is used,
7397 ;; temporarily setting many Org-mode variables like regular
7398 ;; expressions for filling etc. However, when any of those keys is
7399 ;; used at a different location, function uses `key-binding' to look
7400 ;; up if the key has an associated command in another currently active
7401 ;; keymap (minor modes, major mode, global), and executes that
7402 ;; command. There might be problems if any of the keys is otherwise
7403 ;; used as a prefix key.
7405 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7406 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7407 ;; addresses this by checking explicitly for both bindings.
7409 (defvar orgstruct-mode-map (make-sparse-keymap)
7410 "Keymap for the minor `orgstruct-mode'.")
7412 (defvar org-local-vars nil
7413 "List of local variables, for use by `orgstruct-mode'")
7415 ;;;###autoload
7416 (define-minor-mode orgstruct-mode
7417 "Toggle the minor more `orgstruct-mode'.
7418 This mode is for using Org-mode structure commands in other modes.
7419 The following key behave as if Org-mode was active, if the cursor
7420 is on a headline, or on a plain list item (both in the definition
7421 of Org-mode).
7423 M-up Move entry/item up
7424 M-down Move entry/item down
7425 M-left Promote
7426 M-right Demote
7427 M-S-up Move entry/item up
7428 M-S-down Move entry/item down
7429 M-S-left Promote subtree
7430 M-S-right Demote subtree
7431 M-q Fill paragraph and items like in Org-mode
7432 C-c ^ Sort entries
7433 C-c - Cycle list bullet
7434 TAB Cycle item visibility
7435 M-RET Insert new heading/item
7436 S-M-RET Insert new TODO heading / Checkbox item
7437 C-c C-c Set tags / toggle checkbox"
7438 nil " OrgStruct" nil
7439 (org-load-modules-maybe)
7440 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7442 ;;;###autoload
7443 (defun turn-on-orgstruct ()
7444 "Unconditionally turn on `orgstruct-mode'."
7445 (orgstruct-mode 1))
7447 (defun orgstruct++-mode (&optional arg)
7448 "Toggle `orgstruct-mode', the enhanced version of it.
7449 In addition to setting orgstruct-mode, this also exports all indentation
7450 and autofilling variables from org-mode into the buffer. It will also
7451 recognize item context in multiline items.
7452 Note that turning off orgstruct-mode will *not* remove the
7453 indentation/paragraph settings. This can only be done by refreshing the
7454 major mode, for example with \\[normal-mode]."
7455 (interactive "P")
7456 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7457 (if (< arg 1)
7458 (orgstruct-mode -1)
7459 (orgstruct-mode 1)
7460 (let (var val)
7461 (mapc
7462 (lambda (x)
7463 (when (string-match
7464 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7465 (symbol-name (car x)))
7466 (setq var (car x) val (nth 1 x))
7467 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7468 org-local-vars)
7469 (org-set-local 'orgstruct-is-++ t))))
7471 (defvar orgstruct-is-++ nil
7472 "Is orgstruct-mode in ++ version in the current-buffer?")
7473 (make-variable-buffer-local 'orgstruct-is-++)
7475 ;;;###autoload
7476 (defun turn-on-orgstruct++ ()
7477 "Unconditionally turn on `orgstruct++-mode'."
7478 (orgstruct++-mode 1))
7480 (defun orgstruct-error ()
7481 "Error when there is no default binding for a structure key."
7482 (interactive)
7483 (error "This key has no function outside structure elements"))
7485 (defun orgstruct-setup ()
7486 "Setup orgstruct keymaps."
7487 (let ((nfunc 0)
7488 (bindings
7489 (list
7490 '([(meta up)] org-metaup)
7491 '([(meta down)] org-metadown)
7492 '([(meta left)] org-metaleft)
7493 '([(meta right)] org-metaright)
7494 '([(meta shift up)] org-shiftmetaup)
7495 '([(meta shift down)] org-shiftmetadown)
7496 '([(meta shift left)] org-shiftmetaleft)
7497 '([(meta shift right)] org-shiftmetaright)
7498 '([?\e (up)] org-metaup)
7499 '([?\e (down)] org-metadown)
7500 '([?\e (left)] org-metaleft)
7501 '([?\e (right)] org-metaright)
7502 '([?\e (shift up)] org-shiftmetaup)
7503 '([?\e (shift down)] org-shiftmetadown)
7504 '([?\e (shift left)] org-shiftmetaleft)
7505 '([?\e (shift right)] org-shiftmetaright)
7506 '([(shift up)] org-shiftup)
7507 '([(shift down)] org-shiftdown)
7508 '([(shift left)] org-shiftleft)
7509 '([(shift right)] org-shiftright)
7510 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7511 '("\M-q" fill-paragraph)
7512 '("\C-c^" org-sort)
7513 '("\C-c-" org-cycle-list-bullet)))
7514 elt key fun cmd)
7515 (while (setq elt (pop bindings))
7516 (setq nfunc (1+ nfunc))
7517 (setq key (org-key (car elt))
7518 fun (nth 1 elt)
7519 cmd (orgstruct-make-binding fun nfunc key))
7520 (org-defkey orgstruct-mode-map key cmd))
7522 ;; Special treatment needed for TAB and RET
7523 (org-defkey orgstruct-mode-map [(tab)]
7524 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7525 (org-defkey orgstruct-mode-map "\C-i"
7526 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7528 (org-defkey orgstruct-mode-map "\M-\C-m"
7529 (orgstruct-make-binding 'org-insert-heading 105
7530 "\M-\C-m" [(meta return)]))
7531 (org-defkey orgstruct-mode-map [(meta return)]
7532 (orgstruct-make-binding 'org-insert-heading 106
7533 [(meta return)] "\M-\C-m"))
7535 (org-defkey orgstruct-mode-map [(shift meta return)]
7536 (orgstruct-make-binding 'org-insert-todo-heading 107
7537 [(meta return)] "\M-\C-m"))
7539 (org-defkey orgstruct-mode-map "\e\C-m"
7540 (orgstruct-make-binding 'org-insert-heading 108
7541 "\e\C-m" [?\e (return)]))
7542 (org-defkey orgstruct-mode-map [?\e (return)]
7543 (orgstruct-make-binding 'org-insert-heading 109
7544 [?\e (return)] "\e\C-m"))
7545 (org-defkey orgstruct-mode-map [?\e (shift return)]
7546 (orgstruct-make-binding 'org-insert-todo-heading 110
7547 [?\e (return)] "\e\C-m"))
7549 (unless org-local-vars
7550 (setq org-local-vars (org-get-local-variables)))
7554 (defun orgstruct-make-binding (fun n &rest keys)
7555 "Create a function for binding in the structure minor mode.
7556 FUN is the command to call inside a table. N is used to create a unique
7557 command name. KEYS are keys that should be checked in for a command
7558 to execute outside of tables."
7559 (eval
7560 (list 'defun
7561 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7562 '(arg)
7563 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7564 "Outside of structure, run the binding of `"
7565 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7566 "'.")
7567 '(interactive "p")
7568 (list 'if
7569 `(org-context-p 'headline 'item
7570 (and orgstruct-is-++
7571 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7572 'item-body))
7573 (list 'org-run-like-in-org-mode (list 'quote fun))
7574 (list 'let '(orgstruct-mode)
7575 (list 'call-interactively
7576 (append '(or)
7577 (mapcar (lambda (k)
7578 (list 'key-binding k))
7579 keys)
7580 '('orgstruct-error))))))))
7582 (defun org-context-p (&rest contexts)
7583 "Check if local context is any of CONTEXTS.
7584 Possible values in the list of contexts are `table', `headline', and `item'."
7585 (let ((pos (point)))
7586 (goto-char (point-at-bol))
7587 (prog1 (or (and (memq 'table contexts)
7588 (looking-at "[ \t]*|"))
7589 (and (memq 'headline contexts)
7590 ;;????????? (looking-at "\\*+"))
7591 (looking-at outline-regexp))
7592 (and (memq 'item contexts)
7593 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7594 (and (memq 'item-body contexts)
7595 (org-in-item-p)))
7596 (goto-char pos))))
7598 (defun org-get-local-variables ()
7599 "Return a list of all local variables in an org-mode buffer."
7600 (let (varlist)
7601 (with-current-buffer (get-buffer-create "*Org tmp*")
7602 (erase-buffer)
7603 (org-mode)
7604 (setq varlist (buffer-local-variables)))
7605 (kill-buffer "*Org tmp*")
7606 (delq nil
7607 (mapcar
7608 (lambda (x)
7609 (setq x
7610 (if (symbolp x)
7611 (list x)
7612 (list (car x) (list 'quote (cdr x)))))
7613 (if (string-match
7614 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7615 (symbol-name (car x)))
7616 x nil))
7617 varlist))))
7619 ;;;###autoload
7620 (defun org-run-like-in-org-mode (cmd)
7621 "Run a command, pretending that the current buffer is in Org-mode.
7622 This will temporarily bind local variables that are typically bound in
7623 Org-mode to the values they have in Org-mode, and then interactively
7624 call CMD."
7625 (org-load-modules-maybe)
7626 (unless org-local-vars
7627 (setq org-local-vars (org-get-local-variables)))
7628 (eval (list 'let org-local-vars
7629 (list 'call-interactively (list 'quote cmd)))))
7631 ;;;; Archiving
7633 (defun org-get-category (&optional pos)
7634 "Get the category applying to position POS."
7635 (get-text-property (or pos (point)) 'org-category))
7637 (defun org-refresh-category-properties ()
7638 "Refresh category text properties in the buffer."
7639 (let ((def-cat (cond
7640 ((null org-category)
7641 (if buffer-file-name
7642 (file-name-sans-extension
7643 (file-name-nondirectory buffer-file-name))
7644 "???"))
7645 ((symbolp org-category) (symbol-name org-category))
7646 (t org-category)))
7647 beg end cat pos optionp)
7648 (org-unmodified
7649 (save-excursion
7650 (save-restriction
7651 (widen)
7652 (goto-char (point-min))
7653 (put-text-property (point) (point-max) 'org-category def-cat)
7654 (while (re-search-forward
7655 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7656 (setq pos (match-end 0)
7657 optionp (equal (char-after (match-beginning 0)) ?#)
7658 cat (org-trim (match-string 2)))
7659 (if optionp
7660 (setq beg (point-at-bol) end (point-max))
7661 (org-back-to-heading t)
7662 (setq beg (point) end (org-end-of-subtree t t)))
7663 (put-text-property beg end 'org-category cat)
7664 (goto-char pos)))))))
7667 ;;;; Link Stuff
7669 ;;; Link abbreviations
7671 (defun org-link-expand-abbrev (link)
7672 "Apply replacements as defined in `org-link-abbrev-alist."
7673 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7674 (let* ((key (match-string 1 link))
7675 (as (or (assoc key org-link-abbrev-alist-local)
7676 (assoc key org-link-abbrev-alist)))
7677 (tag (and (match-end 2) (match-string 3 link)))
7678 rpl)
7679 (if (not as)
7680 link
7681 (setq rpl (cdr as))
7682 (cond
7683 ((symbolp rpl) (funcall rpl tag))
7684 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7685 ((string-match "%h" rpl)
7686 (replace-match (url-hexify-string (or tag "")) t t rpl))
7687 (t (concat rpl tag)))))
7688 link))
7690 ;;; Storing and inserting links
7692 (defvar org-insert-link-history nil
7693 "Minibuffer history for links inserted with `org-insert-link'.")
7695 (defvar org-stored-links nil
7696 "Contains the links stored with `org-store-link'.")
7698 (defvar org-store-link-plist nil
7699 "Plist with info about the most recently link created with `org-store-link'.")
7701 (defvar org-link-protocols nil
7702 "Link protocols added to Org-mode using `org-add-link-type'.")
7704 (defvar org-store-link-functions nil
7705 "List of functions that are called to create and store a link.
7706 Each function will be called in turn until one returns a non-nil
7707 value. Each function should check if it is responsible for creating
7708 this link (for example by looking at the major mode).
7709 If not, it must exit and return nil.
7710 If yes, it should return a non-nil value after a calling
7711 `org-store-link-props' with a list of properties and values.
7712 Special properties are:
7714 :type The link prefix. like \"http\". This must be given.
7715 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7716 This is obligatory as well.
7717 :description Optional default description for the second pair
7718 of brackets in an Org-mode link. The user can still change
7719 this when inserting this link into an Org-mode buffer.
7721 In addition to these, any additional properties can be specified
7722 and then used in remember templates.")
7724 (defun org-add-link-type (type &optional follow export)
7725 "Add TYPE to the list of `org-link-types'.
7726 Re-compute all regular expressions depending on `org-link-types'
7728 FOLLOW and EXPORT are two functions.
7730 FOLLOW should take the link path as the single argument and do whatever
7731 is necessary to follow the link, for example find a file or display
7732 a mail message.
7734 EXPORT should format the link path for export to one of the export formats.
7735 It should be a function accepting three arguments:
7737 path the path of the link, the text after the prefix (like \"http:\")
7738 desc the description of the link, if any, nil if there was no description
7739 format the export format, a symbol like `html' or `latex'.
7741 The function may use the FORMAT information to return different values
7742 depending on the format. The return value will be put literally into
7743 the exported file.
7744 Org-mode has a built-in default for exporting links. If you are happy with
7745 this default, there is no need to define an export function for the link
7746 type. For a simple example of an export function, see `org-bbdb.el'."
7747 (add-to-list 'org-link-types type t)
7748 (org-make-link-regexps)
7749 (if (assoc type org-link-protocols)
7750 (setcdr (assoc type org-link-protocols) (list follow export))
7751 (push (list type follow export) org-link-protocols)))
7753 (defvar org-agenda-buffer-name)
7755 ;;;###autoload
7756 (defun org-store-link (arg)
7757 "\\<org-mode-map>Store an org-link to the current location.
7758 This link is added to `org-stored-links' and can later be inserted
7759 into an org-buffer with \\[org-insert-link].
7761 For some link types, a prefix arg is interpreted:
7762 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7763 For file links, arg negates `org-context-in-file-links'."
7764 (interactive "P")
7765 (org-load-modules-maybe)
7766 (setq org-store-link-plist nil) ; reset
7767 (let ((outline-regexp (org-get-limited-outline-regexp))
7768 link cpltxt desc description search txt custom-id)
7769 (cond
7771 ((run-hook-with-args-until-success 'org-store-link-functions)
7772 (setq link (plist-get org-store-link-plist :link)
7773 desc (or (plist-get org-store-link-plist :description) link)))
7775 ((equal (buffer-name) "*Org Edit Src Example*")
7776 (let (label gc)
7777 (while (or (not label)
7778 (save-excursion
7779 (save-restriction
7780 (widen)
7781 (goto-char (point-min))
7782 (re-search-forward
7783 (regexp-quote (format org-coderef-label-format label))
7784 nil t))))
7785 (when label (message "Label exists already") (sit-for 2))
7786 (setq label (read-string "Code line label: " label)))
7787 (end-of-line 1)
7788 (setq link (format org-coderef-label-format label))
7789 (setq gc (- 79 (length link)))
7790 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7791 (insert link)
7792 (setq link (concat "(" label ")") desc nil)))
7794 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7795 ;; We are in the agenda, link to referenced location
7796 (let ((m (or (get-text-property (point) 'org-hd-marker)
7797 (get-text-property (point) 'org-marker))))
7798 (when m
7799 (org-with-point-at m
7800 (call-interactively 'org-store-link)))))
7802 ((eq major-mode 'calendar-mode)
7803 (let ((cd (calendar-cursor-to-date)))
7804 (setq link
7805 (format-time-string
7806 (car org-time-stamp-formats)
7807 (apply 'encode-time
7808 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7809 nil nil nil))))
7810 (org-store-link-props :type "calendar" :date cd)))
7812 ((eq major-mode 'w3-mode)
7813 (setq cpltxt (if (and (buffer-name)
7814 (not (string-match "Untitled" (buffer-name))))
7815 (buffer-name)
7816 (url-view-url t))
7817 link (org-make-link (url-view-url t)))
7818 (org-store-link-props :type "w3" :url (url-view-url t)))
7820 ((eq major-mode 'w3m-mode)
7821 (setq cpltxt (or w3m-current-title w3m-current-url)
7822 link (org-make-link w3m-current-url))
7823 (org-store-link-props :type "w3m" :url (url-view-url t)))
7825 ((setq search (run-hook-with-args-until-success
7826 'org-create-file-search-functions))
7827 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7828 "::" search))
7829 (setq cpltxt (or description link)))
7831 ((eq major-mode 'image-mode)
7832 (setq cpltxt (concat "file:"
7833 (abbreviate-file-name buffer-file-name))
7834 link (org-make-link cpltxt))
7835 (org-store-link-props :type "image" :file buffer-file-name))
7837 ((eq major-mode 'dired-mode)
7838 ;; link to the file in the current line
7839 (let ((file (dired-get-filename nil t)))
7840 (setq file (if file
7841 (abbreviate-file-name
7842 (expand-file-name (dired-get-filename nil t)))
7843 ;; otherwise, no file so use current directory.
7844 default-directory))
7845 (setq cpltxt (concat "file:" file)
7846 link (org-make-link cpltxt))))
7848 ((and buffer-file-name (org-mode-p))
7849 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7850 (cond
7851 ((org-in-regexp "<<\\(.*?\\)>>")
7852 (setq cpltxt
7853 (concat "file:"
7854 (abbreviate-file-name buffer-file-name)
7855 "::" (match-string 1))
7856 link (org-make-link cpltxt)))
7857 ((and (featurep 'org-id)
7858 (or (eq org-link-to-org-use-id t)
7859 (and (eq org-link-to-org-use-id 'create-if-interactive)
7860 (interactive-p))
7861 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7862 (interactive-p)
7863 (not custom-id))
7864 (and org-link-to-org-use-id
7865 (condition-case nil
7866 (org-entry-get nil "ID")
7867 (error nil)))))
7868 ;; We can make a link using the ID.
7869 (setq link (condition-case nil
7870 (prog1 (org-id-store-link)
7871 (setq desc (plist-get org-store-link-plist
7872 :description)))
7873 (error
7874 ;; probably before first headline, link to file only
7875 (concat "file:"
7876 (abbreviate-file-name buffer-file-name))))))
7878 ;; Just link to current headline
7879 (setq cpltxt (concat "file:"
7880 (abbreviate-file-name buffer-file-name)))
7881 ;; Add a context search string
7882 (when (org-xor org-context-in-file-links arg)
7883 (setq txt (cond
7884 ((org-on-heading-p) nil)
7885 ((org-region-active-p)
7886 (buffer-substring (region-beginning) (region-end)))
7887 (t nil)))
7888 (when (or (null txt) (string-match "\\S-" txt))
7889 (setq cpltxt
7890 (concat cpltxt "::"
7891 (condition-case nil
7892 (org-make-org-heading-search-string txt)
7893 (error "")))
7894 desc (or (nth 4 (ignore-errors
7895 (org-heading-components))) "NONE"))))
7896 (if (string-match "::\\'" cpltxt)
7897 (setq cpltxt (substring cpltxt 0 -2)))
7898 (setq link (org-make-link cpltxt)))))
7900 ((buffer-file-name (buffer-base-buffer))
7901 ;; Just link to this file here.
7902 (setq cpltxt (concat "file:"
7903 (abbreviate-file-name
7904 (buffer-file-name (buffer-base-buffer)))))
7905 ;; Add a context string
7906 (when (org-xor org-context-in-file-links arg)
7907 (setq txt (if (org-region-active-p)
7908 (buffer-substring (region-beginning) (region-end))
7909 (buffer-substring (point-at-bol) (point-at-eol))))
7910 ;; Only use search option if there is some text.
7911 (when (string-match "\\S-" txt)
7912 (setq cpltxt
7913 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7914 desc "NONE")))
7915 (setq link (org-make-link cpltxt)))
7917 ((interactive-p)
7918 (error "Cannot link to a buffer which is not visiting a file"))
7920 (t (setq link nil)))
7922 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7923 (setq link (or link cpltxt)
7924 desc (or desc cpltxt))
7925 (if (equal desc "NONE") (setq desc nil))
7927 (if (and (or (interactive-p) executing-kbd-macro) link)
7928 (progn
7929 (setq org-stored-links
7930 (cons (list link desc) org-stored-links))
7931 (message "Stored: %s" (or desc link))
7932 (when custom-id
7933 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7934 "::#" custom-id))
7935 (setq org-stored-links
7936 (cons (list link desc) org-stored-links))))
7937 (and link (org-make-link-string link desc)))))
7939 (defun org-store-link-props (&rest plist)
7940 "Store link properties, extract names and addresses."
7941 (let (x adr)
7942 (when (setq x (plist-get plist :from))
7943 (setq adr (mail-extract-address-components x))
7944 (setq plist (plist-put plist :fromname (car adr)))
7945 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7946 (when (setq x (plist-get plist :to))
7947 (setq adr (mail-extract-address-components x))
7948 (setq plist (plist-put plist :toname (car adr)))
7949 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7950 (let ((from (plist-get plist :from))
7951 (to (plist-get plist :to)))
7952 (when (and from to org-from-is-user-regexp)
7953 (setq plist
7954 (plist-put plist :fromto
7955 (if (string-match org-from-is-user-regexp from)
7956 (concat "to %t")
7957 (concat "from %f"))))))
7958 (setq org-store-link-plist plist))
7960 (defun org-add-link-props (&rest plist)
7961 "Add these properties to the link property list."
7962 (let (key value)
7963 (while plist
7964 (setq key (pop plist) value (pop plist))
7965 (setq org-store-link-plist
7966 (plist-put org-store-link-plist key value)))))
7968 (defun org-email-link-description (&optional fmt)
7969 "Return the description part of an email link.
7970 This takes information from `org-store-link-plist' and formats it
7971 according to FMT (default from `org-email-link-description-format')."
7972 (setq fmt (or fmt org-email-link-description-format))
7973 (let* ((p org-store-link-plist)
7974 (to (plist-get p :toaddress))
7975 (from (plist-get p :fromaddress))
7976 (table
7977 (list
7978 (cons "%c" (plist-get p :fromto))
7979 (cons "%F" (plist-get p :from))
7980 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7981 (cons "%T" (plist-get p :to))
7982 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7983 (cons "%s" (plist-get p :subject))
7984 (cons "%m" (plist-get p :message-id)))))
7985 (when (string-match "%c" fmt)
7986 ;; Check if the user wrote this message
7987 (if (and org-from-is-user-regexp from to
7988 (save-match-data (string-match org-from-is-user-regexp from)))
7989 (setq fmt (replace-match "to %t" t t fmt))
7990 (setq fmt (replace-match "from %f" t t fmt))))
7991 (org-replace-escapes fmt table)))
7993 (defun org-make-org-heading-search-string (&optional string heading)
7994 "Make search string for STRING or current headline."
7995 (interactive)
7996 (let ((s (or string (org-get-heading))))
7997 (unless (and string (not heading))
7998 ;; We are using a headline, clean up garbage in there.
7999 (if (string-match org-todo-regexp s)
8000 (setq s (replace-match "" t t s)))
8001 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8002 (setq s (replace-match "" t t s)))
8003 (setq s (org-trim s))
8004 (if (string-match (concat "^\\(" org-quote-string "\\|"
8005 org-comment-string "\\)") s)
8006 (setq s (replace-match "" t t s)))
8007 (while (string-match org-ts-regexp s)
8008 (setq s (replace-match "" t t s))))
8009 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8010 (setq s (replace-match " " t t s)))
8011 (or string (setq s (concat "*" s))) ; Add * for headlines
8012 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8014 (defun org-make-link (&rest strings)
8015 "Concatenate STRINGS."
8016 (apply 'concat strings))
8018 (defun org-make-link-string (link &optional description)
8019 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8020 (unless (string-match "\\S-" link)
8021 (error "Empty link"))
8022 (when (and description
8023 (stringp description)
8024 (not (string-match "\\S-" description)))
8025 (setq description nil))
8026 (when (stringp description)
8027 ;; Remove brackets from the description, they are fatal.
8028 (while (string-match "\\[" description)
8029 (setq description (replace-match "{" t t description)))
8030 (while (string-match "\\]" description)
8031 (setq description (replace-match "}" t t description))))
8032 (when (equal (org-link-escape link) description)
8033 ;; No description needed, it is identical
8034 (setq description nil))
8035 (when (and (not description)
8036 (not (equal link (org-link-escape link))))
8037 (setq description (org-extract-attributes link)))
8038 (concat "[[" (org-link-escape link) "]"
8039 (if description (concat "[" description "]") "")
8040 "]"))
8042 (defconst org-link-escape-chars
8043 '((?\ . "%20")
8044 (?\[ . "%5B")
8045 (?\] . "%5D")
8046 (?\340 . "%E0") ; `a
8047 (?\342 . "%E2") ; ^a
8048 (?\347 . "%E7") ; ,c
8049 (?\350 . "%E8") ; `e
8050 (?\351 . "%E9") ; 'e
8051 (?\352 . "%EA") ; ^e
8052 (?\356 . "%EE") ; ^i
8053 (?\364 . "%F4") ; ^o
8054 (?\371 . "%F9") ; `u
8055 (?\373 . "%FB") ; ^u
8056 (?\; . "%3B")
8057 ;; (?? . "%3F")
8058 (?= . "%3D")
8059 (?+ . "%2B")
8061 "Association list of escapes for some characters problematic in links.
8062 This is the list that is used for internal purposes.")
8064 (defvar org-url-encoding-use-url-hexify nil)
8066 (defconst org-link-escape-chars-browser
8067 '((?\ . "%20")) ; 32 for the SPC char
8068 "Association list of escapes for some characters problematic in links.
8069 This is the list that is used before handing over to the browser.")
8071 (defun org-link-escape (text &optional table)
8072 "Escape characters in TEXT that are problematic for links."
8073 (if (and org-url-encoding-use-url-hexify (not table))
8074 (url-hexify-string text)
8075 (setq table (or table org-link-escape-chars))
8076 (when text
8077 (let ((re (mapconcat (lambda (x) (regexp-quote
8078 (char-to-string (car x))))
8079 table "\\|")))
8080 (while (string-match re text)
8081 (setq text
8082 (replace-match
8083 (cdr (assoc (string-to-char (match-string 0 text))
8084 table))
8085 t t text)))
8086 text))))
8088 (defun org-link-unescape (text &optional table)
8089 "Reverse the action of `org-link-escape'."
8090 (if (and org-url-encoding-use-url-hexify (not table))
8091 (url-unhex-string text)
8092 (setq table (or table org-link-escape-chars))
8093 (when text
8094 (let ((case-fold-search t)
8095 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8096 table "\\|")))
8097 (while (string-match re text)
8098 (setq text
8099 (replace-match
8100 (char-to-string (car (rassoc (upcase (match-string 0 text))
8101 table)))
8102 t t text)))
8103 text))))
8105 (defun org-xor (a b)
8106 "Exclusive or."
8107 (if a (not b) b))
8109 (defun org-fixup-message-id-for-http (s)
8110 "Replace special characters in a message id, so it can be used in an http query."
8111 (while (string-match "<" s)
8112 (setq s (replace-match "%3C" t t s)))
8113 (while (string-match ">" s)
8114 (setq s (replace-match "%3E" t t s)))
8115 (while (string-match "@" s)
8116 (setq s (replace-match "%40" t t s)))
8119 ;;;###autoload
8120 (defun org-insert-link-global ()
8121 "Insert a link like Org-mode does.
8122 This command can be called in any mode to insert a link in Org-mode syntax."
8123 (interactive)
8124 (org-load-modules-maybe)
8125 (org-run-like-in-org-mode 'org-insert-link))
8127 (defun org-insert-link (&optional complete-file link-location)
8128 "Insert a link. At the prompt, enter the link.
8130 Completion can be used to insert any of the link protocol prefixes like
8131 http or ftp in use.
8133 The history can be used to select a link previously stored with
8134 `org-store-link'. When the empty string is entered (i.e. if you just
8135 press RET at the prompt), the link defaults to the most recently
8136 stored link. As SPC triggers completion in the minibuffer, you need to
8137 use M-SPC or C-q SPC to force the insertion of a space character.
8139 You will also be prompted for a description, and if one is given, it will
8140 be displayed in the buffer instead of the link.
8142 If there is already a link at point, this command will allow you to edit link
8143 and description parts.
8145 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8146 be selected using completion. The path to the file will be relative to the
8147 current directory if the file is in the current directory or a subdirectory.
8148 Otherwise, the link will be the absolute path as completed in the minibuffer
8149 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8150 option `org-link-file-path-type'.
8152 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8153 the current directory or below.
8155 With three \\[universal-argument] prefixes, negate the meaning of
8156 `org-keep-stored-link-after-insertion'.
8158 If `org-make-link-description-function' is non-nil, this function will be
8159 called with the link target, and the result will be the default
8160 link description.
8162 If the LINK-LOCATION parameter is non-nil, this value will be
8163 used as the link location instead of reading one interactively."
8164 (interactive "P")
8165 (let* ((wcf (current-window-configuration))
8166 (region (if (org-region-active-p)
8167 (buffer-substring (region-beginning) (region-end))))
8168 (remove (and region (list (region-beginning) (region-end))))
8169 (desc region)
8170 tmphist ; byte-compile incorrectly complains about this
8171 (link link-location)
8172 entry file all-prefixes)
8173 (cond
8174 (link-location) ; specified by arg, just use it.
8175 ((org-in-regexp org-bracket-link-regexp 1)
8176 ;; We do have a link at point, and we are going to edit it.
8177 (setq remove (list (match-beginning 0) (match-end 0)))
8178 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8179 (setq link (read-string "Link: "
8180 (org-link-unescape
8181 (org-match-string-no-properties 1)))))
8182 ((or (org-in-regexp org-angle-link-re)
8183 (org-in-regexp org-plain-link-re))
8184 ;; Convert to bracket link
8185 (setq remove (list (match-beginning 0) (match-end 0))
8186 link (read-string "Link: "
8187 (org-remove-angle-brackets (match-string 0)))))
8188 ((member complete-file '((4) (16)))
8189 ;; Completing read for file names.
8190 (setq link (org-file-complete-link complete-file)))
8192 ;; Read link, with completion for stored links.
8193 (with-output-to-temp-buffer "*Org Links*"
8194 (princ "Insert a link.
8195 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8196 (when org-stored-links
8197 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8198 (princ (mapconcat
8199 (lambda (x)
8200 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8201 (reverse org-stored-links) "\n"))))
8202 (let ((cw (selected-window)))
8203 (select-window (get-buffer-window "*Org Links*"))
8204 (setq truncate-lines t)
8205 (unless (pos-visible-in-window-p (point-max))
8206 (org-fit-window-to-buffer))
8207 (and (window-live-p cw) (select-window cw)))
8208 ;; Fake a link history, containing the stored links.
8209 (setq tmphist (append (mapcar 'car org-stored-links)
8210 org-insert-link-history))
8211 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8212 (mapcar 'car org-link-abbrev-alist)
8213 org-link-types))
8214 (unwind-protect
8215 (progn
8216 (setq link
8217 (let ((org-completion-use-ido nil)
8218 (org-completion-use-iswitchb nil))
8219 (org-completing-read
8220 "Link: "
8221 (append
8222 (mapcar (lambda (x) (list (concat x ":")))
8223 all-prefixes)
8224 (mapcar 'car org-stored-links))
8225 nil nil nil
8226 'tmphist
8227 (car (car org-stored-links)))))
8228 (if (not (string-match "\\S-" link))
8229 (error "No link selected"))
8230 (if (or (member link all-prefixes)
8231 (and (equal ":" (substring link -1))
8232 (member (substring link 0 -1) all-prefixes)
8233 (setq link (substring link 0 -1))))
8234 (setq link (org-link-try-special-completion link))))
8235 (set-window-configuration wcf)
8236 (kill-buffer "*Org Links*"))
8237 (setq entry (assoc link org-stored-links))
8238 (or entry (push link org-insert-link-history))
8239 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8240 (not org-keep-stored-link-after-insertion))
8241 (setq org-stored-links (delq (assoc link org-stored-links)
8242 org-stored-links)))
8243 (setq desc (or desc (nth 1 entry)))))
8245 (if (string-match org-plain-link-re link)
8246 ;; URL-like link, normalize the use of angular brackets.
8247 (setq link (org-make-link (org-remove-angle-brackets link))))
8249 ;; Check if we are linking to the current file with a search option
8250 ;; If yes, simplify the link by using only the search option.
8251 (when (and buffer-file-name
8252 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8253 (let* ((path (match-string 1 link))
8254 (case-fold-search nil)
8255 (search (match-string 2 link)))
8256 (save-match-data
8257 (if (equal (file-truename buffer-file-name) (file-truename path))
8258 ;; We are linking to this same file, with a search option
8259 (setq link search)))))
8261 ;; Check if we can/should use a relative path. If yes, simplify the link
8262 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8263 (let* ((type (match-string 1 link))
8264 (path (match-string 2 link))
8265 (origpath path)
8266 (case-fold-search nil))
8267 (cond
8268 ((or (eq org-link-file-path-type 'absolute)
8269 (equal complete-file '(16)))
8270 (setq path (abbreviate-file-name (expand-file-name path))))
8271 ((eq org-link-file-path-type 'noabbrev)
8272 (setq path (expand-file-name path)))
8273 ((eq org-link-file-path-type 'relative)
8274 (setq path (file-relative-name path)))
8276 (save-match-data
8277 (if (string-match (concat "^" (regexp-quote
8278 (file-name-as-directory
8279 (expand-file-name "."))))
8280 (expand-file-name path))
8281 ;; We are linking a file with relative path name.
8282 (setq path (substring (expand-file-name path)
8283 (match-end 0)))
8284 (setq path (abbreviate-file-name (expand-file-name path)))))))
8285 (setq link (concat type path))
8286 (if (equal desc origpath)
8287 (setq desc path))))
8289 (if org-make-link-description-function
8290 (setq desc (funcall org-make-link-description-function link desc)))
8292 (setq desc (read-string "Description: " desc))
8293 (unless (string-match "\\S-" desc) (setq desc nil))
8294 (if remove (apply 'delete-region remove))
8295 (insert (org-make-link-string link desc))))
8297 (defun org-link-try-special-completion (type)
8298 "If there is completion support for link type TYPE, offer it."
8299 (let ((fun (intern (concat "org-" type "-complete-link"))))
8300 (if (functionp fun)
8301 (funcall fun)
8302 (read-string "Link (no completion support): " (concat type ":")))))
8304 (defun org-file-complete-link (&optional arg)
8305 "Create a file link using completion."
8306 (let (file link)
8307 (setq file (read-file-name "File: "))
8308 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8309 (pwd1 (file-name-as-directory (abbreviate-file-name
8310 (expand-file-name ".")))))
8311 (cond
8312 ((equal arg '(16))
8313 (setq link (org-make-link
8314 "file:"
8315 (abbreviate-file-name (expand-file-name file)))))
8316 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8317 (setq link (org-make-link "file:" (match-string 1 file))))
8318 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8319 (expand-file-name file))
8320 (setq link (org-make-link
8321 "file:" (match-string 1 (expand-file-name file)))))
8322 (t (setq link (org-make-link "file:" file)))))
8323 link))
8325 (defun org-completing-read (&rest args)
8326 "Completing-read with SPACE being a normal character."
8327 (let ((minibuffer-local-completion-map
8328 (copy-keymap minibuffer-local-completion-map)))
8329 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8330 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8331 (apply 'org-icompleting-read args)))
8333 (defun org-completing-read-no-i (&rest args)
8334 (let (org-completion-use-ido org-completion-use-iswitchb)
8335 (apply 'org-completing-read args)))
8337 (defun org-iswitchb-completing-read (prompt choices &rest args)
8338 "Use iswitch as a completing-read replacement to choose from choices.
8339 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8340 from."
8341 (let* ((iswitchb-use-virtual-buffers nil)
8342 (iswitchb-make-buflist-hook
8343 (lambda ()
8344 (setq iswitchb-temp-buflist choices))))
8345 (iswitchb-read-buffer prompt)))
8347 (defun org-icompleting-read (&rest args)
8348 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8349 (org-without-partial-completion
8350 (if (and org-completion-use-ido
8351 (fboundp 'ido-completing-read)
8352 (boundp 'ido-mode) ido-mode
8353 (listp (second args)))
8354 (let ((ido-enter-matching-directory nil))
8355 (apply 'ido-completing-read (concat (car args))
8356 (if (consp (car (nth 1 args)))
8357 (mapcar (lambda (x) (car x)) (nth 1 args))
8358 (nth 1 args))
8359 (cddr args)))
8360 (if (and org-completion-use-iswitchb
8361 (boundp 'iswitchb-mode) iswitchb-mode
8362 (listp (second args)))
8363 (apply 'org-iswitchb-completing-read (concat (car args))
8364 (if (consp (car (nth 1 args)))
8365 (mapcar (lambda (x) (car x)) (nth 1 args))
8366 (nth 1 args))
8367 (cddr args))
8368 (apply 'completing-read args)))))
8370 (defun org-extract-attributes (s)
8371 "Extract the attributes cookie from a string and set as text property."
8372 (let (a attr (start 0) key value)
8373 (save-match-data
8374 (when (string-match "{{\\([^}]+\\)}}$" s)
8375 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8376 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8377 (setq key (match-string 1 a) value (match-string 2 a)
8378 start (match-end 0)
8379 attr (plist-put attr (intern key) value))))
8380 (org-add-props s nil 'org-attr attr))
8383 (defun org-extract-attributes-from-string (tag)
8384 (let (key value attr)
8385 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8386 (setq key (match-string 1 tag) value (match-string 2 tag)
8387 tag (replace-match "" t t tag)
8388 attr (plist-put attr (intern key) value)))
8389 (cons tag attr)))
8391 (defun org-attributes-to-string (plist)
8392 "Format a property list into an HTML attribute list."
8393 (let ((s "") key value)
8394 (while plist
8395 (setq key (pop plist) value (pop plist))
8396 (and value
8397 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8400 ;;; Opening/following a link
8402 (defvar org-link-search-failed nil)
8404 (defvar org-open-link-functions nil
8405 "Hook for functions finding a plain text link.
8406 These functions must take a single argument, the link content.
8407 They will be called for links that look like [[link text][description]]
8408 when LINK TEXT does not have a protocol like \"http:\" and does not look
8409 like a filename (e.g. \"./blue.png\").
8411 These functions will be called *before* Org attempts to resolve the
8412 link by doing text searches in the current buffer - so if you want a
8413 link \"[[target]]\" to still find \"<<target>>\", your function should
8414 handle this as a special case.
8416 When the function does handle the link, it must return a non-nil value.
8417 If it decides that it is not responsible for this link, it must return
8418 nil to indicate that that Org-mode can continue with other options
8419 like exact and fuzzy text search.")
8421 (defun org-next-link ()
8422 "Move forward to the next link.
8423 If the link is in hidden text, expose it."
8424 (interactive)
8425 (when (and org-link-search-failed (eq this-command last-command))
8426 (goto-char (point-min))
8427 (message "Link search wrapped back to beginning of buffer"))
8428 (setq org-link-search-failed nil)
8429 (let* ((pos (point))
8430 (ct (org-context))
8431 (a (assoc :link ct)))
8432 (if a (goto-char (nth 2 a)))
8433 (if (re-search-forward org-any-link-re nil t)
8434 (progn
8435 (goto-char (match-beginning 0))
8436 (if (org-invisible-p) (org-show-context)))
8437 (goto-char pos)
8438 (setq org-link-search-failed t)
8439 (error "No further link found"))))
8441 (defun org-previous-link ()
8442 "Move backward to the previous link.
8443 If the link is in hidden text, expose it."
8444 (interactive)
8445 (when (and org-link-search-failed (eq this-command last-command))
8446 (goto-char (point-max))
8447 (message "Link search wrapped back to end of buffer"))
8448 (setq org-link-search-failed nil)
8449 (let* ((pos (point))
8450 (ct (org-context))
8451 (a (assoc :link ct)))
8452 (if a (goto-char (nth 1 a)))
8453 (if (re-search-backward org-any-link-re nil t)
8454 (progn
8455 (goto-char (match-beginning 0))
8456 (if (org-invisible-p) (org-show-context)))
8457 (goto-char pos)
8458 (setq org-link-search-failed t)
8459 (error "No further link found"))))
8461 (defun org-translate-link (s)
8462 "Translate a link string if a translation function has been defined."
8463 (if (and org-link-translation-function
8464 (fboundp org-link-translation-function)
8465 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8466 (progn
8467 (setq s (funcall org-link-translation-function
8468 (match-string 1) (match-string 2)))
8469 (concat (car s) ":" (cdr s)))
8472 (defun org-translate-link-from-planner (type path)
8473 "Translate a link from Emacs Planner syntax so that Org can follow it.
8474 This is still an experimental function, your mileage may vary."
8475 (cond
8476 ((member type '("http" "https" "news" "ftp"))
8477 ;; standard Internet links are the same.
8478 nil)
8479 ((and (equal type "irc") (string-match "^//" path))
8480 ;; Planner has two / at the beginning of an irc link, we have 1.
8481 ;; We should have zero, actually....
8482 (setq path (substring path 1)))
8483 ((and (equal type "lisp") (string-match "^/" path))
8484 ;; Planner has a slash, we do not.
8485 (setq type "elisp" path (substring path 1)))
8486 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8487 ;; A typical message link. Planner has the id after the final slash,
8488 ;; we separate it with a hash mark
8489 (setq path (concat (match-string 1 path) "#"
8490 (org-remove-angle-brackets (match-string 2 path)))))
8492 (cons type path))
8494 (defun org-find-file-at-mouse (ev)
8495 "Open file link or URL at mouse."
8496 (interactive "e")
8497 (mouse-set-point ev)
8498 (org-open-at-point 'in-emacs))
8500 (defun org-open-at-mouse (ev)
8501 "Open file link or URL at mouse."
8502 (interactive "e")
8503 (mouse-set-point ev)
8504 (if (eq major-mode 'org-agenda-mode)
8505 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8506 (org-open-at-point))
8508 (defvar org-window-config-before-follow-link nil
8509 "The window configuration before following a link.
8510 This is saved in case the need arises to restore it.")
8512 (defvar org-open-link-marker (make-marker)
8513 "Marker pointing to the location where `org-open-at-point; was called.")
8515 ;;;###autoload
8516 (defun org-open-at-point-global ()
8517 "Follow a link like Org-mode does.
8518 This command can be called in any mode to follow a link that has
8519 Org-mode syntax."
8520 (interactive)
8521 (org-run-like-in-org-mode 'org-open-at-point))
8523 ;;;###autoload
8524 (defun org-open-link-from-string (s &optional arg reference-buffer)
8525 "Open a link in the string S, as if it was in Org-mode."
8526 (interactive "sLink: \nP")
8527 (let ((reference-buffer (or reference-buffer (current-buffer))))
8528 (with-temp-buffer
8529 (let ((org-inhibit-startup t))
8530 (org-mode)
8531 (insert s)
8532 (goto-char (point-min))
8533 (when reference-buffer
8534 (setq org-link-abbrev-alist-local
8535 (with-current-buffer reference-buffer
8536 org-link-abbrev-alist-local)))
8537 (org-open-at-point arg reference-buffer)))))
8539 (defun org-open-at-point (&optional in-emacs reference-buffer)
8540 "Open link at or after point.
8541 If there is no link at point, this function will search forward up to
8542 the end of the current line.
8543 Normally, files will be opened by an appropriate application. If the
8544 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8545 With a double prefix argument, try to open outside of Emacs, in the
8546 application the system uses for this file type."
8547 (interactive "P")
8548 (org-load-modules-maybe)
8549 (move-marker org-open-link-marker (point))
8550 (setq org-window-config-before-follow-link (current-window-configuration))
8551 (org-remove-occur-highlights nil nil t)
8552 (cond
8553 ((and (org-on-heading-p)
8554 (not (org-in-regexp
8555 (concat org-plain-link-re "\\|"
8556 org-bracket-link-regexp "\\|"
8557 org-angle-link-re "\\|"
8558 "[ \t]:[^ \t\n]+:[ \t]*$")))
8559 (not (get-text-property (point) 'org-linked-text)))
8560 (or (org-offer-links-in-entry in-emacs)
8561 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8562 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8563 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8564 (org-footnote-action))
8566 (let (type path link line search (pos (point)))
8567 (catch 'match
8568 (save-excursion
8569 (skip-chars-forward "^]\n\r")
8570 (when (org-in-regexp org-bracket-link-regexp 1)
8571 (setq link (org-extract-attributes
8572 (org-link-unescape (org-match-string-no-properties 1))))
8573 (while (string-match " *\n *" link)
8574 (setq link (replace-match " " t t link)))
8575 (setq link (org-link-expand-abbrev link))
8576 (cond
8577 ((or (file-name-absolute-p link)
8578 (string-match "^\\.\\.?/" link))
8579 (setq type "file" path link))
8580 ((string-match org-link-re-with-space3 link)
8581 (setq type (match-string 1 link) path (match-string 2 link)))
8582 (t (setq type "thisfile" path link)))
8583 (throw 'match t)))
8585 (when (get-text-property (point) 'org-linked-text)
8586 (setq type "thisfile"
8587 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8588 (1+ (point)) (point))
8589 path (buffer-substring
8590 (previous-single-property-change pos 'org-linked-text)
8591 (next-single-property-change pos 'org-linked-text)))
8592 (throw 'match t))
8594 (save-excursion
8595 (when (or (org-in-regexp org-angle-link-re)
8596 (org-in-regexp org-plain-link-re))
8597 (setq type (match-string 1) path (match-string 2))
8598 (throw 'match t)))
8599 (save-excursion
8600 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8601 (setq type "tags"
8602 path (match-string 1))
8603 (while (string-match ":" path)
8604 (setq path (replace-match "+" t t path)))
8605 (throw 'match t)))
8606 (when (org-in-regexp "<\\([^><\n]+\\)>")
8607 (setq type "tree-match"
8608 path (match-string 1))
8609 (throw 'match t)))
8610 (unless path
8611 (error "No link found"))
8613 ;; switch back to reference buffer
8614 ;; needed when if called in a temporary buffer through
8615 ;; org-open-link-from-string
8616 (with-current-buffer (or reference-buffer (current-buffer))
8618 ;; Remove any trailing spaces in path
8619 (if (string-match " +\\'" path)
8620 (setq path (replace-match "" t t path)))
8621 (if (and org-link-translation-function
8622 (fboundp org-link-translation-function))
8623 ;; Check if we need to translate the link
8624 (let ((tmp (funcall org-link-translation-function type path)))
8625 (setq type (car tmp) path (cdr tmp))))
8627 (cond
8629 ((assoc type org-link-protocols)
8630 (funcall (nth 1 (assoc type org-link-protocols)) path))
8632 ((equal type "mailto")
8633 (let ((cmd (car org-link-mailto-program))
8634 (args (cdr org-link-mailto-program)) args1
8635 (address path) (subject "") a)
8636 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8637 (setq address (match-string 1 path)
8638 subject (org-link-escape (match-string 2 path))))
8639 (while args
8640 (cond
8641 ((not (stringp (car args))) (push (pop args) args1))
8642 (t (setq a (pop args))
8643 (if (string-match "%a" a)
8644 (setq a (replace-match address t t a)))
8645 (if (string-match "%s" a)
8646 (setq a (replace-match subject t t a)))
8647 (push a args1))))
8648 (apply cmd (nreverse args1))))
8650 ((member type '("http" "https" "ftp" "news"))
8651 (browse-url (concat type ":" (org-link-escape
8652 path org-link-escape-chars-browser))))
8654 ((member type '("message"))
8655 (browse-url (concat type ":" path)))
8657 ((string= type "tags")
8658 (org-tags-view in-emacs path))
8660 ((string= type "tree-match")
8661 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8663 ((string= type "file")
8664 (if (string-match "::\\([0-9]+\\)\\'" path)
8665 (setq line (string-to-number (match-string 1 path))
8666 path (substring path 0 (match-beginning 0)))
8667 (if (string-match "::\\(.+\\)\\'" path)
8668 (setq search (match-string 1 path)
8669 path (substring path 0 (match-beginning 0)))))
8670 (if (string-match "[*?{]" (file-name-nondirectory path))
8671 (dired path)
8672 (org-open-file path in-emacs line search)))
8674 ((string= type "news")
8675 (require 'org-gnus)
8676 (org-gnus-follow-link path))
8678 ((string= type "shell")
8679 (let ((cmd path))
8680 (if (or (not org-confirm-shell-link-function)
8681 (funcall org-confirm-shell-link-function
8682 (format "Execute \"%s\" in shell? "
8683 (org-add-props cmd nil
8684 'face 'org-warning))))
8685 (progn
8686 (message "Executing %s" cmd)
8687 (shell-command cmd))
8688 (error "Abort"))))
8690 ((string= type "elisp")
8691 (let ((cmd path))
8692 (if (or (not org-confirm-elisp-link-function)
8693 (funcall org-confirm-elisp-link-function
8694 (format "Execute \"%s\" as elisp? "
8695 (org-add-props cmd nil
8696 'face 'org-warning))))
8697 (message "%s => %s" cmd
8698 (if (equal (string-to-char cmd) ?\()
8699 (eval (read cmd))
8700 (call-interactively (read cmd))))
8701 (error "Abort"))))
8703 ((and (string= type "thisfile")
8704 (run-hook-with-args-until-success
8705 'org-open-link-functions path)))
8707 ((string= type "thisfile")
8708 (if in-emacs
8709 (switch-to-buffer-other-window
8710 (org-get-buffer-for-internal-link (current-buffer)))
8711 (org-mark-ring-push))
8712 (let ((cmd `(org-link-search
8713 ,path
8714 ,(cond ((equal in-emacs '(4)) 'occur)
8715 ((equal in-emacs '(16)) 'org-occur)
8716 (t nil))
8717 ,pos)))
8718 (condition-case nil (eval cmd)
8719 (error (progn (widen) (eval cmd))))))
8722 (browse-url-at-point)))))))
8723 (move-marker org-open-link-marker nil)
8724 (run-hook-with-args 'org-follow-link-hook))
8726 (defun org-offer-links-in-entry (&optional nth zero)
8727 "Offer links in the current entry and follow the selected link.
8728 If there is only one link, follow it immediately as well.
8729 If NTH is an integer, immediately pick the NTH link found.
8730 If ZERO is a string, check also this string for a link, and if
8731 there is one, offer it as link number zero."
8732 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8733 "\\(" org-angle-link-re "\\)\\|"
8734 "\\(" org-plain-link-re "\\)"))
8735 (cnt ?0)
8736 (in-emacs (if (integerp nth) nil nth))
8737 have-zero end links link c)
8738 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8739 (push (match-string 0 zero) links)
8740 (setq cnt (1- cnt) have-zero t))
8741 (save-excursion
8742 (org-back-to-heading t)
8743 (setq end (save-excursion (outline-next-heading) (point)))
8744 (while (re-search-forward re end t)
8745 (push (match-string 0) links))
8746 (setq links (org-uniquify (reverse links))))
8748 (cond
8749 ((null links)
8750 (message "No links"))
8751 ((equal (length links) 1)
8752 (setq link (list (car links))))
8753 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8754 (setq link (nth (if have-zero nth (1- nth)) links)))
8755 (t ; we have to select a link
8756 (save-excursion
8757 (save-window-excursion
8758 (delete-other-windows)
8759 (with-output-to-temp-buffer "*Select Link*"
8760 (mapc (lambda (l)
8761 (if (not (string-match org-bracket-link-regexp l))
8762 (princ (format "[%c] %s\n" (incf cnt)
8763 (org-remove-angle-brackets l)))
8764 (if (match-end 3)
8765 (princ (format "[%c] %s (%s)\n" (incf cnt)
8766 (match-string 3 l) (match-string 1 l)))
8767 (princ (format "[%c] %s\n" (incf cnt)
8768 (match-string 1 l))))))
8769 links))
8770 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8771 (message "Select link to open, RET to open all:")
8772 (setq c (read-char-exclusive))
8773 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8774 (when (equal c ?q) (error "Abort"))
8775 (if (equal c ?\C-m)
8776 (setq link links)
8777 (setq nth (- c ?0))
8778 (if have-zero (setq nth (1+ nth)))
8779 (unless (and (integerp nth) (>= (length links) nth))
8780 (error "Invalid link selection"))
8781 (setq link (list (nth (1- nth) links))))))
8782 (if link
8783 (let ((buf (current-buffer)))
8784 (dolist (l link)
8785 (org-open-link-from-string l in-emacs buf))
8787 nil)))
8789 ;; Add special file links that specify the way of opening
8791 (org-add-link-type "file+sys" 'org-open-file-with-system)
8792 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8793 (defun org-open-file-with-system (path)
8794 "Open file at PATH using the system way of opeing it."
8795 (org-open-file path 'system))
8796 (defun org-open-file-with-emacs (path)
8797 "Open file at PATH in emacs."
8798 (org-open-file path 'emacs))
8799 (defun org-remove-file-link-modifiers ()
8800 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8801 (goto-char (point-min))
8802 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8803 (org-if-unprotected
8804 (replace-match "file:" t t))))
8805 (eval-after-load "org-exp"
8806 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8807 'org-remove-file-link-modifiers))
8809 ;;;; Time estimates
8811 (defun org-get-effort (&optional pom)
8812 "Get the effort estimate for the current entry."
8813 (org-entry-get pom org-effort-property))
8815 ;;; File search
8817 (defvar org-create-file-search-functions nil
8818 "List of functions to construct the right search string for a file link.
8819 These functions are called in turn with point at the location to
8820 which the link should point.
8822 A function in the hook should first test if it would like to
8823 handle this file type, for example by checking the major-mode or
8824 the file extension. If it decides not to handle this file, it
8825 should just return nil to give other functions a chance. If it
8826 does handle the file, it must return the search string to be used
8827 when following the link. The search string will be part of the
8828 file link, given after a double colon, and `org-open-at-point'
8829 will automatically search for it. If special measures must be
8830 taken to make the search successful, another function should be
8831 added to the companion hook `org-execute-file-search-functions',
8832 which see.
8834 A function in this hook may also use `setq' to set the variable
8835 `description' to provide a suggestion for the descriptive text to
8836 be used for this link when it gets inserted into an Org-mode
8837 buffer with \\[org-insert-link].")
8839 (defvar org-execute-file-search-functions nil
8840 "List of functions to execute a file search triggered by a link.
8842 Functions added to this hook must accept a single argument, the
8843 search string that was part of the file link, the part after the
8844 double colon. The function must first check if it would like to
8845 handle this search, for example by checking the major-mode or the
8846 file extension. If it decides not to handle this search, it
8847 should just return nil to give other functions a chance. If it
8848 does handle the search, it must return a non-nil value to keep
8849 other functions from trying.
8851 Each function can access the current prefix argument through the
8852 variable `current-prefix-argument'. Note that a single prefix is
8853 used to force opening a link in Emacs, so it may be good to only
8854 use a numeric or double prefix to guide the search function.
8856 In case this is needed, a function in this hook can also restore
8857 the window configuration before `org-open-at-point' was called using:
8859 (set-window-configuration org-window-config-before-follow-link)")
8861 (defun org-link-search (s &optional type avoid-pos)
8862 "Search for a link search option.
8863 If S is surrounded by forward slashes, it is interpreted as a
8864 regular expression. In org-mode files, this will create an `org-occur'
8865 sparse tree. In ordinary files, `occur' will be used to list matches.
8866 If the current buffer is in `dired-mode', grep will be used to search
8867 in all files. If AVOID-POS is given, ignore matches near that position."
8868 (let ((case-fold-search t)
8869 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8870 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8871 (append '(("") (" ") ("\t") ("\n"))
8872 org-emphasis-alist)
8873 "\\|") "\\)"))
8874 (pos (point))
8875 (pre nil) (post nil)
8876 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8877 (cond
8878 ;; First check if there are any special
8879 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8880 ;; Now try the builtin stuff
8881 ((and (equal (string-to-char s0) ?#)
8882 (> (length s0) 1)
8883 (save-excursion
8884 (goto-char (point-min))
8885 (and
8886 (re-search-forward
8887 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8888 (setq type 'dedicated
8889 pos (match-beginning 0))))
8890 ;; There is an exact target for this
8891 (goto-char pos)
8892 (org-back-to-heading t)))
8893 ((save-excursion
8894 (goto-char (point-min))
8895 (and
8896 (re-search-forward
8897 (concat "<<" (regexp-quote s0) ">>") nil t)
8898 (setq type 'dedicated
8899 pos (match-beginning 0))))
8900 ;; There is an exact target for this
8901 (goto-char pos))
8902 ((and (string-match "^(\\(.*\\))$" s0)
8903 (save-excursion
8904 (goto-char (point-min))
8905 (and
8906 (re-search-forward
8907 (concat "[^[]" (regexp-quote
8908 (format org-coderef-label-format
8909 (match-string 1 s0))))
8910 nil t)
8911 (setq type 'dedicated
8912 pos (1+ (match-beginning 0))))))
8913 ;; There is a coderef target for this
8914 (goto-char pos))
8915 ((string-match "^/\\(.*\\)/$" s)
8916 ;; A regular expression
8917 (cond
8918 ((org-mode-p)
8919 (org-occur (match-string 1 s)))
8920 ;;((eq major-mode 'dired-mode)
8921 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8922 (t (org-do-occur (match-string 1 s)))))
8924 ;; A normal search strings
8925 (when (equal (string-to-char s) ?*)
8926 ;; Anchor on headlines, post may include tags.
8927 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8928 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8929 s (substring s 1)))
8930 (remove-text-properties
8931 0 (length s)
8932 '(face nil mouse-face nil keymap nil fontified nil) s)
8933 ;; Make a series of regular expressions to find a match
8934 (setq words (org-split-string s "[ \n\r\t]+")
8936 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8937 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8938 "\\)" markers)
8939 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8940 re2a (concat "[ \t\r\n]" re2a_)
8941 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8942 re4 (concat "[^a-zA-Z_]" re4_)
8944 re1 (concat pre re2 post)
8945 re3 (concat pre (if pre re4_ re4) post)
8946 re5 (concat pre ".*" re4)
8947 re2 (concat pre re2)
8948 re2a (concat pre (if pre re2a_ re2a))
8949 re4 (concat pre (if pre re4_ re4))
8950 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8951 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8952 re5 "\\)"
8954 (cond
8955 ((eq type 'org-occur) (org-occur reall))
8956 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8957 (t (goto-char (point-min))
8958 (setq type 'fuzzy)
8959 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8960 (org-search-not-self 1 re1 nil t)
8961 (org-search-not-self 1 re2 nil t)
8962 (org-search-not-self 1 re2a nil t)
8963 (org-search-not-self 1 re3 nil t)
8964 (org-search-not-self 1 re4 nil t)
8965 (org-search-not-self 1 re5 nil t)
8967 (goto-char (match-beginning 1))
8968 (goto-char pos)
8969 (error "No match")))))
8971 ;; Normal string-search
8972 (goto-char (point-min))
8973 (if (search-forward s nil t)
8974 (goto-char (match-beginning 0))
8975 (error "No match"))))
8976 (and (org-mode-p) (org-show-context 'link-search))
8977 type))
8979 (defun org-search-not-self (group &rest args)
8980 "Execute `re-search-forward', but only accept matches that do not
8981 enclose the position of `org-open-link-marker'."
8982 (let ((m org-open-link-marker))
8983 (catch 'exit
8984 (while (apply 're-search-forward args)
8985 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8986 (goto-char (match-end group))
8987 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8988 (> (match-beginning 0) (marker-position m))
8989 (< (match-end 0) (marker-position m)))
8990 (save-match-data
8991 (or (not (org-in-regexp
8992 org-bracket-link-analytic-regexp 1))
8993 (not (match-end 4)) ; no description
8994 (and (<= (match-beginning 4) (point))
8995 (>= (match-end 4) (point))))))
8996 (throw 'exit (point))))))))
8998 (defun org-get-buffer-for-internal-link (buffer)
8999 "Return a buffer to be used for displaying the link target of internal links."
9000 (cond
9001 ((not org-display-internal-link-with-indirect-buffer)
9002 buffer)
9003 ((string-match "(Clone)$" (buffer-name buffer))
9004 (message "Buffer is already a clone, not making another one")
9005 ;; we also do not modify visibility in this case
9006 buffer)
9007 (t ; make a new indirect buffer for displaying the link
9008 (let* ((bn (buffer-name buffer))
9009 (ibn (concat bn "(Clone)"))
9010 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9011 (with-current-buffer ib (org-overview))
9012 ib))))
9014 (defun org-do-occur (regexp &optional cleanup)
9015 "Call the Emacs command `occur'.
9016 If CLEANUP is non-nil, remove the printout of the regular expression
9017 in the *Occur* buffer. This is useful if the regex is long and not useful
9018 to read."
9019 (occur regexp)
9020 (when cleanup
9021 (let ((cwin (selected-window)) win beg end)
9022 (when (setq win (get-buffer-window "*Occur*"))
9023 (select-window win))
9024 (goto-char (point-min))
9025 (when (re-search-forward "match[a-z]+" nil t)
9026 (setq beg (match-end 0))
9027 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9028 (setq end (1- (match-beginning 0)))))
9029 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9030 (goto-char (point-min))
9031 (select-window cwin))))
9033 ;;; The mark ring for links jumps
9035 (defvar org-mark-ring nil
9036 "Mark ring for positions before jumps in Org-mode.")
9037 (defvar org-mark-ring-last-goto nil
9038 "Last position in the mark ring used to go back.")
9039 ;; Fill and close the ring
9040 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9041 (loop for i from 1 to org-mark-ring-length do
9042 (push (make-marker) org-mark-ring))
9043 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9044 org-mark-ring)
9046 (defun org-mark-ring-push (&optional pos buffer)
9047 "Put the current position or POS into the mark ring and rotate it."
9048 (interactive)
9049 (setq pos (or pos (point)))
9050 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9051 (move-marker (car org-mark-ring)
9052 (or pos (point))
9053 (or buffer (current-buffer)))
9054 (message "%s"
9055 (substitute-command-keys
9056 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9058 (defun org-mark-ring-goto (&optional n)
9059 "Jump to the previous position in the mark ring.
9060 With prefix arg N, jump back that many stored positions. When
9061 called several times in succession, walk through the entire ring.
9062 Org-mode commands jumping to a different position in the current file,
9063 or to another Org-mode file, automatically push the old position
9064 onto the ring."
9065 (interactive "p")
9066 (let (p m)
9067 (if (eq last-command this-command)
9068 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9069 (setq p org-mark-ring))
9070 (setq org-mark-ring-last-goto p)
9071 (setq m (car p))
9072 (switch-to-buffer (marker-buffer m))
9073 (goto-char m)
9074 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9076 (defun org-remove-angle-brackets (s)
9077 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9078 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9080 (defun org-add-angle-brackets (s)
9081 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9082 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9084 (defun org-remove-double-quotes (s)
9085 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9086 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9089 ;;; Following specific links
9091 (defun org-follow-timestamp-link ()
9092 (cond
9093 ((org-at-date-range-p t)
9094 (let ((org-agenda-start-on-weekday)
9095 (t1 (match-string 1))
9096 (t2 (match-string 2)))
9097 (setq t1 (time-to-days (org-time-string-to-time t1))
9098 t2 (time-to-days (org-time-string-to-time t2)))
9099 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9100 ((org-at-timestamp-p t)
9101 (org-agenda-list nil (time-to-days (org-time-string-to-time
9102 (substring (match-string 1) 0 10)))
9104 (t (error "This should not happen"))))
9107 ;;; Following file links
9108 (defvar org-wait nil)
9109 (defun org-open-file (path &optional in-emacs line search)
9110 "Open the file at PATH.
9111 First, this expands any special file name abbreviations. Then the
9112 configuration variable `org-file-apps' is checked if it contains an
9113 entry for this file type, and if yes, the corresponding command is launched.
9115 If no application is found, Emacs simply visits the file.
9117 With optional prefix argument IN-EMACS, Emacs will visit the file.
9118 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9119 and to use an external application to visit the file.
9121 Optional LINE specifies a line to go to, optional SEARCH a string to
9122 search for. If LINE or SEARCH is given, but IN-EMACS is nil, it will
9123 be assumed that org-open-file was called to open a file: link, and the
9124 original link to match against org-file-apps will be reconstructed
9125 from PATH and whichever of LINE or SEARCH is given.
9127 If the file does not exist, an error is thrown."
9128 (let* ((file (if (equal path "")
9129 buffer-file-name
9130 (substitute-in-file-name (expand-file-name path))))
9131 (apps (append org-file-apps (org-default-apps)))
9132 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9133 (dirp (if remp nil (file-directory-p file)))
9134 (file (if (and dirp org-open-directory-means-index-dot-org)
9135 (concat (file-name-as-directory file) "index.org")
9136 file))
9137 (a-m-a-p (assq 'auto-mode apps))
9138 (dfile (downcase file))
9139 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9140 (link (cond ((and (eq line nil)
9141 (eq search nil))
9142 file)
9143 (line
9144 (concat file "::" (number-to-string line)))
9145 (search
9146 (concat file "::" search))))
9147 (dlink (downcase link))
9148 (old-buffer (current-buffer))
9149 (old-pos (point))
9150 (old-mode major-mode)
9151 ext cmd link-match-data)
9152 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9153 (setq ext (match-string 1 dfile))
9154 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9155 (setq ext (match-string 1 dfile))))
9156 (cond
9157 ((member in-emacs '((16) system))
9158 (setq cmd (cdr (assoc 'system apps))))
9159 (in-emacs (setq cmd 'emacs))
9161 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9162 (and dirp (cdr (assoc 'directory apps)))
9163 ;; if we find a match in org-file-apps, store the match
9164 ;; data for later
9165 (let ((match (assoc-default dlink (org-apps-regexp-alist
9166 apps a-m-a-p)
9167 'string-match)))
9168 (if match
9169 (progn (setq link-match-data (match-data))
9170 match)
9171 nil))
9172 (cdr (assoc ext apps))
9173 (cdr (assoc t apps))))))
9174 (when (eq cmd 'system)
9175 (setq cmd (cdr (assoc 'system apps))))
9176 (when (eq cmd 'default)
9177 (setq cmd (cdr (assoc t apps))))
9178 (when (eq cmd 'mailcap)
9179 (require 'mailcap)
9180 (mailcap-parse-mailcaps)
9181 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9182 (command (mailcap-mime-info mime-type)))
9183 (if (stringp command)
9184 (setq cmd command)
9185 (setq cmd 'emacs))))
9186 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9187 (not (file-exists-p file))
9188 (not org-open-non-existing-files))
9189 (error "No such file: %s" file))
9190 (cond
9191 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9192 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9193 (while (string-match "['\"]%s['\"]" cmd)
9194 (setq cmd (replace-match "%s" t t cmd)))
9195 (while (string-match "%s" cmd)
9196 (setq cmd (replace-match
9197 (save-match-data
9198 (shell-quote-argument
9199 (convert-standard-filename file)))
9200 t t cmd)))
9201 ;; Replace "%1", "%2" etc. in command with group matches from regex
9202 (save-match-data
9203 (let ((match-index 1)
9204 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9205 (set-match-data link-match-data)
9206 (while (<= match-index number-of-groups)
9207 (let ((regex (concat "%" (number-to-string match-index)))
9208 (replace-with (match-string match-index dlink)))
9209 (while (string-match regex cmd)
9210 (setq cmd (replace-match replace-with t t cmd))))
9211 (setq match-index (+ match-index 1)))))
9213 (save-window-excursion
9214 (start-process-shell-command cmd nil cmd)
9215 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9217 ((or (stringp cmd)
9218 (eq cmd 'emacs))
9219 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9220 (widen)
9221 (if line (org-goto-line line)
9222 (if search (org-link-search search))))
9223 ((consp cmd)
9224 (let ((file (convert-standard-filename file)))
9225 (save-match-data
9226 (set-match-data link-match-data)
9227 (eval cmd))))
9228 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9229 (and (org-mode-p) (eq old-mode 'org-mode)
9230 (or (not (equal old-buffer (current-buffer)))
9231 (not (equal old-pos (point))))
9232 (org-mark-ring-push old-pos old-buffer))))
9234 (defun org-default-apps ()
9235 "Return the default applications for this operating system."
9236 (cond
9237 ((eq system-type 'darwin)
9238 org-file-apps-defaults-macosx)
9239 ((eq system-type 'windows-nt)
9240 org-file-apps-defaults-windowsnt)
9241 (t org-file-apps-defaults-gnu)))
9243 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9244 "Convert extensions to regular expressions in the cars of LIST.
9245 Also, weed out any non-string entries, because the return value is used
9246 only for regexp matching.
9247 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9248 point to the symbol `emacs', indicating that the file should
9249 be opened in Emacs."
9250 (append
9251 (delq nil
9252 (mapcar (lambda (x)
9253 (if (not (stringp (car x)))
9255 (if (string-match "\\W" (car x))
9257 (cons (concat "\\." (car x) "\\(::.*\\)?\\'")
9258 (cdr x)))))
9259 list))
9260 (if add-auto-mode
9261 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9263 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9264 (defun org-file-remote-p (file)
9265 "Test whether FILE specifies a location on a remote system.
9266 Return non-nil if the location is indeed remote.
9268 For example, the filename \"/user@host:/foo\" specifies a location
9269 on the system \"/user@host:\"."
9270 (cond ((fboundp 'file-remote-p)
9271 (file-remote-p file))
9272 ((fboundp 'tramp-handle-file-remote-p)
9273 (tramp-handle-file-remote-p file))
9274 ((and (boundp 'ange-ftp-name-format)
9275 (string-match (car ange-ftp-name-format) file))
9277 (t nil)))
9280 ;;;; Refiling
9282 (defun org-get-org-file ()
9283 "Read a filename, with default directory `org-directory'."
9284 (let ((default (or org-default-notes-file remember-data-file)))
9285 (read-file-name (format "File name [%s]: " default)
9286 (file-name-as-directory org-directory)
9287 default)))
9289 (defun org-notes-order-reversed-p ()
9290 "Check if the current file should receive notes in reversed order."
9291 (cond
9292 ((not org-reverse-note-order) nil)
9293 ((eq t org-reverse-note-order) t)
9294 ((not (listp org-reverse-note-order)) nil)
9295 (t (catch 'exit
9296 (let ((all org-reverse-note-order)
9297 entry)
9298 (while (setq entry (pop all))
9299 (if (string-match (car entry) buffer-file-name)
9300 (throw 'exit (cdr entry))))
9301 nil)))))
9303 (defvar org-refile-target-table nil
9304 "The list of refile targets, created by `org-refile'.")
9306 (defvar org-agenda-new-buffers nil
9307 "Buffers created to visit agenda files.")
9309 (defun org-get-refile-targets (&optional default-buffer)
9310 "Produce a table with refile targets."
9311 (let ((case-fold-search nil)
9312 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9313 (entries (or org-refile-targets '((nil . (:level . 1)))))
9314 targets txt re files f desc descre fast-path-p level pos0)
9315 (message "Getting targets...")
9316 (with-current-buffer (or default-buffer (current-buffer))
9317 (while (setq entry (pop entries))
9318 (setq files (car entry) desc (cdr entry))
9319 (setq fast-path-p nil)
9320 (cond
9321 ((null files) (setq files (list (current-buffer))))
9322 ((eq files 'org-agenda-files)
9323 (setq files (org-agenda-files 'unrestricted)))
9324 ((and (symbolp files) (fboundp files))
9325 (setq files (funcall files)))
9326 ((and (symbolp files) (boundp files))
9327 (setq files (symbol-value files))))
9328 (if (stringp files) (setq files (list files)))
9329 (cond
9330 ((eq (car desc) :tag)
9331 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9332 ((eq (car desc) :todo)
9333 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9334 ((eq (car desc) :regexp)
9335 (setq descre (cdr desc)))
9336 ((eq (car desc) :level)
9337 (setq descre (concat "^\\*\\{" (number-to-string
9338 (if org-odd-levels-only
9339 (1- (* 2 (cdr desc)))
9340 (cdr desc)))
9341 "\\}[ \t]")))
9342 ((eq (car desc) :maxlevel)
9343 (setq fast-path-p t)
9344 (setq descre (concat "^\\*\\{1," (number-to-string
9345 (if org-odd-levels-only
9346 (1- (* 2 (cdr desc)))
9347 (cdr desc)))
9348 "\\}[ \t]")))
9349 (t (error "Bad refiling target description %s" desc)))
9350 (while (setq f (pop files))
9351 (with-current-buffer
9352 (if (bufferp f) f (org-get-agenda-file-buffer f))
9353 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9354 (setq f (and f (expand-file-name f)))
9355 (if (eq org-refile-use-outline-path 'file)
9356 (push (list (file-name-nondirectory f) f nil nil) targets))
9357 (save-excursion
9358 (save-restriction
9359 (widen)
9360 (goto-char (point-min))
9361 (while (re-search-forward descre nil t)
9362 (goto-char (setq pos0 (point-at-bol)))
9363 (catch 'next
9364 (when org-refile-target-verify-function
9365 (save-match-data
9366 (or (funcall org-refile-target-verify-function)
9367 (throw 'next t))))
9368 (when (looking-at org-complex-heading-regexp)
9369 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9370 txt (org-link-display-format (match-string 4))
9371 re (concat "^" (regexp-quote
9372 (buffer-substring (match-beginning 1)
9373 (match-end 4)))))
9374 (if (match-end 5) (setq re (concat re "[ \t]+"
9375 (regexp-quote
9376 (match-string 5)))))
9377 (setq re (concat re "[ \t]*$"))
9378 (when org-refile-use-outline-path
9379 (setq txt (mapconcat 'org-protect-slash
9380 (append
9381 (if (eq org-refile-use-outline-path 'file)
9382 (list (file-name-nondirectory
9383 (buffer-file-name (buffer-base-buffer))))
9384 (if (eq org-refile-use-outline-path 'full-file-path)
9385 (list (buffer-file-name (buffer-base-buffer)))))
9386 (org-get-outline-path fast-path-p level txt)
9387 (list txt))
9388 "/")))
9389 (push (list txt f re (point)) targets)))
9390 (when (= (point) pos0)
9391 ;; verification function has not moved point
9392 (goto-char (point-at-eol))))))))))
9393 (message "Getting targets...done")
9394 (nreverse targets)))
9396 (defun org-protect-slash (s)
9397 (while (string-match "/" s)
9398 (setq s (replace-match "\\" t t s)))
9401 (defvar org-olpa (make-vector 20 nil))
9403 (defun org-get-outline-path (&optional fastp level heading)
9404 "Return the outline path to the current entry, as a list.
9405 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9406 routine which makes outline path derivations for an entire file,
9407 avoiding backtracing."
9408 (if fastp
9409 (progn
9410 (if (> level 19)
9411 (error "Outline path failure, more than 19 levels."))
9412 (loop for i from level upto 19 do
9413 (aset org-olpa i nil))
9414 (prog1
9415 (delq nil (append org-olpa nil))
9416 (aset org-olpa level heading)))
9417 (let (rtn case-fold-search)
9418 (save-excursion
9419 (save-restriction
9420 (widen)
9421 (while (org-up-heading-safe)
9422 (when (looking-at org-complex-heading-regexp)
9423 (push (org-match-string-no-properties 4) rtn)))
9424 rtn)))))
9426 (defun org-format-outline-path (path &optional width prefix)
9427 "Format the outlie path PATH for display.
9428 Width is the maximum number of characters that is available.
9429 Prefix is a prefix to be included in the returned string,
9430 such as the file name."
9431 (setq width (or width 79))
9432 (if prefix (setq width (- width (length prefix))))
9433 (if (not path)
9434 (or prefix "")
9435 (let* ((nsteps (length path))
9436 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9437 (maxwidth (if (<= total-width width)
9438 10000 ;; everything fits
9439 ;; we need to shorten the level headings
9440 (/ (- width nsteps) nsteps)))
9441 (org-odd-levels-only nil)
9442 (n 0)
9443 (total (1+ (length prefix))))
9444 (setq maxwidth (max maxwidth 10))
9445 (concat prefix
9446 (mapconcat
9447 (lambda (h)
9448 (setq n (1+ n))
9449 (if (and (= n nsteps) (< maxwidth 10000))
9450 (setq maxwidth (- total-width total)))
9451 (if (< (length h) maxwidth)
9452 (progn (setq total (+ total (length h) 1)) h)
9453 (setq h (substring h 0 (- maxwidth 2))
9454 total (+ total maxwidth 1))
9455 (if (string-match "[ \t]+\\'" h)
9456 (setq h (substring h 0 (match-beginning 0))))
9457 (setq h (concat h "..")))
9458 (org-add-props h nil 'face
9459 (nth (% (1- n) org-n-level-faces)
9460 org-level-faces))
9462 path "/")))))
9464 (defun org-display-outline-path (&optional file current)
9465 "Display the current outline path in the echo area."
9466 (interactive "P")
9467 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9468 (case-fold-search nil)
9469 (path (and (org-mode-p) (org-get-outline-path))))
9470 (if current (setq path (append path
9471 (save-excursion
9472 (org-back-to-heading t)
9473 (if (looking-at org-complex-heading-regexp)
9474 (list (match-string 4)))))))
9475 (message "%s"
9476 (org-format-outline-path
9477 path
9478 (1- (frame-width))
9479 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9481 (defvar org-refile-history nil
9482 "History for refiling operations.")
9484 (defvar org-after-refile-insert-hook nil
9485 "Hook run after `org-refile' has inserted its stuff at the new location.
9486 Note that this is still *before* the stuff will be removed from
9487 the *old* location.")
9489 (defun org-refile (&optional goto default-buffer rfloc)
9490 "Move the entry at point to another heading.
9491 The list of target headings is compiled using the information in
9492 `org-refile-targets', which see. This list is created before each use
9493 and will therefore always be up-to-date.
9495 At the target location, the entry is filed as a subitem of the target heading.
9496 Depending on `org-reverse-note-order', the new subitem will either be the
9497 first or the last subitem.
9499 If there is an active region, all entries in that region will be moved.
9500 However, the region must fulfil the requirement that the first heading
9501 is the first one sets the top-level of the moved text - at most siblings
9502 below it are allowed.
9504 With prefix arg GOTO, the command will only visit the target location,
9505 not actually move anything.
9506 With a double prefix `C-u C-u', go to the location where the last refiling
9507 operation has put the subtree.
9508 With a prefix argument of `2', refile to the running clock.
9510 RFLOC can be a refile location obtained in a different way.
9512 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9513 (interactive "P")
9514 (let* ((cbuf (current-buffer))
9515 (regionp (org-region-active-p))
9516 (region-start (and regionp (region-beginning)))
9517 (region-end (and regionp (region-end)))
9518 (region-length (and regionp (- region-end region-start)))
9519 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9520 pos it nbuf file re level reversed)
9521 (setq last-command nil)
9522 (when regionp
9523 (goto-char region-start)
9524 (or (bolp) (goto-char (point-at-bol)))
9525 (setq region-start (point))
9526 (unless (org-kill-is-subtree-p
9527 (buffer-substring region-start region-end))
9528 (error "The region is not a (sequence of) subtree(s)")))
9529 (if (equal goto '(16))
9530 (org-refile-goto-last-stored)
9531 (when (or
9532 (and (equal goto 2)
9533 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9534 (prog1
9535 (setq it (list (or org-clock-heading "running clock")
9536 (buffer-file-name
9537 (marker-buffer org-clock-hd-marker))
9539 (marker-position org-clock-hd-marker)))
9540 (setq goto nil)))
9541 (setq it (or rfloc
9542 (save-excursion
9543 (org-refile-get-location
9544 (if goto "Goto: " "Refile to: ") default-buffer
9545 org-refile-allow-creating-parent-nodes)))))
9546 (setq file (nth 1 it)
9547 re (nth 2 it)
9548 pos (nth 3 it))
9549 (if (and (not goto)
9551 (equal (buffer-file-name) file)
9552 (if regionp
9553 (and (>= pos region-start)
9554 (<= pos region-end))
9555 (and (>= pos (point))
9556 (< pos (save-excursion
9557 (org-end-of-subtree t t))))))
9558 (error "Cannot refile to position inside the tree or region"))
9560 (setq nbuf (or (find-buffer-visiting file)
9561 (find-file-noselect file)))
9562 (if goto
9563 (progn
9564 (switch-to-buffer nbuf)
9565 (goto-char pos)
9566 (org-show-context 'org-goto))
9567 (if regionp
9568 (progn
9569 (org-kill-new (buffer-substring region-start region-end))
9570 (org-save-markers-in-region region-start region-end))
9571 (org-copy-subtree 1 nil t))
9572 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9573 (find-file-noselect file)))
9574 (setq reversed (org-notes-order-reversed-p))
9575 (save-excursion
9576 (save-restriction
9577 (widen)
9578 (if pos
9579 (progn
9580 (goto-char pos)
9581 (looking-at outline-regexp)
9582 (setq level (org-get-valid-level (funcall outline-level) 1))
9583 (goto-char
9584 (if reversed
9585 (or (outline-next-heading) (point-max))
9586 (or (save-excursion (org-get-next-sibling))
9587 (org-end-of-subtree t t)
9588 (point-max)))))
9589 (setq level 1)
9590 (if (not reversed)
9591 (goto-char (point-max))
9592 (goto-char (point-min))
9593 (or (outline-next-heading) (goto-char (point-max)))))
9594 (if (not (bolp)) (newline))
9595 (org-paste-subtree level)
9596 (when org-log-refile
9597 (org-add-log-setup 'refile nil nil 'findpos
9598 org-log-refile)
9599 (unless (eq org-log-refile 'note)
9600 (save-excursion (org-add-log-note))))
9601 (and org-auto-align-tags (org-set-tags nil t))
9602 (bookmark-set "org-refile-last-stored")
9603 (if (fboundp 'deactivate-mark) (deactivate-mark))
9604 (run-hooks 'org-after-refile-insert-hook))))
9605 (if regionp
9606 (delete-region (point) (+ (point) region-length))
9607 (org-cut-subtree))
9608 (when (featurep 'org-inlinetask)
9609 (org-inlinetask-remove-END-maybe))
9610 (setq org-markers-to-move nil)
9611 (message "Refiled to \"%s\"" (car it))))))
9612 (org-reveal))
9614 (defun org-refile-goto-last-stored ()
9615 "Go to the location where the last refile was stored."
9616 (interactive)
9617 (bookmark-jump "org-refile-last-stored")
9618 (message "This is the location of the last refile"))
9620 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9621 "Prompt the user for a refile location, using PROMPT."
9622 (let ((org-refile-targets org-refile-targets)
9623 (org-refile-use-outline-path org-refile-use-outline-path))
9624 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9625 (unless org-refile-target-table
9626 (error "No refile targets"))
9627 (let* ((cbuf (current-buffer))
9628 (partial-completion-mode nil)
9629 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9630 (cfunc (if (and org-refile-use-outline-path
9631 org-outline-path-complete-in-steps)
9632 'org-olpath-completing-read
9633 'org-icompleting-read))
9634 (extra (if org-refile-use-outline-path "/" ""))
9635 (filename (and cfn (expand-file-name cfn)))
9636 (tbl (mapcar
9637 (lambda (x)
9638 (if (and (not (member org-refile-use-outline-path
9639 '(file full-file-path)))
9640 (not (equal filename (nth 1 x))))
9641 (cons (concat (car x) extra " ("
9642 (file-name-nondirectory (nth 1 x)) ")")
9643 (cdr x))
9644 (cons (concat (car x) extra) (cdr x))))
9645 org-refile-target-table))
9646 (completion-ignore-case t)
9647 pa answ parent-target child parent old-hist)
9648 (setq old-hist org-refile-history)
9649 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9650 nil 'org-refile-history))
9651 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9652 (if pa
9653 (progn
9654 (when (or (not org-refile-history)
9655 (not (eq old-hist org-refile-history))
9656 (not (equal (car pa) (car org-refile-history))))
9657 (setq org-refile-history
9658 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9659 org-refile-history
9660 (cdr org-refile-history))))
9661 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9662 (pop org-refile-history)))
9664 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9665 (progn
9666 (setq parent (match-string 1 answ)
9667 child (match-string 2 answ))
9668 (setq parent-target (or (assoc parent tbl)
9669 (assoc (concat parent "/") tbl)))
9670 (when (and parent-target
9671 (or (eq new-nodes t)
9672 (and (eq new-nodes 'confirm)
9673 (y-or-n-p (format "Create new node \"%s\"? "
9674 child)))))
9675 (org-refile-new-child parent-target child)))
9676 (error "Invalid target location")))))
9678 (defun org-refile-new-child (parent-target child)
9679 "Use refile target PARENT-TARGET to add new CHILD below it."
9680 (unless parent-target
9681 (error "Cannot find parent for new node"))
9682 (let ((file (nth 1 parent-target))
9683 (pos (nth 3 parent-target))
9684 level)
9685 (with-current-buffer (or (find-buffer-visiting file)
9686 (find-file-noselect file))
9687 (save-excursion
9688 (save-restriction
9689 (widen)
9690 (if pos
9691 (goto-char pos)
9692 (goto-char (point-max))
9693 (if (not (bolp)) (newline)))
9694 (when (looking-at outline-regexp)
9695 (setq level (funcall outline-level))
9696 (org-end-of-subtree t t))
9697 (org-back-over-empty-lines)
9698 (insert "\n" (make-string
9699 (if pos (org-get-valid-level level 1) 1) ?*)
9700 " " child "\n")
9701 (beginning-of-line 0)
9702 (list (concat (car parent-target) "/" child) file "" (point)))))))
9704 (defun org-olpath-completing-read (prompt collection &rest args)
9705 "Read an outline path like a file name."
9706 (let ((thetable collection)
9707 (org-completion-use-ido nil) ; does not work with ido.
9708 (org-completion-use-iswitchb nil)) ; or iswitchb
9709 (apply
9710 'org-icompleting-read prompt
9711 (lambda (string predicate &optional flag)
9712 (let (rtn r f (l (length string)))
9713 (cond
9714 ((eq flag nil)
9715 ;; try completion
9716 (try-completion string thetable))
9717 ((eq flag t)
9718 ;; all-completions
9719 (setq rtn (all-completions string thetable predicate))
9720 (mapcar
9721 (lambda (x)
9722 (setq r (substring x l))
9723 (if (string-match " ([^)]*)$" x)
9724 (setq f (match-string 0 x))
9725 (setq f ""))
9726 (if (string-match "/" r)
9727 (concat string (substring r 0 (match-end 0)) f)
9729 rtn))
9730 ((eq flag 'lambda)
9731 ;; exact match?
9732 (assoc string thetable)))
9734 args)))
9736 ;;;; Dynamic blocks
9738 (defun org-find-dblock (name)
9739 "Find the first dynamic block with name NAME in the buffer.
9740 If not found, stay at current position and return nil."
9741 (let (pos)
9742 (save-excursion
9743 (goto-char (point-min))
9744 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9745 nil t)
9746 (match-beginning 0))))
9747 (if pos (goto-char pos))
9748 pos))
9750 (defconst org-dblock-start-re
9751 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9752 "Matches the start line of a dynamic block, with parameters.")
9754 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9755 "Matches the end of a dynamic block.")
9757 (defun org-create-dblock (plist)
9758 "Create a dynamic block section, with parameters taken from PLIST.
9759 PLIST must contain a :name entry which is used as name of the block."
9760 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9761 (end-of-line 1)
9762 (newline))
9763 (let ((col (current-column))
9764 (name (plist-get plist :name)))
9765 (insert "#+BEGIN: " name)
9766 (while plist
9767 (if (eq (car plist) :name)
9768 (setq plist (cddr plist))
9769 (insert " " (prin1-to-string (pop plist)))))
9770 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9771 (beginning-of-line -2)))
9773 (defun org-prepare-dblock ()
9774 "Prepare dynamic block for refresh.
9775 This empties the block, puts the cursor at the insert position and returns
9776 the property list including an extra property :name with the block name."
9777 (unless (looking-at org-dblock-start-re)
9778 (error "Not at a dynamic block"))
9779 (let* ((begdel (1+ (match-end 0)))
9780 (name (org-no-properties (match-string 1)))
9781 (params (append (list :name name)
9782 (read (concat "(" (match-string 3) ")")))))
9783 (save-excursion
9784 (beginning-of-line 1)
9785 (skip-chars-forward " \t")
9786 (setq params (plist-put params :indentation-column (current-column))))
9787 (unless (re-search-forward org-dblock-end-re nil t)
9788 (error "Dynamic block not terminated"))
9789 (setq params
9790 (append params
9791 (list :content (buffer-substring
9792 begdel (match-beginning 0)))))
9793 (delete-region begdel (match-beginning 0))
9794 (goto-char begdel)
9795 (open-line 1)
9796 params))
9798 (defun org-map-dblocks (&optional command)
9799 "Apply COMMAND to all dynamic blocks in the current buffer.
9800 If COMMAND is not given, use `org-update-dblock'."
9801 (let ((cmd (or command 'org-update-dblock)))
9802 (save-excursion
9803 (goto-char (point-min))
9804 (while (re-search-forward org-dblock-start-re nil t)
9805 (goto-char (match-beginning 0))
9806 (save-excursion
9807 (condition-case nil
9808 (funcall cmd)
9809 (error (message "Error during update of dynamic block"))))
9810 (unless (re-search-forward org-dblock-end-re nil t)
9811 (error "Dynamic block not terminated"))))))
9813 (defun org-dblock-update (&optional arg)
9814 "User command for updating dynamic blocks.
9815 Update the dynamic block at point. With prefix ARG, update all dynamic
9816 blocks in the buffer."
9817 (interactive "P")
9818 (if arg
9819 (org-update-all-dblocks)
9820 (or (looking-at org-dblock-start-re)
9821 (org-beginning-of-dblock))
9822 (org-update-dblock)))
9824 (defun org-update-dblock ()
9825 "Update the dynamic block at point
9826 This means to empty the block, parse for parameters and then call
9827 the correct writing function."
9828 (save-window-excursion
9829 (let* ((pos (point))
9830 (line (org-current-line))
9831 (params (org-prepare-dblock))
9832 (name (plist-get params :name))
9833 (indent (plist-get params :indentation-column))
9834 (cmd (intern (concat "org-dblock-write:" name))))
9835 (message "Updating dynamic block `%s' at line %d..." name line)
9836 (funcall cmd params)
9837 (message "Updating dynamic block `%s' at line %d...done" name line)
9838 (goto-char pos)
9839 (when (and indent (> indent 0))
9840 (setq indent (make-string indent ?\ ))
9841 (save-excursion
9842 (org-beginning-of-dblock)
9843 (forward-line 1)
9844 (while (not (looking-at org-dblock-end-re))
9845 (insert indent)
9846 (beginning-of-line 2))
9847 (when (looking-at org-dblock-end-re)
9848 (and (looking-at "[ \t]+")
9849 (replace-match ""))
9850 (insert indent)))))))
9852 (defun org-beginning-of-dblock ()
9853 "Find the beginning of the dynamic block at point.
9854 Error if there is no such block at point."
9855 (let ((pos (point))
9856 beg)
9857 (end-of-line 1)
9858 (if (and (re-search-backward org-dblock-start-re nil t)
9859 (setq beg (match-beginning 0))
9860 (re-search-forward org-dblock-end-re nil t)
9861 (> (match-end 0) pos))
9862 (goto-char beg)
9863 (goto-char pos)
9864 (error "Not in a dynamic block"))))
9866 (defun org-update-all-dblocks ()
9867 "Update all dynamic blocks in the buffer.
9868 This function can be used in a hook."
9869 (when (org-mode-p)
9870 (org-map-dblocks 'org-update-dblock)))
9873 ;;;; Completion
9875 (defconst org-additional-option-like-keywords
9876 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9877 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9878 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9879 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9880 "BEGIN:" "END:"
9881 "ORGTBL" "TBLFM:" "TBLNAME:"
9882 "BEGIN_EXAMPLE" "END_EXAMPLE"
9883 "BEGIN_QUOTE" "END_QUOTE"
9884 "BEGIN_VERSE" "END_VERSE"
9885 "BEGIN_CENTER" "END_CENTER"
9886 "BEGIN_SRC" "END_SRC"
9887 "CATEGORY" "COLUMNS"
9888 "CAPTION" "LABEL"
9889 "SETUPFILE"
9890 "BIND"
9891 "MACRO"))
9893 (defcustom org-structure-template-alist
9895 ("s" "#+begin_src ?\n\n#+end_src"
9896 "<src lang=\"?\">\n\n</src>")
9897 ("e" "#+begin_example\n?\n#+end_example"
9898 "<example>\n?\n</example>")
9899 ("q" "#+begin_quote\n?\n#+end_quote"
9900 "<quote>\n?\n</quote>")
9901 ("v" "#+begin_verse\n?\n#+end_verse"
9902 "<verse>\n?\n/verse>")
9903 ("c" "#+begin_center\n?\n#+end_center"
9904 "<center>\n?\n/center>")
9905 ("l" "#+begin_latex\n?\n#+end_latex"
9906 "<literal style=\"latex\">\n?\n</literal>")
9907 ("L" "#+latex: "
9908 "<literal style=\"latex\">?</literal>")
9909 ("h" "#+begin_html\n?\n#+end_html"
9910 "<literal style=\"html\">\n?\n</literal>")
9911 ("H" "#+html: "
9912 "<literal style=\"html\">?</literal>")
9913 ("a" "#+begin_ascii\n?\n#+end_ascii")
9914 ("A" "#+ascii: ")
9915 ("i" "#+include %file ?"
9916 "<include file=%file markup=\"?\">")
9918 "Structure completion elements.
9919 This is a list of abbreviation keys and values. The value gets inserted
9920 it you type @samp{.} followed by the key and then the completion key,
9921 usually `M-TAB'. %file will be replaced by a file name after prompting
9922 for the file using completion.
9923 There are two templates for each key, the first uses the original Org syntax,
9924 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9925 the default when the /org-mtags.el/ module has been loaded. See also the
9926 variable `org-mtags-prefer-muse-templates'.
9927 This is an experimental feature, it is undecided if it is going to stay in."
9928 :group 'org-completion
9929 :type '(repeat
9930 (string :tag "Key")
9931 (string :tag "Template")
9932 (string :tag "Muse Template")))
9934 (defun org-try-structure-completion ()
9935 "Try to complete a structure template before point.
9936 This looks for strings like \"<e\" on an otherwise empty line and
9937 expands them."
9938 (let ((l (buffer-substring (point-at-bol) (point)))
9940 (when (and (looking-at "[ \t]*$")
9941 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9942 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9943 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9944 (match-beginning 1)) a)
9945 t)))
9947 (defun org-complete-expand-structure-template (start cell)
9948 "Expand a structure template."
9949 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9950 (rpl (nth (if musep 2 1) cell))
9951 (ind ""))
9952 (delete-region start (point))
9953 (when (string-match "\\`#\\+" rpl)
9954 (cond
9955 ((bolp))
9956 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9957 (setq ind (buffer-substring (point-at-bol) (point))))
9958 (t (newline))))
9959 (setq start (point))
9960 (if (string-match "%file" rpl)
9961 (setq rpl (replace-match
9962 (concat
9963 "\""
9964 (save-match-data
9965 (abbreviate-file-name (read-file-name "Include file: ")))
9966 "\"")
9967 t t rpl)))
9968 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9969 (concat "\n" ind)))
9970 (insert rpl)
9971 (if (re-search-backward "\\?" start t) (delete-char 1))))
9974 (defun org-complete (&optional arg)
9975 "Perform completion on word at point.
9976 At the beginning of a headline, this completes TODO keywords as given in
9977 `org-todo-keywords'.
9978 If the current word is preceded by a backslash, completes the TeX symbols
9979 that are supported for HTML support.
9980 If the current word is preceded by \"#+\", completes special words for
9981 setting file options.
9982 In the line after \"#+STARTUP:, complete valid keywords.\"
9983 At all other locations, this simply calls the value of
9984 `org-completion-fallback-command'."
9985 (interactive "P")
9986 (org-without-partial-completion
9987 (catch 'exit
9988 (let* ((a nil)
9989 (end (point))
9990 (beg1 (save-excursion
9991 (skip-chars-backward (org-re "[:alnum:]_@"))
9992 (point)))
9993 (beg (save-excursion
9994 (skip-chars-backward "a-zA-Z0-9_:$")
9995 (point)))
9996 (confirm (lambda (x) (stringp (car x))))
9997 (searchhead (equal (char-before beg) ?*))
9998 (struct
9999 (when (and (member (char-before beg1) '(?. ?<))
10000 (setq a (assoc (buffer-substring beg1 (point))
10001 org-structure-template-alist)))
10002 (org-complete-expand-structure-template (1- beg1) a)
10003 (throw 'exit t)))
10004 (tag (and (equal (char-before beg1) ?:)
10005 (equal (char-after (point-at-bol)) ?*)))
10006 (prop (and (equal (char-before beg1) ?:)
10007 (not (equal (char-after (point-at-bol)) ?*))))
10008 (texp (equal (char-before beg) ?\\))
10009 (link (equal (char-before beg) ?\[))
10010 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10011 beg)
10012 "#+"))
10013 (startup (string-match "^#\\+STARTUP:.*"
10014 (buffer-substring (point-at-bol) (point))))
10015 (completion-ignore-case opt)
10016 (type nil)
10017 (tbl nil)
10018 (table (cond
10019 (opt
10020 (setq type :opt)
10021 (require 'org-exp)
10022 (append
10023 (delq nil
10024 (mapcar
10025 (lambda (x)
10026 (if (string-match
10027 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10028 (cons (match-string 2 x)
10029 (match-string 1 x))))
10030 (org-split-string (org-get-current-options) "\n")))
10031 (mapcar 'list org-additional-option-like-keywords)))
10032 (startup
10033 (setq type :startup)
10034 org-startup-options)
10035 (link (append org-link-abbrev-alist-local
10036 org-link-abbrev-alist))
10037 (texp
10038 (setq type :tex)
10039 (append org-entities-user org-entities))
10040 ((string-match "\\`\\*+[ \t]+\\'"
10041 (buffer-substring (point-at-bol) beg))
10042 (setq type :todo)
10043 (mapcar 'list org-todo-keywords-1))
10044 (searchhead
10045 (setq type :searchhead)
10046 (save-excursion
10047 (goto-char (point-min))
10048 (while (re-search-forward org-todo-line-regexp nil t)
10049 (push (list
10050 (org-make-org-heading-search-string
10051 (match-string 3) t))
10052 tbl)))
10053 tbl)
10054 (tag (setq type :tag beg beg1)
10055 (or org-tag-alist (org-get-buffer-tags)))
10056 (prop (setq type :prop beg beg1)
10057 (mapcar 'list (org-buffer-property-keys nil t t)))
10058 (t (progn
10059 (call-interactively org-completion-fallback-command)
10060 (throw 'exit nil)))))
10061 (pattern (buffer-substring-no-properties beg end))
10062 (completion (try-completion pattern table confirm)))
10063 (cond ((eq completion t)
10064 (if (not (assoc (upcase pattern) table))
10065 (message "Already complete")
10066 (if (and (equal type :opt)
10067 (not (member (car (assoc (upcase pattern) table))
10068 org-additional-option-like-keywords)))
10069 (insert (substring (cdr (assoc (upcase pattern) table))
10070 (length pattern)))
10071 (if (memq type '(:tag :prop)) (insert ":")))))
10072 ((null completion)
10073 (message "Can't find completion for \"%s\"" pattern)
10074 (ding))
10075 ((not (string= pattern completion))
10076 (delete-region beg end)
10077 (if (string-match " +$" completion)
10078 (setq completion (replace-match "" t t completion)))
10079 (insert completion)
10080 (if (get-buffer-window "*Completions*")
10081 (delete-window (get-buffer-window "*Completions*")))
10082 (if (assoc completion table)
10083 (if (eq type :todo) (insert " ")
10084 (if (memq type '(:tag :prop)) (insert ":"))))
10085 (if (and (equal type :opt) (assoc completion table))
10086 (message "%s" (substitute-command-keys
10087 "Press \\[org-complete] again to insert example settings"))))
10089 (message "Making completion list...")
10090 (let ((list (sort (all-completions pattern table confirm)
10091 'string<)))
10092 (with-output-to-temp-buffer "*Completions*"
10093 (condition-case nil
10094 ;; Protection needed for XEmacs and emacs 21
10095 (display-completion-list list pattern)
10096 (error (display-completion-list list)))))
10097 (message "Making completion list...%s" "done")))))))
10099 ;;;; TODO, DEADLINE, Comments
10101 (defun org-toggle-comment ()
10102 "Change the COMMENT state of an entry."
10103 (interactive)
10104 (save-excursion
10105 (org-back-to-heading)
10106 (let (case-fold-search)
10107 (if (looking-at (concat outline-regexp
10108 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10109 (replace-match "" t t nil 1)
10110 (if (looking-at outline-regexp)
10111 (progn
10112 (goto-char (match-end 0))
10113 (insert org-comment-string " ")))))))
10115 (defvar org-last-todo-state-is-todo nil
10116 "This is non-nil when the last TODO state change led to a TODO state.
10117 If the last change removed the TODO tag or switched to DONE, then
10118 this is nil.")
10120 (defvar org-setting-tags nil) ; dynamically skipped
10122 (defun org-parse-local-options (string var)
10123 "Parse STRING for startup setting relevant for variable VAR."
10124 (let ((rtn (symbol-value var))
10125 e opts)
10126 (save-match-data
10127 (if (or (not string) (not (string-match "\\S-" string)))
10129 (setq opts (delq nil (mapcar (lambda (x)
10130 (setq e (assoc x org-startup-options))
10131 (if (eq (nth 1 e) var) e nil))
10132 (org-split-string string "[ \t]+"))))
10133 (if (not opts)
10135 (setq rtn nil)
10136 (while (setq e (pop opts))
10137 (if (not (nth 3 e))
10138 (setq rtn (nth 2 e))
10139 (if (not (listp rtn)) (setq rtn nil))
10140 (push (nth 2 e) rtn)))
10141 rtn)))))
10143 (defvar org-todo-setup-filter-hook nil
10144 "Hook for functions that pre-filter todo specs.
10146 Each function takes a todo spec and returns either `nil' or the spec
10147 transformed into canonical form." )
10149 (defvar org-todo-get-default-hook nil
10150 "Hook for functions that get a default item for todo.
10152 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10153 `nil' or a string to be used for the todo mark." )
10155 (defvar org-agenda-headline-snapshot-before-repeat)
10157 (defun org-todo (&optional arg)
10158 "Change the TODO state of an item.
10159 The state of an item is given by a keyword at the start of the heading,
10160 like
10161 *** TODO Write paper
10162 *** DONE Call mom
10164 The different keywords are specified in the variable `org-todo-keywords'.
10165 By default the available states are \"TODO\" and \"DONE\".
10166 So for this example: when the item starts with TODO, it is changed to DONE.
10167 When it starts with DONE, the DONE is removed. And when neither TODO nor
10168 DONE are present, add TODO at the beginning of the heading.
10170 With C-u prefix arg, use completion to determine the new state.
10171 With numeric prefix arg, switch to that state.
10172 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10173 With a triple C-u prefix, circumvent any state blocking.
10175 For calling through lisp, arg is also interpreted in the following way:
10176 'none -> empty state
10177 \"\"(empty string) -> switch to empty state
10178 'done -> switch to DONE
10179 'nextset -> switch to the next set of keywords
10180 'previousset -> switch to the previous set of keywords
10181 \"WAITING\" -> switch to the specified keyword, but only if it
10182 really is a member of `org-todo-keywords'."
10183 (interactive "P")
10184 (if (equal arg '(16)) (setq arg 'nextset))
10185 (let ((org-blocker-hook org-blocker-hook)
10186 (case-fold-search nil))
10187 (when (equal arg '(64))
10188 (setq arg nil org-blocker-hook nil))
10189 (when (and org-blocker-hook
10190 (or org-inhibit-blocking
10191 (org-entry-get nil "NOBLOCKING")))
10192 (setq org-blocker-hook nil))
10193 (save-excursion
10194 (catch 'exit
10195 (org-back-to-heading t)
10196 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10197 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10198 (looking-at " *"))
10199 (let* ((match-data (match-data))
10200 (startpos (point-at-bol))
10201 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10202 (org-log-done org-log-done)
10203 (org-log-repeat org-log-repeat)
10204 (org-todo-log-states org-todo-log-states)
10205 (this (match-string 1))
10206 (hl-pos (match-beginning 0))
10207 (head (org-get-todo-sequence-head this))
10208 (ass (assoc head org-todo-kwd-alist))
10209 (interpret (nth 1 ass))
10210 (done-word (nth 3 ass))
10211 (final-done-word (nth 4 ass))
10212 (last-state (or this ""))
10213 (completion-ignore-case t)
10214 (member (member this org-todo-keywords-1))
10215 (tail (cdr member))
10216 (state (cond
10217 ((and org-todo-key-trigger
10218 (or (and (equal arg '(4))
10219 (eq org-use-fast-todo-selection 'prefix))
10220 (and (not arg) org-use-fast-todo-selection
10221 (not (eq org-use-fast-todo-selection
10222 'prefix)))))
10223 ;; Use fast selection
10224 (org-fast-todo-selection))
10225 ((and (equal arg '(4))
10226 (or (not org-use-fast-todo-selection)
10227 (not org-todo-key-trigger)))
10228 ;; Read a state with completion
10229 (org-icompleting-read
10230 "State: " (mapcar (lambda(x) (list x))
10231 org-todo-keywords-1)
10232 nil t))
10233 ((eq arg 'right)
10234 (if this
10235 (if tail (car tail) nil)
10236 (car org-todo-keywords-1)))
10237 ((eq arg 'left)
10238 (if (equal member org-todo-keywords-1)
10240 (if this
10241 (nth (- (length org-todo-keywords-1)
10242 (length tail) 2)
10243 org-todo-keywords-1)
10244 (org-last org-todo-keywords-1))))
10245 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10246 (setq arg nil))) ; hack to fall back to cycling
10247 (arg
10248 ;; user or caller requests a specific state
10249 (cond
10250 ((equal arg "") nil)
10251 ((eq arg 'none) nil)
10252 ((eq arg 'done) (or done-word (car org-done-keywords)))
10253 ((eq arg 'nextset)
10254 (or (car (cdr (member head org-todo-heads)))
10255 (car org-todo-heads)))
10256 ((eq arg 'previousset)
10257 (let ((org-todo-heads (reverse org-todo-heads)))
10258 (or (car (cdr (member head org-todo-heads)))
10259 (car org-todo-heads))))
10260 ((car (member arg org-todo-keywords-1)))
10261 ((stringp arg)
10262 (error "State `%s' not valid in this file" arg))
10263 ((nth (1- (prefix-numeric-value arg))
10264 org-todo-keywords-1))))
10265 ((null member) (or head (car org-todo-keywords-1)))
10266 ((equal this final-done-word) nil) ;; -> make empty
10267 ((null tail) nil) ;; -> first entry
10268 ((memq interpret '(type priority))
10269 (if (eq this-command last-command)
10270 (car tail)
10271 (if (> (length tail) 0)
10272 (or done-word (car org-done-keywords))
10273 nil)))
10275 (car tail))))
10276 (state (or
10277 (run-hook-with-args-until-success
10278 'org-todo-get-default-hook state last-state)
10279 state))
10280 (next (if state (concat " " state " ") " "))
10281 (change-plist (list :type 'todo-state-change :from this :to state
10282 :position startpos))
10283 dolog now-done-p)
10284 (when org-blocker-hook
10285 (setq org-last-todo-state-is-todo
10286 (not (member this org-done-keywords)))
10287 (unless (save-excursion
10288 (save-match-data
10289 (run-hook-with-args-until-failure
10290 'org-blocker-hook change-plist)))
10291 (if (interactive-p)
10292 (error "TODO state change from %s to %s blocked" this state)
10293 ;; fail silently
10294 (message "TODO state change from %s to %s blocked" this state)
10295 (throw 'exit nil))))
10296 (store-match-data match-data)
10297 (replace-match next t t)
10298 (unless (pos-visible-in-window-p hl-pos)
10299 (message "TODO state changed to %s" (org-trim next)))
10300 (unless head
10301 (setq head (org-get-todo-sequence-head state)
10302 ass (assoc head org-todo-kwd-alist)
10303 interpret (nth 1 ass)
10304 done-word (nth 3 ass)
10305 final-done-word (nth 4 ass)))
10306 (when (memq arg '(nextset previousset))
10307 (message "Keyword-Set %d/%d: %s"
10308 (- (length org-todo-sets) -1
10309 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10310 (length org-todo-sets)
10311 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10312 (setq org-last-todo-state-is-todo
10313 (not (member state org-done-keywords)))
10314 (setq now-done-p (and (member state org-done-keywords)
10315 (not (member this org-done-keywords))))
10316 (and logging (org-local-logging logging))
10317 (when (and (or org-todo-log-states org-log-done)
10318 (not (eq org-inhibit-logging t))
10319 (not (memq arg '(nextset previousset))))
10320 ;; we need to look at recording a time and note
10321 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10322 (nth 2 (assoc this org-todo-log-states))))
10323 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10324 (setq dolog 'time))
10325 (when (and state
10326 (member state org-not-done-keywords)
10327 (not (member this org-not-done-keywords)))
10328 ;; This is now a todo state and was not one before
10329 ;; If there was a CLOSED time stamp, get rid of it.
10330 (org-add-planning-info nil nil 'closed))
10331 (when (and now-done-p org-log-done)
10332 ;; It is now done, and it was not done before
10333 (org-add-planning-info 'closed (org-current-time))
10334 (if (and (not dolog) (eq 'note org-log-done))
10335 (org-add-log-setup 'done state this 'findpos 'note)))
10336 (when (and state dolog)
10337 ;; This is a non-nil state, and we need to log it
10338 (org-add-log-setup 'state state this 'findpos dolog)))
10339 ;; Fixup tag positioning
10340 (org-todo-trigger-tag-changes state)
10341 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10342 (when org-provide-todo-statistics
10343 (org-update-parent-todo-statistics))
10344 (run-hooks 'org-after-todo-state-change-hook)
10345 (if (and arg (not (member state org-done-keywords)))
10346 (setq head (org-get-todo-sequence-head state)))
10347 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10348 ;; Do we need to trigger a repeat?
10349 (when now-done-p
10350 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10351 ;; This is for the agenda, take a snapshot of the headline.
10352 (save-match-data
10353 (setq org-agenda-headline-snapshot-before-repeat
10354 (org-get-heading))))
10355 (org-auto-repeat-maybe state))
10356 ;; Fixup cursor location if close to the keyword
10357 (if (and (outline-on-heading-p)
10358 (not (bolp))
10359 (save-excursion (beginning-of-line 1)
10360 (looking-at org-todo-line-regexp))
10361 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10362 (progn
10363 (goto-char (or (match-end 2) (match-end 1)))
10364 (and (looking-at " ") (just-one-space))))
10365 (when org-trigger-hook
10366 (save-excursion
10367 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10369 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10370 "Block turning an entry into a TODO, using the hierarchy.
10371 This checks whether the current task should be blocked from state
10372 changes. Such blocking occurs when:
10374 1. The task has children which are not all in a completed state.
10376 2. A task has a parent with the property :ORDERED:, and there
10377 are siblings prior to the current task with incomplete
10378 status.
10380 3. The parent of the task is blocked because it has siblings that should
10381 be done first, or is child of a block grandparent TODO entry."
10383 (if (not org-enforce-todo-dependencies)
10384 t ; if locally turned off don't block
10385 (catch 'dont-block
10386 ;; If this is not a todo state change, or if this entry is already DONE,
10387 ;; do not block
10388 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10389 (member (plist-get change-plist :from)
10390 (cons 'done org-done-keywords))
10391 (member (plist-get change-plist :to)
10392 (cons 'todo org-not-done-keywords))
10393 (not (plist-get change-plist :to)))
10394 (throw 'dont-block t))
10395 ;; If this task has children, and any are undone, it's blocked
10396 (save-excursion
10397 (org-back-to-heading t)
10398 (let ((this-level (funcall outline-level)))
10399 (outline-next-heading)
10400 (let ((child-level (funcall outline-level)))
10401 (while (and (not (eobp))
10402 (> child-level this-level))
10403 ;; this todo has children, check whether they are all
10404 ;; completed
10405 (if (and (not (org-entry-is-done-p))
10406 (org-entry-is-todo-p))
10407 (throw 'dont-block nil))
10408 (outline-next-heading)
10409 (setq child-level (funcall outline-level))))))
10410 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10411 ;; any previous siblings are undone, it's blocked
10412 (save-excursion
10413 (org-back-to-heading t)
10414 (let* ((pos (point))
10415 (parent-pos (and (org-up-heading-safe) (point))))
10416 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10417 (when (and (org-entry-get (point) "ORDERED")
10418 (forward-line 1)
10419 (re-search-forward org-not-done-heading-regexp pos t))
10420 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10421 ;; Search further up the hierarchy, to see if an anchestor is blocked
10422 (while t
10423 (goto-char parent-pos)
10424 (if (not (looking-at org-not-done-heading-regexp))
10425 (throw 'dont-block t)) ; do not block, parent is not a TODO
10426 (setq pos (point))
10427 (setq parent-pos (and (org-up-heading-safe) (point)))
10428 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10429 (when (and (org-entry-get (point) "ORDERED")
10430 (forward-line 1)
10431 (re-search-forward org-not-done-heading-regexp pos t))
10432 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10434 (defcustom org-track-ordered-property-with-tag nil
10435 "Should the ORDERED property also be shown as a tag?
10436 The ORDERED property decides if an entry should require subtasks to be
10437 completed in sequence. Since a property is not very visible, setting
10438 this option means that toggling the ORDERED property with the command
10439 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10440 not relevant for the behavior, but it makes things more visible.
10442 Note that toggling the tag with tags commands will not change the property
10443 and therefore not influence behavior!
10445 This can be t, meaning the tag ORDERED should be used, It can also be a
10446 string to select a different tag for this task."
10447 :group 'org-todo
10448 :type '(choice
10449 (const :tag "No tracking" nil)
10450 (const :tag "Track with ORDERED tag" t)
10451 (string :tag "Use other tag")))
10453 (defun org-toggle-ordered-property ()
10454 "Toggle the ORDERED property of the current entry.
10455 For better visibility, you can track the value of this property with a tag.
10456 See variable `org-track-ordered-property-with-tag'."
10457 (interactive)
10458 (let* ((t1 org-track-ordered-property-with-tag)
10459 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10460 (save-excursion
10461 (org-back-to-heading)
10462 (if (org-entry-get nil "ORDERED")
10463 (progn
10464 (org-delete-property "ORDERED")
10465 (and tag (org-toggle-tag tag 'off))
10466 (message "Subtasks can be completed in arbitrary order"))
10467 (org-entry-put nil "ORDERED" "t")
10468 (and tag (org-toggle-tag tag 'on))
10469 (message "Subtasks must be completed in sequence")))))
10471 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10472 (defun org-block-todo-from-checkboxes (change-plist)
10473 "Block turning an entry into a TODO, using checkboxes.
10474 This checks whether the current task should be blocked from state
10475 changes because there are unchecked boxes in this entry."
10476 (if (not org-enforce-todo-checkbox-dependencies)
10477 t ; if locally turned off don't block
10478 (catch 'dont-block
10479 ;; If this is not a todo state change, or if this entry is already DONE,
10480 ;; do not block
10481 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10482 (member (plist-get change-plist :from)
10483 (cons 'done org-done-keywords))
10484 (member (plist-get change-plist :to)
10485 (cons 'todo org-not-done-keywords))
10486 (not (plist-get change-plist :to)))
10487 (throw 'dont-block t))
10488 ;; If this task has checkboxes that are not checked, it's blocked
10489 (save-excursion
10490 (org-back-to-heading t)
10491 (let ((beg (point)) end)
10492 (outline-next-heading)
10493 (setq end (point))
10494 (goto-char beg)
10495 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10496 end t)
10497 (progn
10498 (if (boundp 'org-blocked-by-checkboxes)
10499 (setq org-blocked-by-checkboxes t))
10500 (throw 'dont-block nil)))))
10501 t))) ; do not block
10503 (defun org-entry-blocked-p ()
10504 "Is the current entry blocked?"
10505 (if (org-entry-get nil "NOBLOCKING")
10506 nil ;; Never block this entry
10507 (not
10508 (run-hook-with-args-until-failure
10509 'org-blocker-hook
10510 (list :type 'todo-state-change
10511 :position (point)
10512 :from 'todo
10513 :to 'done)))))
10515 (defun org-update-statistics-cookies (all)
10516 "Update the statistics cookie, either from TODO or from checkboxes.
10517 This should be called with the cursor in a line with a statistics cookie."
10518 (interactive "P")
10519 (if all
10520 (progn
10521 (org-update-checkbox-count 'all)
10522 (org-map-entries 'org-update-parent-todo-statistics))
10523 (if (not (org-on-heading-p))
10524 (org-update-checkbox-count)
10525 (let ((pos (move-marker (make-marker) (point)))
10526 end l1 l2)
10527 (ignore-errors (org-back-to-heading t))
10528 (if (not (org-on-heading-p))
10529 (org-update-checkbox-count)
10530 (setq l1 (org-outline-level))
10531 (setq end (save-excursion
10532 (outline-next-heading)
10533 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10534 (point)))
10535 (if (and (save-excursion
10536 (re-search-forward
10537 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10538 (not (save-excursion (re-search-forward
10539 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10540 (org-update-checkbox-count)
10541 (if (and l2 (> l2 l1))
10542 (progn
10543 (goto-char end)
10544 (org-update-parent-todo-statistics))
10545 (goto-char pos)
10546 (beginning-of-line 1)
10547 (while (re-search-forward
10548 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10549 (point-at-eol) t)
10550 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10551 (goto-char pos)
10552 (move-marker pos nil)))))
10554 (defvar org-entry-property-inherited-from) ;; defined below
10555 (defun org-update-parent-todo-statistics ()
10556 "Update any statistics cookie in the parent of the current headline.
10557 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10558 the entire subtree and this will travel up the hierarchy and update
10559 statistics everywhere."
10560 (interactive)
10561 (let* ((lim 0) prop
10562 (recursive (or (not org-hierarchical-todo-statistics)
10563 (string-match
10564 "\\<recursive\\>"
10565 (or (setq prop (org-entry-get
10566 nil "COOKIE_DATA" 'inherit)) ""))))
10567 (lim (or (and prop (marker-position
10568 org-entry-property-inherited-from))
10569 lim))
10570 (first t)
10571 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10572 level ltoggle l1 new ndel
10573 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10574 (catch 'exit
10575 (save-excursion
10576 (beginning-of-line 1)
10577 (if (org-at-heading-p)
10578 (setq ltoggle (funcall outline-level))
10579 (error "This should not happen"))
10580 (while (and (setq level (org-up-heading-safe))
10581 (or recursive first)
10582 (>= (point) lim))
10583 (setq first nil cookie-present nil)
10584 (unless (and level
10585 (not (string-match
10586 "\\<checkbox\\>"
10587 (downcase
10588 (or (org-entry-get
10589 nil "COOKIE_DATA")
10590 "")))))
10591 (throw 'exit nil))
10592 (while (re-search-forward box-re (point-at-eol) t)
10593 (setq cnt-all 0 cnt-done 0 cookie-present t)
10594 (setq is-percent (match-end 2))
10595 (save-match-data
10596 (unless (outline-next-heading) (throw 'exit nil))
10597 (while (and (looking-at org-complex-heading-regexp)
10598 (> (setq l1 (length (match-string 1))) level))
10599 (setq kwd (and (or recursive (= l1 ltoggle))
10600 (match-string 2)))
10601 (if (or (eq org-provide-todo-statistics 'all-headlines)
10602 (and (listp org-provide-todo-statistics)
10603 (or (member kwd org-provide-todo-statistics)
10604 (member kwd org-done-keywords))))
10605 (setq cnt-all (1+ cnt-all))
10606 (if (eq org-provide-todo-statistics t)
10607 (and kwd (setq cnt-all (1+ cnt-all)))))
10608 (and (member kwd org-done-keywords)
10609 (setq cnt-done (1+ cnt-done)))
10610 (outline-next-heading)))
10611 (setq new
10612 (if is-percent
10613 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10614 (format "[%d/%d]" cnt-done cnt-all))
10615 ndel (- (match-end 0) (match-beginning 0)))
10616 (goto-char (match-beginning 0))
10617 (insert new)
10618 (delete-region (point) (+ (point) ndel)))
10619 (when cookie-present
10620 (run-hook-with-args 'org-after-todo-statistics-hook
10621 cnt-done (- cnt-all cnt-done))))))
10622 (run-hooks 'org-todo-statistics-hook)))
10624 (defvar org-after-todo-statistics-hook nil
10625 "Hook that is called after a TODO statistics cookie has been updated.
10626 Each function is called with two arguments: the number of not-done entries
10627 and the number of done entries.
10629 For example, the following function, when added to this hook, will switch
10630 an entry to DONE when all children are done, and back to TODO when new
10631 entries are set to a TODO status. Note that this hook is only called
10632 when there is a statistics cookie in the headline!
10634 (defun org-summary-todo (n-done n-not-done)
10635 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10636 (let (org-log-done org-log-states) ; turn off logging
10637 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10640 (defvar org-todo-statistics-hook nil
10641 "Hook that is run whenever Org thinks TODO statistics should be updated.
10642 This hook runs even if there is no statistics cookie present, in which case
10643 `org-after-todo-statistics-hook' would not run.")
10645 (defun org-todo-trigger-tag-changes (state)
10646 "Apply the changes defined in `org-todo-state-tags-triggers'."
10647 (let ((l org-todo-state-tags-triggers)
10648 changes)
10649 (when (or (not state) (equal state ""))
10650 (setq changes (append changes (cdr (assoc "" l)))))
10651 (when (and (stringp state) (> (length state) 0))
10652 (setq changes (append changes (cdr (assoc state l)))))
10653 (when (member state org-not-done-keywords)
10654 (setq changes (append changes (cdr (assoc 'todo l)))))
10655 (when (member state org-done-keywords)
10656 (setq changes (append changes (cdr (assoc 'done l)))))
10657 (dolist (c changes)
10658 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10660 (defun org-local-logging (value)
10661 "Get logging settings from a property VALUE."
10662 (let* (words w a)
10663 ;; directly set the variables, they are already local.
10664 (setq org-log-done nil
10665 org-log-repeat nil
10666 org-todo-log-states nil)
10667 (setq words (org-split-string value))
10668 (while (setq w (pop words))
10669 (cond
10670 ((setq a (assoc w org-startup-options))
10671 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10672 (set (nth 1 a) (nth 2 a))))
10673 ((setq a (org-extract-log-state-settings w))
10674 (and (member (car a) org-todo-keywords-1)
10675 (push a org-todo-log-states)))))))
10677 (defun org-get-todo-sequence-head (kwd)
10678 "Return the head of the TODO sequence to which KWD belongs.
10679 If KWD is not set, check if there is a text property remembering the
10680 right sequence."
10681 (let (p)
10682 (cond
10683 ((not kwd)
10684 (or (get-text-property (point-at-bol) 'org-todo-head)
10685 (progn
10686 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10687 nil (point-at-eol)))
10688 (get-text-property p 'org-todo-head))))
10689 ((not (member kwd org-todo-keywords-1))
10690 (car org-todo-keywords-1))
10691 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10693 (defun org-fast-todo-selection ()
10694 "Fast TODO keyword selection with single keys.
10695 Returns the new TODO keyword, or nil if no state change should occur."
10696 (let* ((fulltable org-todo-key-alist)
10697 (done-keywords org-done-keywords) ;; needed for the faces.
10698 (maxlen (apply 'max (mapcar
10699 (lambda (x)
10700 (if (stringp (car x)) (string-width (car x)) 0))
10701 fulltable)))
10702 (expert nil)
10703 (fwidth (+ maxlen 3 1 3))
10704 (ncol (/ (- (window-width) 4) fwidth))
10705 tg cnt e c tbl
10706 groups ingroup)
10707 (save-excursion
10708 (save-window-excursion
10709 (if expert
10710 (set-buffer (get-buffer-create " *Org todo*"))
10711 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10712 (erase-buffer)
10713 (org-set-local 'org-done-keywords done-keywords)
10714 (setq tbl fulltable cnt 0)
10715 (while (setq e (pop tbl))
10716 (cond
10717 ((equal e '(:startgroup))
10718 (push '() groups) (setq ingroup t)
10719 (when (not (= cnt 0))
10720 (setq cnt 0)
10721 (insert "\n"))
10722 (insert "{ "))
10723 ((equal e '(:endgroup))
10724 (setq ingroup nil cnt 0)
10725 (insert "}\n"))
10726 ((equal e '(:newline))
10727 (when (not (= cnt 0))
10728 (setq cnt 0)
10729 (insert "\n")
10730 (setq e (car tbl))
10731 (while (equal (car tbl) '(:newline))
10732 (insert "\n")
10733 (setq tbl (cdr tbl)))))
10735 (setq tg (car e) c (cdr e))
10736 (if ingroup (push tg (car groups)))
10737 (setq tg (org-add-props tg nil 'face
10738 (org-get-todo-face tg)))
10739 (if (and (= cnt 0) (not ingroup)) (insert " "))
10740 (insert "[" c "] " tg (make-string
10741 (- fwidth 4 (length tg)) ?\ ))
10742 (when (= (setq cnt (1+ cnt)) ncol)
10743 (insert "\n")
10744 (if ingroup (insert " "))
10745 (setq cnt 0)))))
10746 (insert "\n")
10747 (goto-char (point-min))
10748 (if (not expert) (org-fit-window-to-buffer))
10749 (message "[a-z..]:Set [SPC]:clear")
10750 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10751 (cond
10752 ((or (= c ?\C-g)
10753 (and (= c ?q) (not (rassoc c fulltable))))
10754 (setq quit-flag t))
10755 ((= c ?\ ) nil)
10756 ((setq e (rassoc c fulltable) tg (car e))
10758 (t (setq quit-flag t)))))))
10760 (defun org-entry-is-todo-p ()
10761 (member (org-get-todo-state) org-not-done-keywords))
10763 (defun org-entry-is-done-p ()
10764 (member (org-get-todo-state) org-done-keywords))
10766 (defun org-get-todo-state ()
10767 (save-excursion
10768 (org-back-to-heading t)
10769 (and (looking-at org-todo-line-regexp)
10770 (match-end 2)
10771 (match-string 2))))
10773 (defun org-at-date-range-p (&optional inactive-ok)
10774 "Is the cursor inside a date range?"
10775 (interactive)
10776 (save-excursion
10777 (catch 'exit
10778 (let ((pos (point)))
10779 (skip-chars-backward "^[<\r\n")
10780 (skip-chars-backward "<[")
10781 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10782 (>= (match-end 0) pos)
10783 (throw 'exit t))
10784 (skip-chars-backward "^<[\r\n")
10785 (skip-chars-backward "<[")
10786 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10787 (>= (match-end 0) pos)
10788 (throw 'exit t)))
10789 nil)))
10791 (defun org-get-repeat (&optional tagline)
10792 "Check if there is a deadline/schedule with repeater in this entry."
10793 (save-match-data
10794 (save-excursion
10795 (org-back-to-heading t)
10796 (and (re-search-forward (if tagline
10797 (concat tagline "\\s-*" org-repeat-re)
10798 org-repeat-re)
10799 (org-entry-end-position) t)
10800 (match-string-no-properties 1)))))
10802 (defvar org-last-changed-timestamp)
10803 (defvar org-last-inserted-timestamp)
10804 (defvar org-log-post-message)
10805 (defvar org-log-note-purpose)
10806 (defvar org-log-note-how)
10807 (defvar org-log-note-extra)
10808 (defun org-auto-repeat-maybe (done-word)
10809 "Check if the current headline contains a repeated deadline/schedule.
10810 If yes, set TODO state back to what it was and change the base date
10811 of repeating deadline/scheduled time stamps to new date.
10812 This function is run automatically after each state change to a DONE state."
10813 ;; last-state is dynamically scoped into this function
10814 (let* ((repeat (org-get-repeat))
10815 (aa (assoc last-state org-todo-kwd-alist))
10816 (interpret (nth 1 aa))
10817 (head (nth 2 aa))
10818 (whata '(("d" . day) ("m" . month) ("y" . year)))
10819 (msg "Entry repeats: ")
10820 (org-log-done nil)
10821 (org-todo-log-states nil)
10822 (nshiftmax 10) (nshift 0)
10823 re type n what ts time)
10824 (when repeat
10825 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10826 (org-todo (if (eq interpret 'type) last-state head))
10827 (org-entry-put nil "LAST_REPEAT" (format-time-string
10828 (org-time-stamp-format t t)))
10829 (when org-log-repeat
10830 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10831 (memq 'org-add-log-note post-command-hook))
10832 ;; OK, we are already setup for some record
10833 (if (eq org-log-repeat 'note)
10834 ;; make sure we take a note, not only a time stamp
10835 (setq org-log-note-how 'note))
10836 ;; Set up for taking a record
10837 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10838 last-state
10839 'findpos org-log-repeat)))
10840 (org-back-to-heading t)
10841 (org-add-planning-info nil nil 'closed)
10842 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10843 org-deadline-time-regexp "\\)\\|\\("
10844 org-ts-regexp "\\)"))
10845 (while (re-search-forward
10846 re (save-excursion (outline-next-heading) (point)) t)
10847 (setq type (if (match-end 1) org-scheduled-string
10848 (if (match-end 3) org-deadline-string "Plain:"))
10849 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10850 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10851 (setq n (string-to-number (match-string 2 ts))
10852 what (match-string 3 ts))
10853 (if (equal what "w") (setq n (* n 7) what "d"))
10854 ;; Preparation, see if we need to modify the start date for the change
10855 (when (match-end 1)
10856 (setq time (save-match-data (org-time-string-to-time ts)))
10857 (cond
10858 ((equal (match-string 1 ts) ".")
10859 ;; Shift starting date to today
10860 (org-timestamp-change
10861 (- (time-to-days (current-time)) (time-to-days time))
10862 'day))
10863 ((equal (match-string 1 ts) "+")
10864 (while (or (= nshift 0)
10865 (<= (time-to-days time) (time-to-days (current-time))))
10866 (when (= (incf nshift) nshiftmax)
10867 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10868 (error "Abort")))
10869 (org-timestamp-change n (cdr (assoc what whata)))
10870 (org-at-timestamp-p t)
10871 (setq ts (match-string 1))
10872 (setq time (save-match-data (org-time-string-to-time ts))))
10873 (org-timestamp-change (- n) (cdr (assoc what whata)))
10874 ;; rematch, so that we have everything in place for the real shift
10875 (org-at-timestamp-p t)
10876 (setq ts (match-string 1))
10877 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10878 (org-timestamp-change n (cdr (assoc what whata)))
10879 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10880 (setq org-log-post-message msg)
10881 (message "%s" msg))))
10883 (defun org-show-todo-tree (arg)
10884 "Make a compact tree which shows all headlines marked with TODO.
10885 The tree will show the lines where the regexp matches, and all higher
10886 headlines above the match.
10887 With a \\[universal-argument] prefix, prompt for a regexp to match.
10888 With a numeric prefix N, construct a sparse tree for the Nth element
10889 of `org-todo-keywords-1'."
10890 (interactive "P")
10891 (let ((case-fold-search nil)
10892 (kwd-re
10893 (cond ((null arg) org-not-done-regexp)
10894 ((equal arg '(4))
10895 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10896 (mapcar 'list org-todo-keywords-1))))
10897 (concat "\\("
10898 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10899 "\\)\\>")))
10900 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10901 (regexp-quote (nth (1- (prefix-numeric-value arg))
10902 org-todo-keywords-1)))
10903 (t (error "Invalid prefix argument: %s" arg)))))
10904 (message "%d TODO entries found"
10905 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10907 (defun org-deadline (&optional remove time)
10908 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10909 With argument REMOVE, remove any deadline from the item.
10910 When TIME is set, it should be an internal time specification, and the
10911 scheduling will use the corresponding date."
10912 (interactive "P")
10913 (let* ((old-date (org-entry-get nil "DEADLINE"))
10914 (repeater (and old-date
10915 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10916 (match-string 1 old-date))))
10917 (if remove
10918 (progn
10919 (when (and old-date org-log-redeadline)
10920 (org-add-log-setup 'deldeadline nil old-date 'findpos
10921 org-log-redeadline))
10922 (org-remove-timestamp-with-keyword org-deadline-string)
10923 (message "Item no longer has a deadline."))
10924 (org-add-planning-info 'deadline time 'closed)
10925 (when (and old-date org-log-redeadline
10926 (not (equal old-date
10927 (substring org-last-inserted-timestamp 1 -1))))
10928 (org-add-log-setup 'redeadline nil old-date 'findpos
10929 org-log-redeadline))
10930 (when repeater
10931 (save-excursion
10932 (org-back-to-heading t)
10933 (when (re-search-forward (concat org-deadline-string " "
10934 org-last-inserted-timestamp)
10935 (save-excursion
10936 (outline-next-heading) (point)) t)
10937 (goto-char (1- (match-end 0)))
10938 (insert " " repeater)
10939 (setq org-last-inserted-timestamp
10940 (concat (substring org-last-inserted-timestamp 0 -1)
10941 " " repeater
10942 (substring org-last-inserted-timestamp -1))))))
10943 (message "Deadline on %s" org-last-inserted-timestamp))))
10945 (defun org-schedule (&optional remove time)
10946 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10947 With argument REMOVE, remove any scheduling date from the item.
10948 When TIME is set, it should be an internal time specification, and the
10949 scheduling will use the corresponding date."
10950 (interactive "P")
10951 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10952 (repeater (and old-date
10953 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10954 (match-string 1 old-date))))
10955 (if remove
10956 (progn
10957 (when (and old-date org-log-reschedule)
10958 (org-add-log-setup 'delschedule nil old-date 'findpos
10959 org-log-reschedule))
10960 (org-remove-timestamp-with-keyword org-scheduled-string)
10961 (message "Item is no longer scheduled."))
10962 (org-add-planning-info 'scheduled time 'closed)
10963 (when (and old-date org-log-reschedule
10964 (not (equal old-date
10965 (substring org-last-inserted-timestamp 1 -1))))
10966 (org-add-log-setup 'reschedule nil old-date 'findpos
10967 org-log-reschedule))
10968 (when repeater
10969 (save-excursion
10970 (org-back-to-heading t)
10971 (when (re-search-forward (concat org-scheduled-string " "
10972 org-last-inserted-timestamp)
10973 (save-excursion
10974 (outline-next-heading) (point)) t)
10975 (goto-char (1- (match-end 0)))
10976 (insert " " repeater)
10977 (setq org-last-inserted-timestamp
10978 (concat (substring org-last-inserted-timestamp 0 -1)
10979 " " repeater
10980 (substring org-last-inserted-timestamp -1))))))
10981 (message "Scheduled to %s" org-last-inserted-timestamp))))
10983 (defun org-get-scheduled-time (pom &optional inherit)
10984 "Get the scheduled time as a time tuple, of a format suitable
10985 for calling org-schedule with, or if there is no scheduling,
10986 returns nil."
10987 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10988 (when time
10989 (apply 'encode-time (org-parse-time-string time)))))
10991 (defun org-get-deadline-time (pom &optional inherit)
10992 "Get the deadine as a time tuple, of a format suitable for
10993 calling org-deadline with, or if there is no scheduling, returns
10994 nil."
10995 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10996 (when time
10997 (apply 'encode-time (org-parse-time-string time)))))
10999 (defun org-remove-timestamp-with-keyword (keyword)
11000 "Remove all time stamps with KEYWORD in the current entry."
11001 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11002 beg)
11003 (save-excursion
11004 (org-back-to-heading t)
11005 (setq beg (point))
11006 (outline-next-heading)
11007 (while (re-search-backward re beg t)
11008 (replace-match "")
11009 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11010 (equal (char-before) ?\ ))
11011 (backward-delete-char 1)
11012 (if (string-match "^[ \t]*$" (buffer-substring
11013 (point-at-bol) (point-at-eol)))
11014 (delete-region (point-at-bol)
11015 (min (point-max) (1+ (point-at-eol))))))))))
11017 (defun org-add-planning-info (what &optional time &rest remove)
11018 "Insert new timestamp with keyword in the line directly after the headline.
11019 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11020 If non is given, the user is prompted for a date.
11021 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11022 be removed."
11023 (interactive)
11024 (let (org-time-was-given org-end-time-was-given ts
11025 end default-time default-input)
11027 (catch 'exit
11028 (when (and (not time) (memq what '(scheduled deadline)))
11029 ;; Try to get a default date/time from existing timestamp
11030 (save-excursion
11031 (org-back-to-heading t)
11032 (setq end (save-excursion (outline-next-heading) (point)))
11033 (when (re-search-forward (if (eq what 'scheduled)
11034 org-scheduled-time-regexp
11035 org-deadline-time-regexp)
11036 end t)
11037 (setq ts (match-string 1)
11038 default-time
11039 (apply 'encode-time (org-parse-time-string ts))
11040 default-input (and ts (org-get-compact-tod ts))))))
11041 (when what
11042 ;; If necessary, get the time from the user
11043 (setq time (or time (org-read-date nil 'to-time nil nil
11044 default-time default-input))))
11046 (when (and org-insert-labeled-timestamps-at-point
11047 (member what '(scheduled deadline)))
11048 (insert
11049 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11050 (org-insert-time-stamp time org-time-was-given
11051 nil nil nil (list org-end-time-was-given))
11052 (setq what nil))
11053 (save-excursion
11054 (save-restriction
11055 (let (col list elt ts buffer-invisibility-spec)
11056 (org-back-to-heading t)
11057 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11058 (goto-char (match-end 1))
11059 (setq col (current-column))
11060 (goto-char (match-end 0))
11061 (if (eobp) (insert "\n") (forward-char 1))
11062 (when (and (not what)
11063 (not (looking-at
11064 (concat "[ \t]*"
11065 org-keyword-time-not-clock-regexp))))
11066 ;; Nothing to add, nothing to remove...... :-)
11067 (throw 'exit nil))
11068 (if (and (not (looking-at outline-regexp))
11069 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11070 "[^\r\n]*"))
11071 (not (equal (match-string 1) org-clock-string)))
11072 (narrow-to-region (match-beginning 0) (match-end 0))
11073 (insert-before-markers "\n")
11074 (backward-char 1)
11075 (narrow-to-region (point) (point))
11076 (and org-adapt-indentation (org-indent-to-column col)))
11077 ;; Check if we have to remove something.
11078 (setq list (cons what remove))
11079 (while list
11080 (setq elt (pop list))
11081 (goto-char (point-min))
11082 (when (or (and (eq elt 'scheduled)
11083 (re-search-forward org-scheduled-time-regexp nil t))
11084 (and (eq elt 'deadline)
11085 (re-search-forward org-deadline-time-regexp nil t))
11086 (and (eq elt 'closed)
11087 (re-search-forward org-closed-time-regexp nil t)))
11088 (replace-match "")
11089 (if (looking-at "--+<[^>]+>") (replace-match ""))
11090 (skip-chars-backward " ")
11091 (if (looking-at " +") (replace-match ""))))
11092 (goto-char (point-max))
11093 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11094 (when what
11095 (insert
11096 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11097 (cond ((eq what 'scheduled) org-scheduled-string)
11098 ((eq what 'deadline) org-deadline-string)
11099 ((eq what 'closed) org-closed-string))
11100 " ")
11101 (setq ts (org-insert-time-stamp
11102 time
11103 (or org-time-was-given
11104 (and (eq what 'closed) org-log-done-with-time))
11105 (eq what 'closed)
11106 nil nil (list org-end-time-was-given)))
11107 (end-of-line 1))
11108 (goto-char (point-min))
11109 (widen)
11110 (if (and (looking-at "[ \t]+\n")
11111 (equal (char-before) ?\n))
11112 (delete-region (1- (point)) (point-at-eol)))
11113 ts))))))
11115 (defvar org-log-note-marker (make-marker))
11116 (defvar org-log-note-purpose nil)
11117 (defvar org-log-note-state nil)
11118 (defvar org-log-note-previous-state nil)
11119 (defvar org-log-note-how nil)
11120 (defvar org-log-note-extra nil)
11121 (defvar org-log-note-window-configuration nil)
11122 (defvar org-log-note-return-to (make-marker))
11123 (defvar org-log-post-message nil
11124 "Message to be displayed after a log note has been stored.
11125 The auto-repeater uses this.")
11127 (defun org-add-note ()
11128 "Add a note to the current entry.
11129 This is done in the same way as adding a state change note."
11130 (interactive)
11131 (org-add-log-setup 'note nil nil 'findpos nil))
11133 (defvar org-property-end-re)
11134 (defun org-add-log-setup (&optional purpose state prev-state
11135 findpos how &optional extra)
11136 "Set up the post command hook to take a note.
11137 If this is about to TODO state change, the new state is expected in STATE.
11138 When FINDPOS is non-nil, find the correct position for the note in
11139 the current entry. If not, assume that it can be inserted at point.
11140 HOW is an indicator what kind of note should be created.
11141 EXTRA is additional text that will be inserted into the notes buffer."
11142 (let* ((org-log-into-drawer (org-log-into-drawer))
11143 (drawer (cond ((stringp org-log-into-drawer)
11144 org-log-into-drawer)
11145 (org-log-into-drawer "LOGBOOK")
11146 (t nil))))
11147 (save-restriction
11148 (save-excursion
11149 (when findpos
11150 (org-back-to-heading t)
11151 (narrow-to-region (point) (save-excursion
11152 (outline-next-heading) (point)))
11153 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11154 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11155 "[^\r\n]*\\)?"))
11156 (goto-char (match-end 0))
11157 (cond
11158 (drawer
11159 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11160 nil t)
11161 (progn
11162 (goto-char (match-end 0))
11163 (or org-log-states-order-reversed
11164 (and (re-search-forward org-property-end-re nil t)
11165 (goto-char (1- (match-beginning 0))))))
11166 (insert "\n:" drawer ":\n:END:")
11167 (beginning-of-line 0)
11168 (org-indent-line-function)
11169 (beginning-of-line 2)
11170 (org-indent-line-function)
11171 (end-of-line 0)))
11172 ((and org-log-state-notes-insert-after-drawers
11173 (save-excursion
11174 (forward-line) (looking-at org-drawer-regexp)))
11175 (forward-line)
11176 (while (looking-at org-drawer-regexp)
11177 (goto-char (match-end 0))
11178 (re-search-forward org-property-end-re (point-max) t)
11179 (forward-line))
11180 (forward-line -1)))
11181 (unless org-log-states-order-reversed
11182 (and (= (char-after) ?\n) (forward-char 1))
11183 (org-skip-over-state-notes)
11184 (skip-chars-backward " \t\n\r")))
11185 (move-marker org-log-note-marker (point))
11186 (setq org-log-note-purpose purpose
11187 org-log-note-state state
11188 org-log-note-previous-state prev-state
11189 org-log-note-how how
11190 org-log-note-extra extra)
11191 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11193 (defun org-skip-over-state-notes ()
11194 "Skip past the list of State notes in an entry."
11195 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11196 (while (looking-at "[ \t]*- State")
11197 (condition-case nil
11198 (org-next-item)
11199 (error (org-end-of-item)))))
11201 (defun org-add-log-note (&optional purpose)
11202 "Pop up a window for taking a note, and add this note later at point."
11203 (remove-hook 'post-command-hook 'org-add-log-note)
11204 (setq org-log-note-window-configuration (current-window-configuration))
11205 (delete-other-windows)
11206 (move-marker org-log-note-return-to (point))
11207 (switch-to-buffer (marker-buffer org-log-note-marker))
11208 (goto-char org-log-note-marker)
11209 (org-switch-to-buffer-other-window "*Org Note*")
11210 (erase-buffer)
11211 (if (memq org-log-note-how '(time state))
11212 (let (current-prefix-arg) (org-store-log-note))
11213 (let ((org-inhibit-startup t)) (org-mode))
11214 (insert (format "# Insert note for %s.
11215 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11216 (cond
11217 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11218 ((eq org-log-note-purpose 'done) "closed todo item")
11219 ((eq org-log-note-purpose 'state)
11220 (format "state change from \"%s\" to \"%s\""
11221 (or org-log-note-previous-state "")
11222 (or org-log-note-state "")))
11223 ((eq org-log-note-purpose 'reschedule)
11224 "rescheduling")
11225 ((eq org-log-note-purpose 'delschedule)
11226 "no longer scheduled")
11227 ((eq org-log-note-purpose 'redeadline)
11228 "changing deadline")
11229 ((eq org-log-note-purpose 'deldeadline)
11230 "removing deadline")
11231 ((eq org-log-note-purpose 'refile)
11232 "refiling")
11233 ((eq org-log-note-purpose 'note)
11234 "this entry")
11235 (t (error "This should not happen")))))
11236 (if org-log-note-extra (insert org-log-note-extra))
11237 (org-set-local 'org-finish-function 'org-store-log-note)))
11239 (defvar org-note-abort nil) ; dynamically scoped
11240 (defun org-store-log-note ()
11241 "Finish taking a log note, and insert it to where it belongs."
11242 (let ((txt (buffer-string))
11243 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11244 lines ind)
11245 (kill-buffer (current-buffer))
11246 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11247 (setq txt (replace-match "" t t txt)))
11248 (if (string-match "\\s-+\\'" txt)
11249 (setq txt (replace-match "" t t txt)))
11250 (setq lines (org-split-string txt "\n"))
11251 (when (and note (string-match "\\S-" note))
11252 (setq note
11253 (org-replace-escapes
11254 note
11255 (list (cons "%u" (user-login-name))
11256 (cons "%U" user-full-name)
11257 (cons "%t" (format-time-string
11258 (org-time-stamp-format 'long 'inactive)
11259 (current-time)))
11260 (cons "%s" (if org-log-note-state
11261 (concat "\"" org-log-note-state "\"")
11262 ""))
11263 (cons "%S" (if org-log-note-previous-state
11264 (concat "\"" org-log-note-previous-state "\"")
11265 "\"\"")))))
11266 (if lines (setq note (concat note " \\\\")))
11267 (push note lines))
11268 (when (or current-prefix-arg org-note-abort)
11269 (when org-log-into-drawer
11270 (org-remove-empty-drawer-at
11271 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11272 org-log-note-marker))
11273 (setq lines nil))
11274 (when lines
11275 (with-current-buffer (marker-buffer org-log-note-marker)
11276 (save-excursion
11277 (goto-char org-log-note-marker)
11278 (move-marker org-log-note-marker nil)
11279 (end-of-line 1)
11280 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11281 (insert "- " (pop lines))
11282 (org-indent-line-function)
11283 (beginning-of-line 1)
11284 (looking-at "[ \t]*")
11285 (setq ind (concat (match-string 0) " "))
11286 (end-of-line 1)
11287 (while lines (insert "\n" ind (pop lines)))
11288 (message "Note stored")
11289 (org-back-to-heading t)
11290 (org-cycle-hide-drawers 'children)))))
11291 (set-window-configuration org-log-note-window-configuration)
11292 (with-current-buffer (marker-buffer org-log-note-return-to)
11293 (goto-char org-log-note-return-to))
11294 (move-marker org-log-note-return-to nil)
11295 (and org-log-post-message (message "%s" org-log-post-message)))
11297 (defun org-remove-empty-drawer-at (drawer pos)
11298 "Remove an empty drawer DRAWER at position POS.
11299 POS may also be a marker."
11300 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11301 (save-excursion
11302 (save-restriction
11303 (widen)
11304 (goto-char pos)
11305 (if (org-in-regexp
11306 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11307 (replace-match ""))))))
11309 (defun org-sparse-tree (&optional arg)
11310 "Create a sparse tree, prompt for the details.
11311 This command can create sparse trees. You first need to select the type
11312 of match used to create the tree:
11314 t Show entries with a specific TODO keyword.
11315 m Show entries selected by a tags/property match.
11316 p Enter a property name and its value (both with completion on existing
11317 names/values) and show entries with that property.
11318 / Show entries matching a regular expression (`r' can be used as well)
11319 d Show deadlines due within `org-deadline-warning-days'.
11320 b Show deadlines and scheduled items before a date.
11321 a Show deadlines and scheduled items after a date."
11322 (interactive "P")
11323 (let (ans kwd value)
11324 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11325 (setq ans (read-char-exclusive))
11326 (cond
11327 ((equal ans ?d)
11328 (call-interactively 'org-check-deadlines))
11329 ((equal ans ?b)
11330 (call-interactively 'org-check-before-date))
11331 ((equal ans ?a)
11332 (call-interactively 'org-check-after-date))
11333 ((equal ans ?t)
11334 (org-show-todo-tree '(4)))
11335 ((member ans '(?T ?m))
11336 (call-interactively 'org-match-sparse-tree))
11337 ((member ans '(?p ?P))
11338 (setq kwd (org-icompleting-read "Property: "
11339 (mapcar 'list (org-buffer-property-keys))))
11340 (setq value (org-icompleting-read "Value: "
11341 (mapcar 'list (org-property-values kwd))))
11342 (unless (string-match "\\`{.*}\\'" value)
11343 (setq value (concat "\"" value "\"")))
11344 (org-match-sparse-tree arg (concat kwd "=" value)))
11345 ((member ans '(?r ?R ?/))
11346 (call-interactively 'org-occur))
11347 (t (error "No such sparse tree command \"%c\"" ans)))))
11349 (defvar org-occur-highlights nil
11350 "List of overlays used for occur matches.")
11351 (make-variable-buffer-local 'org-occur-highlights)
11352 (defvar org-occur-parameters nil
11353 "Parameters of the active org-occur calls.
11354 This is a list, each call to org-occur pushes as cons cell,
11355 containing the regular expression and the callback, onto the list.
11356 The list can contain several entries if `org-occur' has been called
11357 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11358 will only contain one set of parameters. When the highlights are
11359 removed (for example with `C-c C-c', or with the next edit (depending
11360 on `org-remove-highlights-with-change'), this variable is emptied
11361 as well.")
11362 (make-variable-buffer-local 'org-occur-parameters)
11364 (defun org-occur (regexp &optional keep-previous callback)
11365 "Make a compact tree which shows all matches of REGEXP.
11366 The tree will show the lines where the regexp matches, and all higher
11367 headlines above the match. It will also show the heading after the match,
11368 to make sure editing the matching entry is easy.
11369 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11370 call to `org-occur' will be kept, to allow stacking of calls to this
11371 command.
11372 If CALLBACK is non-nil, it is a function which is called to confirm
11373 that the match should indeed be shown."
11374 (interactive "sRegexp: \nP")
11375 (when (equal regexp "")
11376 (error "Regexp cannot be empty"))
11377 (unless keep-previous
11378 (org-remove-occur-highlights nil nil t))
11379 (push (cons regexp callback) org-occur-parameters)
11380 (let ((cnt 0))
11381 (save-excursion
11382 (goto-char (point-min))
11383 (if (or (not keep-previous) ; do not want to keep
11384 (not org-occur-highlights)) ; no previous matches
11385 ;; hide everything
11386 (org-overview))
11387 (while (re-search-forward regexp nil t)
11388 (when (or (not callback)
11389 (save-match-data (funcall callback)))
11390 (setq cnt (1+ cnt))
11391 (when org-highlight-sparse-tree-matches
11392 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11393 (org-show-context 'occur-tree))))
11394 (when org-remove-highlights-with-change
11395 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11396 nil 'local))
11397 (unless org-sparse-tree-open-archived-trees
11398 (org-hide-archived-subtrees (point-min) (point-max)))
11399 (run-hooks 'org-occur-hook)
11400 (if (interactive-p)
11401 (message "%d match(es) for regexp %s" cnt regexp))
11402 cnt))
11404 (defun org-show-context (&optional key)
11405 "Make sure point and context and visible.
11406 How much context is shown depends upon the variables
11407 `org-show-hierarchy-above', `org-show-following-heading'. and
11408 `org-show-siblings'."
11409 (let ((heading-p (org-on-heading-p t))
11410 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11411 (following-p (org-get-alist-option org-show-following-heading key))
11412 (entry-p (org-get-alist-option org-show-entry-below key))
11413 (siblings-p (org-get-alist-option org-show-siblings key)))
11414 (catch 'exit
11415 ;; Show heading or entry text
11416 (if (and heading-p (not entry-p))
11417 (org-flag-heading nil) ; only show the heading
11418 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11419 (org-show-hidden-entry))) ; show entire entry
11420 (when following-p
11421 ;; Show next sibling, or heading below text
11422 (save-excursion
11423 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11424 (org-flag-heading nil))))
11425 (when siblings-p (org-show-siblings))
11426 (when hierarchy-p
11427 ;; show all higher headings, possibly with siblings
11428 (save-excursion
11429 (while (and (condition-case nil
11430 (progn (org-up-heading-all 1) t)
11431 (error nil))
11432 (not (bobp)))
11433 (org-flag-heading nil)
11434 (when siblings-p (org-show-siblings))))))))
11436 (defvar org-reveal-start-hook nil
11437 "Hook run before revealing a location.")
11439 (defun org-reveal (&optional siblings)
11440 "Show current entry, hierarchy above it, and the following headline.
11441 This can be used to show a consistent set of context around locations
11442 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11443 not t for the search context.
11445 With optional argument SIBLINGS, on each level of the hierarchy all
11446 siblings are shown. This repairs the tree structure to what it would
11447 look like when opened with hierarchical calls to `org-cycle'.
11448 With double optional argument `C-u C-u', go to the parent and show the
11449 entire tree."
11450 (interactive "P")
11451 (run-hooks 'org-reveal-start-hook)
11452 (let ((org-show-hierarchy-above t)
11453 (org-show-following-heading t)
11454 (org-show-siblings (if siblings t org-show-siblings)))
11455 (org-show-context nil))
11456 (when (equal siblings '(16))
11457 (save-excursion
11458 (when (org-up-heading-safe)
11459 (org-show-subtree)
11460 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11462 (defun org-highlight-new-match (beg end)
11463 "Highlight from BEG to END and mark the highlight is an occur headline."
11464 (let ((ov (org-make-overlay beg end)))
11465 (org-overlay-put ov 'face 'secondary-selection)
11466 (push ov org-occur-highlights)))
11468 (defun org-remove-occur-highlights (&optional beg end noremove)
11469 "Remove the occur highlights from the buffer.
11470 BEG and END are ignored. If NOREMOVE is nil, remove this function
11471 from the `before-change-functions' in the current buffer."
11472 (interactive)
11473 (unless org-inhibit-highlight-removal
11474 (mapc 'org-delete-overlay org-occur-highlights)
11475 (setq org-occur-highlights nil)
11476 (setq org-occur-parameters nil)
11477 (unless noremove
11478 (remove-hook 'before-change-functions
11479 'org-remove-occur-highlights 'local))))
11481 ;;;; Priorities
11483 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11484 "Regular expression matching the priority indicator.")
11486 (defvar org-remove-priority-next-time nil)
11488 (defun org-priority-up ()
11489 "Increase the priority of the current item."
11490 (interactive)
11491 (org-priority 'up))
11493 (defun org-priority-down ()
11494 "Decrease the priority of the current item."
11495 (interactive)
11496 (org-priority 'down))
11498 (defun org-priority (&optional action)
11499 "Change the priority of an item by ARG.
11500 ACTION can be `set', `up', `down', or a character."
11501 (interactive)
11502 (unless org-enable-priority-commands
11503 (error "Priority commands are disabled"))
11504 (setq action (or action 'set))
11505 (let (current new news have remove)
11506 (save-excursion
11507 (org-back-to-heading t)
11508 (if (looking-at org-priority-regexp)
11509 (setq current (string-to-char (match-string 2))
11510 have t)
11511 (setq current org-default-priority))
11512 (cond
11513 ((eq action 'remove)
11514 (setq remove t new ?\ ))
11515 ((or (eq action 'set)
11516 (if (featurep 'xemacs) (characterp action) (integerp action)))
11517 (if (not (eq action 'set))
11518 (setq new action)
11519 (message "Priority %c-%c, SPC to remove: "
11520 org-highest-priority org-lowest-priority)
11521 (setq new (read-char-exclusive)))
11522 (if (and (= (upcase org-highest-priority) org-highest-priority)
11523 (= (upcase org-lowest-priority) org-lowest-priority))
11524 (setq new (upcase new)))
11525 (cond ((equal new ?\ ) (setq remove t))
11526 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11527 (error "Priority must be between `%c' and `%c'"
11528 org-highest-priority org-lowest-priority))))
11529 ((eq action 'up)
11530 (if (and (not have) (eq last-command this-command))
11531 (setq new org-lowest-priority)
11532 (setq new (if (and org-priority-start-cycle-with-default (not have))
11533 org-default-priority (1- current)))))
11534 ((eq action 'down)
11535 (if (and (not have) (eq last-command this-command))
11536 (setq new org-highest-priority)
11537 (setq new (if (and org-priority-start-cycle-with-default (not have))
11538 org-default-priority (1+ current)))))
11539 (t (error "Invalid action")))
11540 (if (or (< (upcase new) org-highest-priority)
11541 (> (upcase new) org-lowest-priority))
11542 (setq remove t))
11543 (setq news (format "%c" new))
11544 (if have
11545 (if remove
11546 (replace-match "" t t nil 1)
11547 (replace-match news t t nil 2))
11548 (if remove
11549 (error "No priority cookie found in line")
11550 (let ((case-fold-search nil))
11551 (looking-at org-todo-line-regexp))
11552 (if (match-end 2)
11553 (progn
11554 (goto-char (match-end 2))
11555 (insert " [#" news "]"))
11556 (goto-char (match-beginning 3))
11557 (insert "[#" news "] "))))
11558 (org-preserve-lc (org-set-tags nil 'align)))
11559 (if remove
11560 (message "Priority removed")
11561 (message "Priority of current item set to %s" news))))
11563 (defun org-get-priority (s)
11564 "Find priority cookie and return priority."
11565 (save-match-data
11566 (if (not (string-match org-priority-regexp s))
11567 (* 1000 (- org-lowest-priority org-default-priority))
11568 (* 1000 (- org-lowest-priority
11569 (string-to-char (match-string 2 s)))))))
11571 ;;;; Tags
11573 (defvar org-agenda-archives-mode)
11574 (defvar org-map-continue-from nil
11575 "Position from where mapping should continue.
11576 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11578 (defvar org-scanner-tags nil
11579 "The current tag list while the tags scanner is running.")
11580 (defvar org-trust-scanner-tags nil
11581 "Should `org-get-tags-at' use the tags fro the scanner.
11582 This is for internal dynamical scoping only.
11583 When this is non-nil, the function `org-get-tags-at' will return the value
11584 of `org-scanner-tags' instead of building the list by itself. This
11585 can lead to large speed-ups when the tags scanner is used in a file with
11586 many entries, and when the list of tags is retrieved, for example to
11587 obtain a list of properties. Building the tags list for each entry in such
11588 a file becomes an N^2 operation - but with this variable set, it scales
11589 as N.")
11591 (defun org-scan-tags (action matcher &optional todo-only)
11592 "Scan headline tags with inheritance and produce output ACTION.
11594 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11595 or `agenda' to produce an entry list for an agenda view. It can also be
11596 a Lisp form or a function that should be called at each matched headline, in
11597 this case the return value is a list of all return values from these calls.
11599 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11600 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11601 only lines with a TODO keyword are included in the output."
11602 (require 'org-agenda)
11603 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11604 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11605 (org-re
11606 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11607 (props (list 'face 'default
11608 'done-face 'org-agenda-done
11609 'undone-face 'default
11610 'mouse-face 'highlight
11611 'org-not-done-regexp org-not-done-regexp
11612 'org-todo-regexp org-todo-regexp
11613 'help-echo
11614 (format "mouse-2 or RET jump to org file %s"
11615 (abbreviate-file-name
11616 (or (buffer-file-name (buffer-base-buffer))
11617 (buffer-name (buffer-base-buffer)))))))
11618 (case-fold-search nil)
11619 (org-map-continue-from nil)
11620 lspos tags tags-list
11621 (tags-alist (list (cons 0 org-file-tags)))
11622 (llast 0) rtn rtn1 level category i txt
11623 todo marker entry priority)
11624 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11625 (setq action (list 'lambda nil action)))
11626 (save-excursion
11627 (goto-char (point-min))
11628 (when (eq action 'sparse-tree)
11629 (org-overview)
11630 (org-remove-occur-highlights))
11631 (while (re-search-forward re nil t)
11632 (catch :skip
11633 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11634 tags (if (match-end 4) (org-match-string-no-properties 4)))
11635 (goto-char (setq lspos (match-beginning 0)))
11636 (setq level (org-reduced-level (funcall outline-level))
11637 category (org-get-category))
11638 (setq i llast llast level)
11639 ;; remove tag lists from same and sublevels
11640 (while (>= i level)
11641 (when (setq entry (assoc i tags-alist))
11642 (setq tags-alist (delete entry tags-alist)))
11643 (setq i (1- i)))
11644 ;; add the next tags
11645 (when tags
11646 (setq tags (org-split-string tags ":")
11647 tags-alist
11648 (cons (cons level tags) tags-alist)))
11649 ;; compile tags for current headline
11650 (setq tags-list
11651 (if org-use-tag-inheritance
11652 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11653 tags)
11654 org-scanner-tags tags-list)
11655 (when org-use-tag-inheritance
11656 (setcdr (car tags-alist)
11657 (mapcar (lambda (x)
11658 (setq x (copy-sequence x))
11659 (org-add-prop-inherited x))
11660 (cdar tags-alist))))
11661 (when (and tags org-use-tag-inheritance
11662 (or (not (eq t org-use-tag-inheritance))
11663 org-tags-exclude-from-inheritance))
11664 ;; selective inheritance, remove uninherited ones
11665 (setcdr (car tags-alist)
11666 (org-remove-uniherited-tags (cdar tags-alist))))
11667 (when (and (or (not todo-only)
11668 (and (member todo org-not-done-keywords)
11669 (or (not org-agenda-tags-todo-honor-ignore-options)
11670 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11671 (let ((case-fold-search t)) (eval matcher))
11673 (not (member org-archive-tag tags-list))
11674 ;; we have an archive tag, should we use this anyway?
11675 (or (not org-agenda-skip-archived-trees)
11676 (and (eq action 'agenda) org-agenda-archives-mode))))
11677 (unless (eq action 'sparse-tree) (org-agenda-skip))
11679 ;; select this headline
11681 (cond
11682 ((eq action 'sparse-tree)
11683 (and org-highlight-sparse-tree-matches
11684 (org-get-heading) (match-end 0)
11685 (org-highlight-new-match
11686 (match-beginning 0) (match-beginning 1)))
11687 (org-show-context 'tags-tree))
11688 ((eq action 'agenda)
11689 (setq txt (org-format-agenda-item
11691 (concat
11692 (if (eq org-tags-match-list-sublevels 'indented)
11693 (make-string (1- level) ?.) "")
11694 (org-get-heading))
11695 category
11696 tags-list
11698 priority (org-get-priority txt))
11699 (goto-char lspos)
11700 (setq marker (org-agenda-new-marker))
11701 (org-add-props txt props
11702 'org-marker marker 'org-hd-marker marker 'org-category category
11703 'todo-state todo
11704 'priority priority 'type "tagsmatch")
11705 (push txt rtn))
11706 ((functionp action)
11707 (setq org-map-continue-from nil)
11708 (save-excursion
11709 (setq rtn1 (funcall action))
11710 (push rtn1 rtn)))
11711 (t (error "Invalid action")))
11713 ;; if we are to skip sublevels, jump to end of subtree
11714 (unless org-tags-match-list-sublevels
11715 (org-end-of-subtree t)
11716 (backward-char 1))))
11717 ;; Get the correct position from where to continue
11718 (if org-map-continue-from
11719 (goto-char org-map-continue-from)
11720 (and (= (point) lspos) (end-of-line 1)))))
11721 (when (and (eq action 'sparse-tree)
11722 (not org-sparse-tree-open-archived-trees))
11723 (org-hide-archived-subtrees (point-min) (point-max)))
11724 (nreverse rtn)))
11726 (defun org-remove-uniherited-tags (tags)
11727 "Remove all tags that are not inherited from the list TAGS."
11728 (cond
11729 ((eq org-use-tag-inheritance t)
11730 (if org-tags-exclude-from-inheritance
11731 (org-delete-all org-tags-exclude-from-inheritance tags)
11732 tags))
11733 ((not org-use-tag-inheritance) nil)
11734 ((stringp org-use-tag-inheritance)
11735 (delq nil (mapcar
11736 (lambda (x)
11737 (if (and (string-match org-use-tag-inheritance x)
11738 (not (member x org-tags-exclude-from-inheritance)))
11739 x nil))
11740 tags)))
11741 ((listp org-use-tag-inheritance)
11742 (delq nil (mapcar
11743 (lambda (x)
11744 (if (member x org-use-tag-inheritance) x nil))
11745 tags)))))
11747 (defvar todo-only) ;; dynamically scoped
11749 (defun org-match-sparse-tree (&optional todo-only match)
11750 "Create a sparse tree according to tags string MATCH.
11751 MATCH can contain positive and negative selection of tags, like
11752 \"+WORK+URGENT-WITHBOSS\".
11753 If optional argument TODO-ONLY is non-nil, only select lines that are
11754 also TODO lines."
11755 (interactive "P")
11756 (org-prepare-agenda-buffers (list (current-buffer)))
11757 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11759 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11761 (defvar org-cached-props nil)
11762 (defun org-cached-entry-get (pom property)
11763 (if (or (eq t org-use-property-inheritance)
11764 (and (stringp org-use-property-inheritance)
11765 (string-match org-use-property-inheritance property))
11766 (and (listp org-use-property-inheritance)
11767 (member property org-use-property-inheritance)))
11768 ;; Caching is not possible, check it directly
11769 (org-entry-get pom property 'inherit)
11770 ;; Get all properties, so that we can do complicated checks easily
11771 (cdr (assoc property (or org-cached-props
11772 (setq org-cached-props
11773 (org-entry-properties pom)))))))
11775 (defun org-global-tags-completion-table (&optional files)
11776 "Return the list of all tags in all agenda buffer/files."
11777 (save-excursion
11778 (org-uniquify
11779 (delq nil
11780 (apply 'append
11781 (mapcar
11782 (lambda (file)
11783 (set-buffer (find-file-noselect file))
11784 (append (org-get-buffer-tags)
11785 (mapcar (lambda (x) (if (stringp (car-safe x))
11786 (list (car-safe x)) nil))
11787 org-tag-alist)))
11788 (if (and files (car files))
11789 files
11790 (org-agenda-files))))))))
11792 (defun org-make-tags-matcher (match)
11793 "Create the TAGS//TODO matcher form for the selection string MATCH."
11794 ;; todo-only is scoped dynamically into this function, and the function
11795 ;; may change it if the matcher asks for it.
11796 (unless match
11797 ;; Get a new match request, with completion
11798 (let ((org-last-tags-completion-table
11799 (org-global-tags-completion-table)))
11800 (setq match (org-completing-read-no-i
11801 "Match: " 'org-tags-completion-function nil nil nil
11802 'org-tags-history))))
11804 ;; Parse the string and create a lisp form
11805 (let ((match0 match)
11806 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11807 minus tag mm
11808 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11809 orterms term orlist re-p str-p level-p level-op time-p
11810 prop-p pn pv po cat-p gv rest)
11811 (if (string-match "/+" match)
11812 ;; match contains also a todo-matching request
11813 (progn
11814 (setq tagsmatch (substring match 0 (match-beginning 0))
11815 todomatch (substring match (match-end 0)))
11816 (if (string-match "^!" todomatch)
11817 (setq todo-only t todomatch (substring todomatch 1)))
11818 (if (string-match "^\\s-*$" todomatch)
11819 (setq todomatch nil)))
11820 ;; only matching tags
11821 (setq tagsmatch match todomatch nil))
11823 ;; Make the tags matcher
11824 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11825 (setq tagsmatcher t)
11826 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11827 (while (setq term (pop orterms))
11828 (while (and (equal (substring term -1) "\\") orterms)
11829 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11830 (while (string-match re term)
11831 (setq rest (substring term (match-end 0))
11832 minus (and (match-end 1)
11833 (equal (match-string 1 term) "-"))
11834 tag (match-string 2 term)
11835 re-p (equal (string-to-char tag) ?{)
11836 level-p (match-end 4)
11837 prop-p (match-end 5)
11838 mm (cond
11839 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11840 (level-p
11841 (setq level-op (org-op-to-function (match-string 3 term)))
11842 `(,level-op level ,(string-to-number
11843 (match-string 4 term))))
11844 (prop-p
11845 (setq pn (match-string 5 term)
11846 po (match-string 6 term)
11847 pv (match-string 7 term)
11848 cat-p (equal pn "CATEGORY")
11849 re-p (equal (string-to-char pv) ?{)
11850 str-p (equal (string-to-char pv) ?\")
11851 time-p (save-match-data
11852 (string-match "^\"[[<].*[]>]\"$" pv))
11853 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11854 (if time-p (setq pv (org-matcher-time pv)))
11855 (setq po (org-op-to-function po (if time-p 'time str-p)))
11856 (cond
11857 ((equal pn "CATEGORY")
11858 (setq gv '(get-text-property (point) 'org-category)))
11859 ((equal pn "TODO")
11860 (setq gv 'todo))
11862 (setq gv `(org-cached-entry-get nil ,pn))))
11863 (if re-p
11864 (if (eq po 'org<>)
11865 `(not (string-match ,pv (or ,gv "")))
11866 `(string-match ,pv (or ,gv "")))
11867 (if str-p
11868 `(,po (or ,gv "") ,pv)
11869 `(,po (string-to-number (or ,gv ""))
11870 ,(string-to-number pv) ))))
11871 (t `(member ,tag tags-list)))
11872 mm (if minus (list 'not mm) mm)
11873 term rest)
11874 (push mm tagsmatcher))
11875 (push (if (> (length tagsmatcher) 1)
11876 (cons 'and tagsmatcher)
11877 (car tagsmatcher))
11878 orlist)
11879 (setq tagsmatcher nil))
11880 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11881 (setq tagsmatcher
11882 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11883 ;; Make the todo matcher
11884 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11885 (setq todomatcher t)
11886 (setq orterms (org-split-string todomatch "|") orlist nil)
11887 (while (setq term (pop orterms))
11888 (while (string-match re term)
11889 (setq minus (and (match-end 1)
11890 (equal (match-string 1 term) "-"))
11891 kwd (match-string 2 term)
11892 re-p (equal (string-to-char kwd) ?{)
11893 term (substring term (match-end 0))
11894 mm (if re-p
11895 `(string-match ,(substring kwd 1 -1) todo)
11896 (list 'equal 'todo kwd))
11897 mm (if minus (list 'not mm) mm))
11898 (push mm todomatcher))
11899 (push (if (> (length todomatcher) 1)
11900 (cons 'and todomatcher)
11901 (car todomatcher))
11902 orlist)
11903 (setq todomatcher nil))
11904 (setq todomatcher (if (> (length orlist) 1)
11905 (cons 'or orlist) (car orlist))))
11907 ;; Return the string and lisp forms of the matcher
11908 (setq matcher (if todomatcher
11909 (list 'and tagsmatcher todomatcher)
11910 tagsmatcher))
11911 (cons match0 matcher)))
11913 (defun org-op-to-function (op &optional stringp)
11914 "Turn an operator into the appropriate function."
11915 (setq op
11916 (cond
11917 ((equal op "<" ) '(< string< org-time<))
11918 ((equal op ">" ) '(> org-string> org-time>))
11919 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11920 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11921 ((member op '("=" "==")) '(= string= org-time=))
11922 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11923 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11925 (defun org<> (a b) (not (= a b)))
11926 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11927 (defun org-string>= (a b) (not (string< a b)))
11928 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11929 (defun org-string<> (a b) (not (string= a b)))
11930 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11931 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11932 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11933 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11934 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11935 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11936 (defun org-2ft (s)
11937 "Convert S to a floating point time.
11938 If S is already a number, just return it. If it is a string, parse
11939 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11940 (cond
11941 ((numberp s) s)
11942 ((stringp s)
11943 (condition-case nil
11944 (float-time (apply 'encode-time (org-parse-time-string s)))
11945 (error 0.)))
11946 (t 0.)))
11948 (defun org-time-today ()
11949 "Time in seconds today at 0:00.
11950 Returns the float number of seconds since the beginning of the
11951 epoch to the beginning of today (00:00)."
11952 (float-time (apply 'encode-time
11953 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11955 (defun org-matcher-time (s)
11956 "Interpret a time comparison value."
11957 (save-match-data
11958 (cond
11959 ((string= s "<now>") (float-time))
11960 ((string= s "<today>") (org-time-today))
11961 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11962 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11963 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11964 (+ (org-time-today)
11965 (* (string-to-number (match-string 1 s))
11966 (cdr (assoc (match-string 2 s)
11967 '(("d" . 86400.0) ("w" . 604800.0)
11968 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11969 (t (org-2ft s)))))
11971 (defun org-match-any-p (re list)
11972 "Does re match any element of list?"
11973 (setq list (mapcar (lambda (x) (string-match re x)) list))
11974 (delq nil list))
11976 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11977 (defvar org-tags-overlay (org-make-overlay 1 1))
11978 (org-detach-overlay org-tags-overlay)
11980 (defun org-get-local-tags-at (&optional pos)
11981 "Get a list of tags defined in the current headline."
11982 (org-get-tags-at pos 'local))
11984 (defun org-get-local-tags ()
11985 "Get a list of tags defined in the current headline."
11986 (org-get-tags-at nil 'local))
11988 (defun org-get-tags-at (&optional pos local)
11989 "Get a list of all headline tags applicable at POS.
11990 POS defaults to point. If tags are inherited, the list contains
11991 the targets in the same sequence as the headlines appear, i.e.
11992 the tags of the current headline come last.
11993 When LOCAL is non-nil, only return tags from the current headline,
11994 ignore inherited ones."
11995 (interactive)
11996 (if (and org-trust-scanner-tags
11997 (or (not pos) (equal pos (point)))
11998 (not local))
11999 org-scanner-tags
12000 (let (tags ltags lastpos parent)
12001 (save-excursion
12002 (save-restriction
12003 (widen)
12004 (goto-char (or pos (point)))
12005 (save-match-data
12006 (catch 'done
12007 (condition-case nil
12008 (progn
12009 (org-back-to-heading t)
12010 (while (not (equal lastpos (point)))
12011 (setq lastpos (point))
12012 (when (looking-at
12013 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12014 (setq ltags (org-split-string
12015 (org-match-string-no-properties 1) ":"))
12016 (when parent
12017 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12018 (setq tags (append
12019 (if parent
12020 (org-remove-uniherited-tags ltags)
12021 ltags)
12022 tags)))
12023 (or org-use-tag-inheritance (throw 'done t))
12024 (if local (throw 'done t))
12025 (or (org-up-heading-safe) (error nil))
12026 (setq parent t)))
12027 (error nil)))))
12028 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12030 (defun org-add-prop-inherited (s)
12031 (add-text-properties 0 (length s) '(inherited t) s)
12034 (defun org-toggle-tag (tag &optional onoff)
12035 "Toggle the tag TAG for the current line.
12036 If ONOFF is `on' or `off', don't toggle but set to this state."
12037 (let (res current)
12038 (save-excursion
12039 (org-back-to-heading t)
12040 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12041 (point-at-eol) t)
12042 (progn
12043 (setq current (match-string 1))
12044 (replace-match ""))
12045 (setq current ""))
12046 (setq current (nreverse (org-split-string current ":")))
12047 (cond
12048 ((eq onoff 'on)
12049 (setq res t)
12050 (or (member tag current) (push tag current)))
12051 ((eq onoff 'off)
12052 (or (not (member tag current)) (setq current (delete tag current))))
12053 (t (if (member tag current)
12054 (setq current (delete tag current))
12055 (setq res t)
12056 (push tag current))))
12057 (end-of-line 1)
12058 (if current
12059 (progn
12060 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12061 (org-set-tags nil t))
12062 (delete-horizontal-space))
12063 (run-hooks 'org-after-tags-change-hook))
12064 res))
12066 (defun org-align-tags-here (to-col)
12067 ;; Assumes that this is a headline
12068 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12069 (beginning-of-line 1)
12070 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12071 (< pos (match-beginning 2)))
12072 (progn
12073 (setq tags-l (- (match-end 2) (match-beginning 2)))
12074 (goto-char (match-beginning 1))
12075 (insert " ")
12076 (delete-region (point) (1+ (match-beginning 2)))
12077 (setq ncol (max (1+ (current-column))
12078 (1+ col)
12079 (if (> to-col 0)
12080 to-col
12081 (- (abs to-col) tags-l))))
12082 (setq p (point))
12083 (insert (make-string (- ncol (current-column)) ?\ ))
12084 (setq ncol (current-column))
12085 (when indent-tabs-mode (tabify p (point-at-eol)))
12086 (org-move-to-column (min ncol col) t))
12087 (goto-char pos))))
12089 (defun org-set-tags-command (&optional arg just-align)
12090 "Call the set-tags command for the current entry."
12091 (interactive "P")
12092 (if (org-on-heading-p)
12093 (org-set-tags arg just-align)
12094 (save-excursion
12095 (org-back-to-heading t)
12096 (org-set-tags arg just-align))))
12098 (defun org-set-tags-to (data)
12099 "Set the tags of the current entry to DATA, replacing the current tags.
12100 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12101 If DATA is nil or the empty string, any tags will be removed."
12102 (interactive "sTags: ")
12103 (setq data
12104 (cond
12105 ((eq data nil) "")
12106 ((equal data "") "")
12107 ((stringp data)
12108 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12109 ":"))
12110 ((listp data)
12111 (concat ":" (mapconcat 'identity data ":") ":"))
12112 (t nil)))
12113 (when data
12114 (save-excursion
12115 (org-back-to-heading t)
12116 (when (looking-at org-complex-heading-regexp)
12117 (if (match-end 5)
12118 (progn
12119 (goto-char (match-beginning 5))
12120 (insert data)
12121 (delete-region (point) (point-at-eol))
12122 (org-set-tags nil 'align))
12123 (goto-char (point-at-eol))
12124 (insert " " data)
12125 (org-set-tags nil 'align)))
12126 (beginning-of-line 1)
12127 (if (looking-at ".*?\\([ \t]+\\)$")
12128 (delete-region (match-beginning 1) (match-end 1))))))
12130 (defun org-set-tags (&optional arg just-align)
12131 "Set the tags for the current headline.
12132 With prefix ARG, realign all tags in headings in the current buffer."
12133 (interactive "P")
12134 (let* ((re (concat "^" outline-regexp))
12135 (current (org-get-tags-string))
12136 (col (current-column))
12137 (org-setting-tags t)
12138 table current-tags inherited-tags ; computed below when needed
12139 tags p0 c0 c1 rpl)
12140 (if arg
12141 (save-excursion
12142 (goto-char (point-min))
12143 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12144 (while (re-search-forward re nil t)
12145 (org-set-tags nil t)
12146 (end-of-line 1)))
12147 (message "All tags realigned to column %d" org-tags-column))
12148 (if just-align
12149 (setq tags current)
12150 ;; Get a new set of tags from the user
12151 (save-excursion
12152 (setq table (append org-tag-persistent-alist
12153 (or org-tag-alist (org-get-buffer-tags))
12154 (and org-complete-tags-always-offer-all-agenda-tags
12155 (org-global-tags-completion-table (org-agenda-files))))
12156 org-last-tags-completion-table table
12157 current-tags (org-split-string current ":")
12158 inherited-tags (nreverse
12159 (nthcdr (length current-tags)
12160 (nreverse (org-get-tags-at))))
12161 tags
12162 (if (or (eq t org-use-fast-tag-selection)
12163 (and org-use-fast-tag-selection
12164 (delq nil (mapcar 'cdr table))))
12165 (org-fast-tag-selection
12166 current-tags inherited-tags table
12167 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12168 (let ((org-add-colon-after-tag-completion t))
12169 (org-trim
12170 (org-without-partial-completion
12171 (org-icompleting-read "Tags: " 'org-tags-completion-function
12172 nil nil current 'org-tags-history)))))))
12173 (while (string-match "[-+&]+" tags)
12174 ;; No boolean logic, just a list
12175 (setq tags (replace-match ":" t t tags))))
12177 (if org-tags-sort-function
12178 (setq tags (mapconcat 'identity
12179 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12180 org-tags-sort-function) ":")))
12182 (if (string-match "\\`[\t ]*\\'" tags)
12183 (setq tags "")
12184 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12185 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12187 ;; Insert new tags at the correct column
12188 (beginning-of-line 1)
12189 (cond
12190 ((and (equal current "") (equal tags "")))
12191 ((re-search-forward
12192 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12193 (point-at-eol) t)
12194 (if (equal tags "")
12195 (setq rpl "")
12196 (goto-char (match-beginning 0))
12197 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12198 (1+ (point)) (point))
12199 c1 (max (1+ c0) (if (> org-tags-column 0)
12200 org-tags-column
12201 (- (- org-tags-column) (length tags))))
12202 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12203 (replace-match rpl t t)
12204 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12205 tags)
12206 (t (error "Tags alignment failed")))
12207 (org-move-to-column col)
12208 (unless just-align
12209 (run-hooks 'org-after-tags-change-hook)))))
12211 (defun org-change-tag-in-region (beg end tag off)
12212 "Add or remove TAG for each entry in the region.
12213 This works in the agenda, and also in an org-mode buffer."
12214 (interactive
12215 (list (region-beginning) (region-end)
12216 (let ((org-last-tags-completion-table
12217 (if (org-mode-p)
12218 (org-get-buffer-tags)
12219 (org-global-tags-completion-table))))
12220 (org-icompleting-read
12221 "Tag: " 'org-tags-completion-function nil nil nil
12222 'org-tags-history))
12223 (progn
12224 (message "[s]et or [r]emove? ")
12225 (equal (read-char-exclusive) ?r))))
12226 (if (fboundp 'deactivate-mark) (deactivate-mark))
12227 (let ((agendap (equal major-mode 'org-agenda-mode))
12228 l1 l2 m buf pos newhead (cnt 0))
12229 (goto-char end)
12230 (setq l2 (1- (org-current-line)))
12231 (goto-char beg)
12232 (setq l1 (org-current-line))
12233 (loop for l from l1 to l2 do
12234 (org-goto-line l)
12235 (setq m (get-text-property (point) 'org-hd-marker))
12236 (when (or (and (org-mode-p) (org-on-heading-p))
12237 (and agendap m))
12238 (setq buf (if agendap (marker-buffer m) (current-buffer))
12239 pos (if agendap m (point)))
12240 (with-current-buffer buf
12241 (save-excursion
12242 (save-restriction
12243 (goto-char pos)
12244 (setq cnt (1+ cnt))
12245 (org-toggle-tag tag (if off 'off 'on))
12246 (setq newhead (org-get-heading)))))
12247 (and agendap (org-agenda-change-all-lines newhead m))))
12248 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12250 (defun org-tags-completion-function (string predicate &optional flag)
12251 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12252 (confirm (lambda (x) (stringp (car x)))))
12253 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12254 (setq s1 (match-string 1 string)
12255 s2 (match-string 2 string))
12256 (setq s1 "" s2 string))
12257 (cond
12258 ((eq flag nil)
12259 ;; try completion
12260 (setq rtn (try-completion s2 ctable confirm))
12261 (if (stringp rtn)
12262 (setq rtn
12263 (concat s1 s2 (substring rtn (length s2))
12264 (if (and org-add-colon-after-tag-completion
12265 (assoc rtn ctable))
12266 ":" ""))))
12267 rtn)
12268 ((eq flag t)
12269 ;; all-completions
12270 (all-completions s2 ctable confirm)
12272 ((eq flag 'lambda)
12273 ;; exact match?
12274 (assoc s2 ctable)))
12277 (defun org-fast-tag-insert (kwd tags face &optional end)
12278 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12279 (insert (format "%-12s" (concat kwd ":"))
12280 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12281 (or end "")))
12283 (defun org-fast-tag-show-exit (flag)
12284 (save-excursion
12285 (org-goto-line 3)
12286 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12287 (replace-match ""))
12288 (when flag
12289 (end-of-line 1)
12290 (org-move-to-column (- (window-width) 19) t)
12291 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12293 (defun org-set-current-tags-overlay (current prefix)
12294 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12295 (if (featurep 'xemacs)
12296 (org-overlay-display org-tags-overlay (concat prefix s)
12297 'secondary-selection)
12298 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12299 (org-overlay-display org-tags-overlay (concat prefix s)))))
12301 (defvar org-last-tag-selection-key nil)
12302 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12303 "Fast tag selection with single keys.
12304 CURRENT is the current list of tags in the headline, INHERITED is the
12305 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12306 possibly with grouping information. TODO-TABLE is a similar table with
12307 TODO keywords, should these have keys assigned to them.
12308 If the keys are nil, a-z are automatically assigned.
12309 Returns the new tags string, or nil to not change the current settings."
12310 (let* ((fulltable (append table todo-table))
12311 (maxlen (apply 'max (mapcar
12312 (lambda (x)
12313 (if (stringp (car x)) (string-width (car x)) 0))
12314 fulltable)))
12315 (buf (current-buffer))
12316 (expert (eq org-fast-tag-selection-single-key 'expert))
12317 (buffer-tags nil)
12318 (fwidth (+ maxlen 3 1 3))
12319 (ncol (/ (- (window-width) 4) fwidth))
12320 (i-face 'org-done)
12321 (c-face 'org-todo)
12322 tg cnt e c char c1 c2 ntable tbl rtn
12323 ov-start ov-end ov-prefix
12324 (exit-after-next org-fast-tag-selection-single-key)
12325 (done-keywords org-done-keywords)
12326 groups ingroup)
12327 (save-excursion
12328 (beginning-of-line 1)
12329 (if (looking-at
12330 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12331 (setq ov-start (match-beginning 1)
12332 ov-end (match-end 1)
12333 ov-prefix "")
12334 (setq ov-start (1- (point-at-eol))
12335 ov-end (1+ ov-start))
12336 (skip-chars-forward "^\n\r")
12337 (setq ov-prefix
12338 (concat
12339 (buffer-substring (1- (point)) (point))
12340 (if (> (current-column) org-tags-column)
12342 (make-string (- org-tags-column (current-column)) ?\ ))))))
12343 (org-move-overlay org-tags-overlay ov-start ov-end)
12344 (save-window-excursion
12345 (if expert
12346 (set-buffer (get-buffer-create " *Org tags*"))
12347 (delete-other-windows)
12348 (split-window-vertically)
12349 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12350 (erase-buffer)
12351 (org-set-local 'org-done-keywords done-keywords)
12352 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12353 (org-fast-tag-insert "Current" current c-face "\n\n")
12354 (org-fast-tag-show-exit exit-after-next)
12355 (org-set-current-tags-overlay current ov-prefix)
12356 (setq tbl fulltable char ?a cnt 0)
12357 (while (setq e (pop tbl))
12358 (cond
12359 ((equal (car e) :startgroup)
12360 (push '() groups) (setq ingroup t)
12361 (when (not (= cnt 0))
12362 (setq cnt 0)
12363 (insert "\n"))
12364 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12365 ((equal (car e) :endgroup)
12366 (setq ingroup nil cnt 0)
12367 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12368 ((equal e '(:newline))
12369 (when (not (= cnt 0))
12370 (setq cnt 0)
12371 (insert "\n")
12372 (setq e (car tbl))
12373 (while (equal (car tbl) '(:newline))
12374 (insert "\n")
12375 (setq tbl (cdr tbl)))))
12377 (setq tg (copy-sequence (car e)) c2 nil)
12378 (if (cdr e)
12379 (setq c (cdr e))
12380 ;; automatically assign a character.
12381 (setq c1 (string-to-char
12382 (downcase (substring
12383 tg (if (= (string-to-char tg) ?@) 1 0)))))
12384 (if (or (rassoc c1 ntable) (rassoc c1 table))
12385 (while (or (rassoc char ntable) (rassoc char table))
12386 (setq char (1+ char)))
12387 (setq c2 c1))
12388 (setq c (or c2 char)))
12389 (if ingroup (push tg (car groups)))
12390 (setq tg (org-add-props tg nil 'face
12391 (cond
12392 ((not (assoc tg table))
12393 (org-get-todo-face tg))
12394 ((member tg current) c-face)
12395 ((member tg inherited) i-face)
12396 (t nil))))
12397 (if (and (= cnt 0) (not ingroup)) (insert " "))
12398 (insert "[" c "] " tg (make-string
12399 (- fwidth 4 (length tg)) ?\ ))
12400 (push (cons tg c) ntable)
12401 (when (= (setq cnt (1+ cnt)) ncol)
12402 (insert "\n")
12403 (if ingroup (insert " "))
12404 (setq cnt 0)))))
12405 (setq ntable (nreverse ntable))
12406 (insert "\n")
12407 (goto-char (point-min))
12408 (if (not expert) (org-fit-window-to-buffer))
12409 (setq rtn
12410 (catch 'exit
12411 (while t
12412 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12413 (if (not groups) "no " "")
12414 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12415 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12416 (setq org-last-tag-selection-key c)
12417 (cond
12418 ((= c ?\r) (throw 'exit t))
12419 ((= c ?!)
12420 (setq groups (not groups))
12421 (goto-char (point-min))
12422 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12423 ((= c ?\C-c)
12424 (if (not expert)
12425 (org-fast-tag-show-exit
12426 (setq exit-after-next (not exit-after-next)))
12427 (setq expert nil)
12428 (delete-other-windows)
12429 (split-window-vertically)
12430 (org-switch-to-buffer-other-window " *Org tags*")
12431 (org-fit-window-to-buffer)))
12432 ((or (= c ?\C-g)
12433 (and (= c ?q) (not (rassoc c ntable))))
12434 (org-detach-overlay org-tags-overlay)
12435 (setq quit-flag t))
12436 ((= c ?\ )
12437 (setq current nil)
12438 (if exit-after-next (setq exit-after-next 'now)))
12439 ((= c ?\t)
12440 (condition-case nil
12441 (setq tg (org-icompleting-read
12442 "Tag: "
12443 (or buffer-tags
12444 (with-current-buffer buf
12445 (org-get-buffer-tags)))))
12446 (quit (setq tg "")))
12447 (when (string-match "\\S-" tg)
12448 (add-to-list 'buffer-tags (list tg))
12449 (if (member tg current)
12450 (setq current (delete tg current))
12451 (push tg current)))
12452 (if exit-after-next (setq exit-after-next 'now)))
12453 ((setq e (rassoc c todo-table) tg (car e))
12454 (with-current-buffer buf
12455 (save-excursion (org-todo tg)))
12456 (if exit-after-next (setq exit-after-next 'now)))
12457 ((setq e (rassoc c ntable) tg (car e))
12458 (if (member tg current)
12459 (setq current (delete tg current))
12460 (loop for g in groups do
12461 (if (member tg g)
12462 (mapc (lambda (x)
12463 (setq current (delete x current)))
12464 g)))
12465 (push tg current))
12466 (if exit-after-next (setq exit-after-next 'now))))
12468 ;; Create a sorted list
12469 (setq current
12470 (sort current
12471 (lambda (a b)
12472 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12473 (if (eq exit-after-next 'now) (throw 'exit t))
12474 (goto-char (point-min))
12475 (beginning-of-line 2)
12476 (delete-region (point) (point-at-eol))
12477 (org-fast-tag-insert "Current" current c-face)
12478 (org-set-current-tags-overlay current ov-prefix)
12479 (while (re-search-forward
12480 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12481 (setq tg (match-string 1))
12482 (add-text-properties
12483 (match-beginning 1) (match-end 1)
12484 (list 'face
12485 (cond
12486 ((member tg current) c-face)
12487 ((member tg inherited) i-face)
12488 (t (get-text-property (match-beginning 1) 'face))))))
12489 (goto-char (point-min)))))
12490 (org-detach-overlay org-tags-overlay)
12491 (if rtn
12492 (mapconcat 'identity current ":")
12493 nil))))
12495 (defun org-get-tags-string ()
12496 "Get the TAGS string in the current headline."
12497 (unless (org-on-heading-p t)
12498 (error "Not on a heading"))
12499 (save-excursion
12500 (beginning-of-line 1)
12501 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12502 (org-match-string-no-properties 1)
12503 "")))
12505 (defun org-get-tags ()
12506 "Get the list of tags specified in the current headline."
12507 (org-split-string (org-get-tags-string) ":"))
12509 (defun org-get-buffer-tags ()
12510 "Get a table of all tags used in the buffer, for completion."
12511 (let (tags)
12512 (save-excursion
12513 (goto-char (point-min))
12514 (while (re-search-forward
12515 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12516 (when (equal (char-after (point-at-bol 0)) ?*)
12517 (mapc (lambda (x) (add-to-list 'tags x))
12518 (org-split-string (org-match-string-no-properties 1) ":")))))
12519 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12520 (mapcar 'list tags)))
12522 ;;;; The mapping API
12524 ;;;###autoload
12525 (defun org-map-entries (func &optional match scope &rest skip)
12526 "Call FUNC at each headline selected by MATCH in SCOPE.
12528 FUNC is a function or a lisp form. The function will be called without
12529 arguments, with the cursor positioned at the beginning of the headline.
12530 The return values of all calls to the function will be collected and
12531 returned as a list.
12533 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12534 does not need to preserve point. After evaluation, the cursor will be
12535 moved to the end of the line (presumably of the headline of the
12536 processed entry) and search continues from there. Under some
12537 circumstances, this may not produce the wanted results. For example,
12538 if you have removed (e.g. archived) the current (sub)tree it could
12539 mean that the next entry will be skipped entirely. In such cases, you
12540 can specify the position from where search should continue by making
12541 FUNC set the variable `org-map-continue-from' to the desired buffer
12542 position.
12544 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12545 Only headlines that are matched by this query will be considered during
12546 the iteration. When MATCH is nil or t, all headlines will be
12547 visited by the iteration.
12549 SCOPE determines the scope of this command. It can be any of:
12551 nil The current buffer, respecting the restriction if any
12552 tree The subtree started with the entry at point
12553 file The current buffer, without restriction
12554 file-with-archives
12555 The current buffer, and any archives associated with it
12556 agenda All agenda files
12557 agenda-with-archives
12558 All agenda files with any archive files associated with them
12559 \(file1 file2 ...)
12560 If this is a list, all files in the list will be scanned
12562 The remaining args are treated as settings for the skipping facilities of
12563 the scanner. The following items can be given here:
12565 archive skip trees with the archive tag.
12566 comment skip trees with the COMMENT keyword
12567 function or Emacs Lisp form:
12568 will be used as value for `org-agenda-skip-function', so whenever
12569 the function returns t, FUNC will not be called for that
12570 entry and search will continue from the point where the
12571 function leaves it.
12573 If your function needs to retrieve the tags including inherited tags
12574 at the *current* entry, you can use the value of the variable
12575 `org-scanner-tags' which will be much faster than getting the value
12576 with `org-get-tags-at'. If your function gets properties with
12577 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12578 to t around the call to `org-entry-properties' to get the same speedup.
12579 Note that if your function moves around to retrieve tags and properties at
12580 a *different* entry, you cannot use these techniques."
12581 (let* ((org-agenda-archives-mode nil) ; just to make sure
12582 (org-agenda-skip-archived-trees (memq 'archive skip))
12583 (org-agenda-skip-comment-trees (memq 'comment skip))
12584 (org-agenda-skip-function
12585 (car (org-delete-all '(comment archive) skip)))
12586 (org-tags-match-list-sublevels t)
12587 matcher file res
12588 org-todo-keywords-for-agenda
12589 org-done-keywords-for-agenda
12590 org-todo-keyword-alist-for-agenda
12591 org-drawers-for-agenda
12592 org-tag-alist-for-agenda)
12594 (cond
12595 ((eq match t) (setq matcher t))
12596 ((eq match nil) (setq matcher t))
12597 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12599 (save-excursion
12600 (save-restriction
12601 (when (eq scope 'tree)
12602 (org-back-to-heading t)
12603 (org-narrow-to-subtree)
12604 (setq scope nil))
12606 (if (not scope)
12607 (progn
12608 (org-prepare-agenda-buffers
12609 (list (buffer-file-name (current-buffer))))
12610 (setq res (org-scan-tags func matcher)))
12611 ;; Get the right scope
12612 (cond
12613 ((and scope (listp scope) (symbolp (car scope)))
12614 (setq scope (eval scope)))
12615 ((eq scope 'agenda)
12616 (setq scope (org-agenda-files t)))
12617 ((eq scope 'agenda-with-archives)
12618 (setq scope (org-agenda-files t))
12619 (setq scope (org-add-archive-files scope)))
12620 ((eq scope 'file)
12621 (setq scope (list (buffer-file-name))))
12622 ((eq scope 'file-with-archives)
12623 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12624 (org-prepare-agenda-buffers scope)
12625 (while (setq file (pop scope))
12626 (with-current-buffer (org-find-base-buffer-visiting file)
12627 (save-excursion
12628 (save-restriction
12629 (widen)
12630 (goto-char (point-min))
12631 (setq res (append res (org-scan-tags func matcher))))))))))
12632 res))
12634 ;;;; Properties
12636 ;;; Setting and retrieving properties
12638 (defconst org-special-properties
12639 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12640 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12641 "The special properties valid in Org-mode.
12643 These are properties that are not defined in the property drawer,
12644 but in some other way.")
12646 (defconst org-default-properties
12647 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12648 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12649 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12650 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12651 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12652 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12653 "Some properties that are used by Org-mode for various purposes.
12654 Being in this list makes sure that they are offered for completion.")
12656 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12657 "Regular expression matching the first line of a property drawer.")
12659 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12660 "Regular expression matching the last line of a property drawer.")
12662 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12663 "Regular expression matching the first line of a property drawer.")
12665 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12666 "Regular expression matching the first line of a property drawer.")
12668 (defconst org-property-drawer-re
12669 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12670 org-property-end-re "\\)\n?")
12671 "Matches an entire property drawer.")
12673 (defconst org-clock-drawer-re
12674 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12675 org-property-end-re "\\)\n?")
12676 "Matches an entire clock drawer.")
12678 (defun org-property-action ()
12679 "Do an action on properties."
12680 (interactive)
12681 (let (c)
12682 (org-at-property-p)
12683 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12684 (setq c (read-char-exclusive))
12685 (cond
12686 ((equal c ?s)
12687 (call-interactively 'org-set-property))
12688 ((equal c ?d)
12689 (call-interactively 'org-delete-property))
12690 ((equal c ?D)
12691 (call-interactively 'org-delete-property-globally))
12692 ((equal c ?c)
12693 (call-interactively 'org-compute-property-at-point))
12694 (t (error "No such property action %c" c)))))
12696 (defun org-set-effort (&optional value)
12697 "Set the effort property of the current entry.
12698 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12699 allowed value."
12700 (interactive "P")
12701 (if (equal value 0) (setq value 10))
12702 (let* ((completion-ignore-case t)
12703 (prop org-effort-property)
12704 (cur (org-entry-get nil prop))
12705 (allowed (org-property-get-allowed-values nil prop 'table))
12706 (existing (mapcar 'list (org-property-values prop)))
12708 (val (cond
12709 ((stringp value) value)
12710 ((and allowed (integerp value))
12711 (or (car (nth (1- value) allowed))
12712 (car (org-last allowed))))
12713 (allowed
12714 (message "Select 1-9,0, [RET%s]: %s"
12715 (if cur (concat "=" cur) "")
12716 (mapconcat 'car allowed " "))
12717 (setq rpl (read-char-exclusive))
12718 (if (equal rpl ?\r)
12720 (setq rpl (- rpl ?0))
12721 (if (equal rpl 0) (setq rpl 10))
12722 (if (and (> rpl 0) (<= rpl (length allowed)))
12723 (car (nth (1- rpl) allowed))
12724 (org-completing-read "Effort: " allowed nil))))
12726 (let (org-completion-use-ido org-completion-use-iswitchb)
12727 (org-completing-read
12728 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12729 (concat "[" cur "]") "")
12730 ": ")
12731 existing nil nil "" nil cur))))))
12732 (unless (equal (org-entry-get nil prop) val)
12733 (org-entry-put nil prop val))
12734 (message "%s is now %s" prop val)))
12736 (defun org-at-property-p ()
12737 "Is cursor inside a property drawer?"
12738 (save-excursion
12739 (beginning-of-line 1)
12740 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12741 (let ((match (match-data)) ;; Keep match-data for use by calling
12742 (p (point)) ;; procedures.
12743 (range (unless (org-before-first-heading-p)
12744 (org-get-property-block))))
12745 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12746 (set-match-data match))))))
12748 (defun org-get-property-block (&optional beg end force)
12749 "Return the (beg . end) range of the body of the property drawer.
12750 BEG and END can be beginning and end of subtree, if not given
12751 they will be found.
12752 If the drawer does not exist and FORCE is non-nil, create the drawer."
12753 (catch 'exit
12754 (save-excursion
12755 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12756 (end (or end (progn (outline-next-heading) (point)))))
12757 (goto-char beg)
12758 (if (re-search-forward org-property-start-re end t)
12759 (setq beg (1+ (match-end 0)))
12760 (if force
12761 (save-excursion
12762 (org-insert-property-drawer)
12763 (setq end (progn (outline-next-heading) (point))))
12764 (throw 'exit nil))
12765 (goto-char beg)
12766 (if (re-search-forward org-property-start-re end t)
12767 (setq beg (1+ (match-end 0)))))
12768 (if (re-search-forward org-property-end-re end t)
12769 (setq end (match-beginning 0))
12770 (or force (throw 'exit nil))
12771 (goto-char beg)
12772 (setq end beg)
12773 (org-indent-line-function)
12774 (insert ":END:\n"))
12775 (cons beg end)))))
12777 (defun org-entry-properties (&optional pom which specific)
12778 "Get all properties of the entry at point-or-marker POM.
12779 This includes the TODO keyword, the tags, time strings for deadline,
12780 scheduled, and clocking, and any additional properties defined in the
12781 entry. The return value is an alist, keys may occur multiple times
12782 if the property key was used several times.
12783 POM may also be nil, in which case the current entry is used.
12784 If WHICH is nil or `all', get all properties. If WHICH is
12785 `special' or `standard', only get that subclass. If WHICH
12786 is a string only get exactly this property. Specific can be a string, the
12787 specific property we are interested in. Specifying it can speed
12788 things up because then unnecessary parsing is avoided."
12789 (setq which (or which 'all))
12790 (org-with-point-at pom
12791 (let ((clockstr (substring org-clock-string 0 -1))
12792 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12793 (case-fold-search nil)
12794 beg end range props sum-props key value string clocksum)
12795 (save-excursion
12796 (when (condition-case nil
12797 (and (org-mode-p) (org-back-to-heading t))
12798 (error nil))
12799 (setq beg (point))
12800 (setq sum-props (get-text-property (point) 'org-summaries))
12801 (setq clocksum (get-text-property (point) :org-clock-minutes))
12802 (outline-next-heading)
12803 (setq end (point))
12804 (when (memq which '(all special))
12805 ;; Get the special properties, like TODO and tags
12806 (goto-char beg)
12807 (when (and (or (not specific) (string= specific "TODO"))
12808 (looking-at org-todo-line-regexp) (match-end 2))
12809 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12810 (when (and (or (not specific) (string= specific "PRIORITY"))
12811 (looking-at org-priority-regexp))
12812 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12813 (when (and (or (not specific) (string= specific "TAGS"))
12814 (setq value (org-get-tags-string))
12815 (string-match "\\S-" value))
12816 (push (cons "TAGS" value) props))
12817 (when (and (or (not specific) (string= specific "ALLTAGS"))
12818 (setq value (org-get-tags-at)))
12819 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12820 ":"))
12821 props))
12822 (when (or (not specific) (string= specific "BLOCKED"))
12823 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12824 (when (or (not specific)
12825 (member specific org-all-time-keywords)
12826 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12827 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12828 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12829 string (if (equal key clockstr)
12830 (org-no-properties
12831 (org-trim
12832 (buffer-substring
12833 (match-beginning 3) (goto-char (point-at-eol)))))
12834 (substring (org-match-string-no-properties 3) 1 -1)))
12835 (unless key
12836 (if (= (char-after (match-beginning 3)) ?\[)
12837 (setq key "TIMESTAMP_IA")
12838 (setq key "TIMESTAMP")))
12839 (when (or (equal key clockstr) (not (assoc key props)))
12840 (push (cons key string) props))))
12844 (when (memq which '(all standard))
12845 ;; Get the standard properties, like :PROP: ...
12846 (setq range (org-get-property-block beg end))
12847 (when range
12848 (goto-char (car range))
12849 (while (re-search-forward
12850 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12851 (cdr range) t)
12852 (setq key (org-match-string-no-properties 1)
12853 value (org-trim (or (org-match-string-no-properties 2) "")))
12854 (unless (member key excluded)
12855 (push (cons key (or value "")) props)))))
12856 (if clocksum
12857 (push (cons "CLOCKSUM"
12858 (org-columns-number-to-string (/ (float clocksum) 60.)
12859 'add_times))
12860 props))
12861 (unless (assoc "CATEGORY" props)
12862 (setq value (or (org-get-category)
12863 (progn (org-refresh-category-properties)
12864 (org-get-category))))
12865 (push (cons "CATEGORY" value) props))
12866 (append sum-props (nreverse props)))))))
12868 (defun org-entry-get (pom property &optional inherit)
12869 "Get value of PROPERTY for entry at point-or-marker POM.
12870 If INHERIT is non-nil and the entry does not have the property,
12871 then also check higher levels of the hierarchy.
12872 If INHERIT is the symbol `selective', use inheritance only if the setting
12873 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12874 If the property is present but empty, the return value is the empty string.
12875 If the property is not present at all, nil is returned."
12876 (org-with-point-at pom
12877 (if (and inherit (if (eq inherit 'selective)
12878 (org-property-inherit-p property)
12880 (org-entry-get-with-inheritance property)
12881 (if (member property org-special-properties)
12882 ;; We need a special property. Use `org-entry-properties' to
12883 ;; retrieve it, but specify the wanted property
12884 (cdr (assoc property (org-entry-properties nil 'special property)))
12885 (let ((range (org-get-property-block)))
12886 (if (and range
12887 (goto-char (car range))
12888 (re-search-forward
12889 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12890 (cdr range) t))
12891 ;; Found the property, return it.
12892 (if (match-end 1)
12893 (org-match-string-no-properties 1)
12894 "")))))))
12896 (defun org-property-or-variable-value (var &optional inherit)
12897 "Check if there is a property fixing the value of VAR.
12898 If yes, return this value. If not, return the current value of the variable."
12899 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12900 (if (and prop (stringp prop) (string-match "\\S-" prop))
12901 (read prop)
12902 (symbol-value var))))
12904 (defun org-entry-delete (pom property)
12905 "Delete the property PROPERTY from entry at point-or-marker POM."
12906 (org-with-point-at pom
12907 (if (member property org-special-properties)
12908 nil ; cannot delete these properties.
12909 (let ((range (org-get-property-block)))
12910 (if (and range
12911 (goto-char (car range))
12912 (re-search-forward
12913 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12914 (cdr range) t))
12915 (progn
12916 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12918 nil)))))
12920 ;; Multi-values properties are properties that contain multiple values
12921 ;; These values are assumed to be single words, separated by whitespace.
12922 (defun org-entry-add-to-multivalued-property (pom property value)
12923 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12924 (let* ((old (org-entry-get pom property))
12925 (values (and old (org-split-string old "[ \t]"))))
12926 (setq value (org-entry-protect-space value))
12927 (unless (member value values)
12928 (setq values (cons value values))
12929 (org-entry-put pom property
12930 (mapconcat 'identity values " ")))))
12932 (defun org-entry-remove-from-multivalued-property (pom property value)
12933 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12934 (let* ((old (org-entry-get pom property))
12935 (values (and old (org-split-string old "[ \t]"))))
12936 (setq value (org-entry-protect-space value))
12937 (when (member value values)
12938 (setq values (delete value values))
12939 (org-entry-put pom property
12940 (mapconcat 'identity values " ")))))
12942 (defun org-entry-member-in-multivalued-property (pom property value)
12943 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12944 (let* ((old (org-entry-get pom property))
12945 (values (and old (org-split-string old "[ \t]"))))
12946 (setq value (org-entry-protect-space value))
12947 (member value values)))
12949 (defun org-entry-get-multivalued-property (pom property)
12950 "Return a list of values in a multivalued property."
12951 (let* ((value (org-entry-get pom property))
12952 (values (and value (org-split-string value "[ \t]"))))
12953 (mapcar 'org-entry-restore-space values)))
12955 (defun org-entry-put-multivalued-property (pom property &rest values)
12956 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12957 VALUES should be a list of strings. Spaces will be protected."
12958 (org-entry-put pom property
12959 (mapconcat 'org-entry-protect-space values " "))
12960 (let* ((value (org-entry-get pom property))
12961 (values (and value (org-split-string value "[ \t]"))))
12962 (mapcar 'org-entry-restore-space values)))
12964 (defun org-entry-protect-space (s)
12965 "Protect spaces and newline in string S."
12966 (while (string-match " " s)
12967 (setq s (replace-match "%20" t t s)))
12968 (while (string-match "\n" s)
12969 (setq s (replace-match "%0A" t t s)))
12972 (defun org-entry-restore-space (s)
12973 "Restore spaces and newline in string S."
12974 (while (string-match "%20" s)
12975 (setq s (replace-match " " t t s)))
12976 (while (string-match "%0A" s)
12977 (setq s (replace-match "\n" t t s)))
12980 (defvar org-entry-property-inherited-from (make-marker)
12981 "Marker pointing to the entry from where a property was inherited.
12982 Each call to `org-entry-get-with-inheritance' will set this marker to the
12983 location of the entry where the inheritance search matched. If there was
12984 no match, the marker will point nowhere.
12985 Note that also `org-entry-get' calls this function, if the INHERIT flag
12986 is set.")
12988 (defun org-entry-get-with-inheritance (property)
12989 "Get entry property, and search higher levels if not present."
12990 (move-marker org-entry-property-inherited-from nil)
12991 (let (tmp)
12992 (save-excursion
12993 (save-restriction
12994 (widen)
12995 (catch 'ex
12996 (while t
12997 (when (setq tmp (org-entry-get nil property))
12998 (org-back-to-heading t)
12999 (move-marker org-entry-property-inherited-from (point))
13000 (throw 'ex tmp))
13001 (or (org-up-heading-safe) (throw 'ex nil)))))
13002 (or tmp
13003 (cdr (assoc property org-file-properties))
13004 (cdr (assoc property org-global-properties))
13005 (cdr (assoc property org-global-properties-fixed))))))
13007 (defvar org-property-changed-functions nil
13008 "Hook called when the value of a property has changed.
13009 Each hook function should accept two arguments, the name of the property
13010 and the new value.")
13012 (defun org-entry-put (pom property value)
13013 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13014 (org-with-point-at pom
13015 (org-back-to-heading t)
13016 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13017 range)
13018 (cond
13019 ((equal property "TODO")
13020 (when (and (stringp value) (string-match "\\S-" value)
13021 (not (member value org-todo-keywords-1)))
13022 (error "\"%s\" is not a valid TODO state" value))
13023 (if (or (not value)
13024 (not (string-match "\\S-" value)))
13025 (setq value 'none))
13026 (org-todo value)
13027 (org-set-tags nil 'align))
13028 ((equal property "PRIORITY")
13029 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13030 (string-to-char value) ?\ ))
13031 (org-set-tags nil 'align))
13032 ((equal property "SCHEDULED")
13033 (if (re-search-forward org-scheduled-time-regexp end t)
13034 (cond
13035 ((eq value 'earlier) (org-timestamp-change -1 'day))
13036 ((eq value 'later) (org-timestamp-change 1 'day))
13037 (t (call-interactively 'org-schedule)))
13038 (call-interactively 'org-schedule)))
13039 ((equal property "DEADLINE")
13040 (if (re-search-forward org-deadline-time-regexp end t)
13041 (cond
13042 ((eq value 'earlier) (org-timestamp-change -1 'day))
13043 ((eq value 'later) (org-timestamp-change 1 'day))
13044 (t (call-interactively 'org-deadline)))
13045 (call-interactively 'org-deadline)))
13046 ((member property org-special-properties)
13047 (error "The %s property can not yet be set with `org-entry-put'"
13048 property))
13049 (t ; a non-special property
13050 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13051 (setq range (org-get-property-block beg end 'force))
13052 (goto-char (car range))
13053 (if (re-search-forward
13054 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13055 (progn
13056 (delete-region (match-beginning 1) (match-end 1))
13057 (goto-char (match-beginning 1)))
13058 (goto-char (cdr range))
13059 (insert "\n")
13060 (backward-char 1)
13061 (org-indent-line-function)
13062 (insert ":" property ":"))
13063 (and value (insert " " value))
13064 (org-indent-line-function)))))
13065 (run-hook-with-args 'org-property-changed-functions property value)))
13067 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13068 "Get all property keys in the current buffer.
13069 With INCLUDE-SPECIALS, also list the special properties that reflect things
13070 like tags and TODO state.
13071 With INCLUDE-DEFAULTS, also include properties that has special meaning
13072 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13073 With INCLUDE-COLUMNS, also include property names given in COLUMN
13074 formats in the current buffer."
13075 (let (rtn range cfmt s p)
13076 (save-excursion
13077 (save-restriction
13078 (widen)
13079 (goto-char (point-min))
13080 (while (re-search-forward org-property-start-re nil t)
13081 (setq range (org-get-property-block))
13082 (goto-char (car range))
13083 (while (re-search-forward
13084 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13085 (cdr range) t)
13086 (add-to-list 'rtn (org-match-string-no-properties 1)))
13087 (outline-next-heading))))
13089 (when include-specials
13090 (setq rtn (append org-special-properties rtn)))
13092 (when include-defaults
13093 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13094 (add-to-list 'rtn org-effort-property))
13096 (when include-columns
13097 (save-excursion
13098 (save-restriction
13099 (widen)
13100 (goto-char (point-min))
13101 (while (re-search-forward
13102 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13103 nil t)
13104 (setq cfmt (match-string 2) s 0)
13105 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13106 cfmt s)
13107 (setq s (match-end 0)
13108 p (match-string 1 cfmt))
13109 (unless (or (equal p "ITEM")
13110 (member p org-special-properties))
13111 (add-to-list 'rtn (match-string 1 cfmt))))))))
13113 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13115 (defun org-property-values (key)
13116 "Return a list of all values of property KEY."
13117 (save-excursion
13118 (save-restriction
13119 (widen)
13120 (goto-char (point-min))
13121 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13122 values)
13123 (while (re-search-forward re nil t)
13124 (add-to-list 'values (org-trim (match-string 1))))
13125 (delete "" values)))))
13127 (defun org-insert-property-drawer ()
13128 "Insert a property drawer into the current entry."
13129 (interactive)
13130 (org-back-to-heading t)
13131 (looking-at outline-regexp)
13132 (let ((indent (if org-adapt-indentation
13133 (- (match-end 0)(match-beginning 0))
13135 (beg (point))
13136 (re (concat "^[ \t]*" org-keyword-time-regexp))
13137 end hiddenp)
13138 (outline-next-heading)
13139 (setq end (point))
13140 (goto-char beg)
13141 (while (re-search-forward re end t))
13142 (setq hiddenp (org-invisible-p))
13143 (end-of-line 1)
13144 (and (equal (char-after) ?\n) (forward-char 1))
13145 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13146 (if (member (match-string 1) '("CLOCK:" ":END:"))
13147 ;; just skip this line
13148 (beginning-of-line 2)
13149 ;; Drawer start, find the end
13150 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13151 (beginning-of-line 1)))
13152 (org-skip-over-state-notes)
13153 (skip-chars-backward " \t\n\r")
13154 (if (eq (char-before) ?*) (forward-char 1))
13155 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13156 (beginning-of-line 0)
13157 (org-indent-to-column indent)
13158 (beginning-of-line 2)
13159 (org-indent-to-column indent)
13160 (beginning-of-line 0)
13161 (if hiddenp
13162 (save-excursion
13163 (org-back-to-heading t)
13164 (hide-entry))
13165 (org-flag-drawer t))))
13167 (defun org-set-property (property value)
13168 "In the current entry, set PROPERTY to VALUE.
13169 When called interactively, this will prompt for a property name, offering
13170 completion on existing and default properties. And then it will prompt
13171 for a value, offering completion either on allowed values (via an inherited
13172 xxx_ALL property) or on existing values in other instances of this property
13173 in the current file."
13174 (interactive
13175 (let* ((completion-ignore-case t)
13176 (keys (org-buffer-property-keys nil t t))
13177 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13178 (prop (if (member prop0 keys)
13179 prop0
13180 (or (cdr (assoc (downcase prop0)
13181 (mapcar (lambda (x) (cons (downcase x) x))
13182 keys)))
13183 prop0)))
13184 (cur (org-entry-get nil prop))
13185 (prompt (concat prop " value"
13186 (if (and cur (string-match "\\S-" cur))
13187 (concat " [" cur "]") "") ": "))
13188 (allowed (org-property-get-allowed-values nil prop 'table))
13189 (existing (mapcar 'list (org-property-values prop)))
13190 (val (if allowed
13191 (org-completing-read prompt allowed nil
13192 (not (get-text-property 0 'org-unrestricted
13193 (caar allowed))))
13194 (let (org-completion-use-ido org-completion-use-iswitchb)
13195 (org-completing-read prompt existing nil nil "" nil cur)))))
13196 (list prop (if (equal val "") cur val))))
13197 (unless (equal (org-entry-get nil property) value)
13198 (org-entry-put nil property value)))
13200 (defun org-delete-property (property)
13201 "In the current entry, delete PROPERTY."
13202 (interactive
13203 (let* ((completion-ignore-case t)
13204 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13205 (list prop)))
13206 (message "Property %s %s" property
13207 (if (org-entry-delete nil property)
13208 "deleted"
13209 "was not present in the entry")))
13211 (defun org-delete-property-globally (property)
13212 "Remove PROPERTY globally, from all entries."
13213 (interactive
13214 (let* ((completion-ignore-case t)
13215 (prop (org-icompleting-read
13216 "Globally remove property: "
13217 (mapcar 'list (org-buffer-property-keys)))))
13218 (list prop)))
13219 (save-excursion
13220 (save-restriction
13221 (widen)
13222 (goto-char (point-min))
13223 (let ((cnt 0))
13224 (while (re-search-forward
13225 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13226 nil t)
13227 (setq cnt (1+ cnt))
13228 (replace-match ""))
13229 (message "Property \"%s\" removed from %d entries" property cnt)))))
13231 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13233 (defun org-compute-property-at-point ()
13234 "Compute the property at point.
13235 This looks for an enclosing column format, extracts the operator and
13236 then applies it to the property in the column format's scope."
13237 (interactive)
13238 (unless (org-at-property-p)
13239 (error "Not at a property"))
13240 (let ((prop (org-match-string-no-properties 2)))
13241 (org-columns-get-format-and-top-level)
13242 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13243 (error "No operator defined for property %s" prop))
13244 (org-columns-compute prop)))
13246 (defvar org-property-allowed-value-functions nil
13247 "Hook for functions supplying allowed values for a specific property.
13248 The functions must take a single argument, the name of the property, and
13249 return a flat list of allowed values. If \":ETC\" is one of
13250 the values, this means that these values are intended as defaults for
13251 completion, but that other values should be allowed too.
13252 The functions must return nil if they are not responsible for this
13253 property.")
13255 (defun org-property-get-allowed-values (pom property &optional table)
13256 "Get allowed values for the property PROPERTY.
13257 When TABLE is non-nil, return an alist that can directly be used for
13258 completion."
13259 (let (vals)
13260 (cond
13261 ((equal property "TODO")
13262 (setq vals (org-with-point-at pom
13263 (append org-todo-keywords-1 '("")))))
13264 ((equal property "PRIORITY")
13265 (let ((n org-lowest-priority))
13266 (while (>= n org-highest-priority)
13267 (push (char-to-string n) vals)
13268 (setq n (1- n)))))
13269 ((member property org-special-properties))
13270 ((setq vals (run-hook-with-args-until-success
13271 'org-property-allowed-value-functions property)))
13273 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13274 (when (and vals (string-match "\\S-" vals))
13275 (setq vals (car (read-from-string (concat "(" vals ")"))))
13276 (setq vals (mapcar (lambda (x)
13277 (cond ((stringp x) x)
13278 ((numberp x) (number-to-string x))
13279 ((symbolp x) (symbol-name x))
13280 (t "???")))
13281 vals)))))
13282 (when (member ":ETC" vals)
13283 (setq vals (remove ":ETC" vals))
13284 (org-add-props (car vals) '(org-unrestricted t)))
13285 (if table (mapcar 'list vals) vals)))
13287 (defun org-property-previous-allowed-value (&optional previous)
13288 "Switch to the next allowed value for this property."
13289 (interactive)
13290 (org-property-next-allowed-value t))
13292 (defun org-property-next-allowed-value (&optional previous)
13293 "Switch to the next allowed value for this property."
13294 (interactive)
13295 (unless (org-at-property-p)
13296 (error "Not at a property"))
13297 (let* ((key (match-string 2))
13298 (value (match-string 3))
13299 (allowed (or (org-property-get-allowed-values (point) key)
13300 (and (member value '("[ ]" "[-]" "[X]"))
13301 '("[ ]" "[X]"))))
13302 nval)
13303 (unless allowed
13304 (error "Allowed values for this property have not been defined"))
13305 (if previous (setq allowed (reverse allowed)))
13306 (if (member value allowed)
13307 (setq nval (car (cdr (member value allowed)))))
13308 (setq nval (or nval (car allowed)))
13309 (if (equal nval value)
13310 (error "Only one allowed value for this property"))
13311 (org-at-property-p)
13312 (replace-match (concat " :" key ": " nval) t t)
13313 (org-indent-line-function)
13314 (beginning-of-line 1)
13315 (skip-chars-forward " \t")
13316 (run-hook-with-args 'org-property-changed-functions key nval)))
13318 (defun org-find-entry-with-id (ident)
13319 "Locate the entry that contains the ID property with exact value IDENT.
13320 IDENT can be a string, a symbol or a number, this function will search for
13321 the string representation of it.
13322 Return the position where this entry starts, or nil if there is no such entry."
13323 (interactive "sID: ")
13324 (let ((id (cond
13325 ((stringp ident) ident)
13326 ((symbol-name ident) (symbol-name ident))
13327 ((numberp ident) (number-to-string ident))
13328 (t (error "IDENT %s must be a string, symbol or number" ident))))
13329 (case-fold-search nil))
13330 (save-excursion
13331 (save-restriction
13332 (widen)
13333 (goto-char (point-min))
13334 (when (re-search-forward
13335 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13336 nil t)
13337 (org-back-to-heading t)
13338 (point))))))
13340 ;;;; Timestamps
13342 (defvar org-last-changed-timestamp nil)
13343 (defvar org-last-inserted-timestamp nil
13344 "The last time stamp inserted with `org-insert-time-stamp'.")
13345 (defvar org-time-was-given) ; dynamically scoped parameter
13346 (defvar org-end-time-was-given) ; dynamically scoped parameter
13347 (defvar org-ts-what) ; dynamically scoped parameter
13349 (defun org-time-stamp (arg &optional inactive)
13350 "Prompt for a date/time and insert a time stamp.
13351 If the user specifies a time like HH:MM, or if this command is called
13352 with a prefix argument, the time stamp will contain date and time.
13353 Otherwise, only the date will be included. All parts of a date not
13354 specified by the user will be filled in from the current date/time.
13355 So if you press just return without typing anything, the time stamp
13356 will represent the current date/time. If there is already a timestamp
13357 at the cursor, it will be modified."
13358 (interactive "P")
13359 (let* ((ts nil)
13360 (default-time
13361 ;; Default time is either today, or, when entering a range,
13362 ;; the range start.
13363 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13364 (save-excursion
13365 (re-search-backward
13366 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13367 (- (point) 20) t)))
13368 (apply 'encode-time (org-parse-time-string (match-string 1)))
13369 (current-time)))
13370 (default-input (and ts (org-get-compact-tod ts)))
13371 org-time-was-given org-end-time-was-given time)
13372 (cond
13373 ((and (org-at-timestamp-p t)
13374 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13375 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13376 (insert "--")
13377 (setq time (let ((this-command this-command))
13378 (org-read-date arg 'totime nil nil
13379 default-time default-input)))
13380 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13381 ((org-at-timestamp-p t)
13382 (setq time (let ((this-command this-command))
13383 (org-read-date arg 'totime nil nil default-time default-input)))
13384 (when (org-at-timestamp-p t) ; just to get the match data
13385 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13386 (replace-match "")
13387 (setq org-last-changed-timestamp
13388 (org-insert-time-stamp
13389 time (or org-time-was-given arg)
13390 inactive nil nil (list org-end-time-was-given))))
13391 (message "Timestamp updated"))
13393 (setq time (let ((this-command this-command))
13394 (org-read-date arg 'totime nil nil default-time default-input)))
13395 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13396 nil nil (list org-end-time-was-given))))))
13398 ;; FIXME: can we use this for something else, like computing time differences?
13399 (defun org-get-compact-tod (s)
13400 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13401 (let* ((t1 (match-string 1 s))
13402 (h1 (string-to-number (match-string 2 s)))
13403 (m1 (string-to-number (match-string 3 s)))
13404 (t2 (and (match-end 4) (match-string 5 s)))
13405 (h2 (and t2 (string-to-number (match-string 6 s))))
13406 (m2 (and t2 (string-to-number (match-string 7 s))))
13407 dh dm)
13408 (if (not t2)
13410 (setq dh (- h2 h1) dm (- m2 m1))
13411 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13412 (concat t1 "+" (number-to-string dh)
13413 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13415 (defun org-time-stamp-inactive (&optional arg)
13416 "Insert an inactive time stamp.
13417 An inactive time stamp is enclosed in square brackets instead of angle
13418 brackets. It is inactive in the sense that it does not trigger agenda entries,
13419 does not link to the calendar and cannot be changed with the S-cursor keys.
13420 So these are more for recording a certain time/date."
13421 (interactive "P")
13422 (org-time-stamp arg 'inactive))
13424 (defvar org-date-ovl (org-make-overlay 1 1))
13425 (org-overlay-put org-date-ovl 'face 'org-warning)
13426 (org-detach-overlay org-date-ovl)
13428 (defvar org-ans1) ; dynamically scoped parameter
13429 (defvar org-ans2) ; dynamically scoped parameter
13431 (defvar org-plain-time-of-day-regexp) ; defined below
13433 (defvar org-overriding-default-time nil) ; dynamically scoped
13434 (defvar org-read-date-overlay nil)
13435 (defvar org-dcst nil) ; dynamically scoped
13436 (defvar org-read-date-history nil)
13437 (defvar org-read-date-final-answer nil)
13439 (defun org-read-date (&optional with-time to-time from-string prompt
13440 default-time default-input)
13441 "Read a date, possibly a time, and make things smooth for the user.
13442 The prompt will suggest to enter an ISO date, but you can also enter anything
13443 which will at least partially be understood by `parse-time-string'.
13444 Unrecognized parts of the date will default to the current day, month, year,
13445 hour and minute. If this command is called to replace a timestamp at point,
13446 of to enter the second timestamp of a range, the default time is taken from the
13447 existing stamp. For example,
13448 3-2-5 --> 2003-02-05
13449 feb 15 --> currentyear-02-15
13450 sep 12 9 --> 2009-09-12
13451 12:45 --> today 12:45
13452 22 sept 0:34 --> currentyear-09-22 0:34
13453 12 --> currentyear-currentmonth-12
13454 Fri --> nearest Friday (today or later)
13455 etc.
13457 Furthermore you can specify a relative date by giving, as the *first* thing
13458 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13459 change in days weeks, months, years.
13460 With a single plus or minus, the date is relative to today. With a double
13461 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13462 +4d --> four days from today
13463 +4 --> same as above
13464 +2w --> two weeks from today
13465 ++5 --> five days from default date
13467 The function understands only English month and weekday abbreviations,
13468 but this can be configured with the variables `parse-time-months' and
13469 `parse-time-weekdays'.
13471 While prompting, a calendar is popped up - you can also select the
13472 date with the mouse (button 1). The calendar shows a period of three
13473 months. To scroll it to other months, use the keys `>' and `<'.
13474 If you don't like the calendar, turn it off with
13475 \(setq org-read-date-popup-calendar nil)
13477 With optional argument TO-TIME, the date will immediately be converted
13478 to an internal time.
13479 With an optional argument WITH-TIME, the prompt will suggest to also
13480 insert a time. Note that when WITH-TIME is not set, you can still
13481 enter a time, and this function will inform the calling routine about
13482 this change. The calling routine may then choose to change the format
13483 used to insert the time stamp into the buffer to include the time.
13484 With optional argument FROM-STRING, read from this string instead from
13485 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13486 the time/date that is used for everything that is not specified by the
13487 user."
13488 (require 'parse-time)
13489 (let* ((org-time-stamp-rounding-minutes
13490 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13491 (org-dcst org-display-custom-times)
13492 (ct (org-current-time))
13493 (def (or org-overriding-default-time default-time ct))
13494 (defdecode (decode-time def))
13495 (dummy (progn
13496 (when (< (nth 2 defdecode) org-extend-today-until)
13497 (setcar (nthcdr 2 defdecode) -1)
13498 (setcar (nthcdr 1 defdecode) 59)
13499 (setq def (apply 'encode-time defdecode)
13500 defdecode (decode-time def)))))
13501 (calendar-frame-setup nil)
13502 (calendar-move-hook nil)
13503 (calendar-view-diary-initially-flag nil)
13504 (view-diary-entries-initially nil)
13505 (calendar-view-holidays-initially-flag nil)
13506 (view-calendar-holidays-initially nil)
13507 (timestr (format-time-string
13508 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13509 (prompt (concat (if prompt (concat prompt " ") "")
13510 (format "Date+time [%s]: " timestr)))
13511 ans (org-ans0 "") org-ans1 org-ans2 final)
13513 (cond
13514 (from-string (setq ans from-string))
13515 (org-read-date-popup-calendar
13516 (save-excursion
13517 (save-window-excursion
13518 (calendar)
13519 (calendar-forward-day (- (time-to-days def)
13520 (calendar-absolute-from-gregorian
13521 (calendar-current-date))))
13522 (org-eval-in-calendar nil t)
13523 (let* ((old-map (current-local-map))
13524 (map (copy-keymap calendar-mode-map))
13525 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13526 (org-defkey map (kbd "RET") 'org-calendar-select)
13527 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13528 'org-calendar-select-mouse)
13529 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13530 'org-calendar-select-mouse)
13531 (org-defkey minibuffer-local-map [(meta shift left)]
13532 (lambda () (interactive)
13533 (org-eval-in-calendar '(calendar-backward-month 1))))
13534 (org-defkey minibuffer-local-map [(meta shift right)]
13535 (lambda () (interactive)
13536 (org-eval-in-calendar '(calendar-forward-month 1))))
13537 (org-defkey minibuffer-local-map [(meta shift up)]
13538 (lambda () (interactive)
13539 (org-eval-in-calendar '(calendar-backward-year 1))))
13540 (org-defkey minibuffer-local-map [(meta shift down)]
13541 (lambda () (interactive)
13542 (org-eval-in-calendar '(calendar-forward-year 1))))
13543 (org-defkey minibuffer-local-map [?\e (shift left)]
13544 (lambda () (interactive)
13545 (org-eval-in-calendar '(calendar-backward-month 1))))
13546 (org-defkey minibuffer-local-map [?\e (shift right)]
13547 (lambda () (interactive)
13548 (org-eval-in-calendar '(calendar-forward-month 1))))
13549 (org-defkey minibuffer-local-map [?\e (shift up)]
13550 (lambda () (interactive)
13551 (org-eval-in-calendar '(calendar-backward-year 1))))
13552 (org-defkey minibuffer-local-map [?\e (shift down)]
13553 (lambda () (interactive)
13554 (org-eval-in-calendar '(calendar-forward-year 1))))
13555 (org-defkey minibuffer-local-map [(shift up)]
13556 (lambda () (interactive)
13557 (org-eval-in-calendar '(calendar-backward-week 1))))
13558 (org-defkey minibuffer-local-map [(shift down)]
13559 (lambda () (interactive)
13560 (org-eval-in-calendar '(calendar-forward-week 1))))
13561 (org-defkey minibuffer-local-map [(shift left)]
13562 (lambda () (interactive)
13563 (org-eval-in-calendar '(calendar-backward-day 1))))
13564 (org-defkey minibuffer-local-map [(shift right)]
13565 (lambda () (interactive)
13566 (org-eval-in-calendar '(calendar-forward-day 1))))
13567 (org-defkey minibuffer-local-map ">"
13568 (lambda () (interactive)
13569 (org-eval-in-calendar '(scroll-calendar-left 1))))
13570 (org-defkey minibuffer-local-map "<"
13571 (lambda () (interactive)
13572 (org-eval-in-calendar '(scroll-calendar-right 1))))
13573 (run-hooks 'org-read-date-minibuffer-setup-hook)
13574 (unwind-protect
13575 (progn
13576 (use-local-map map)
13577 (add-hook 'post-command-hook 'org-read-date-display)
13578 (setq org-ans0 (read-string prompt default-input
13579 'org-read-date-history nil))
13580 ;; org-ans0: from prompt
13581 ;; org-ans1: from mouse click
13582 ;; org-ans2: from calendar motion
13583 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13584 (remove-hook 'post-command-hook 'org-read-date-display)
13585 (use-local-map old-map)
13586 (when org-read-date-overlay
13587 (org-delete-overlay org-read-date-overlay)
13588 (setq org-read-date-overlay nil)))))))
13590 (t ; Naked prompt only
13591 (unwind-protect
13592 (setq ans (read-string prompt default-input
13593 'org-read-date-history timestr))
13594 (when org-read-date-overlay
13595 (org-delete-overlay org-read-date-overlay)
13596 (setq org-read-date-overlay nil)))))
13598 (setq final (org-read-date-analyze ans def defdecode))
13599 (setq org-read-date-final-answer ans)
13601 (if to-time
13602 (apply 'encode-time final)
13603 (if (and (boundp 'org-time-was-given) org-time-was-given)
13604 (format "%04d-%02d-%02d %02d:%02d"
13605 (nth 5 final) (nth 4 final) (nth 3 final)
13606 (nth 2 final) (nth 1 final))
13607 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13609 (defvar def)
13610 (defvar defdecode)
13611 (defvar with-time)
13612 (defvar org-read-date-analyze-futurep nil)
13613 (defun org-read-date-display ()
13614 "Display the current date prompt interpretation in the minibuffer."
13615 (when org-read-date-display-live
13616 (when org-read-date-overlay
13617 (org-delete-overlay org-read-date-overlay))
13618 (let ((p (point)))
13619 (end-of-line 1)
13620 (while (not (equal (buffer-substring
13621 (max (point-min) (- (point) 4)) (point))
13622 " "))
13623 (insert " "))
13624 (goto-char p))
13625 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13626 " " (or org-ans1 org-ans2)))
13627 (org-end-time-was-given nil)
13628 (f (org-read-date-analyze ans def defdecode))
13629 (fmts (if org-dcst
13630 org-time-stamp-custom-formats
13631 org-time-stamp-formats))
13632 (fmt (if (or with-time
13633 (and (boundp 'org-time-was-given) org-time-was-given))
13634 (cdr fmts)
13635 (car fmts)))
13636 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13637 (when (and org-end-time-was-given
13638 (string-match org-plain-time-of-day-regexp txt))
13639 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13640 org-end-time-was-given
13641 (substring txt (match-end 0)))))
13642 (when org-read-date-analyze-futurep
13643 (setq txt (concat txt " (=>F)")))
13644 (setq org-read-date-overlay
13645 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13646 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13648 (defun org-read-date-analyze (ans def defdecode)
13649 "Analyse the combined answer of the date prompt."
13650 ;; FIXME: cleanup and comment
13651 (let ((nowdecode (decode-time (current-time)))
13652 delta deltan deltaw deltadef year month day
13653 hour minute second wday pm h2 m2 tl wday1
13654 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13655 (setq org-read-date-analyze-futurep nil)
13656 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13657 (setq ans "+0"))
13659 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13660 (setq ans (replace-match "" t t ans)
13661 deltan (car delta)
13662 deltaw (nth 1 delta)
13663 deltadef (nth 2 delta)))
13665 ;; Check if there is an iso week date in there
13666 ;; If yes, store the info and postpone interpreting it until the rest
13667 ;; of the parsing is done
13668 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13669 (setq iso-year (if (match-end 1)
13670 (org-small-year-to-year
13671 (string-to-number (match-string 1 ans))))
13672 iso-weekday (if (match-end 3)
13673 (string-to-number (match-string 3 ans)))
13674 iso-week (string-to-number (match-string 2 ans)))
13675 (setq ans (replace-match "" t t ans)))
13677 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13678 (when (string-match
13679 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13680 (setq year (if (match-end 2)
13681 (string-to-number (match-string 2 ans))
13682 (progn (setq kill-year t)
13683 (string-to-number (format-time-string "%Y"))))
13684 month (string-to-number (match-string 3 ans))
13685 day (string-to-number (match-string 4 ans)))
13686 (if (< year 100) (setq year (+ 2000 year)))
13687 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13688 t nil ans)))
13689 ;; Help matching american dates, like 5/30 or 5/30/7
13690 (when (string-match
13691 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13692 (setq year (if (match-end 4)
13693 (string-to-number (match-string 4 ans))
13694 (progn (setq kill-year t)
13695 (string-to-number (format-time-string "%Y"))))
13696 month (string-to-number (match-string 1 ans))
13697 day (string-to-number (match-string 2 ans)))
13698 (if (< year 100) (setq year (+ 2000 year)))
13699 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13700 t nil ans)))
13701 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13702 ;; If there is a time with am/pm, and *no* time without it, we convert
13703 ;; so that matching will be successful.
13704 (loop for i from 1 to 2 do ; twice, for end time as well
13705 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13706 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13707 (setq hour (string-to-number (match-string 1 ans))
13708 minute (if (match-end 3)
13709 (string-to-number (match-string 3 ans))
13711 pm (equal ?p
13712 (string-to-char (downcase (match-string 4 ans)))))
13713 (if (and (= hour 12) (not pm))
13714 (setq hour 0)
13715 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13716 (setq ans (replace-match (format "%02d:%02d" hour minute)
13717 t t ans))))
13719 ;; Check if a time range is given as a duration
13720 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13721 (setq hour (string-to-number (match-string 1 ans))
13722 h2 (+ hour (string-to-number (match-string 3 ans)))
13723 minute (string-to-number (match-string 2 ans))
13724 m2 (+ minute (if (match-end 5) (string-to-number
13725 (match-string 5 ans))0)))
13726 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13727 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13728 t t ans)))
13730 ;; Check if there is a time range
13731 (when (boundp 'org-end-time-was-given)
13732 (setq org-time-was-given nil)
13733 (when (and (string-match org-plain-time-of-day-regexp ans)
13734 (match-end 8))
13735 (setq org-end-time-was-given (match-string 8 ans))
13736 (setq ans (concat (substring ans 0 (match-beginning 7))
13737 (substring ans (match-end 7))))))
13739 (setq tl (parse-time-string ans)
13740 day (or (nth 3 tl) (nth 3 defdecode))
13741 month (or (nth 4 tl)
13742 (if (and org-read-date-prefer-future
13743 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13744 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13745 (nth 4 defdecode)))
13746 year (or (and (not kill-year) (nth 5 tl))
13747 (if (and org-read-date-prefer-future
13748 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13749 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13750 (nth 5 defdecode)))
13751 hour (or (nth 2 tl) (nth 2 defdecode))
13752 minute (or (nth 1 tl) (nth 1 defdecode))
13753 second (or (nth 0 tl) 0)
13754 wday (nth 6 tl))
13756 (when (and (eq org-read-date-prefer-future 'time)
13757 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13758 (equal day (nth 3 nowdecode))
13759 (equal month (nth 4 nowdecode))
13760 (equal year (nth 5 nowdecode))
13761 (nth 2 tl)
13762 (or (< (nth 2 tl) (nth 2 nowdecode))
13763 (and (= (nth 2 tl) (nth 2 nowdecode))
13764 (nth 1 tl)
13765 (< (nth 1 tl) (nth 1 nowdecode)))))
13766 (setq day (1+ day)
13767 futurep t))
13769 ;; Special date definitions below
13770 (cond
13771 (iso-week
13772 ;; There was an iso week
13773 (require 'cal-iso)
13774 (setq futurep nil)
13775 (setq year (or iso-year year)
13776 day (or iso-weekday wday 1)
13777 wday nil ; to make sure that the trigger below does not match
13778 iso-date (calendar-gregorian-from-absolute
13779 (calendar-absolute-from-iso
13780 (list iso-week day year))))
13781 ; FIXME: Should we also push ISO weeks into the future?
13782 ; (when (and org-read-date-prefer-future
13783 ; (not iso-year)
13784 ; (< (calendar-absolute-from-gregorian iso-date)
13785 ; (time-to-days (current-time))))
13786 ; (setq year (1+ year)
13787 ; iso-date (calendar-gregorian-from-absolute
13788 ; (calendar-absolute-from-iso
13789 ; (list iso-week day year)))))
13790 (setq month (car iso-date)
13791 year (nth 2 iso-date)
13792 day (nth 1 iso-date)))
13793 (deltan
13794 (setq futurep nil)
13795 (unless deltadef
13796 (let ((now (decode-time (current-time))))
13797 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13798 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13799 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13800 ((equal deltaw "m") (setq month (+ month deltan)))
13801 ((equal deltaw "y") (setq year (+ year deltan)))))
13802 ((and wday (not (nth 3 tl)))
13803 (setq futurep nil)
13804 ;; Weekday was given, but no day, so pick that day in the week
13805 ;; on or after the derived date.
13806 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13807 (unless (equal wday wday1)
13808 (setq day (+ day (% (- wday wday1 -7) 7))))))
13809 (if (and (boundp 'org-time-was-given)
13810 (nth 2 tl))
13811 (setq org-time-was-given t))
13812 (if (< year 100) (setq year (+ 2000 year)))
13813 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13814 (setq org-read-date-analyze-futurep futurep)
13815 (list second minute hour day month year)))
13817 (defvar parse-time-weekdays)
13819 (defun org-read-date-get-relative (s today default)
13820 "Check string S for special relative date string.
13821 TODAY and DEFAULT are internal times, for today and for a default.
13822 Return shift list (N what def-flag)
13823 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13824 N is the number of WHATs to shift.
13825 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13826 the DEFAULT date rather than TODAY."
13827 (when (and
13828 (string-match
13829 (concat
13830 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13831 "\\([0-9]+\\)?"
13832 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13833 "\\([ \t]\\|$\\)") s)
13834 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13835 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13836 (string-to-char (substring (match-string 1 s) -1))
13837 ?+))
13838 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13839 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13840 (what (if (match-end 3) (match-string 3 s) "d"))
13841 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13842 (date (if rel default today))
13843 (wday (nth 6 (decode-time date)))
13844 delta)
13845 (if wday1
13846 (progn
13847 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13848 (if (= dir ?-) (setq delta (- delta 7)))
13849 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13850 (list delta "d" rel))
13851 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13853 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13854 "Turn a user-specified date into the internal representation.
13855 The internal representation needed by the calendar is (month day year).
13856 This is a wrapper to handle the brain-dead convention in calendar that
13857 user function argument order change dependent on argument order."
13858 (if (boundp 'calendar-date-style)
13859 (cond
13860 ((eq calendar-date-style 'american)
13861 (list arg1 arg2 arg3))
13862 ((eq calendar-date-style 'european)
13863 (list arg2 arg1 arg3))
13864 ((eq calendar-date-style 'iso)
13865 (list arg2 arg3 arg1)))
13866 (if (org-bound-and-true-p european-calendar-style)
13867 (list arg2 arg1 arg3)
13868 (list arg1 arg2 arg3))))
13870 (defun org-eval-in-calendar (form &optional keepdate)
13871 "Eval FORM in the calendar window and return to current window.
13872 Also, store the cursor date in variable org-ans2."
13873 (let ((sf (selected-frame))
13874 (sw (selected-window)))
13875 (select-window (get-buffer-window "*Calendar*" t))
13876 (eval form)
13877 (when (and (not keepdate) (calendar-cursor-to-date))
13878 (let* ((date (calendar-cursor-to-date))
13879 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13880 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13881 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13882 (select-window sw)
13883 (org-select-frame-set-input-focus sf)))
13885 (defun org-calendar-select ()
13886 "Return to `org-read-date' with the date currently selected.
13887 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13888 (interactive)
13889 (when (calendar-cursor-to-date)
13890 (let* ((date (calendar-cursor-to-date))
13891 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13892 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13893 (if (active-minibuffer-window) (exit-minibuffer))))
13895 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13896 "Insert a date stamp for the date given by the internal TIME.
13897 WITH-HM means use the stamp format that includes the time of the day.
13898 INACTIVE means use square brackets instead of angular ones, so that the
13899 stamp will not contribute to the agenda.
13900 PRE and POST are optional strings to be inserted before and after the
13901 stamp.
13902 The command returns the inserted time stamp."
13903 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13904 stamp)
13905 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13906 (insert-before-markers (or pre ""))
13907 (insert-before-markers (setq stamp (format-time-string fmt time)))
13908 (when (listp extra)
13909 (setq extra (car extra))
13910 (if (and (stringp extra)
13911 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13912 (setq extra (format "-%02d:%02d"
13913 (string-to-number (match-string 1 extra))
13914 (string-to-number (match-string 2 extra))))
13915 (setq extra nil)))
13916 (when extra
13917 (backward-char 1)
13918 (insert-before-markers extra)
13919 (forward-char 1))
13920 (insert-before-markers (or post ""))
13921 (setq org-last-inserted-timestamp stamp)))
13923 (defun org-toggle-time-stamp-overlays ()
13924 "Toggle the use of custom time stamp formats."
13925 (interactive)
13926 (setq org-display-custom-times (not org-display-custom-times))
13927 (unless org-display-custom-times
13928 (let ((p (point-min)) (bmp (buffer-modified-p)))
13929 (while (setq p (next-single-property-change p 'display))
13930 (if (and (get-text-property p 'display)
13931 (eq (get-text-property p 'face) 'org-date))
13932 (remove-text-properties
13933 p (setq p (next-single-property-change p 'display))
13934 '(display t))))
13935 (set-buffer-modified-p bmp)))
13936 (if (featurep 'xemacs)
13937 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13938 (org-restart-font-lock)
13939 (setq org-table-may-need-update t)
13940 (if org-display-custom-times
13941 (message "Time stamps are overlayed with custom format")
13942 (message "Time stamp overlays removed")))
13944 (defun org-display-custom-time (beg end)
13945 "Overlay modified time stamp format over timestamp between BEG and END."
13946 (let* ((ts (buffer-substring beg end))
13947 t1 w1 with-hm tf time str w2 (off 0))
13948 (save-match-data
13949 (setq t1 (org-parse-time-string ts t))
13950 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13951 (setq off (- (match-end 0) (match-beginning 0)))))
13952 (setq end (- end off))
13953 (setq w1 (- end beg)
13954 with-hm (and (nth 1 t1) (nth 2 t1))
13955 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13956 time (org-fix-decoded-time t1)
13957 str (org-add-props
13958 (format-time-string
13959 (substring tf 1 -1) (apply 'encode-time time))
13960 nil 'mouse-face 'highlight)
13961 w2 (length str))
13962 (if (not (= w2 w1))
13963 (add-text-properties (1+ beg) (+ 2 beg)
13964 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13965 (if (featurep 'xemacs)
13966 (progn
13967 (put-text-property beg end 'invisible t)
13968 (put-text-property beg end 'end-glyph (make-glyph str)))
13969 (put-text-property beg end 'display str))))
13971 (defun org-translate-time (string)
13972 "Translate all timestamps in STRING to custom format.
13973 But do this only if the variable `org-display-custom-times' is set."
13974 (when org-display-custom-times
13975 (save-match-data
13976 (let* ((start 0)
13977 (re org-ts-regexp-both)
13978 t1 with-hm inactive tf time str beg end)
13979 (while (setq start (string-match re string start))
13980 (setq beg (match-beginning 0)
13981 end (match-end 0)
13982 t1 (save-match-data
13983 (org-parse-time-string (substring string beg end) t))
13984 with-hm (and (nth 1 t1) (nth 2 t1))
13985 inactive (equal (substring string beg (1+ beg)) "[")
13986 tf (funcall (if with-hm 'cdr 'car)
13987 org-time-stamp-custom-formats)
13988 time (org-fix-decoded-time t1)
13989 str (format-time-string
13990 (concat
13991 (if inactive "[" "<") (substring tf 1 -1)
13992 (if inactive "]" ">"))
13993 (apply 'encode-time time))
13994 string (replace-match str t t string)
13995 start (+ start (length str)))))))
13996 string)
13998 (defun org-fix-decoded-time (time)
13999 "Set 0 instead of nil for the first 6 elements of time.
14000 Don't touch the rest."
14001 (let ((n 0))
14002 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14004 (defun org-days-to-time (timestamp-string)
14005 "Difference between TIMESTAMP-STRING and now in days."
14006 (- (time-to-days (org-time-string-to-time timestamp-string))
14007 (time-to-days (current-time))))
14009 (defun org-deadline-close (timestamp-string &optional ndays)
14010 "Is the time in TIMESTAMP-STRING close to the current date?"
14011 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14012 (and (< (org-days-to-time timestamp-string) ndays)
14013 (not (org-entry-is-done-p))))
14015 (defun org-get-wdays (ts)
14016 "Get the deadline lead time appropriate for timestring TS."
14017 (cond
14018 ((<= org-deadline-warning-days 0)
14019 ;; 0 or negative, enforce this value no matter what
14020 (- org-deadline-warning-days))
14021 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14022 ;; lead time is specified.
14023 (floor (* (string-to-number (match-string 1 ts))
14024 (cdr (assoc (match-string 2 ts)
14025 '(("d" . 1) ("w" . 7)
14026 ("m" . 30.4) ("y" . 365.25)))))))
14027 ;; go for the default.
14028 (t org-deadline-warning-days)))
14030 (defun org-calendar-select-mouse (ev)
14031 "Return to `org-read-date' with the date currently selected.
14032 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14033 (interactive "e")
14034 (mouse-set-point ev)
14035 (when (calendar-cursor-to-date)
14036 (let* ((date (calendar-cursor-to-date))
14037 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14038 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14039 (if (active-minibuffer-window) (exit-minibuffer))))
14041 (defun org-check-deadlines (ndays)
14042 "Check if there are any deadlines due or past due.
14043 A deadline is considered due if it happens within `org-deadline-warning-days'
14044 days from today's date. If the deadline appears in an entry marked DONE,
14045 it is not shown. The prefix arg NDAYS can be used to test that many
14046 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14047 (interactive "P")
14048 (let* ((org-warn-days
14049 (cond
14050 ((equal ndays '(4)) 100000)
14051 (ndays (prefix-numeric-value ndays))
14052 (t (abs org-deadline-warning-days))))
14053 (case-fold-search nil)
14054 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14055 (callback
14056 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14058 (message "%d deadlines past-due or due within %d days"
14059 (org-occur regexp nil callback)
14060 org-warn-days)))
14062 (defun org-check-before-date (date)
14063 "Check if there are deadlines or scheduled entries before DATE."
14064 (interactive (list (org-read-date)))
14065 (let ((case-fold-search nil)
14066 (regexp (concat "\\<\\(" org-deadline-string
14067 "\\|" org-scheduled-string
14068 "\\) *<\\([^>]+\\)>"))
14069 (callback
14070 (lambda () (time-less-p
14071 (org-time-string-to-time (match-string 2))
14072 (org-time-string-to-time date)))))
14073 (message "%d entries before %s"
14074 (org-occur regexp nil callback) date)))
14076 (defun org-check-after-date (date)
14077 "Check if there are deadlines or scheduled entries after DATE."
14078 (interactive (list (org-read-date)))
14079 (let ((case-fold-search nil)
14080 (regexp (concat "\\<\\(" org-deadline-string
14081 "\\|" org-scheduled-string
14082 "\\) *<\\([^>]+\\)>"))
14083 (callback
14084 (lambda () (not
14085 (time-less-p
14086 (org-time-string-to-time (match-string 2))
14087 (org-time-string-to-time date))))))
14088 (message "%d entries after %s"
14089 (org-occur regexp nil callback) date)))
14091 (defun org-evaluate-time-range (&optional to-buffer)
14092 "Evaluate a time range by computing the difference between start and end.
14093 Normally the result is just printed in the echo area, but with prefix arg
14094 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14095 If the time range is actually in a table, the result is inserted into the
14096 next column.
14097 For time difference computation, a year is assumed to be exactly 365
14098 days in order to avoid rounding problems."
14099 (interactive "P")
14101 (org-clock-update-time-maybe)
14102 (save-excursion
14103 (unless (org-at-date-range-p t)
14104 (goto-char (point-at-bol))
14105 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14106 (if (not (org-at-date-range-p t))
14107 (error "Not at a time-stamp range, and none found in current line")))
14108 (let* ((ts1 (match-string 1))
14109 (ts2 (match-string 2))
14110 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14111 (match-end (match-end 0))
14112 (time1 (org-time-string-to-time ts1))
14113 (time2 (org-time-string-to-time ts2))
14114 (t1 (org-float-time time1))
14115 (t2 (org-float-time time2))
14116 (diff (abs (- t2 t1)))
14117 (negative (< (- t2 t1) 0))
14118 ;; (ys (floor (* 365 24 60 60)))
14119 (ds (* 24 60 60))
14120 (hs (* 60 60))
14121 (fy "%dy %dd %02d:%02d")
14122 (fy1 "%dy %dd")
14123 (fd "%dd %02d:%02d")
14124 (fd1 "%dd")
14125 (fh "%02d:%02d")
14126 y d h m align)
14127 (if havetime
14128 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14130 d (floor (/ diff ds)) diff (mod diff ds)
14131 h (floor (/ diff hs)) diff (mod diff hs)
14132 m (floor (/ diff 60)))
14133 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14135 d (floor (+ (/ diff ds) 0.5))
14136 h 0 m 0))
14137 (if (not to-buffer)
14138 (message "%s" (org-make-tdiff-string y d h m))
14139 (if (org-at-table-p)
14140 (progn
14141 (goto-char match-end)
14142 (setq align t)
14143 (and (looking-at " *|") (goto-char (match-end 0))))
14144 (goto-char match-end))
14145 (if (looking-at
14146 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14147 (replace-match ""))
14148 (if negative (insert " -"))
14149 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14150 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14151 (insert " " (format fh h m))))
14152 (if align (org-table-align))
14153 (message "Time difference inserted")))))
14155 (defun org-make-tdiff-string (y d h m)
14156 (let ((fmt "")
14157 (l nil))
14158 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14159 l (push y l)))
14160 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14161 l (push d l)))
14162 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14163 l (push h l)))
14164 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14165 l (push m l)))
14166 (apply 'format fmt (nreverse l))))
14168 (defun org-time-string-to-time (s)
14169 (apply 'encode-time (org-parse-time-string s)))
14170 (defun org-time-string-to-seconds (s)
14171 (org-float-time (org-time-string-to-time s)))
14173 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14174 "Convert a time stamp to an absolute day number.
14175 If there is a specifyer for a cyclic time stamp, get the closest date to
14176 DAYNR.
14177 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14178 the variable date is bound by the calendar when this is called."
14179 (cond
14180 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14181 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14182 daynr
14183 (+ daynr 1000)))
14184 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14185 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14186 (time-to-days (current-time))) (match-string 0 s)
14187 prefer show-all))
14188 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14190 (defun org-days-to-iso-week (days)
14191 "Return the iso week number."
14192 (require 'cal-iso)
14193 (car (calendar-iso-from-absolute days)))
14195 (defun org-small-year-to-year (year)
14196 "Convert 2-digit years into 4-digit years.
14197 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14198 The year 2000 cannot be abbreviated. Any year larger than 99
14199 is returned unchanged."
14200 (if (< year 38)
14201 (setq year (+ 2000 year))
14202 (if (< year 100)
14203 (setq year (+ 1900 year))))
14204 year)
14206 (defun org-time-from-absolute (d)
14207 "Return the time corresponding to date D.
14208 D may be an absolute day number, or a calendar-type list (month day year)."
14209 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14210 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14212 (defun org-calendar-holiday ()
14213 "List of holidays, for Diary display in Org-mode."
14214 (require 'holidays)
14215 (let ((hl (funcall
14216 (if (fboundp 'calendar-check-holidays)
14217 'calendar-check-holidays 'check-calendar-holidays) date)))
14218 (if hl (mapconcat 'identity hl "; "))))
14220 (defun org-diary-sexp-entry (sexp entry date)
14221 "Process a SEXP diary ENTRY for DATE."
14222 (require 'diary-lib)
14223 (let ((result (if calendar-debug-sexp
14224 (let ((stack-trace-on-error t))
14225 (eval (car (read-from-string sexp))))
14226 (condition-case nil
14227 (eval (car (read-from-string sexp)))
14228 (error
14229 (beep)
14230 (message "Bad sexp at line %d in %s: %s"
14231 (org-current-line)
14232 (buffer-file-name) sexp)
14233 (sleep-for 2))))))
14234 (cond ((stringp result) result)
14235 ((and (consp result)
14236 (stringp (cdr result))) (cdr result))
14237 (result entry)
14238 (t nil))))
14240 (defun org-diary-to-ical-string (frombuf)
14241 "Get iCalendar entries from diary entries in buffer FROMBUF.
14242 This uses the icalendar.el library."
14243 (let* ((tmpdir (if (featurep 'xemacs)
14244 (temp-directory)
14245 temporary-file-directory))
14246 (tmpfile (make-temp-name
14247 (expand-file-name "orgics" tmpdir)))
14248 buf rtn b e)
14249 (with-current-buffer frombuf
14250 (icalendar-export-region (point-min) (point-max) tmpfile)
14251 (setq buf (find-buffer-visiting tmpfile))
14252 (set-buffer buf)
14253 (goto-char (point-min))
14254 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14255 (setq b (match-beginning 0)))
14256 (goto-char (point-max))
14257 (if (re-search-backward "^END:VEVENT" nil t)
14258 (setq e (match-end 0)))
14259 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14260 (kill-buffer buf)
14261 (delete-file tmpfile)
14262 rtn))
14264 (defun org-closest-date (start current change prefer show-all)
14265 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14266 When PREFER is `past' return a date that is either CURRENT or past.
14267 When PREFER is `future', return a date that is either CURRENT or future.
14268 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14269 ;; Make the proper lists from the dates
14270 (catch 'exit
14271 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14272 dn dw sday cday n1 n2 n0
14273 d m y y1 y2 date1 date2 nmonths nm ny m2)
14275 (setq start (org-date-to-gregorian start)
14276 current (org-date-to-gregorian
14277 (if show-all
14278 current
14279 (time-to-days (current-time))))
14280 sday (calendar-absolute-from-gregorian start)
14281 cday (calendar-absolute-from-gregorian current))
14283 (if (<= cday sday) (throw 'exit sday))
14285 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14286 (setq dn (string-to-number (match-string 1 change))
14287 dw (cdr (assoc (match-string 2 change) a1)))
14288 (error "Invalid change specifyer: %s" change))
14289 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14290 (cond
14291 ((eq dw 'day)
14292 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14293 n2 (+ n1 dn)))
14294 ((eq dw 'year)
14295 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14296 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14297 (setq date1 (list m d y1)
14298 n1 (calendar-absolute-from-gregorian date1)
14299 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14300 n2 (calendar-absolute-from-gregorian date2)))
14301 ((eq dw 'month)
14302 ;; approx number of month between the two dates
14303 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14304 ;; How often does dn fit in there?
14305 (setq d (nth 1 start) m (car start) y (nth 2 start)
14306 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14307 m (+ m nm)
14308 ny (floor (/ m 12))
14309 y (+ y ny)
14310 m (- m (* ny 12)))
14311 (while (> m 12) (setq m (- m 12) y (1+ y)))
14312 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14313 (setq m2 (+ m dn) y2 y)
14314 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14315 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14316 (while (<= n2 cday)
14317 (setq n1 n2 m m2 y y2)
14318 (setq m2 (+ m dn) y2 y)
14319 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14320 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14321 ;; Make sure n1 is the earlier date
14322 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14323 (if show-all
14324 (cond
14325 ((eq prefer 'past) (if (= cday n2) n2 n1))
14326 ((eq prefer 'future) (if (= cday n1) n1 n2))
14327 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14328 (cond
14329 ((eq prefer 'past) (if (= cday n2) n2 n1))
14330 ((eq prefer 'future) (if (= cday n1) n1 n2))
14331 (t (if (= cday n1) n1 n2)))))))
14333 (defun org-date-to-gregorian (date)
14334 "Turn any specification of DATE into a gregorian date for the calendar."
14335 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14336 ((and (listp date) (= (length date) 3)) date)
14337 ((stringp date)
14338 (setq date (org-parse-time-string date))
14339 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14340 ((listp date)
14341 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14343 (defun org-parse-time-string (s &optional nodefault)
14344 "Parse the standard Org-mode time string.
14345 This should be a lot faster than the normal `parse-time-string'.
14346 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14347 hour and minute fields will be nil if not given."
14348 (if (string-match org-ts-regexp0 s)
14349 (list 0
14350 (if (or (match-beginning 8) (not nodefault))
14351 (string-to-number (or (match-string 8 s) "0")))
14352 (if (or (match-beginning 7) (not nodefault))
14353 (string-to-number (or (match-string 7 s) "0")))
14354 (string-to-number (match-string 4 s))
14355 (string-to-number (match-string 3 s))
14356 (string-to-number (match-string 2 s))
14357 nil nil nil)
14358 (error "Not a standard Org-mode time string: %s" s)))
14360 (defun org-timestamp-up (&optional arg)
14361 "Increase the date item at the cursor by one.
14362 If the cursor is on the year, change the year. If it is on the month or
14363 the day, change that.
14364 With prefix ARG, change by that many units."
14365 (interactive "p")
14366 (org-timestamp-change (prefix-numeric-value arg)))
14368 (defun org-timestamp-down (&optional arg)
14369 "Decrease the date item at the cursor by one.
14370 If the cursor is on the year, change the year. If it is on the month or
14371 the day, change that.
14372 With prefix ARG, change by that many units."
14373 (interactive "p")
14374 (org-timestamp-change (- (prefix-numeric-value arg))))
14376 (defun org-timestamp-up-day (&optional arg)
14377 "Increase the date in the time stamp by one day.
14378 With prefix ARG, change that many days."
14379 (interactive "p")
14380 (if (and (not (org-at-timestamp-p t))
14381 (org-on-heading-p))
14382 (org-todo 'up)
14383 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14385 (defun org-timestamp-down-day (&optional arg)
14386 "Decrease the date in the time stamp by one day.
14387 With prefix ARG, change that many days."
14388 (interactive "p")
14389 (if (and (not (org-at-timestamp-p t))
14390 (org-on-heading-p))
14391 (org-todo 'down)
14392 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14394 (defun org-at-timestamp-p (&optional inactive-ok)
14395 "Determine if the cursor is in or at a timestamp."
14396 (interactive)
14397 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14398 (pos (point))
14399 (ans (or (looking-at tsr)
14400 (save-excursion
14401 (skip-chars-backward "^[<\n\r\t")
14402 (if (> (point) (point-min)) (backward-char 1))
14403 (and (looking-at tsr)
14404 (> (- (match-end 0) pos) -1))))))
14405 (and ans
14406 (boundp 'org-ts-what)
14407 (setq org-ts-what
14408 (cond
14409 ((= pos (match-beginning 0)) 'bracket)
14410 ((= pos (1- (match-end 0))) 'bracket)
14411 ((org-pos-in-match-range pos 2) 'year)
14412 ((org-pos-in-match-range pos 3) 'month)
14413 ((org-pos-in-match-range pos 7) 'hour)
14414 ((org-pos-in-match-range pos 8) 'minute)
14415 ((or (org-pos-in-match-range pos 4)
14416 (org-pos-in-match-range pos 5)) 'day)
14417 ((and (> pos (or (match-end 8) (match-end 5)))
14418 (< pos (match-end 0)))
14419 (- pos (or (match-end 8) (match-end 5))))
14420 (t 'day))))
14421 ans))
14423 (defun org-toggle-timestamp-type ()
14424 "Toggle the type (<active> or [inactive]) of a time stamp."
14425 (interactive)
14426 (when (org-at-timestamp-p t)
14427 (let ((beg (match-beginning 0)) (end (match-end 0))
14428 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14429 (save-excursion
14430 (goto-char beg)
14431 (while (re-search-forward "[][<>]" end t)
14432 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14433 t t)))
14434 (message "Timestamp is now %sactive"
14435 (if (equal (char-after beg) ?<) "" "in")))))
14437 (defun org-timestamp-change (n &optional what)
14438 "Change the date in the time stamp at point.
14439 The date will be changed by N times WHAT. WHAT can be `day', `month',
14440 `year', `minute', `second'. If WHAT is not given, the cursor position
14441 in the timestamp determines what will be changed."
14442 (let ((pos (point))
14443 with-hm inactive
14444 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14445 org-ts-what
14446 extra rem
14447 ts time time0)
14448 (if (not (org-at-timestamp-p t))
14449 (error "Not at a timestamp"))
14450 (if (and (not what) (eq org-ts-what 'bracket))
14451 (org-toggle-timestamp-type)
14452 (if (and (not what) (not (eq org-ts-what 'day))
14453 org-display-custom-times
14454 (get-text-property (point) 'display)
14455 (not (get-text-property (1- (point)) 'display)))
14456 (setq org-ts-what 'day))
14457 (setq org-ts-what (or what org-ts-what)
14458 inactive (= (char-after (match-beginning 0)) ?\[)
14459 ts (match-string 0))
14460 (replace-match "")
14461 (if (string-match
14462 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14464 (setq extra (match-string 1 ts)))
14465 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14466 (setq with-hm t))
14467 (setq time0 (org-parse-time-string ts))
14468 (when (and (eq org-ts-what 'minute)
14469 (eq current-prefix-arg nil))
14470 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14471 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14472 (setcar (cdr time0) (+ (nth 1 time0)
14473 (if (> n 0) (- rem) (- dm rem))))))
14474 (setq time
14475 (encode-time (or (car time0) 0)
14476 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14477 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14478 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14479 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14480 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14481 (nthcdr 6 time0)))
14482 (when (and (member org-ts-what '(hour minute))
14483 extra
14484 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14485 (setq extra (org-modify-ts-extra
14486 extra
14487 (if (eq org-ts-what 'hour) 2 5)
14488 n dm)))
14489 (when (integerp org-ts-what)
14490 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14491 (if (eq what 'calendar)
14492 (let ((cal-date (org-get-date-from-calendar)))
14493 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14494 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14495 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14496 (setcar time0 (or (car time0) 0))
14497 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14498 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14499 (setq time (apply 'encode-time time0))))
14500 (setq org-last-changed-timestamp
14501 (org-insert-time-stamp time with-hm inactive nil nil extra))
14502 (org-clock-update-time-maybe)
14503 (goto-char pos)
14504 ;; Try to recenter the calendar window, if any
14505 (if (and org-calendar-follow-timestamp-change
14506 (get-buffer-window "*Calendar*" t)
14507 (memq org-ts-what '(day month year)))
14508 (org-recenter-calendar (time-to-days time))))))
14510 (defun org-modify-ts-extra (s pos n dm)
14511 "Change the different parts of the lead-time and repeat fields in timestamp."
14512 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14513 ng h m new rem)
14514 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14515 (cond
14516 ((or (org-pos-in-match-range pos 2)
14517 (org-pos-in-match-range pos 3))
14518 (setq m (string-to-number (match-string 3 s))
14519 h (string-to-number (match-string 2 s)))
14520 (if (org-pos-in-match-range pos 2)
14521 (setq h (+ h n))
14522 (setq n (* dm (org-no-warnings (signum n))))
14523 (when (not (= 0 (setq rem (% m dm))))
14524 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14525 (setq m (+ m n)))
14526 (if (< m 0) (setq m (+ m 60) h (1- h)))
14527 (if (> m 59) (setq m (- m 60) h (1+ h)))
14528 (setq h (min 24 (max 0 h)))
14529 (setq ng 1 new (format "-%02d:%02d" h m)))
14530 ((org-pos-in-match-range pos 6)
14531 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14532 ((org-pos-in-match-range pos 5)
14533 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14535 ((org-pos-in-match-range pos 9)
14536 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14537 ((org-pos-in-match-range pos 8)
14538 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14540 (when ng
14541 (setq s (concat
14542 (substring s 0 (match-beginning ng))
14544 (substring s (match-end ng))))))
14547 (defun org-recenter-calendar (date)
14548 "If the calendar is visible, recenter it to DATE."
14549 (let* ((win (selected-window))
14550 (cwin (get-buffer-window "*Calendar*" t))
14551 (calendar-move-hook nil))
14552 (when cwin
14553 (select-window cwin)
14554 (calendar-goto-date (if (listp date) date
14555 (calendar-gregorian-from-absolute date)))
14556 (select-window win))))
14558 (defun org-goto-calendar (&optional arg)
14559 "Go to the Emacs calendar at the current date.
14560 If there is a time stamp in the current line, go to that date.
14561 A prefix ARG can be used to force the current date."
14562 (interactive "P")
14563 (let ((tsr org-ts-regexp) diff
14564 (calendar-move-hook nil)
14565 (calendar-view-holidays-initially-flag nil)
14566 (view-calendar-holidays-initially nil)
14567 (calendar-view-diary-initially-flag nil)
14568 (view-diary-entries-initially nil))
14569 (if (or (org-at-timestamp-p)
14570 (save-excursion
14571 (beginning-of-line 1)
14572 (looking-at (concat ".*" tsr))))
14573 (let ((d1 (time-to-days (current-time)))
14574 (d2 (time-to-days
14575 (org-time-string-to-time (match-string 1)))))
14576 (setq diff (- d2 d1))))
14577 (calendar)
14578 (calendar-goto-today)
14579 (if (and diff (not arg)) (calendar-forward-day diff))))
14581 (defun org-get-date-from-calendar ()
14582 "Return a list (month day year) of date at point in calendar."
14583 (with-current-buffer "*Calendar*"
14584 (save-match-data
14585 (calendar-cursor-to-date))))
14587 (defun org-date-from-calendar ()
14588 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14589 If there is already a time stamp at the cursor position, update it."
14590 (interactive)
14591 (if (org-at-timestamp-p t)
14592 (org-timestamp-change 0 'calendar)
14593 (let ((cal-date (org-get-date-from-calendar)))
14594 (org-insert-time-stamp
14595 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14597 (defun org-minutes-to-hh:mm-string (m)
14598 "Compute H:MM from a number of minutes."
14599 (let ((h (/ m 60)))
14600 (setq m (- m (* 60 h)))
14601 (format org-time-clocksum-format h m)))
14603 (defun org-hh:mm-string-to-minutes (s)
14604 "Convert a string H:MM to a number of minutes.
14605 If the string is just a number, interpret it as minutes.
14606 In fact, the first hh:mm or number in the string will be taken,
14607 there can be extra stuff in the string.
14608 If no number is found, the return value is 0."
14609 (cond
14610 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14611 (+ (* (string-to-number (match-string 1 s)) 60)
14612 (string-to-number (match-string 2 s))))
14613 ((string-match "\\([0-9]+\\)" s)
14614 (string-to-number (match-string 1 s)))
14615 (t 0)))
14617 ;;;; Files
14619 (defun org-save-all-org-buffers ()
14620 "Save all Org-mode buffers without user confirmation."
14621 (interactive)
14622 (message "Saving all Org-mode buffers...")
14623 (save-some-buffers t 'org-mode-p)
14624 (when (featurep 'org-id) (org-id-locations-save))
14625 (message "Saving all Org-mode buffers... done"))
14627 (defun org-revert-all-org-buffers ()
14628 "Revert all Org-mode buffers.
14629 Prompt for confirmation when there are unsaved changes.
14630 Be sure you know what you are doing before letting this function
14631 overwrite your changes.
14633 This function is useful in a setup where one tracks org files
14634 with a version control system, to revert on one machine after pulling
14635 changes from another. I believe the procedure must be like this:
14637 1. M-x org-save-all-org-buffers
14638 2. Pull changes from the other machine, resolve conflicts
14639 3. M-x org-revert-all-org-buffers"
14640 (interactive)
14641 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14642 (error "Abort"))
14643 (save-excursion
14644 (save-window-excursion
14645 (mapc
14646 (lambda (b)
14647 (when (and (with-current-buffer b (org-mode-p))
14648 (with-current-buffer b buffer-file-name))
14649 (switch-to-buffer b)
14650 (revert-buffer t 'no-confirm)))
14651 (buffer-list))
14652 (when (and (featurep 'org-id) org-id-track-globally)
14653 (org-id-locations-load)))))
14655 ;;;; Agenda files
14657 ;;;###autoload
14658 (defun org-iswitchb (&optional arg)
14659 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14660 With a prefix argument, restrict available to files.
14661 With two prefix arguments, restrict available buffers to agenda files."
14662 (interactive "P")
14663 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14664 ((equal arg '(16)) (org-buffer-list 'agenda))
14665 (t (org-buffer-list)))))
14666 (switch-to-buffer
14667 (org-icompleting-read "Org buffer: "
14668 (mapcar 'list (mapcar 'buffer-name blist))
14669 nil t))))
14671 ;;;###autoload
14672 (defalias 'org-ido-switchb 'org-iswitchb)
14674 (defun org-buffer-list (&optional predicate exclude-tmp)
14675 "Return a list of Org buffers.
14676 PREDICATE can be `export', `files' or `agenda'.
14678 export restrict the list to Export buffers.
14679 files restrict the list to buffers visiting Org files.
14680 agenda restrict the list to buffers visiting agenda files.
14682 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14683 (let* ((bfn nil)
14684 (agenda-files (and (eq predicate 'agenda)
14685 (mapcar 'file-truename (org-agenda-files t))))
14686 (filter
14687 (cond
14688 ((eq predicate 'files)
14689 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14690 ((eq predicate 'export)
14691 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14692 ((eq predicate 'agenda)
14693 (lambda (b)
14694 (with-current-buffer b
14695 (and (eq major-mode 'org-mode)
14696 (setq bfn (buffer-file-name b))
14697 (member (file-truename bfn) agenda-files)))))
14698 (t (lambda (b) (with-current-buffer b
14699 (or (eq major-mode 'org-mode)
14700 (string-match "\*Org .*Export"
14701 (buffer-name b)))))))))
14702 (delq nil
14703 (mapcar
14704 (lambda(b)
14705 (if (and (funcall filter b)
14706 (or (not exclude-tmp)
14707 (not (string-match "tmp" (buffer-name b)))))
14709 nil))
14710 (buffer-list)))))
14712 (defun org-agenda-files (&optional unrestricted archives)
14713 "Get the list of agenda files.
14714 Optional UNRESTRICTED means return the full list even if a restriction
14715 is currently in place.
14716 When ARCHIVES is t, include all archive files that are really being
14717 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14718 `org-agenda-archives-mode' is t."
14719 (let ((files
14720 (cond
14721 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14722 ((stringp org-agenda-files) (org-read-agenda-file-list))
14723 ((listp org-agenda-files) org-agenda-files)
14724 (t (error "Invalid value of `org-agenda-files'")))))
14725 (setq files (apply 'append
14726 (mapcar (lambda (f)
14727 (if (file-directory-p f)
14728 (directory-files
14729 f t org-agenda-file-regexp)
14730 (list f)))
14731 files)))
14732 (when org-agenda-skip-unavailable-files
14733 (setq files (delq nil
14734 (mapcar (function
14735 (lambda (file)
14736 (and (file-readable-p file) file)))
14737 files))))
14738 (when (or (eq archives t)
14739 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14740 (setq files (org-add-archive-files files)))
14741 files))
14743 (defun org-edit-agenda-file-list ()
14744 "Edit the list of agenda files.
14745 Depending on setup, this either uses customize to edit the variable
14746 `org-agenda-files', or it visits the file that is holding the list. In the
14747 latter case, the buffer is set up in a way that saving it automatically kills
14748 the buffer and restores the previous window configuration."
14749 (interactive)
14750 (if (stringp org-agenda-files)
14751 (let ((cw (current-window-configuration)))
14752 (find-file org-agenda-files)
14753 (org-set-local 'org-window-configuration cw)
14754 (org-add-hook 'after-save-hook
14755 (lambda ()
14756 (set-window-configuration
14757 (prog1 org-window-configuration
14758 (kill-buffer (current-buffer))))
14759 (org-install-agenda-files-menu)
14760 (message "New agenda file list installed"))
14761 nil 'local)
14762 (message "%s" (substitute-command-keys
14763 "Edit list and finish with \\[save-buffer]")))
14764 (customize-variable 'org-agenda-files)))
14766 (defun org-store-new-agenda-file-list (list)
14767 "Set new value for the agenda file list and save it correctly."
14768 (if (stringp org-agenda-files)
14769 (let ((fe (org-read-agenda-file-list t)) b u)
14770 (while (setq b (find-buffer-visiting org-agenda-files))
14771 (kill-buffer b))
14772 (with-temp-file org-agenda-files
14773 (insert
14774 (mapconcat
14775 (lambda (f) ;; Keep un-expanded entries.
14776 (if (setq u (assoc f fe))
14777 (cdr u)
14779 list "\n")
14780 "\n")))
14781 (let ((org-mode-hook nil) (org-inhibit-startup t)
14782 (org-insert-mode-line-in-empty-file nil))
14783 (setq org-agenda-files list)
14784 (customize-save-variable 'org-agenda-files org-agenda-files))))
14786 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14787 "Read the list of agenda files from a file.
14788 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14789 filenames, used by `org-store-new-agenda-file-list' to write back
14790 un-expanded file names."
14791 (when (file-directory-p org-agenda-files)
14792 (error "`org-agenda-files' cannot be a single directory"))
14793 (when (stringp org-agenda-files)
14794 (with-temp-buffer
14795 (insert-file-contents org-agenda-files)
14796 (mapcar
14797 (lambda (f)
14798 (let ((e (expand-file-name (substitute-in-file-name f)
14799 org-directory)))
14800 (if pair-with-expansion
14801 (cons e f)
14802 e)))
14803 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14805 ;;;###autoload
14806 (defun org-cycle-agenda-files ()
14807 "Cycle through the files in `org-agenda-files'.
14808 If the current buffer visits an agenda file, find the next one in the list.
14809 If the current buffer does not, find the first agenda file."
14810 (interactive)
14811 (let* ((fs (org-agenda-files t))
14812 (files (append fs (list (car fs))))
14813 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14814 file)
14815 (unless files (error "No agenda files"))
14816 (catch 'exit
14817 (while (setq file (pop files))
14818 (if (equal (file-truename file) tcf)
14819 (when (car files)
14820 (find-file (car files))
14821 (throw 'exit t))))
14822 (find-file (car fs)))
14823 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14825 (defun org-agenda-file-to-front (&optional to-end)
14826 "Move/add the current file to the top of the agenda file list.
14827 If the file is not present in the list, it is added to the front. If it is
14828 present, it is moved there. With optional argument TO-END, add/move to the
14829 end of the list."
14830 (interactive "P")
14831 (let ((org-agenda-skip-unavailable-files nil)
14832 (file-alist (mapcar (lambda (x)
14833 (cons (file-truename x) x))
14834 (org-agenda-files t)))
14835 (ctf (file-truename buffer-file-name))
14836 x had)
14837 (setq x (assoc ctf file-alist) had x)
14839 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14840 (if to-end
14841 (setq file-alist (append (delq x file-alist) (list x)))
14842 (setq file-alist (cons x (delq x file-alist))))
14843 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14844 (org-install-agenda-files-menu)
14845 (message "File %s to %s of agenda file list"
14846 (if had "moved" "added") (if to-end "end" "front"))))
14848 (defun org-remove-file (&optional file)
14849 "Remove current file from the list of files in variable `org-agenda-files'.
14850 These are the files which are being checked for agenda entries.
14851 Optional argument FILE means use this file instead of the current."
14852 (interactive)
14853 (let* ((org-agenda-skip-unavailable-files nil)
14854 (file (or file buffer-file-name))
14855 (true-file (file-truename file))
14856 (afile (abbreviate-file-name file))
14857 (files (delq nil (mapcar
14858 (lambda (x)
14859 (if (equal true-file
14860 (file-truename x))
14861 nil x))
14862 (org-agenda-files t)))))
14863 (if (not (= (length files) (length (org-agenda-files t))))
14864 (progn
14865 (org-store-new-agenda-file-list files)
14866 (org-install-agenda-files-menu)
14867 (message "Removed file: %s" afile))
14868 (message "File was not in list: %s (not removed)" afile))))
14870 (defun org-file-menu-entry (file)
14871 (vector file (list 'find-file file) t))
14873 (defun org-check-agenda-file (file)
14874 "Make sure FILE exists. If not, ask user what to do."
14875 (when (not (file-exists-p file))
14876 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14877 (abbreviate-file-name file))
14878 (let ((r (downcase (read-char-exclusive))))
14879 (cond
14880 ((equal r ?r)
14881 (org-remove-file file)
14882 (throw 'nextfile t))
14883 (t (error "Abort"))))))
14885 (defun org-get-agenda-file-buffer (file)
14886 "Get a buffer visiting FILE. If the buffer needs to be created, add
14887 it to the list of buffers which might be released later."
14888 (let ((buf (org-find-base-buffer-visiting file)))
14889 (if buf
14890 buf ; just return it
14891 ;; Make a new buffer and remember it
14892 (setq buf (find-file-noselect file))
14893 (if buf (push buf org-agenda-new-buffers))
14894 buf)))
14896 (defun org-release-buffers (blist)
14897 "Release all buffers in list, asking the user for confirmation when needed.
14898 When a buffer is unmodified, it is just killed. When modified, it is saved
14899 \(if the user agrees) and then killed."
14900 (let (buf file)
14901 (while (setq buf (pop blist))
14902 (setq file (buffer-file-name buf))
14903 (when (and (buffer-modified-p buf)
14904 file
14905 (y-or-n-p (format "Save file %s? " file)))
14906 (with-current-buffer buf (save-buffer)))
14907 (kill-buffer buf))))
14909 (defun org-prepare-agenda-buffers (files)
14910 "Create buffers for all agenda files, protect archived trees and comments."
14911 (interactive)
14912 (let ((pa '(:org-archived t))
14913 (pc '(:org-comment t))
14914 (pall '(:org-archived t :org-comment t))
14915 (inhibit-read-only t)
14916 (rea (concat ":" org-archive-tag ":"))
14917 bmp file re)
14918 (save-excursion
14919 (save-restriction
14920 (while (setq file (pop files))
14921 (catch 'nextfile
14922 (if (bufferp file)
14923 (set-buffer file)
14924 (org-check-agenda-file file)
14925 (set-buffer (org-get-agenda-file-buffer file)))
14926 (widen)
14927 (setq bmp (buffer-modified-p))
14928 (org-refresh-category-properties)
14929 (setq org-todo-keywords-for-agenda
14930 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14931 (setq org-done-keywords-for-agenda
14932 (append org-done-keywords-for-agenda org-done-keywords))
14933 (setq org-todo-keyword-alist-for-agenda
14934 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14935 (setq org-drawers-for-agenda
14936 (append org-drawers-for-agenda org-drawers))
14937 (setq org-tag-alist-for-agenda
14938 (append org-tag-alist-for-agenda org-tag-alist))
14940 (save-excursion
14941 (remove-text-properties (point-min) (point-max) pall)
14942 (when org-agenda-skip-archived-trees
14943 (goto-char (point-min))
14944 (while (re-search-forward rea nil t)
14945 (if (org-on-heading-p t)
14946 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14947 (goto-char (point-min))
14948 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14949 (while (re-search-forward re nil t)
14950 (add-text-properties
14951 (match-beginning 0) (org-end-of-subtree t) pc)))
14952 (set-buffer-modified-p bmp)))))
14953 (setq org-todo-keyword-alist-for-agenda
14954 (org-uniquify org-todo-keyword-alist-for-agenda)
14955 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14957 ;;;; Embedded LaTeX
14959 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14960 "Keymap for the minor `org-cdlatex-mode'.")
14962 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14963 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14964 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14965 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14966 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14968 (defvar org-cdlatex-texmathp-advice-is-done nil
14969 "Flag remembering if we have applied the advice to texmathp already.")
14971 (define-minor-mode org-cdlatex-mode
14972 "Toggle the minor `org-cdlatex-mode'.
14973 This mode supports entering LaTeX environment and math in LaTeX fragments
14974 in Org-mode.
14975 \\{org-cdlatex-mode-map}"
14976 nil " OCDL" nil
14977 (when org-cdlatex-mode (require 'cdlatex))
14978 (unless org-cdlatex-texmathp-advice-is-done
14979 (setq org-cdlatex-texmathp-advice-is-done t)
14980 (defadvice texmathp (around org-math-always-on activate)
14981 "Always return t in org-mode buffers.
14982 This is because we want to insert math symbols without dollars even outside
14983 the LaTeX math segments. If Orgmode thinks that point is actually inside
14984 an embedded LaTeX fragment, let texmathp do its job.
14985 \\[org-cdlatex-mode-map]"
14986 (interactive)
14987 (let (p)
14988 (cond
14989 ((not (org-mode-p)) ad-do-it)
14990 ((eq this-command 'cdlatex-math-symbol)
14991 (setq ad-return-value t
14992 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14994 (let ((p (org-inside-LaTeX-fragment-p)))
14995 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14996 (setq ad-return-value t
14997 texmathp-why '("Org-mode embedded math" . 0))
14998 (if p ad-do-it)))))))))
15000 (defun turn-on-org-cdlatex ()
15001 "Unconditionally turn on `org-cdlatex-mode'."
15002 (org-cdlatex-mode 1))
15004 (defun org-inside-LaTeX-fragment-p ()
15005 "Test if point is inside a LaTeX fragment.
15006 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15007 sequence appearing also before point.
15008 Even though the matchers for math are configurable, this function assumes
15009 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15010 delimiters are skipped when they have been removed by customization.
15011 The return value is nil, or a cons cell with the delimiter and
15012 and the position of this delimiter.
15014 This function does a reasonably good job, but can locally be fooled by
15015 for example currency specifications. For example it will assume being in
15016 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15017 fragments that are properly closed, but during editing, we have to live
15018 with the uncertainty caused by missing closing delimiters. This function
15019 looks only before point, not after."
15020 (catch 'exit
15021 (let ((pos (point))
15022 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15023 (lim (progn
15024 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15025 (point)))
15026 dd-on str (start 0) m re)
15027 (goto-char pos)
15028 (when dodollar
15029 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15030 re (nth 1 (assoc "$" org-latex-regexps)))
15031 (while (string-match re str start)
15032 (cond
15033 ((= (match-end 0) (length str))
15034 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15035 ((= (match-end 0) (- (length str) 5))
15036 (throw 'exit nil))
15037 (t (setq start (match-end 0))))))
15038 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15039 (goto-char pos)
15040 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15041 (and (match-beginning 2) (throw 'exit nil))
15042 ;; count $$
15043 (while (re-search-backward "\\$\\$" lim t)
15044 (setq dd-on (not dd-on)))
15045 (goto-char pos)
15046 (if dd-on (cons "$$" m))))))
15048 (defun org-inside-latex-macro-p ()
15049 "Is point inside a LaTeX macro or its arguments?"
15050 (save-match-data
15051 (org-in-regexp
15052 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15054 (defun test ()
15055 (interactive)
15056 (message "%s" (org-inside-latex-macro-p)))
15058 (defun org-try-cdlatex-tab ()
15059 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15060 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15061 - inside a LaTeX fragment, or
15062 - after the first word in a line, where an abbreviation expansion could
15063 insert a LaTeX environment."
15064 (when org-cdlatex-mode
15065 (cond
15066 ((save-excursion
15067 (skip-chars-backward "a-zA-Z0-9*")
15068 (skip-chars-backward " \t")
15069 (bolp))
15070 (cdlatex-tab) t)
15071 ((org-inside-LaTeX-fragment-p)
15072 (cdlatex-tab) t)
15073 (t nil))))
15075 (defun org-cdlatex-underscore-caret (&optional arg)
15076 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15077 Revert to the normal definition outside of these fragments."
15078 (interactive "P")
15079 (if (org-inside-LaTeX-fragment-p)
15080 (call-interactively 'cdlatex-sub-superscript)
15081 (let (org-cdlatex-mode)
15082 (call-interactively (key-binding (vector last-input-event))))))
15084 (defun org-cdlatex-math-modify (&optional arg)
15085 "Execute `cdlatex-math-modify' in LaTeX fragments.
15086 Revert to the normal definition outside of these fragments."
15087 (interactive "P")
15088 (if (org-inside-LaTeX-fragment-p)
15089 (call-interactively 'cdlatex-math-modify)
15090 (let (org-cdlatex-mode)
15091 (call-interactively (key-binding (vector last-input-event))))))
15093 (defvar org-latex-fragment-image-overlays nil
15094 "List of overlays carrying the images of latex fragments.")
15095 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15097 (defun org-remove-latex-fragment-image-overlays ()
15098 "Remove all overlays with LaTeX fragment images in current buffer."
15099 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15100 (setq org-latex-fragment-image-overlays nil))
15102 (defun org-preview-latex-fragment (&optional subtree)
15103 "Preview the LaTeX fragment at point, or all locally or globally.
15104 If the cursor is in a LaTeX fragment, create the image and overlay
15105 it over the source code. If there is no fragment at point, display
15106 all fragments in the current text, from one headline to the next. With
15107 prefix SUBTREE, display all fragments in the current subtree. With a
15108 double prefix `C-u C-u', or when the cursor is before the first headline,
15109 display all fragments in the buffer.
15110 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15111 (interactive "P")
15112 (org-remove-latex-fragment-image-overlays)
15113 (save-excursion
15114 (save-restriction
15115 (let (beg end at msg)
15116 (cond
15117 ((or (equal subtree '(16))
15118 (not (save-excursion
15119 (re-search-backward (concat "^" outline-regexp) nil t))))
15120 (setq beg (point-min) end (point-max)
15121 msg "Creating images for buffer...%s"))
15122 ((equal subtree '(4))
15123 (org-back-to-heading)
15124 (setq beg (point) end (org-end-of-subtree t)
15125 msg "Creating images for subtree...%s"))
15127 (if (setq at (org-inside-LaTeX-fragment-p))
15128 (goto-char (max (point-min) (- (cdr at) 2)))
15129 (org-back-to-heading))
15130 (setq beg (point) end (progn (outline-next-heading) (point))
15131 msg (if at "Creating image...%s"
15132 "Creating images for entry...%s"))))
15133 (message msg "")
15134 (narrow-to-region beg end)
15135 (goto-char beg)
15136 (org-format-latex
15137 (concat "ltxpng/" (file-name-sans-extension
15138 (file-name-nondirectory
15139 buffer-file-name)))
15140 default-directory 'overlays msg at 'forbuffer)
15141 (message msg "done. Use `C-c C-c' to remove images.")))))
15143 (defvar org-latex-regexps
15144 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15145 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15146 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15147 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15148 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15149 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15150 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15151 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15152 "Regular expressions for matching embedded LaTeX.")
15154 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15155 "Replace LaTeX fragments with links to an image, and produce images.
15156 Some of the options can be changed using the variable
15157 `org-format-latex-options'."
15158 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15159 (let* ((prefixnodir (file-name-nondirectory prefix))
15160 (absprefix (expand-file-name prefix dir))
15161 (todir (file-name-directory absprefix))
15162 (opt org-format-latex-options)
15163 (matchers (plist-get opt :matchers))
15164 (re-list org-latex-regexps)
15165 (org-format-latex-header-extra
15166 (plist-get (org-infile-export-plist) :latex-header-extra))
15167 (cnt 0) txt hash link beg end re e checkdir
15168 executables-checked
15169 m n block linkfile movefile ov)
15170 ;; Check the different regular expressions
15171 (while (setq e (pop re-list))
15172 (setq m (car e) re (nth 1 e) n (nth 2 e)
15173 block (if (nth 3 e) "\n\n" ""))
15174 (when (member m matchers)
15175 (goto-char (point-min))
15176 (while (re-search-forward re nil t)
15177 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15178 (not (get-text-property (match-beginning n)
15179 'org-protected))
15180 (or (not overlays)
15181 (not (eq (get-char-property (match-beginning n)
15182 'org-overlay-type)
15183 'org-latex-overlay))))
15184 (setq txt (match-string n)
15185 beg (match-beginning n) end (match-end n)
15186 cnt (1+ cnt))
15187 (let (print-length print-level) ; make sure full list is printed
15188 (setq hash (sha1 (prin1-to-string
15189 (list org-format-latex-header
15190 org-format-latex-header-extra
15191 org-export-latex-default-packages-alist
15192 org-export-latex-packages-alist
15193 org-format-latex-options
15194 forbuffer txt)))
15195 linkfile (format "%s_%s.png" prefix hash)
15196 movefile (format "%s_%s.png" absprefix hash)))
15197 (setq link (concat block "[[file:" linkfile "]]" block))
15198 (if msg (message msg cnt))
15199 (goto-char beg)
15200 (unless checkdir ; make sure the directory exists
15201 (setq checkdir t)
15202 (or (file-directory-p todir) (make-directory todir)))
15204 (unless executables-checked
15205 (org-check-external-command
15206 "latex" "needed to convert LaTeX fragments to images")
15207 (org-check-external-command
15208 "dvipng" "needed to convert LaTeX fragments to images")
15209 (setq executables-checked t))
15211 (unless (file-exists-p movefile)
15212 (org-create-formula-image
15213 txt movefile opt forbuffer))
15214 (if overlays
15215 (progn
15216 (mapc (lambda (o)
15217 (if (eq (org-overlay-get o 'org-overlay-type)
15218 'org-latex-overlay)
15219 (org-delete-overlay o)))
15220 (org-overlays-in beg end))
15221 (setq ov (org-make-overlay beg end))
15222 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
15223 (if (featurep 'xemacs)
15224 (progn
15225 (org-overlay-put ov 'invisible t)
15226 (org-overlay-put
15227 ov 'end-glyph
15228 (make-glyph (vector 'png :file movefile))))
15229 (org-overlay-put
15230 ov 'display
15231 (list 'image :type 'png :file movefile :ascent 'center)))
15232 (push ov org-latex-fragment-image-overlays)
15233 (goto-char end))
15234 (delete-region beg end)
15235 (insert (org-add-props link
15236 (list 'org-latex-src
15237 (replace-regexp-in-string "\"" "" txt)))))))))))
15239 ;; This function borrows from Ganesh Swami's latex2png.el
15240 (defun org-create-formula-image (string tofile options buffer)
15241 "This calls dvipng."
15242 (require 'org-latex)
15243 (let* ((tmpdir (if (featurep 'xemacs)
15244 (temp-directory)
15245 temporary-file-directory))
15246 (texfilebase (make-temp-name
15247 (expand-file-name "orgtex" tmpdir)))
15248 (texfile (concat texfilebase ".tex"))
15249 (dvifile (concat texfilebase ".dvi"))
15250 (pngfile (concat texfilebase ".png"))
15251 (fnh (if (featurep 'xemacs)
15252 (font-height (get-face-font 'default))
15253 (face-attribute 'default :height nil)))
15254 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15255 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15256 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15257 "Black"))
15258 (bg (or (plist-get options (if buffer :background :html-background))
15259 "Transparent")))
15260 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15261 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15262 (with-temp-file texfile
15263 (insert (org-splice-latex-header
15264 org-format-latex-header
15265 org-export-latex-default-packages-alist
15266 org-export-latex-packages-alist
15267 org-format-latex-header-extra))
15268 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15269 (org-export-latex-fix-inputenc))
15270 (let ((dir default-directory))
15271 (condition-case nil
15272 (progn
15273 (cd tmpdir)
15274 (call-process "latex" nil nil nil texfile))
15275 (error nil))
15276 (cd dir))
15277 (if (not (file-exists-p dvifile))
15278 (progn (message "Failed to create dvi file from %s" texfile) nil)
15279 (condition-case nil
15280 (call-process "dvipng" nil nil nil
15281 "-fg" fg "-bg" bg
15282 "-D" dpi
15283 ;;"-x" scale "-y" scale
15284 "-T" "tight"
15285 "-o" pngfile
15286 dvifile)
15287 (error nil))
15288 (if (not (file-exists-p pngfile))
15289 (if org-format-latex-signal-error
15290 (error "Failed to create png file from %s" texfile)
15291 (message "Failed to create png file from %s" texfile)
15292 nil)
15293 ;; Use the requested file name and clean up
15294 (copy-file pngfile tofile 'replace)
15295 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15296 (delete-file (concat texfilebase e)))
15297 pngfile))))
15299 (defun org-splice-latex-header (template packages-1 packages-2 &optional extra)
15300 "Fill a LaTeX header template.
15301 If TEMPLATE contains the string \"[PACKAGES]\", this is where the packages
15302 in the lists PACKAGES-1 and PACKAGES-2 will be inserted, otherwise the come
15303 at the end. If EXTRA is a string, it is also appended."
15304 (let ((packages
15305 (and (or packages-1 packages-2)
15306 (mapconcat (lambda(p)
15307 (if (equal "" (car p))
15308 (format "\\usepackage{%s}" (cadr p))
15309 (format "\\usepackage[%s]{%s}"
15310 (car p) (cadr p))))
15311 (append packages-1 packages-2)
15312 "\n"))))
15313 (if (string-match "\\[PACKAGES\\]" template)
15314 (setq template (replace-match (or packages "") t t template))
15315 (setq template (concat template "\n" packages)))
15316 (if (and extra (string-match "\\S-" extra))
15317 (concat template "\n" extra)
15318 template)))
15320 (defun org-dvipng-color (attr)
15321 "Return an rgb color specification for dvipng."
15322 (apply 'format "rgb %s %s %s"
15323 (mapcar 'org-normalize-color
15324 (color-values (face-attribute 'default attr nil)))))
15326 (defun org-normalize-color (value)
15327 "Return string to be used as color value for an RGB component."
15328 (format "%g" (/ value 65535.0)))
15330 ;;;; Key bindings
15332 ;; Make `C-c C-x' a prefix key
15333 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15335 ;; TAB key with modifiers
15336 (org-defkey org-mode-map "\C-i" 'org-cycle)
15337 (org-defkey org-mode-map [(tab)] 'org-cycle)
15338 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15339 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15340 (org-defkey org-mode-map "\M-\t" 'org-complete)
15341 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15342 ;; The following line is necessary under Suse GNU/Linux
15343 (unless (featurep 'xemacs)
15344 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15345 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15346 (define-key org-mode-map [backtab] 'org-shifttab)
15348 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15349 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15350 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15352 ;; Cursor keys with modifiers
15353 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15354 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15355 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15356 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15358 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15359 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15360 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15361 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15363 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15364 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15365 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15366 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15368 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15369 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15371 ;;; Extra keys for tty access.
15372 ;; We only set them when really needed because otherwise the
15373 ;; menus don't show the simple keys
15375 (when (or org-use-extra-keys
15376 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15377 (not window-system))
15378 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15379 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15380 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15381 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15382 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15383 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15384 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15385 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15386 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15387 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15388 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15389 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15390 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15391 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15392 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15393 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15394 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15395 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15396 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15397 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15398 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15399 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15400 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15401 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15402 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15403 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15404 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15405 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15407 ;; All the other keys
15409 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15410 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15411 (if (boundp 'narrow-map)
15412 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15413 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15414 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15415 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15416 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15417 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15418 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15419 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15420 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15421 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15422 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15423 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15424 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15425 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15426 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15427 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15428 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15429 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15430 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15431 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15432 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15433 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15434 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15435 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15436 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15437 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15438 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15439 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15440 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15441 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15442 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15443 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15444 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15445 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15446 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15447 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15448 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15449 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15450 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15451 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15452 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15453 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15454 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15455 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15456 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15457 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15458 (org-defkey org-mode-map "\C-c^" 'org-sort)
15459 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15460 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15461 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15462 (org-defkey org-mode-map "\C-m" 'org-return)
15463 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15464 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15465 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15466 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15467 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15468 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15469 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15470 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15471 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15472 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15473 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15474 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15475 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15476 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15477 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15478 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15479 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15480 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15481 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15482 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15483 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15485 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15486 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15487 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15488 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15490 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15491 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15492 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15493 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15494 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15495 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15496 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15497 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15498 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15499 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15500 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15501 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15502 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15503 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15504 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15506 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15507 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15508 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15509 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15511 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15513 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15515 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15516 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15518 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15521 (when (featurep 'xemacs)
15522 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15525 (defconst org-speed-commands-default
15527 ("Outline Navigation")
15528 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15529 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15530 ("f" . (org-speed-move-safe 'org-forward-same-level))
15531 ("b" . (org-speed-move-safe 'org-backward-same-level))
15532 ("u" . (org-speed-move-safe 'outline-up-heading))
15533 ("j" . org-goto)
15534 ("g" . (org-refile t))
15535 ("Outline Visibility")
15536 ("c" . org-cycle)
15537 ("C" . org-shifttab)
15538 (" " . org-display-outline-path)
15539 ("Outline Structure Editing")
15540 ("U" . org-shiftmetaup)
15541 ("D" . org-shiftmetadown)
15542 ("r" . org-metaright)
15543 ("l" . org-metaleft)
15544 ("R" . org-shiftmetaright)
15545 ("L" . org-shiftmetaleft)
15546 ("i" . (progn (forward-char 1) (call-interactively
15547 'org-insert-heading-respect-content)))
15548 ("^" . org-sort)
15549 ("w" . org-refile)
15550 ("a" . org-archive-subtree-default-with-confirmation)
15551 ("." . outline-mark-subtree)
15552 ("Clock Commands")
15553 ("I" . org-clock-in)
15554 ("O" . org-clock-out)
15555 ("Meta Data Editing")
15556 ("t" . org-todo)
15557 ("0" . (org-priority ?\ ))
15558 ("1" . (org-priority ?A))
15559 ("2" . (org-priority ?B))
15560 ("3" . (org-priority ?C))
15561 (";" . org-set-tags-command)
15562 ("e" . org-set-effort)
15563 ("Agenda Views etc")
15564 ("v" . org-agenda)
15565 ("/" . org-sparse-tree)
15566 ("Misc")
15567 ("o" . org-open-at-point)
15568 ("?" . org-speed-command-help)
15570 "The default speed commands.")
15572 (defun org-print-speed-command (e)
15573 (if (> (length (car e)) 1)
15574 (progn
15575 (princ "\n")
15576 (princ (car e))
15577 (princ "\n")
15578 (princ (make-string (length (car e)) ?-))
15579 (princ "\n"))
15580 (princ (car e))
15581 (princ " ")
15582 (if (symbolp (cdr e))
15583 (princ (symbol-name (cdr e)))
15584 (prin1 (cdr e)))
15585 (princ "\n")))
15587 (defun org-speed-command-help ()
15588 "Show the available speed commands."
15589 (interactive)
15590 (if (not org-use-speed-commands)
15591 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15592 (with-output-to-temp-buffer "*Help*"
15593 (princ "User-defined Speed commands\n===========================\n")
15594 (mapc 'org-print-speed-command org-speed-commands-user)
15595 (princ "\n")
15596 (princ "Built-in Speed commands\n=======================\n")
15597 (mapc 'org-print-speed-command org-speed-commands-default))
15598 (with-current-buffer "*Help*"
15599 (setq truncate-lines t))))
15601 (defun org-speed-move-safe (cmd)
15602 "Execute CMD, but make sure that the cursor always ends up in a headline.
15603 If not, return to the original position and throw an error."
15604 (interactive)
15605 (let ((pos (point)))
15606 (call-interactively cmd)
15607 (unless (and (bolp) (org-on-heading-p))
15608 (goto-char pos)
15609 (error "Boundary reached while executing %s" cmd))))
15611 (defvar org-self-insert-command-undo-counter 0)
15613 (defvar org-table-auto-blank-field) ; defined in org-table.el
15614 (defvar org-speed-command nil)
15615 (defun org-self-insert-command (N)
15616 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15617 If the cursor is in a table looking at whitespace, the whitespace is
15618 overwritten, and the table is not marked as requiring realignment."
15619 (interactive "p")
15620 (cond
15621 ((and org-use-speed-commands
15622 (or (and (bolp) (looking-at outline-regexp))
15623 (and (functionp org-use-speed-commands)
15624 (funcall org-use-speed-commands)))
15625 (setq
15626 org-speed-command
15627 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15628 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15629 (cond
15630 ((commandp org-speed-command)
15631 (setq this-command org-speed-command)
15632 (call-interactively org-speed-command))
15633 ((functionp org-speed-command)
15634 (funcall org-speed-command))
15635 ((and org-speed-command (listp org-speed-command))
15636 (eval org-speed-command))
15637 (t (let (org-use-speed-commands)
15638 (call-interactively 'org-self-insert-command)))))
15639 ((and
15640 (org-table-p)
15641 (progn
15642 ;; check if we blank the field, and if that triggers align
15643 (and (featurep 'org-table) org-table-auto-blank-field
15644 (member last-command
15645 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15646 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15647 ;; got extra space, this field does not determine column width
15648 (let (org-table-may-need-update) (org-table-blank-field))
15649 ;; no extra space, this field may determine column width
15650 (org-table-blank-field)))
15652 (eq N 1)
15653 (looking-at "[^|\n]* |"))
15654 (let (org-table-may-need-update)
15655 (goto-char (1- (match-end 0)))
15656 (delete-backward-char 1)
15657 (goto-char (match-beginning 0))
15658 (self-insert-command N)))
15660 (setq org-table-may-need-update t)
15661 (self-insert-command N)
15662 (org-fix-tags-on-the-fly)
15663 (if org-self-insert-cluster-for-undo
15664 (if (not (eq last-command 'org-self-insert-command))
15665 (setq org-self-insert-command-undo-counter 1)
15666 (if (>= org-self-insert-command-undo-counter 20)
15667 (setq org-self-insert-command-undo-counter 1)
15668 (and (> org-self-insert-command-undo-counter 0)
15669 buffer-undo-list
15670 (not (cadr buffer-undo-list)) ; remove nil entry
15671 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15672 (setq org-self-insert-command-undo-counter
15673 (1+ org-self-insert-command-undo-counter))))))))
15675 (defun org-fix-tags-on-the-fly ()
15676 (when (and (equal (char-after (point-at-bol)) ?*)
15677 (org-on-heading-p))
15678 (org-align-tags-here org-tags-column)))
15680 (defun org-delete-backward-char (N)
15681 "Like `delete-backward-char', insert whitespace at field end in tables.
15682 When deleting backwards, in tables this function will insert whitespace in
15683 front of the next \"|\" separator, to keep the table aligned. The table will
15684 still be marked for re-alignment if the field did fill the entire column,
15685 because, in this case the deletion might narrow the column."
15686 (interactive "p")
15687 (if (and (org-table-p)
15688 (eq N 1)
15689 (string-match "|" (buffer-substring (point-at-bol) (point)))
15690 (looking-at ".*?|"))
15691 (let ((pos (point))
15692 (noalign (looking-at "[^|\n\r]* |"))
15693 (c org-table-may-need-update))
15694 (backward-delete-char N)
15695 (skip-chars-forward "^|")
15696 (insert " ")
15697 (goto-char (1- pos))
15698 ;; noalign: if there were two spaces at the end, this field
15699 ;; does not determine the width of the column.
15700 (if noalign (setq org-table-may-need-update c)))
15701 (backward-delete-char N)
15702 (org-fix-tags-on-the-fly)))
15704 (defun org-delete-char (N)
15705 "Like `delete-char', but insert whitespace at field end in tables.
15706 When deleting characters, in tables this function will insert whitespace in
15707 front of the next \"|\" separator, to keep the table aligned. The table will
15708 still be marked for re-alignment if the field did fill the entire column,
15709 because, in this case the deletion might narrow the column."
15710 (interactive "p")
15711 (if (and (org-table-p)
15712 (not (bolp))
15713 (not (= (char-after) ?|))
15714 (eq N 1))
15715 (if (looking-at ".*?|")
15716 (let ((pos (point))
15717 (noalign (looking-at "[^|\n\r]* |"))
15718 (c org-table-may-need-update))
15719 (replace-match (concat
15720 (substring (match-string 0) 1 -1)
15721 " |"))
15722 (goto-char pos)
15723 ;; noalign: if there were two spaces at the end, this field
15724 ;; does not determine the width of the column.
15725 (if noalign (setq org-table-may-need-update c)))
15726 (delete-char N))
15727 (delete-char N)
15728 (org-fix-tags-on-the-fly)))
15730 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15731 (put 'org-self-insert-command 'delete-selection t)
15732 (put 'orgtbl-self-insert-command 'delete-selection t)
15733 (put 'org-delete-char 'delete-selection 'supersede)
15734 (put 'org-delete-backward-char 'delete-selection 'supersede)
15735 (put 'org-yank 'delete-selection 'yank)
15737 ;; Make `flyspell-mode' delay after some commands
15738 (put 'org-self-insert-command 'flyspell-delayed t)
15739 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15740 (put 'org-delete-char 'flyspell-delayed t)
15741 (put 'org-delete-backward-char 'flyspell-delayed t)
15743 ;; Make pabbrev-mode expand after org-mode commands
15744 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15745 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15747 ;; How to do this: Measure non-white length of current string
15748 ;; If equal to column width, we should realign.
15750 (defun org-remap (map &rest commands)
15751 "In MAP, remap the functions given in COMMANDS.
15752 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15753 (let (new old)
15754 (while commands
15755 (setq old (pop commands) new (pop commands))
15756 (if (fboundp 'command-remapping)
15757 (org-defkey map (vector 'remap old) new)
15758 (substitute-key-definition old new map global-map)))))
15760 (when (eq org-enable-table-editor 'optimized)
15761 ;; If the user wants maximum table support, we need to hijack
15762 ;; some standard editing functions
15763 (org-remap org-mode-map
15764 'self-insert-command 'org-self-insert-command
15765 'delete-char 'org-delete-char
15766 'delete-backward-char 'org-delete-backward-char)
15767 (org-defkey org-mode-map "|" 'org-force-self-insert))
15769 (defvar org-ctrl-c-ctrl-c-hook nil
15770 "Hook for functions attaching themselves to `C-c C-c'.
15771 This can be used to add additional functionality to the C-c C-c key which
15772 executes context-dependent commands.
15773 Each function will be called with no arguments. The function must check
15774 if the context is appropriate for it to act. If yes, it should do its
15775 thing and then return a non-nil value. If the context is wrong,
15776 just do nothing and return nil.")
15778 (defvar org-tab-first-hook nil
15779 "Hook for functions to attach themselves to TAB.
15780 See `org-ctrl-c-ctrl-c-hook' for more information.
15781 This hook runs as the first action when TAB is pressed, even before
15782 `org-cycle' messes around with the `outline-regexp' to cater for
15783 inline tasks and plain list item folding.
15784 If any function in this hook returns t, not other actions like table
15785 field motion visibility cycling will be done.")
15787 (defvar org-tab-after-check-for-table-hook nil
15788 "Hook for functions to attach themselves to TAB.
15789 See `org-ctrl-c-ctrl-c-hook' for more information.
15790 This hook runs after it has been established that the cursor is not in a
15791 table, but before checking if the cursor is in a headline or if global cycling
15792 should be done.
15793 If any function in this hook returns t, not other actions like visibility
15794 cycling will be done.")
15796 (defvar org-tab-after-check-for-cycling-hook nil
15797 "Hook for functions to attach themselves to TAB.
15798 See `org-ctrl-c-ctrl-c-hook' for more information.
15799 This hook runs after it has been established that not table field motion and
15800 not visibility should be done because of current context. This is probably
15801 the place where a package like yasnippets can hook in.")
15803 (defvar org-tab-before-tab-emulation-hook nil
15804 "Hook for functions to attach themselves to TAB.
15805 See `org-ctrl-c-ctrl-c-hook' for more information.
15806 This hook runs after every other options for TAB have been exhausted, but
15807 before indentation and \t insertion takes place.")
15809 (defvar org-metaleft-hook nil
15810 "Hook for functions attaching themselves to `M-left'.
15811 See `org-ctrl-c-ctrl-c-hook' for more information.")
15812 (defvar org-metaright-hook nil
15813 "Hook for functions attaching themselves to `M-right'.
15814 See `org-ctrl-c-ctrl-c-hook' for more information.")
15815 (defvar org-metaup-hook nil
15816 "Hook for functions attaching themselves to `M-up'.
15817 See `org-ctrl-c-ctrl-c-hook' for more information.")
15818 (defvar org-metadown-hook nil
15819 "Hook for functions attaching themselves to `M-down'.
15820 See `org-ctrl-c-ctrl-c-hook' for more information.")
15821 (defvar org-shiftmetaleft-hook nil
15822 "Hook for functions attaching themselves to `M-S-left'.
15823 See `org-ctrl-c-ctrl-c-hook' for more information.")
15824 (defvar org-shiftmetaright-hook nil
15825 "Hook for functions attaching themselves to `M-S-right'.
15826 See `org-ctrl-c-ctrl-c-hook' for more information.")
15827 (defvar org-shiftmetaup-hook nil
15828 "Hook for functions attaching themselves to `M-S-up'.
15829 See `org-ctrl-c-ctrl-c-hook' for more information.")
15830 (defvar org-shiftmetadown-hook nil
15831 "Hook for functions attaching themselves to `M-S-down'.
15832 See `org-ctrl-c-ctrl-c-hook' for more information.")
15833 (defvar org-metareturn-hook nil
15834 "Hook for functions attaching themselves to `M-RET'.
15835 See `org-ctrl-c-ctrl-c-hook' for more information.")
15837 (defun org-modifier-cursor-error ()
15838 "Throw an error, a modified cursor command was applied in wrong context."
15839 (error "This command is active in special context like tables, headlines or items"))
15841 (defun org-shiftselect-error ()
15842 "Throw an error because Shift-Cursor command was applied in wrong context."
15843 (if (and (boundp 'shift-select-mode) shift-select-mode)
15844 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15845 (error "This command works only in special context like headlines or timestamps")))
15847 (defun org-call-for-shift-select (cmd)
15848 (let ((this-command-keys-shift-translated t))
15849 (call-interactively cmd)))
15851 (defun org-shifttab (&optional arg)
15852 "Global visibility cycling or move to previous table field.
15853 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15854 on context.
15855 See the individual commands for more information."
15856 (interactive "P")
15857 (cond
15858 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15859 ((integerp arg)
15860 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15861 (message "Content view to level: %d" arg)
15862 (org-content (prefix-numeric-value arg2))
15863 (setq org-cycle-global-status 'overview)))
15864 (t (call-interactively 'org-global-cycle))))
15866 (defun org-shiftmetaleft ()
15867 "Promote subtree or delete table column.
15868 Calls `org-promote-subtree', `org-outdent-item',
15869 or `org-table-delete-column', depending on context.
15870 See the individual commands for more information."
15871 (interactive)
15872 (cond
15873 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15874 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15875 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15876 ((org-at-item-p) (call-interactively 'org-outdent-item))
15877 (t (org-modifier-cursor-error))))
15879 (defun org-shiftmetaright ()
15880 "Demote subtree or insert table column.
15881 Calls `org-demote-subtree', `org-indent-item',
15882 or `org-table-insert-column', depending on context.
15883 See the individual commands for more information."
15884 (interactive)
15885 (cond
15886 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15887 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15888 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15889 ((org-at-item-p) (call-interactively 'org-indent-item))
15890 (t (org-modifier-cursor-error))))
15892 (defun org-shiftmetaup (&optional arg)
15893 "Move subtree up or kill table row.
15894 Calls `org-move-subtree-up' or `org-table-kill-row' or
15895 `org-move-item-up' depending on context. See the individual commands
15896 for more information."
15897 (interactive "P")
15898 (cond
15899 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15900 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15901 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15902 ((org-at-item-p) (call-interactively 'org-move-item-up))
15903 (t (org-modifier-cursor-error))))
15905 (defun org-shiftmetadown (&optional arg)
15906 "Move subtree down or insert table row.
15907 Calls `org-move-subtree-down' or `org-table-insert-row' or
15908 `org-move-item-down', depending on context. See the individual
15909 commands for more information."
15910 (interactive "P")
15911 (cond
15912 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15913 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15914 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15915 ((org-at-item-p) (call-interactively 'org-move-item-down))
15916 (t (org-modifier-cursor-error))))
15918 (defun org-metaleft (&optional arg)
15919 "Promote heading or move table column to left.
15920 Calls `org-do-promote' or `org-table-move-column', depending on context.
15921 With no specific context, calls the Emacs default `backward-word'.
15922 See the individual commands for more information."
15923 (interactive "P")
15924 (cond
15925 ((run-hook-with-args-until-success 'org-metaleft-hook))
15926 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15927 ((or (org-on-heading-p)
15928 (and (org-region-active-p)
15929 (save-excursion
15930 (goto-char (region-beginning))
15931 (org-on-heading-p))))
15932 (call-interactively 'org-do-promote))
15933 ((or (org-at-item-p)
15934 (and (org-region-active-p)
15935 (save-excursion
15936 (goto-char (region-beginning))
15937 (org-at-item-p))))
15938 (call-interactively 'org-outdent-item))
15939 (t (call-interactively 'backward-word))))
15941 (defun org-metaright (&optional arg)
15942 "Demote subtree or move table column to right.
15943 Calls `org-do-demote' or `org-table-move-column', depending on context.
15944 With no specific context, calls the Emacs default `forward-word'.
15945 See the individual commands for more information."
15946 (interactive "P")
15947 (cond
15948 ((run-hook-with-args-until-success 'org-metaright-hook))
15949 ((org-at-table-p) (call-interactively 'org-table-move-column))
15950 ((or (org-on-heading-p)
15951 (and (org-region-active-p)
15952 (save-excursion
15953 (goto-char (region-beginning))
15954 (org-on-heading-p))))
15955 (call-interactively 'org-do-demote))
15956 ((or (org-at-item-p)
15957 (and (org-region-active-p)
15958 (save-excursion
15959 (goto-char (region-beginning))
15960 (org-at-item-p))))
15961 (call-interactively 'org-indent-item))
15962 (t (call-interactively 'forward-word))))
15964 (defun org-metaup (&optional arg)
15965 "Move subtree up or move table row up.
15966 Calls `org-move-subtree-up' or `org-table-move-row' or
15967 `org-move-item-up', depending on context. See the individual commands
15968 for more information."
15969 (interactive "P")
15970 (cond
15971 ((run-hook-with-args-until-success 'org-metaup-hook))
15972 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15973 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15974 ((org-at-item-p) (call-interactively 'org-move-item-up))
15975 (t (transpose-lines 1) (beginning-of-line -1))))
15977 (defun org-metadown (&optional arg)
15978 "Move subtree down or move table row down.
15979 Calls `org-move-subtree-down' or `org-table-move-row' or
15980 `org-move-item-down', depending on context. See the individual
15981 commands for more information."
15982 (interactive "P")
15983 (cond
15984 ((run-hook-with-args-until-success 'org-metadown-hook))
15985 ((org-at-table-p) (call-interactively 'org-table-move-row))
15986 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15987 ((org-at-item-p) (call-interactively 'org-move-item-down))
15988 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15990 (defun org-shiftup (&optional arg)
15991 "Increase item in timestamp or increase priority of current headline.
15992 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15993 depending on context. See the individual commands for more information."
15994 (interactive "P")
15995 (cond
15996 ((and org-support-shift-select (org-region-active-p))
15997 (org-call-for-shift-select 'previous-line))
15998 ((org-at-timestamp-p t)
15999 (call-interactively (if org-edit-timestamp-down-means-later
16000 'org-timestamp-down 'org-timestamp-up)))
16001 ((and (not (eq org-support-shift-select 'always))
16002 org-enable-priority-commands
16003 (org-on-heading-p))
16004 (call-interactively 'org-priority-up))
16005 ((and (not org-support-shift-select) (org-at-item-p))
16006 (call-interactively 'org-previous-item))
16007 ((org-clocktable-try-shift 'up arg))
16008 (org-support-shift-select
16009 (org-call-for-shift-select 'previous-line))
16010 (t (org-shiftselect-error))))
16012 (defun org-shiftdown (&optional arg)
16013 "Decrease item in timestamp or decrease priority of current headline.
16014 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16015 depending on context. See the individual commands for more information."
16016 (interactive "P")
16017 (cond
16018 ((and org-support-shift-select (org-region-active-p))
16019 (org-call-for-shift-select 'next-line))
16020 ((org-at-timestamp-p t)
16021 (call-interactively (if org-edit-timestamp-down-means-later
16022 'org-timestamp-up 'org-timestamp-down)))
16023 ((and (not (eq org-support-shift-select 'always))
16024 org-enable-priority-commands
16025 (org-on-heading-p))
16026 (call-interactively 'org-priority-down))
16027 ((and (not org-support-shift-select) (org-at-item-p))
16028 (call-interactively 'org-next-item))
16029 ((org-clocktable-try-shift 'down arg))
16030 (org-support-shift-select
16031 (org-call-for-shift-select 'next-line))
16032 (t (org-shiftselect-error))))
16034 (defun org-shiftright (&optional arg)
16035 "Cycle the thing at point or in the current line, depending on context.
16036 Depending on context, this does one of the following:
16038 - switch a timestamp at point one day into the future
16039 - on a headline, switch to the next TODO keyword.
16040 - on an item, switch entire list to the next bullet type
16041 - on a property line, switch to the next allowed value
16042 - on a clocktable definition line, move time block into the future"
16043 (interactive "P")
16044 (cond
16045 ((and org-support-shift-select (org-region-active-p))
16046 (org-call-for-shift-select 'forward-char))
16047 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16048 ((and (not (eq org-support-shift-select 'always))
16049 (org-on-heading-p))
16050 (let ((org-inhibit-logging
16051 (not org-treat-S-cursor-todo-selection-as-state-change))
16052 (org-inhibit-blocking
16053 (not org-treat-S-cursor-todo-selection-as-state-change)))
16054 (org-call-with-arg 'org-todo 'right)))
16055 ((or (and org-support-shift-select
16056 (not (eq org-support-shift-select 'always))
16057 (org-at-item-bullet-p))
16058 (and (not org-support-shift-select) (org-at-item-p)))
16059 (org-call-with-arg 'org-cycle-list-bullet nil))
16060 ((and (not (eq org-support-shift-select 'always))
16061 (org-at-property-p))
16062 (call-interactively 'org-property-next-allowed-value))
16063 ((org-clocktable-try-shift 'right arg))
16064 (org-support-shift-select
16065 (org-call-for-shift-select 'forward-char))
16066 (t (org-shiftselect-error))))
16068 (defun org-shiftleft (&optional arg)
16069 "Cycle the thing at point or in the current line, depending on context.
16070 Depending on context, this does one of the following:
16072 - switch a timestamp at point one day into the past
16073 - on a headline, switch to the previous TODO keyword.
16074 - on an item, switch entire list to the previous bullet type
16075 - on a property line, switch to the previous allowed value
16076 - on a clocktable definition line, move time block into the past"
16077 (interactive "P")
16078 (cond
16079 ((and org-support-shift-select (org-region-active-p))
16080 (org-call-for-shift-select 'backward-char))
16081 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16082 ((and (not (eq org-support-shift-select 'always))
16083 (org-on-heading-p))
16084 (let ((org-inhibit-logging
16085 (not org-treat-S-cursor-todo-selection-as-state-change))
16086 (org-inhibit-blocking
16087 (not org-treat-S-cursor-todo-selection-as-state-change)))
16088 (org-call-with-arg 'org-todo 'left)))
16089 ((or (and org-support-shift-select
16090 (not (eq org-support-shift-select 'always))
16091 (org-at-item-bullet-p))
16092 (and (not org-support-shift-select) (org-at-item-p)))
16093 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16094 ((and (not (eq org-support-shift-select 'always))
16095 (org-at-property-p))
16096 (call-interactively 'org-property-previous-allowed-value))
16097 ((org-clocktable-try-shift 'left arg))
16098 (org-support-shift-select
16099 (org-call-for-shift-select 'backward-char))
16100 (t (org-shiftselect-error))))
16102 (defun org-shiftcontrolright ()
16103 "Switch to next TODO set."
16104 (interactive)
16105 (cond
16106 ((and org-support-shift-select (org-region-active-p))
16107 (org-call-for-shift-select 'forward-word))
16108 ((and (not (eq org-support-shift-select 'always))
16109 (org-on-heading-p))
16110 (org-call-with-arg 'org-todo 'nextset))
16111 (org-support-shift-select
16112 (org-call-for-shift-select 'forward-word))
16113 (t (org-shiftselect-error))))
16115 (defun org-shiftcontrolleft ()
16116 "Switch to previous TODO set."
16117 (interactive)
16118 (cond
16119 ((and org-support-shift-select (org-region-active-p))
16120 (org-call-for-shift-select 'backward-word))
16121 ((and (not (eq org-support-shift-select 'always))
16122 (org-on-heading-p))
16123 (org-call-with-arg 'org-todo 'previousset))
16124 (org-support-shift-select
16125 (org-call-for-shift-select 'backward-word))
16126 (t (org-shiftselect-error))))
16128 (defun org-ctrl-c-ret ()
16129 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16130 (interactive)
16131 (cond
16132 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16133 (t (call-interactively 'org-insert-heading))))
16135 (defun org-copy-special ()
16136 "Copy region in table or copy current subtree.
16137 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16138 See the individual commands for more information."
16139 (interactive)
16140 (call-interactively
16141 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16143 (defun org-cut-special ()
16144 "Cut region in table or cut current subtree.
16145 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16146 See the individual commands for more information."
16147 (interactive)
16148 (call-interactively
16149 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16151 (defun org-paste-special (arg)
16152 "Paste rectangular region into table, or past subtree relative to level.
16153 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16154 See the individual commands for more information."
16155 (interactive "P")
16156 (if (org-at-table-p)
16157 (org-table-paste-rectangle)
16158 (org-paste-subtree arg)))
16160 (defun org-edit-special ()
16161 "Call a special editor for the stuff at point.
16162 When at a table, call the formula editor with `org-table-edit-formulas'.
16163 When at the first line of an src example, call `org-edit-src-code'.
16164 When in an #+include line, visit the include file. Otherwise call
16165 `ffap' to visit the file at point."
16166 (interactive)
16167 (cond
16168 ((org-at-table.el-p)
16169 (org-edit-src-code))
16170 ((org-at-table-p)
16171 (call-interactively 'org-table-edit-formulas))
16172 ((save-excursion
16173 (beginning-of-line 1)
16174 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16175 (find-file (org-trim (match-string 1))))
16176 ((org-edit-src-code))
16177 ((org-edit-fixed-width-region))
16178 (t (call-interactively 'ffap))))
16181 (defun org-ctrl-c-ctrl-c (&optional arg)
16182 "Set tags in headline, or update according to changed information at point.
16184 This command does many different things, depending on context:
16186 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16187 this is what we do.
16189 - If the cursor is on a statistics cookie, update it.
16191 - If the cursor is in a headline, prompt for tags and insert them
16192 into the current line, aligned to `org-tags-column'. When called
16193 with prefix arg, realign all tags in the current buffer.
16195 - If the cursor is in one of the special #+KEYWORD lines, this
16196 triggers scanning the buffer for these lines and updating the
16197 information.
16199 - If the cursor is inside a table, realign the table. This command
16200 works even if the automatic table editor has been turned off.
16202 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16203 the entire table.
16205 - If the cursor is at a footnote reference or definition, jump to
16206 the corresponding definition or references, respectively.
16208 - If the cursor is a the beginning of a dynamic block, update it.
16210 - If the current buffer is a remember buffer, close note and file
16211 it. A prefix argument of 1 files to the default location
16212 without further interaction. A prefix argument of 2 files to
16213 the currently clocking task.
16215 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16216 links in this buffer.
16218 - If the cursor is on a numbered item in a plain list, renumber the
16219 ordered list.
16221 - If the cursor is on a checkbox, toggle it."
16222 (interactive "P")
16223 (let ((org-enable-table-editor t))
16224 (cond
16225 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16226 org-occur-highlights
16227 org-latex-fragment-image-overlays)
16228 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16229 (org-remove-occur-highlights)
16230 (org-remove-latex-fragment-image-overlays)
16231 (message "Temporary highlights/overlays removed from current buffer"))
16232 ((and (local-variable-p 'org-finish-function (current-buffer))
16233 (fboundp org-finish-function))
16234 (funcall org-finish-function))
16235 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16236 ((or (looking-at (org-re org-property-start-re))
16237 (org-at-property-p))
16238 (call-interactively 'org-property-action))
16239 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16240 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16241 (or (org-on-heading-p) (org-at-item-p)))
16242 (call-interactively 'org-update-statistics-cookies))
16243 ((org-on-heading-p) (call-interactively 'org-set-tags))
16244 ((org-at-table.el-p)
16245 (message "Use C-c ' to edit table.el tables"))
16246 ((org-at-table-p)
16247 (org-table-maybe-eval-formula)
16248 (if arg
16249 (call-interactively 'org-table-recalculate)
16250 (org-table-maybe-recalculate-line))
16251 (call-interactively 'org-table-align))
16252 ((or (org-footnote-at-reference-p)
16253 (org-footnote-at-definition-p))
16254 (call-interactively 'org-footnote-action))
16255 ((org-at-item-checkbox-p)
16256 (call-interactively 'org-toggle-checkbox))
16257 ((org-at-item-p)
16258 (if arg
16259 (call-interactively 'org-toggle-checkbox)
16260 (call-interactively 'org-maybe-renumber-ordered-list)))
16261 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16262 ;; Dynamic block
16263 (beginning-of-line 1)
16264 (save-excursion (org-update-dblock)))
16265 ((save-excursion
16266 (beginning-of-line 1)
16267 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16268 (cond
16269 ((equal (match-string 1) "TBLFM")
16270 ;; Recalculate the table before this line
16271 (save-excursion
16272 (beginning-of-line 1)
16273 (skip-chars-backward " \r\n\t")
16274 (if (org-at-table-p)
16275 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16277 (let ((org-inhibit-startup-visibility-stuff t)
16278 (org-startup-align-all-tables nil))
16279 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16280 (message "Local setup has been refreshed"))))
16281 ((org-clock-update-time-maybe))
16282 (t (error "C-c C-c can do nothing useful at this location")))))
16284 (defun org-mode-restart ()
16285 "Restart Org-mode, to scan again for special lines.
16286 Also updates the keyword regular expressions."
16287 (interactive)
16288 (org-mode)
16289 (message "Org-mode restarted"))
16291 (defun org-kill-note-or-show-branches ()
16292 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16293 (interactive)
16294 (if (not org-finish-function)
16295 (call-interactively 'show-branches)
16296 (let ((org-note-abort t))
16297 (funcall org-finish-function))))
16299 (defun org-return (&optional indent)
16300 "Goto next table row or insert a newline.
16301 Calls `org-table-next-row' or `newline', depending on context.
16302 See the individual commands for more information."
16303 (interactive)
16304 (cond
16305 ((bobp) (if indent (newline-and-indent) (newline)))
16306 ((org-at-table-p)
16307 (org-table-justify-field-maybe)
16308 (call-interactively 'org-table-next-row))
16309 ((and org-return-follows-link
16310 (eq (get-text-property (point) 'face) 'org-link))
16311 (call-interactively 'org-open-at-point))
16312 ((and (org-at-heading-p)
16313 (looking-at
16314 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16315 (org-show-entry)
16316 (end-of-line 1)
16317 (newline))
16318 (t (if indent (newline-and-indent) (newline)))))
16320 (defun org-return-indent ()
16321 "Goto next table row or insert a newline and indent.
16322 Calls `org-table-next-row' or `newline-and-indent', depending on
16323 context. See the individual commands for more information."
16324 (interactive)
16325 (org-return t))
16327 (defun org-ctrl-c-star ()
16328 "Compute table, or change heading status of lines.
16329 Calls `org-table-recalculate' or `org-toggle-heading',
16330 depending on context."
16331 (interactive)
16332 (cond
16333 ((org-at-table-p)
16334 (call-interactively 'org-table-recalculate))
16336 ;; Convert all lines in region to list items
16337 (call-interactively 'org-toggle-heading))))
16339 (defun org-ctrl-c-minus ()
16340 "Insert separator line in table or modify bullet status of line.
16341 Also turns a plain line or a region of lines into list items.
16342 Calls `org-table-insert-hline', `org-toggle-item', or
16343 `org-cycle-list-bullet', depending on context."
16344 (interactive)
16345 (cond
16346 ((org-at-table-p)
16347 (call-interactively 'org-table-insert-hline))
16348 ((org-region-active-p)
16349 (call-interactively 'org-toggle-item))
16350 ((org-in-item-p)
16351 (call-interactively 'org-cycle-list-bullet))
16353 (call-interactively 'org-toggle-item))))
16355 (defun org-toggle-item ()
16356 "Convert headings or normal lines to items, items to normal lines.
16357 If there is no active region, only the current line is considered.
16359 If the first line in the region is a headline, convert all headlines to items.
16361 If the first line in the region is an item, convert all items to normal lines.
16363 If the first line is normal text, add an item bullet to each line."
16364 (interactive)
16365 (let (l2 l beg end)
16366 (if (org-region-active-p)
16367 (setq beg (region-beginning) end (region-end))
16368 (setq beg (point-at-bol)
16369 end (min (1+ (point-at-eol)) (point-max))))
16370 (save-excursion
16371 (goto-char end)
16372 (setq l2 (org-current-line))
16373 (goto-char beg)
16374 (beginning-of-line 1)
16375 (setq l (1- (org-current-line)))
16376 (if (org-at-item-p)
16377 ;; We already have items, de-itemize
16378 (while (< (setq l (1+ l)) l2)
16379 (when (org-at-item-p)
16380 (goto-char (match-beginning 2))
16381 (delete-region (match-beginning 2) (match-end 2))
16382 (and (looking-at "[ \t]+") (replace-match "")))
16383 (beginning-of-line 2))
16384 (if (org-on-heading-p)
16385 ;; Headings, convert to items
16386 (while (< (setq l (1+ l)) l2)
16387 (if (looking-at org-outline-regexp)
16388 (replace-match "- " t t))
16389 (beginning-of-line 2))
16390 ;; normal lines, turn them into items
16391 (while (< (setq l (1+ l)) l2)
16392 (unless (org-at-item-p)
16393 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16394 (replace-match "\\1- \\2")))
16395 (beginning-of-line 2)))))))
16397 (defun org-toggle-heading (&optional nstars)
16398 "Convert headings to normal text, or items or text to headings.
16399 If there is no active region, only the current line is considered.
16401 If the first line is a heading, remove the stars from all headlines
16402 in the region.
16404 If the first line is a plain list item, turn all plain list items
16405 into headings.
16407 If the first line is a normal line, turn each and every line in the
16408 region into a heading.
16410 When converting a line into a heading, the number of stars is chosen
16411 such that the lines become children of the current entry. However,
16412 when a prefix argument is given, its value determines the number of
16413 stars to add."
16414 (interactive "P")
16415 (let (l2 l itemp beg end)
16416 (if (org-region-active-p)
16417 (setq beg (region-beginning) end (region-end))
16418 (setq beg (point-at-bol)
16419 end (min (1+ (point-at-eol)) (point-max))))
16420 (save-excursion
16421 (goto-char end)
16422 (setq l2 (org-current-line))
16423 (goto-char beg)
16424 (beginning-of-line 1)
16425 (setq l (1- (org-current-line)))
16426 (if (org-on-heading-p)
16427 ;; We already have headlines, de-star them
16428 (while (< (setq l (1+ l)) l2)
16429 (when (org-on-heading-p t)
16430 (and (looking-at outline-regexp) (replace-match "")))
16431 (beginning-of-line 2))
16432 (setq itemp (org-at-item-p))
16433 (let* ((stars
16434 (if nstars
16435 (make-string (prefix-numeric-value current-prefix-arg)
16437 (save-excursion
16438 (if (re-search-backward org-complex-heading-regexp nil t)
16439 (match-string 1) ""))))
16440 (add-stars (cond (nstars "")
16441 ((equal stars "") "*")
16442 (org-odd-levels-only "**")
16443 (t "*")))
16444 (rpl (concat stars add-stars " ")))
16445 (while (< (setq l (1+ l)) l2)
16446 (if itemp
16447 (and (org-at-item-p) (replace-match rpl t t))
16448 (unless (org-on-heading-p)
16449 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16450 (replace-match (concat rpl (match-string 2))))))
16451 (beginning-of-line 2)))))))
16453 (defun org-meta-return (&optional arg)
16454 "Insert a new heading or wrap a region in a table.
16455 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16456 See the individual commands for more information."
16457 (interactive "P")
16458 (cond
16459 ((run-hook-with-args-until-success 'org-metareturn-hook))
16460 ((org-at-table-p)
16461 (call-interactively 'org-table-wrap-region))
16462 (t (call-interactively 'org-insert-heading))))
16464 ;;; Menu entries
16466 ;; Define the Org-mode menus
16467 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16468 '("Tbl"
16469 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16470 ["Next Field" org-cycle (org-at-table-p)]
16471 ["Previous Field" org-shifttab (org-at-table-p)]
16472 ["Next Row" org-return (org-at-table-p)]
16473 "--"
16474 ["Blank Field" org-table-blank-field (org-at-table-p)]
16475 ["Edit Field" org-table-edit-field (org-at-table-p)]
16476 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16477 "--"
16478 ("Column"
16479 ["Move Column Left" org-metaleft (org-at-table-p)]
16480 ["Move Column Right" org-metaright (org-at-table-p)]
16481 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16482 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16483 ("Row"
16484 ["Move Row Up" org-metaup (org-at-table-p)]
16485 ["Move Row Down" org-metadown (org-at-table-p)]
16486 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16487 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16488 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16489 "--"
16490 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16491 ("Rectangle"
16492 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16493 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16494 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16495 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16496 "--"
16497 ("Calculate"
16498 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16499 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16500 ["Edit Formulas" org-edit-special (org-at-table-p)]
16501 "--"
16502 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16503 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16504 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16505 "--"
16506 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16507 "--"
16508 ["Sum Column/Rectangle" org-table-sum
16509 (or (org-at-table-p) (org-region-active-p))]
16510 ["Which Column?" org-table-current-column (org-at-table-p)])
16511 ["Debug Formulas"
16512 org-table-toggle-formula-debugger
16513 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16514 ["Show Col/Row Numbers"
16515 org-table-toggle-coordinate-overlays
16516 :style toggle
16517 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16518 "--"
16519 ["Create" org-table-create (and (not (org-at-table-p))
16520 org-enable-table-editor)]
16521 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16522 ["Import from File" org-table-import (not (org-at-table-p))]
16523 ["Export to File" org-table-export (org-at-table-p)]
16524 "--"
16525 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16527 (easy-menu-define org-org-menu org-mode-map "Org menu"
16528 '("Org"
16529 ("Show/Hide"
16530 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16531 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16532 ["Sparse Tree..." org-sparse-tree t]
16533 ["Reveal Context" org-reveal t]
16534 ["Show All" show-all t]
16535 "--"
16536 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16537 "--"
16538 ["New Heading" org-insert-heading t]
16539 ("Navigate Headings"
16540 ["Up" outline-up-heading t]
16541 ["Next" outline-next-visible-heading t]
16542 ["Previous" outline-previous-visible-heading t]
16543 ["Next Same Level" outline-forward-same-level t]
16544 ["Previous Same Level" outline-backward-same-level t]
16545 "--"
16546 ["Jump" org-goto t])
16547 ("Edit Structure"
16548 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16549 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16550 "--"
16551 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16552 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16553 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16554 "--"
16555 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16556 "--"
16557 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16558 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16559 ["Demote Heading" org-metaright (not (org-at-table-p))]
16560 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16561 "--"
16562 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16563 "--"
16564 ["Convert to odd levels" org-convert-to-odd-levels t]
16565 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16566 ("Editing"
16567 ["Emphasis..." org-emphasize t]
16568 ["Edit Source Example" org-edit-special t]
16569 "--"
16570 ["Footnote new/jump" org-footnote-action t]
16571 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16572 ("Archive"
16573 ["Archive (default method)" org-archive-subtree-default t]
16574 "--"
16575 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16576 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16577 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16579 "--"
16580 ("Hyperlinks"
16581 ["Store Link (Global)" org-store-link t]
16582 ["Find existing link to here" org-occur-link-in-agenda-files t]
16583 ["Insert Link" org-insert-link t]
16584 ["Follow Link" org-open-at-point t]
16585 "--"
16586 ["Next link" org-next-link t]
16587 ["Previous link" org-previous-link t]
16588 "--"
16589 ["Descriptive Links"
16590 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16591 :style radio
16592 :selected (member '(org-link) buffer-invisibility-spec)]
16593 ["Literal Links"
16594 (progn
16595 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16596 :style radio
16597 :selected (not (member '(org-link) buffer-invisibility-spec))])
16598 "--"
16599 ("TODO Lists"
16600 ["TODO/DONE/-" org-todo t]
16601 ("Select keyword"
16602 ["Next keyword" org-shiftright (org-on-heading-p)]
16603 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16604 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16605 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16606 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16607 ["Show TODO Tree" org-show-todo-tree t]
16608 ["Global TODO list" org-todo-list t]
16609 "--"
16610 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16611 :selected org-enforce-todo-dependencies :style toggle :active t]
16612 "Settings for tree at point"
16613 ["Do Children sequentially" org-toggle-ordered-property :style radio
16614 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16615 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16616 ["Do Children parallel" org-toggle-ordered-property :style radio
16617 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16618 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16619 "--"
16620 ["Set Priority" org-priority t]
16621 ["Priority Up" org-shiftup t]
16622 ["Priority Down" org-shiftdown t]
16623 "--"
16624 ["Get news from all feeds" org-feed-update-all t]
16625 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16626 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16627 ("TAGS and Properties"
16628 ["Set Tags" org-set-tags-command t]
16629 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16630 "--"
16631 ["Set property" org-set-property t]
16632 ["Column view of properties" org-columns t]
16633 ["Insert Column View DBlock" org-insert-columns-dblock t])
16634 ("Dates and Scheduling"
16635 ["Timestamp" org-time-stamp t]
16636 ["Timestamp (inactive)" org-time-stamp-inactive t]
16637 ("Change Date"
16638 ["1 Day Later" org-shiftright t]
16639 ["1 Day Earlier" org-shiftleft t]
16640 ["1 ... Later" org-shiftup t]
16641 ["1 ... Earlier" org-shiftdown t])
16642 ["Compute Time Range" org-evaluate-time-range t]
16643 ["Schedule Item" org-schedule t]
16644 ["Deadline" org-deadline t]
16645 "--"
16646 ["Custom time format" org-toggle-time-stamp-overlays
16647 :style radio :selected org-display-custom-times]
16648 "--"
16649 ["Goto Calendar" org-goto-calendar t]
16650 ["Date from Calendar" org-date-from-calendar t]
16651 "--"
16652 ["Start/Restart Timer" org-timer-start t]
16653 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16654 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16655 ["Insert Timer String" org-timer t]
16656 ["Insert Timer Item" org-timer-item t])
16657 ("Logging work"
16658 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16659 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16660 ["Clock out" org-clock-out t]
16661 ["Clock cancel" org-clock-cancel t]
16662 "--"
16663 ["Mark as default task" org-clock-mark-default-task t]
16664 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16665 ["Goto running clock" org-clock-goto t]
16666 "--"
16667 ["Display times" org-clock-display t]
16668 ["Create clock table" org-clock-report t]
16669 "--"
16670 ["Record DONE time"
16671 (progn (setq org-log-done (not org-log-done))
16672 (message "Switching to %s will %s record a timestamp"
16673 (car org-done-keywords)
16674 (if org-log-done "automatically" "not")))
16675 :style toggle :selected org-log-done])
16676 "--"
16677 ["Agenda Command..." org-agenda t]
16678 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16679 ("File List for Agenda")
16680 ("Special views current file"
16681 ["TODO Tree" org-show-todo-tree t]
16682 ["Check Deadlines" org-check-deadlines t]
16683 ["Timeline" org-timeline t]
16684 ["Tags/Property tree" org-match-sparse-tree t])
16685 "--"
16686 ["Export/Publish..." org-export t]
16687 ("LaTeX"
16688 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16689 :selected org-cdlatex-mode]
16690 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16691 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16692 ["Modify math symbol" org-cdlatex-math-modify
16693 (org-inside-LaTeX-fragment-p)]
16694 ["Insert citation" org-reftex-citation t]
16695 "--"
16696 ["Export LaTeX fragments as images"
16697 (if (featurep 'org-exp)
16698 (setq org-export-with-LaTeX-fragments
16699 (not org-export-with-LaTeX-fragments))
16700 (require 'org-exp))
16701 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16702 org-export-with-LaTeX-fragments)]
16703 "--"
16704 ["Template for BEAMER" org-beamer-settings-template t])
16705 "--"
16706 ("MobileOrg"
16707 ["Push Files and Views" org-mobile-push t]
16708 ["Get Captured and Flagged" org-mobile-pull t]
16709 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16710 "--"
16711 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16712 "--"
16713 ("Documentation"
16714 ["Show Version" org-version t]
16715 ["Info Documentation" org-info t])
16716 ("Customize"
16717 ["Browse Org Group" org-customize t]
16718 "--"
16719 ["Expand This Menu" org-create-customize-menu
16720 (fboundp 'customize-menu-create)])
16721 ["Send bug report" org-submit-bug-report t]
16722 "--"
16723 ("Refresh/Reload"
16724 ["Refresh setup current buffer" org-mode-restart t]
16725 ["Reload Org (after update)" org-reload t]
16726 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16729 (defun org-info (&optional node)
16730 "Read documentation for Org-mode in the info system.
16731 With optional NODE, go directly to that node."
16732 (interactive)
16733 (info (format "(org)%s" (or node ""))))
16735 ;;;###autoload
16736 (defun org-submit-bug-report ()
16737 "Submit a bug report on Org-mode via mail.
16739 Don't hesitate to report any problems or inaccurate documentation.
16741 If you don't have setup sending mail from (X)Emacs, please copy the
16742 output buffer into your mail program, as it gives us important
16743 information about your Org-mode version and configuration."
16744 (interactive)
16745 (require 'reporter)
16746 (org-load-modules-maybe)
16747 (org-require-autoloaded-modules)
16748 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16749 (reporter-submit-bug-report
16750 "emacs-orgmode@gnu.org"
16751 (org-version)
16752 (let (list)
16753 (save-window-excursion
16754 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16755 (delete-other-windows)
16756 (erase-buffer)
16757 (insert "You are about to submit a bug report to the Org-mode mailing list.
16759 We would like to add your full Org-mode and Outline configuration to the
16760 bug report. This greatly simplifies the work of the maintainer and
16761 other experts on the mailing list.
16763 HOWEVER, some variables you have customized may contain private
16764 information. The names of customers, colleagues, or friends, might
16765 appear in the form of file names, tags, todo states, or search strings.
16766 If you answer yes to the prompt, you might want to check and remove
16767 such private information before sending the email.")
16768 (add-text-properties (point-min) (point-max) '(face org-warning))
16769 (when (yes-or-no-p "Include your Org-mode configuration ")
16770 (mapatoms
16771 (lambda (v)
16772 (and (boundp v)
16773 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16774 (or (and (symbol-value v)
16775 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16776 (and
16777 (get v 'custom-type) (get v 'standard-value)
16778 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16779 (push v list)))))
16780 (kill-buffer (get-buffer "*Warn about privacy*"))
16781 list))
16782 nil nil
16783 "Remember to cover the basics, that is, what you expected to happen and
16784 what in fact did happen. You don't know how to make a good report? See
16786 http://orgmode.org/manual/Feedback.html#Feedback
16788 Your bug report will be posted to the Org-mode mailing list.
16789 ------------------------------------------------------------------------")
16790 (save-excursion
16791 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16792 (replace-match "\\1Bug: \\3 [\\2]")))))
16795 (defun org-install-agenda-files-menu ()
16796 (let ((bl (buffer-list)))
16797 (save-excursion
16798 (while bl
16799 (set-buffer (pop bl))
16800 (if (org-mode-p) (setq bl nil)))
16801 (when (org-mode-p)
16802 (easy-menu-change
16803 '("Org") "File List for Agenda"
16804 (append
16805 (list
16806 ["Edit File List" (org-edit-agenda-file-list) t]
16807 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16808 ["Remove Current File from List" org-remove-file t]
16809 ["Cycle through agenda files" org-cycle-agenda-files t]
16810 ["Occur in all agenda files" org-occur-in-agenda-files t]
16811 "--")
16812 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16814 ;;;; Documentation
16816 ;;;###autoload
16817 (defun org-require-autoloaded-modules ()
16818 (interactive)
16819 (mapc 'require
16820 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16821 org-docbook org-exp org-html org-icalendar
16822 org-id org-latex
16823 org-publish org-remember org-table
16824 org-timer org-xoxo)))
16826 ;;;###autoload
16827 (defun org-reload (&optional uncompiled)
16828 "Reload all org lisp files.
16829 With prefix arg UNCOMPILED, load the uncompiled versions."
16830 (interactive "P")
16831 (require 'find-func)
16832 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16833 (dir-org (file-name-directory (org-find-library-name "org")))
16834 (dir-org-contrib (ignore-errors
16835 (file-name-directory
16836 (org-find-library-name "org-contribdir"))))
16837 (files
16838 (append (directory-files dir-org t file-re)
16839 (and dir-org-contrib
16840 (directory-files dir-org-contrib t file-re))))
16841 (remove-re (concat (if (featurep 'xemacs)
16842 "org-colview" "org-colview-xemacs")
16843 "\\'")))
16844 (setq files (mapcar 'file-name-sans-extension files))
16845 (setq files (mapcar
16846 (lambda (x) (if (string-match remove-re x) nil x))
16847 files))
16848 (setq files (delq nil files))
16849 (mapc
16850 (lambda (f)
16851 (when (featurep (intern (file-name-nondirectory f)))
16852 (if (and (not uncompiled)
16853 (file-exists-p (concat f ".elc")))
16854 (load (concat f ".elc") nil nil t)
16855 (load (concat f ".el") nil nil t))))
16856 files))
16857 (org-version))
16859 ;;;###autoload
16860 (defun org-customize ()
16861 "Call the customize function with org as argument."
16862 (interactive)
16863 (org-load-modules-maybe)
16864 (org-require-autoloaded-modules)
16865 (customize-browse 'org))
16867 (defun org-create-customize-menu ()
16868 "Create a full customization menu for Org-mode, insert it into the menu."
16869 (interactive)
16870 (org-load-modules-maybe)
16871 (org-require-autoloaded-modules)
16872 (if (fboundp 'customize-menu-create)
16873 (progn
16874 (easy-menu-change
16875 '("Org") "Customize"
16876 `(["Browse Org group" org-customize t]
16877 "--"
16878 ,(customize-menu-create 'org)
16879 ["Set" Custom-set t]
16880 ["Save" Custom-save t]
16881 ["Reset to Current" Custom-reset-current t]
16882 ["Reset to Saved" Custom-reset-saved t]
16883 ["Reset to Standard Settings" Custom-reset-standard t]))
16884 (message "\"Org\"-menu now contains full customization menu"))
16885 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16887 ;;;; Miscellaneous stuff
16889 ;;; Generally useful functions
16891 (defun org-get-at-bol (property)
16892 "Get text property PROPERTY at beginning of line."
16893 (get-text-property (point-at-bol) property))
16895 (defun org-find-text-property-in-string (prop s)
16896 "Return the first non-nil value of property PROP in string S."
16897 (or (get-text-property 0 prop s)
16898 (get-text-property (or (next-single-property-change 0 prop s) 0)
16899 prop s)))
16901 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16902 "Display the given MESSAGE as a warning."
16903 (if (fboundp 'display-warning)
16904 (display-warning 'org message
16905 (if (featurep 'xemacs)
16906 'warning
16907 :warning))
16908 (let ((buf (get-buffer-create "*Org warnings*")))
16909 (with-current-buffer buf
16910 (goto-char (point-max))
16911 (insert "Warning (Org): " message)
16912 (unless (bolp)
16913 (newline)))
16914 (display-buffer buf)
16915 (sit-for 0))))
16917 (defun org-in-commented-line ()
16918 "Is point in a line starting with `#'?"
16919 (equal (char-after (point-at-bol)) ?#))
16921 (defun org-in-verbatim-emphasis ()
16922 (save-match-data
16923 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16925 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16926 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16927 (if (and marker (marker-buffer marker)
16928 (buffer-live-p (marker-buffer marker)))
16929 (progn
16930 (switch-to-buffer (marker-buffer marker))
16931 (if (or (> marker (point-max)) (< marker (point-min)))
16932 (widen))
16933 (goto-char marker)
16934 (org-show-context 'org-goto))
16935 (if bookmark
16936 (bookmark-jump bookmark)
16937 (error "Cannot find location"))))
16939 (defun org-quote-csv-field (s)
16940 "Quote field for inclusion in CSV material."
16941 (if (string-match "[\",]" s)
16942 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16945 (defun org-plist-delete (plist property)
16946 "Delete PROPERTY from PLIST.
16947 This is in contrast to merely setting it to 0."
16948 (let (p)
16949 (while plist
16950 (if (not (eq property (car plist)))
16951 (setq p (plist-put p (car plist) (nth 1 plist))))
16952 (setq plist (cddr plist)))
16955 (defun org-force-self-insert (N)
16956 "Needed to enforce self-insert under remapping."
16957 (interactive "p")
16958 (self-insert-command N))
16960 (defun org-string-width (s)
16961 "Compute width of string, ignoring invisible characters.
16962 This ignores character with invisibility property `org-link', and also
16963 characters with property `org-cwidth', because these will become invisible
16964 upon the next fontification round."
16965 (let (b l)
16966 (when (or (eq t buffer-invisibility-spec)
16967 (assq 'org-link buffer-invisibility-spec))
16968 (while (setq b (text-property-any 0 (length s)
16969 'invisible 'org-link s))
16970 (setq s (concat (substring s 0 b)
16971 (substring s (or (next-single-property-change
16972 b 'invisible s) (length s)))))))
16973 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16974 (setq s (concat (substring s 0 b)
16975 (substring s (or (next-single-property-change
16976 b 'org-cwidth s) (length s))))))
16977 (setq l (string-width s) b -1)
16978 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16979 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16982 (defun org-get-indentation (&optional line)
16983 "Get the indentation of the current line, interpreting tabs.
16984 When LINE is given, assume it represents a line and compute its indentation."
16985 (if line
16986 (if (string-match "^ *" (org-remove-tabs line))
16987 (match-end 0))
16988 (save-excursion
16989 (beginning-of-line 1)
16990 (skip-chars-forward " \t")
16991 (current-column))))
16993 (defun org-remove-tabs (s &optional width)
16994 "Replace tabulators in S with spaces.
16995 Assumes that s is a single line, starting in column 0."
16996 (setq width (or width tab-width))
16997 (while (string-match "\t" s)
16998 (setq s (replace-match
16999 (make-string
17000 (- (* width (/ (+ (match-beginning 0) width) width))
17001 (match-beginning 0)) ?\ )
17002 t t s)))
17005 (defun org-fix-indentation (line ind)
17006 "Fix indentation in LINE.
17007 IND is a cons cell with target and minimum indentation.
17008 If the current indentation in LINE is smaller than the minimum,
17009 leave it alone. If it is larger than ind, set it to the target."
17010 (let* ((l (org-remove-tabs line))
17011 (i (org-get-indentation l))
17012 (i1 (car ind)) (i2 (cdr ind)))
17013 (if (>= i i2) (setq l (substring line i2)))
17014 (if (> i1 0)
17015 (concat (make-string i1 ?\ ) l)
17016 l)))
17018 (defun org-remove-indentation (code &optional n)
17019 "Remove the maximum common indentation from the lines in CODE.
17020 N may optionally be the number of spaces to remove."
17021 (with-temp-buffer
17022 (insert code)
17023 (org-do-remove-indentation n)
17024 (buffer-string)))
17026 (defun org-do-remove-indentation (&optional n)
17027 "Remove the maximum common indentation from the buffer."
17028 (untabify (point-min) (point-max))
17029 (let ((min 10000) re)
17030 (if n
17031 (setq min n)
17032 (goto-char (point-min))
17033 (while (re-search-forward "^ *[^ \n]" nil t)
17034 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17035 (unless (or (= min 0) (= min 10000))
17036 (setq re (format "^ \\{%d\\}" min))
17037 (goto-char (point-min))
17038 (while (re-search-forward re nil t)
17039 (replace-match "")
17040 (end-of-line 1))
17041 min)))
17043 (defun org-fill-template (template alist)
17044 "Find each %key of ALIST in TEMPLATE and replace it."
17045 (let ((case-fold-search nil)
17046 entry key value)
17047 (setq alist (sort (copy-sequence alist)
17048 (lambda (a b) (< (length (car a)) (length (car b))))))
17049 (while (setq entry (pop alist))
17050 (setq template
17051 (replace-regexp-in-string
17052 (concat "%" (regexp-quote (car entry)))
17053 (cdr entry) template t t)))
17054 template))
17056 (defun org-base-buffer (buffer)
17057 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17058 (if (not buffer)
17059 buffer
17060 (or (buffer-base-buffer buffer)
17061 buffer)))
17063 (defun org-trim (s)
17064 "Remove whitespace at beginning and end of string."
17065 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17066 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17069 (defun org-wrap (string &optional width lines)
17070 "Wrap string to either a number of lines, or a width in characters.
17071 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17072 that costs. If there is a word longer than WIDTH, the text is actually
17073 wrapped to the length of that word.
17074 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17075 many lines, whatever width that takes.
17076 The return value is a list of lines, without newlines at the end."
17077 (let* ((words (org-split-string string "[ \t\n]+"))
17078 (maxword (apply 'max (mapcar 'org-string-width words)))
17079 w ll)
17080 (cond (width
17081 (org-do-wrap words (max maxword width)))
17082 (lines
17083 (setq w maxword)
17084 (setq ll (org-do-wrap words maxword))
17085 (if (<= (length ll) lines)
17087 (setq ll words)
17088 (while (> (length ll) lines)
17089 (setq w (1+ w))
17090 (setq ll (org-do-wrap words w)))
17091 ll))
17092 (t (error "Cannot wrap this")))))
17094 (defun org-do-wrap (words width)
17095 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17096 (let (lines line)
17097 (while words
17098 (setq line (pop words))
17099 (while (and words (< (+ (length line) (length (car words))) width))
17100 (setq line (concat line " " (pop words))))
17101 (setq lines (push line lines)))
17102 (nreverse lines)))
17104 (defun org-split-string (string &optional separators)
17105 "Splits STRING into substrings at SEPARATORS.
17106 No empty strings are returned if there are matches at the beginning
17107 and end of string."
17108 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17109 (start 0)
17110 notfirst
17111 (list nil))
17112 (while (and (string-match rexp string
17113 (if (and notfirst
17114 (= start (match-beginning 0))
17115 (< start (length string)))
17116 (1+ start) start))
17117 (< (match-beginning 0) (length string)))
17118 (setq notfirst t)
17119 (or (eq (match-beginning 0) 0)
17120 (and (eq (match-beginning 0) (match-end 0))
17121 (eq (match-beginning 0) start))
17122 (setq list
17123 (cons (substring string start (match-beginning 0))
17124 list)))
17125 (setq start (match-end 0)))
17126 (or (eq start (length string))
17127 (setq list
17128 (cons (substring string start)
17129 list)))
17130 (nreverse list)))
17132 (defun org-quote-vert (s)
17133 "Replace \"|\" with \"\\vert\"."
17134 (while (string-match "|" s)
17135 (setq s (replace-match "\\vert" t t s)))
17138 (defun org-uuidgen-p (s)
17139 "Is S an ID created by UUIDGEN?"
17140 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17142 (defun org-context ()
17143 "Return a list of contexts of the current cursor position.
17144 If several contexts apply, all are returned.
17145 Each context entry is a list with a symbol naming the context, and
17146 two positions indicating start and end of the context. Possible
17147 contexts are:
17149 :headline anywhere in a headline
17150 :headline-stars on the leading stars in a headline
17151 :todo-keyword on a TODO keyword (including DONE) in a headline
17152 :tags on the TAGS in a headline
17153 :priority on the priority cookie in a headline
17154 :item on the first line of a plain list item
17155 :item-bullet on the bullet/number of a plain list item
17156 :checkbox on the checkbox in a plain list item
17157 :table in an org-mode table
17158 :table-special on a special filed in a table
17159 :table-table in a table.el table
17160 :link on a hyperlink
17161 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17162 :target on a <<target>>
17163 :radio-target on a <<<radio-target>>>
17164 :latex-fragment on a LaTeX fragment
17165 :latex-preview on a LaTeX fragment with overlayed preview image
17167 This function expects the position to be visible because it uses font-lock
17168 faces as a help to recognize the following contexts: :table-special, :link,
17169 and :keyword."
17170 (let* ((f (get-text-property (point) 'face))
17171 (faces (if (listp f) f (list f)))
17172 (p (point)) clist o)
17173 ;; First the large context
17174 (cond
17175 ((org-on-heading-p t)
17176 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17177 (when (progn
17178 (beginning-of-line 1)
17179 (looking-at org-todo-line-tags-regexp))
17180 (push (org-point-in-group p 1 :headline-stars) clist)
17181 (push (org-point-in-group p 2 :todo-keyword) clist)
17182 (push (org-point-in-group p 4 :tags) clist))
17183 (goto-char p)
17184 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17185 (if (looking-at "\\[#[A-Z0-9]\\]")
17186 (push (org-point-in-group p 0 :priority) clist)))
17188 ((org-at-item-p)
17189 (push (org-point-in-group p 2 :item-bullet) clist)
17190 (push (list :item (point-at-bol)
17191 (save-excursion (org-end-of-item) (point)))
17192 clist)
17193 (and (org-at-item-checkbox-p)
17194 (push (org-point-in-group p 0 :checkbox) clist)))
17196 ((org-at-table-p)
17197 (push (list :table (org-table-begin) (org-table-end)) clist)
17198 (if (memq 'org-formula faces)
17199 (push (list :table-special
17200 (previous-single-property-change p 'face)
17201 (next-single-property-change p 'face)) clist)))
17202 ((org-at-table-p 'any)
17203 (push (list :table-table) clist)))
17204 (goto-char p)
17206 ;; Now the small context
17207 (cond
17208 ((org-at-timestamp-p)
17209 (push (org-point-in-group p 0 :timestamp) clist))
17210 ((memq 'org-link faces)
17211 (push (list :link
17212 (previous-single-property-change p 'face)
17213 (next-single-property-change p 'face)) clist))
17214 ((memq 'org-special-keyword faces)
17215 (push (list :keyword
17216 (previous-single-property-change p 'face)
17217 (next-single-property-change p 'face)) clist))
17218 ((org-on-target-p)
17219 (push (org-point-in-group p 0 :target) clist)
17220 (goto-char (1- (match-beginning 0)))
17221 (if (looking-at org-radio-target-regexp)
17222 (push (org-point-in-group p 0 :radio-target) clist))
17223 (goto-char p))
17224 ((setq o (car (delq nil
17225 (mapcar
17226 (lambda (x)
17227 (if (memq x org-latex-fragment-image-overlays) x))
17228 (org-overlays-at (point))))))
17229 (push (list :latex-fragment
17230 (org-overlay-start o) (org-overlay-end o)) clist)
17231 (push (list :latex-preview
17232 (org-overlay-start o) (org-overlay-end o)) clist))
17233 ((org-inside-LaTeX-fragment-p)
17234 ;; FIXME: positions wrong.
17235 (push (list :latex-fragment (point) (point)) clist)))
17237 (setq clist (nreverse (delq nil clist)))
17238 clist))
17240 ;; FIXME: Compare with at-regexp-p Do we need both?
17241 (defun org-in-regexp (re &optional nlines visually)
17242 "Check if point is inside a match of regexp.
17243 Normally only the current line is checked, but you can include NLINES extra
17244 lines both before and after point into the search.
17245 If VISUALLY is set, require that the cursor is not after the match but
17246 really on, so that the block visually is on the match."
17247 (catch 'exit
17248 (let ((pos (point))
17249 (eol (point-at-eol (+ 1 (or nlines 0))))
17250 (inc (if visually 1 0)))
17251 (save-excursion
17252 (beginning-of-line (- 1 (or nlines 0)))
17253 (while (re-search-forward re eol t)
17254 (if (and (<= (match-beginning 0) pos)
17255 (>= (+ inc (match-end 0)) pos))
17256 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17258 (defun org-at-regexp-p (regexp)
17259 "Is point inside a match of REGEXP in the current line?"
17260 (catch 'exit
17261 (save-excursion
17262 (let ((pos (point)) (end (point-at-eol)))
17263 (beginning-of-line 1)
17264 (while (re-search-forward regexp end t)
17265 (if (and (<= (match-beginning 0) pos)
17266 (>= (match-end 0) pos))
17267 (throw 'exit t)))
17268 nil))))
17270 (defun org-in-regexps-block-p (start-re end-re)
17271 "Returns t if the current point is between matches of START-RE and END-RE.
17272 This will also return to if point is on one of the two matches."
17273 (interactive)
17274 (let ((p (point)))
17275 (save-excursion
17276 (and (or (org-at-regexp-p start-re)
17277 (re-search-backward start-re nil t))
17278 (re-search-forward end-re nil t)
17279 (>= (point) p)))))
17281 (defun org-occur-in-agenda-files (regexp &optional nlines)
17282 "Call `multi-occur' with buffers for all agenda files."
17283 (interactive "sOrg-files matching: \np")
17284 (let* ((files (org-agenda-files))
17285 (tnames (mapcar 'file-truename files))
17286 (extra org-agenda-text-search-extra-files)
17288 (when (eq (car extra) 'agenda-archives)
17289 (setq extra (cdr extra))
17290 (setq files (org-add-archive-files files)))
17291 (while (setq f (pop extra))
17292 (unless (member (file-truename f) tnames)
17293 (add-to-list 'files f 'append)
17294 (add-to-list 'tnames (file-truename f) 'append)))
17295 (multi-occur
17296 (mapcar (lambda (x)
17297 (with-current-buffer
17298 (or (get-file-buffer x) (find-file-noselect x))
17299 (widen)
17300 (current-buffer)))
17301 files)
17302 regexp)))
17304 (if (boundp 'occur-mode-find-occurrence-hook)
17305 ;; Emacs 23
17306 (add-hook 'occur-mode-find-occurrence-hook
17307 (lambda ()
17308 (when (org-mode-p)
17309 (org-reveal))))
17310 ;; Emacs 22
17311 (defadvice occur-mode-goto-occurrence
17312 (after org-occur-reveal activate)
17313 (and (org-mode-p) (org-reveal)))
17314 (defadvice occur-mode-goto-occurrence-other-window
17315 (after org-occur-reveal activate)
17316 (and (org-mode-p) (org-reveal)))
17317 (defadvice occur-mode-display-occurrence
17318 (after org-occur-reveal activate)
17319 (when (org-mode-p)
17320 (let ((pos (occur-mode-find-occurrence)))
17321 (with-current-buffer (marker-buffer pos)
17322 (save-excursion
17323 (goto-char pos)
17324 (org-reveal)))))))
17326 (defun org-occur-link-in-agenda-files ()
17327 "Create a link and search for it in the agendas.
17328 The link is not stored in `org-stored-links', it is just created
17329 for the search purpose."
17330 (interactive)
17331 (let ((link (condition-case nil
17332 (org-store-link nil)
17333 (error "Unable to create a link to here"))))
17334 (org-occur-in-agenda-files (regexp-quote link))))
17336 (defun org-uniquify (list)
17337 "Remove duplicate elements from LIST."
17338 (let (res)
17339 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17340 res))
17342 (defun org-delete-all (elts list)
17343 "Remove all elements in ELTS from LIST."
17344 (while elts
17345 (setq list (delete (pop elts) list)))
17346 list)
17348 (defun org-back-over-empty-lines ()
17349 "Move backwards over whitespace, to the beginning of the first empty line.
17350 Returns the number of empty lines passed."
17351 (let ((pos (point)))
17352 (skip-chars-backward " \t\n\r")
17353 (beginning-of-line 2)
17354 (goto-char (min (point) pos))
17355 (count-lines (point) pos)))
17357 (defun org-skip-whitespace ()
17358 (skip-chars-forward " \t\n\r"))
17360 (defun org-point-in-group (point group &optional context)
17361 "Check if POINT is in match-group GROUP.
17362 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17363 match. If the match group does ot exist or point is not inside it,
17364 return nil."
17365 (and (match-beginning group)
17366 (>= point (match-beginning group))
17367 (<= point (match-end group))
17368 (if context
17369 (list context (match-beginning group) (match-end group))
17370 t)))
17372 (defun org-switch-to-buffer-other-window (&rest args)
17373 "Switch to buffer in a second window on the current frame.
17374 In particular, do not allow pop-up frames."
17375 (let (pop-up-frames special-display-buffer-names special-display-regexps
17376 special-display-function)
17377 (apply 'switch-to-buffer-other-window args)))
17379 (defun org-combine-plists (&rest plists)
17380 "Create a single property list from all plists in PLISTS.
17381 The process starts by copying the first list, and then setting properties
17382 from the other lists. Settings in the last list are the most significant
17383 ones and overrule settings in the other lists."
17384 (let ((rtn (copy-sequence (pop plists)))
17385 p v ls)
17386 (while plists
17387 (setq ls (pop plists))
17388 (while ls
17389 (setq p (pop ls) v (pop ls))
17390 (setq rtn (plist-put rtn p v))))
17391 rtn))
17393 (defun org-move-line-down (arg)
17394 "Move the current line down. With prefix argument, move it past ARG lines."
17395 (interactive "p")
17396 (let ((col (current-column))
17397 beg end pos)
17398 (beginning-of-line 1) (setq beg (point))
17399 (beginning-of-line 2) (setq end (point))
17400 (beginning-of-line (+ 1 arg))
17401 (setq pos (move-marker (make-marker) (point)))
17402 (insert (delete-and-extract-region beg end))
17403 (goto-char pos)
17404 (org-move-to-column col)))
17406 (defun org-move-line-up (arg)
17407 "Move the current line up. With prefix argument, move it past ARG lines."
17408 (interactive "p")
17409 (let ((col (current-column))
17410 beg end pos)
17411 (beginning-of-line 1) (setq beg (point))
17412 (beginning-of-line 2) (setq end (point))
17413 (beginning-of-line (- arg))
17414 (setq pos (move-marker (make-marker) (point)))
17415 (insert (delete-and-extract-region beg end))
17416 (goto-char pos)
17417 (org-move-to-column col)))
17419 (defun org-replace-escapes (string table)
17420 "Replace %-escapes in STRING with values in TABLE.
17421 TABLE is an association list with keys like \"%a\" and string values.
17422 The sequences in STRING may contain normal field width and padding information,
17423 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17424 so values can contain further %-escapes if they are define later in TABLE."
17425 (let ((case-fold-search nil)
17426 e re rpl)
17427 (while (setq e (pop table))
17428 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17429 (while (string-match re string)
17430 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17431 (cdr e)))
17432 (setq string (replace-match rpl t t string))))
17433 string))
17436 (defun org-sublist (list start end)
17437 "Return a section of LIST, from START to END.
17438 Counting starts at 1."
17439 (let (rtn (c start))
17440 (setq list (nthcdr (1- start) list))
17441 (while (and list (<= c end))
17442 (push (pop list) rtn)
17443 (setq c (1+ c)))
17444 (nreverse rtn)))
17446 (defun org-find-base-buffer-visiting (file)
17447 "Like `find-buffer-visiting' but always return the base buffer and
17448 not an indirect buffer."
17449 (let ((buf (or (get-file-buffer file)
17450 (find-buffer-visiting file))))
17451 (if buf
17452 (or (buffer-base-buffer buf) buf)
17453 nil)))
17455 (defun org-image-file-name-regexp (&optional extensions)
17456 "Return regexp matching the file names of images.
17457 If EXTENSIONS is given, only match these."
17458 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17459 (image-file-name-regexp)
17460 (let ((image-file-name-extensions
17461 (or extensions
17462 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17463 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17464 (concat "\\."
17465 (regexp-opt (nconc (mapcar 'upcase
17466 image-file-name-extensions)
17467 image-file-name-extensions)
17469 "\\'"))))
17471 (defun org-file-image-p (file &optional extensions)
17472 "Return non-nil if FILE is an image."
17473 (save-match-data
17474 (string-match (org-image-file-name-regexp extensions) file)))
17476 (defun org-get-cursor-date ()
17477 "Return the date at cursor in as a time.
17478 This works in the calendar and in the agenda, anywhere else it just
17479 returns the current time."
17480 (let (date day defd)
17481 (cond
17482 ((eq major-mode 'calendar-mode)
17483 (setq date (calendar-cursor-to-date)
17484 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17485 ((eq major-mode 'org-agenda-mode)
17486 (setq day (get-text-property (point) 'day))
17487 (if day
17488 (setq date (calendar-gregorian-from-absolute day)
17489 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17490 (nth 2 date))))))
17491 (or defd (current-time))))
17493 (defvar org-agenda-action-marker (make-marker)
17494 "Marker pointing to the entry for the next agenda action.")
17496 (defun org-mark-entry-for-agenda-action ()
17497 "Mark the current entry as target of an agenda action.
17498 Agenda actions are actions executed from the agenda with the key `k',
17499 which make use of the date at the cursor."
17500 (interactive)
17501 (move-marker org-agenda-action-marker
17502 (save-excursion (org-back-to-heading t) (point))
17503 (current-buffer))
17504 (message
17505 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17507 ;;; Paragraph filling stuff.
17508 ;; We want this to be just right, so use the full arsenal.
17510 (defun org-indent-line-function ()
17511 "Indent line like previous, but further if previous was headline or item."
17512 (interactive)
17513 (let* ((pos (point))
17514 (itemp (org-at-item-p))
17515 (case-fold-search t)
17516 (org-drawer-regexp (or org-drawer-regexp "\000"))
17517 column bpos bcol tpos tcol bullet btype bullet-type)
17518 ;; Find the previous relevant line
17519 (beginning-of-line 1)
17520 (cond
17521 ((looking-at "#") (setq column 0))
17522 ((looking-at "\\*+ ") (setq column 0))
17523 ((and (looking-at "[ \t]*:END:")
17524 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17525 (save-excursion
17526 (goto-char (1- (match-beginning 1)))
17527 (setq column (current-column))))
17528 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17529 (save-excursion
17530 (re-search-backward
17531 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17532 (setq column (org-get-indentation (match-string 0))))
17534 (beginning-of-line 0)
17535 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17536 (not (looking-at "[ \t]*:END:"))
17537 (not (looking-at org-drawer-regexp)))
17538 (beginning-of-line 0))
17539 (cond
17540 ((looking-at "\\*+[ \t]+")
17541 (if (not org-adapt-indentation)
17542 (setq column 0)
17543 (goto-char (match-end 0))
17544 (setq column (current-column))))
17545 ((looking-at org-drawer-regexp)
17546 (goto-char (1- (match-beginning 1)))
17547 (setq column (current-column)))
17548 ((looking-at "\\([ \t]*\\):END:")
17549 (goto-char (match-end 1))
17550 (setq column (current-column)))
17551 ((org-in-item-p)
17552 (org-beginning-of-item)
17553 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17554 (setq bpos (match-beginning 1) tpos (match-end 0)
17555 bcol (progn (goto-char bpos) (current-column))
17556 tcol (progn (goto-char tpos) (current-column))
17557 bullet (match-string 1)
17558 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17559 (if (> tcol (+ bcol org-description-max-indent))
17560 (setq tcol (+ bcol 5)))
17561 (if (not itemp)
17562 (setq column tcol)
17563 (goto-char pos)
17564 (beginning-of-line 1)
17565 (if (looking-at "\\S-")
17566 (progn
17567 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17568 (setq bullet (match-string 1)
17569 btype (if (string-match "[0-9]" bullet) "n" bullet))
17570 (setq column (if (equal btype bullet-type) bcol tcol)))
17571 (setq column (org-get-indentation)))))
17572 (t (setq column (org-get-indentation))))))
17573 (goto-char pos)
17574 (if (<= (current-column) (current-indentation))
17575 (org-indent-line-to column)
17576 (save-excursion (org-indent-line-to column)))
17577 (setq column (current-column))
17578 (beginning-of-line 1)
17579 (if (looking-at
17580 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17581 (replace-match (concat (match-string 1)
17582 (format org-property-format
17583 (match-string 2) (match-string 3)))
17584 t t))
17585 (org-move-to-column column)))
17587 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17588 "Variable to store copy of `adaptive-fill-regexp'.
17589 Since `adaptive-fill-regexp' is set to never match, we need to
17590 store a backup of its value before entering `org-mode' so that
17591 the functionality can be provided as a fall-back.")
17593 (defun org-set-autofill-regexps ()
17594 (interactive)
17595 ;; In the paragraph separator we include headlines, because filling
17596 ;; text in a line directly attached to a headline would otherwise
17597 ;; fill the headline as well.
17598 (org-set-local 'comment-start-skip "^#+[ \t]*")
17599 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17600 ;; The paragraph starter includes hand-formatted lists.
17601 (org-set-local
17602 'paragraph-start
17603 (concat
17604 "\f" "\\|"
17605 "[ ]*$" "\\|"
17606 "\\*+ " "\\|"
17607 "[ \t]*#" "\\|"
17608 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17609 "[ \t]*[:|]" "\\|"
17610 "\\$\\$" "\\|"
17611 "\\\\\\(begin\\|end\\|[][]\\)"))
17612 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17613 ;; But only if the user has not turned off tables or fixed-width regions
17614 (org-set-local
17615 'auto-fill-inhibit-regexp
17616 (concat "\\*+ \\|#\\+"
17617 "\\|[ \t]*" org-keyword-time-regexp
17618 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17619 (concat
17620 "\\|[ \t]*["
17621 (if org-enable-table-editor "|" "")
17622 (if org-enable-fixed-width-editor ":" "")
17623 "]"))))
17624 ;; We use our own fill-paragraph function, to make sure that tables
17625 ;; and fixed-width regions are not wrapped. That function will pass
17626 ;; through to `fill-paragraph' when appropriate.
17627 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17628 ;; Adaptive filling: To get full control, first make sure that
17629 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17630 (unless (local-variable-p 'adaptive-fill-regexp)
17631 (org-set-local 'org-adaptive-fill-regexp-backup
17632 adaptive-fill-regexp))
17633 (org-set-local 'adaptive-fill-regexp "\000")
17634 (org-set-local 'adaptive-fill-function
17635 'org-adaptive-fill-function)
17636 (org-set-local
17637 'align-mode-rules-list
17638 '((org-in-buffer-settings
17639 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17640 (modes . '(org-mode))))))
17642 (defun org-fill-paragraph (&optional justify)
17643 "Re-align a table, pass through to fill-paragraph if no table."
17644 (let ((table-p (org-at-table-p))
17645 (table.el-p (org-at-table.el-p)))
17646 (cond ((and (equal (char-after (point-at-bol)) ?*)
17647 (save-excursion (goto-char (point-at-bol))
17648 (looking-at outline-regexp)))
17649 t) ; skip headlines
17650 (table.el-p t) ; skip table.el tables
17651 (table-p (org-table-align) t) ; align org-mode tables
17652 (t nil)))) ; call paragraph-fill
17654 ;; For reference, this is the default value of adaptive-fill-regexp
17655 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17657 (defun org-adaptive-fill-function ()
17658 "Return a fill prefix for org-mode files.
17659 In particular, this makes sure hanging paragraphs for hand-formatted lists
17660 work correctly."
17661 (cond
17662 ;; Comment line
17663 ((looking-at "#[ \t]+")
17664 (match-string-no-properties 0))
17665 ;; Description list
17666 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17667 (save-excursion
17668 (if (> (match-end 1) (+ (match-beginning 1)
17669 org-description-max-indent))
17670 (goto-char (+ (match-beginning 1) 5))
17671 (goto-char (match-end 0)))
17672 (make-string (current-column) ?\ )))
17673 ;; Ordered or unordered list
17674 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17675 (save-excursion
17676 (goto-char (match-end 0))
17677 (make-string (current-column) ?\ )))
17678 ;; Other text
17679 ((looking-at org-adaptive-fill-regexp-backup)
17680 (match-string-no-properties 0))))
17682 ;;; Other stuff.
17684 (defun org-toggle-fixed-width-section (arg)
17685 "Toggle the fixed-width export.
17686 If there is no active region, the QUOTE keyword at the current headline is
17687 inserted or removed. When present, it causes the text between this headline
17688 and the next to be exported as fixed-width text, and unmodified.
17689 If there is an active region, this command adds or removes a colon as the
17690 first character of this line. If the first character of a line is a colon,
17691 this line is also exported in fixed-width font."
17692 (interactive "P")
17693 (let* ((cc 0)
17694 (regionp (org-region-active-p))
17695 (beg (if regionp (region-beginning) (point)))
17696 (end (if regionp (region-end)))
17697 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17698 (case-fold-search nil)
17699 (re "[ \t]*\\(: \\)")
17700 off)
17701 (if regionp
17702 (save-excursion
17703 (goto-char beg)
17704 (setq cc (current-column))
17705 (beginning-of-line 1)
17706 (setq off (looking-at re))
17707 (while (> nlines 0)
17708 (setq nlines (1- nlines))
17709 (beginning-of-line 1)
17710 (cond
17711 (arg
17712 (org-move-to-column cc t)
17713 (insert ": \n")
17714 (forward-line -1))
17715 ((and off (looking-at re))
17716 (replace-match "" t t nil 1))
17717 ((not off) (org-move-to-column cc t) (insert ": ")))
17718 (forward-line 1)))
17719 (save-excursion
17720 (org-back-to-heading)
17721 (if (looking-at (concat outline-regexp
17722 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17723 (replace-match "" t t nil 1)
17724 (if (looking-at outline-regexp)
17725 (progn
17726 (goto-char (match-end 0))
17727 (insert org-quote-string " "))))))))
17729 (defun org-reftex-citation ()
17730 "Use reftex-citation to insert a citation into the buffer.
17731 This looks for a line like
17733 #+BIBLIOGRAPHY: foo plain option:-d
17735 and derives from it that foo.bib is the bibliography file relevant
17736 for this document. It then installs the necessary environment for RefTeX
17737 to work in this buffer and calls `reftex-citation' to insert a citation
17738 into the buffer.
17740 Export of such citations to both LaTeX and HTML is handled by the contributed
17741 package org-exp-bibtex by Taru Karttunen."
17742 (interactive)
17743 (let ((reftex-docstruct-symbol 'rds)
17744 (reftex-cite-format "\\cite{%l}")
17745 rds bib)
17746 (save-excursion
17747 (save-restriction
17748 (widen)
17749 (let ((case-fold-search t)
17750 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17751 (if (not (save-excursion
17752 (or (re-search-forward re nil t)
17753 (re-search-backward re nil t))))
17754 (error "No bibliography defined in file")
17755 (setq bib (concat (match-string 1) ".bib")
17756 rds (list (list 'bib bib)))))))
17757 (call-interactively 'reftex-citation)))
17759 ;;;; Functions extending outline functionality
17761 (defun org-beginning-of-line (&optional arg)
17762 "Go to the beginning of the current line. If that is invisible, continue
17763 to a visible line beginning. This makes the function of C-a more intuitive.
17764 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17765 first attempt, and only move to after the tags when the cursor is already
17766 beyond the end of the headline."
17767 (interactive "P")
17768 (let ((pos (point))
17769 (special (if (consp org-special-ctrl-a/e)
17770 (car org-special-ctrl-a/e)
17771 org-special-ctrl-a/e))
17772 refpos)
17773 (if (org-bound-and-true-p line-move-visual)
17774 (beginning-of-visual-line 1)
17775 (beginning-of-line 1))
17776 (if (and arg (fboundp 'move-beginning-of-line))
17777 (call-interactively 'move-beginning-of-line)
17778 (if (bobp)
17780 (backward-char 1)
17781 (if (org-invisible-p)
17782 (while (and (not (bobp)) (org-invisible-p))
17783 (backward-char 1)
17784 (beginning-of-line 1))
17785 (forward-char 1))))
17786 (when special
17787 (cond
17788 ((and (looking-at org-complex-heading-regexp)
17789 (= (char-after (match-end 1)) ?\ ))
17790 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17791 (point-at-eol)))
17792 (goto-char
17793 (if (eq special t)
17794 (cond ((> pos refpos) refpos)
17795 ((= pos (point)) refpos)
17796 (t (point)))
17797 (cond ((> pos (point)) (point))
17798 ((not (eq last-command this-command)) (point))
17799 (t refpos)))))
17800 ((org-at-item-p)
17801 (goto-char
17802 (if (eq special t)
17803 (cond ((> pos (match-end 4)) (match-end 4))
17804 ((= pos (point)) (match-end 4))
17805 (t (point)))
17806 (cond ((> pos (point)) (point))
17807 ((not (eq last-command this-command)) (point))
17808 (t (match-end 4))))))))
17809 (org-no-warnings
17810 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17812 (defun org-end-of-line (&optional arg)
17813 "Go to the end of the line.
17814 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17815 first attempt, and only move to after the tags when the cursor is already
17816 beyond the end of the headline."
17817 (interactive "P")
17818 (let ((special (if (consp org-special-ctrl-a/e)
17819 (cdr org-special-ctrl-a/e)
17820 org-special-ctrl-a/e)))
17821 (if (or (not special)
17822 (not (org-on-heading-p))
17823 arg)
17824 (call-interactively
17825 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17826 ((fboundp 'move-end-of-line) 'move-end-of-line)
17827 (t 'end-of-line)))
17828 (let ((pos (point)))
17829 (beginning-of-line 1)
17830 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17831 (if (eq special t)
17832 (if (or (< pos (match-beginning 1))
17833 (= pos (match-end 0)))
17834 (goto-char (match-beginning 1))
17835 (goto-char (match-end 0)))
17836 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17837 (goto-char (match-end 0))
17838 (goto-char (match-beginning 1))))
17839 (call-interactively (if (fboundp 'move-end-of-line)
17840 'move-end-of-line
17841 'end-of-line)))))
17842 (org-no-warnings
17843 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17845 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17846 (define-key org-mode-map "\C-e" 'org-end-of-line)
17847 (define-key org-mode-map [home] 'org-beginning-of-line)
17848 (define-key org-mode-map [end] 'org-end-of-line)
17850 (defun org-backward-sentence (&optional arg)
17851 "Go to beginning of sentence, or beginning of table field.
17852 This will call `backward-sentence' or `org-table-beginning-of-field',
17853 depending on context."
17854 (interactive "P")
17855 (cond
17856 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17857 (t (call-interactively 'backward-sentence))))
17859 (defun org-forward-sentence (&optional arg)
17860 "Go to end of sentence, or end of table field.
17861 This will call `forward-sentence' or `org-table-end-of-field',
17862 depending on context."
17863 (interactive "P")
17864 (cond
17865 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17866 (t (call-interactively 'forward-sentence))))
17868 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17869 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17871 (defun org-kill-line (&optional arg)
17872 "Kill line, to tags or end of line."
17873 (interactive "P")
17874 (cond
17875 ((or (not org-special-ctrl-k)
17876 (bolp)
17877 (not (org-on-heading-p)))
17878 (call-interactively 'kill-line))
17879 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17880 (kill-region (point) (match-beginning 1))
17881 (org-set-tags nil t))
17882 (t (kill-region (point) (point-at-eol)))))
17884 (define-key org-mode-map "\C-k" 'org-kill-line)
17886 (defun org-yank (&optional arg)
17887 "Yank. If the kill is a subtree, treat it specially.
17888 This command will look at the current kill and check if is a single
17889 subtree, or a series of subtrees[1]. If it passes the test, and if the
17890 cursor is at the beginning of a line or after the stars of a currently
17891 empty headline, then the yank is handled specially. How exactly depends
17892 on the value of the following variables, both set by default.
17894 org-yank-folded-subtrees
17895 When set, the subtree(s) will be folded after insertion, but only
17896 if doing so would now swallow text after the yanked text.
17898 org-yank-adjusted-subtrees
17899 When set, the subtree will be promoted or demoted in order to
17900 fit into the local outline tree structure, which means that the level
17901 will be adjusted so that it becomes the smaller one of the two
17902 *visible* surrounding headings.
17904 Any prefix to this command will cause `yank' to be called directly with
17905 no special treatment. In particular, a simple `C-u' prefix will just
17906 plainly yank the text as it is.
17908 \[1] The test checks if the first non-white line is a heading
17909 and if there are no other headings with fewer stars."
17910 (interactive "P")
17911 (org-yank-generic 'yank arg))
17913 (defun org-yank-generic (command arg)
17914 "Perform some yank-like command.
17916 This function implements the behavior described in the `org-yank'
17917 documentation. However, it has been generalized to work for any
17918 interactive command with similar behavior."
17920 ;; pretend to be command COMMAND
17921 (setq this-command command)
17923 (if arg
17924 (call-interactively command)
17926 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17927 (and (org-kill-is-subtree-p)
17928 (or (bolp)
17929 (and (looking-at "[ \t]*$")
17930 (string-match
17931 "\\`\\*+\\'"
17932 (buffer-substring (point-at-bol) (point)))))))
17933 swallowp)
17934 (cond
17935 ((and subtreep org-yank-folded-subtrees)
17936 (let ((beg (point))
17937 end)
17938 (if (and subtreep org-yank-adjusted-subtrees)
17939 (org-paste-subtree nil nil 'for-yank)
17940 (call-interactively command))
17942 (setq end (point))
17943 (goto-char beg)
17944 (when (and (bolp) subtreep
17945 (not (setq swallowp
17946 (org-yank-folding-would-swallow-text beg end))))
17947 (or (looking-at outline-regexp)
17948 (re-search-forward (concat "^" outline-regexp) end t))
17949 (while (and (< (point) end) (looking-at outline-regexp))
17950 (hide-subtree)
17951 (org-cycle-show-empty-lines 'folded)
17952 (condition-case nil
17953 (outline-forward-same-level 1)
17954 (error (goto-char end)))))
17955 (when swallowp
17956 (message
17957 "Inserted text not folded because that would swallow text"))
17959 (goto-char end)
17960 (skip-chars-forward " \t\n\r")
17961 (beginning-of-line 1)
17962 (push-mark beg 'nomsg)))
17963 ((and subtreep org-yank-adjusted-subtrees)
17964 (let ((beg (point-at-bol)))
17965 (org-paste-subtree nil nil 'for-yank)
17966 (push-mark beg 'nomsg)))
17968 (call-interactively command))))))
17970 (defun org-yank-folding-would-swallow-text (beg end)
17971 "Would hide-subtree at BEG swallow any text after END?"
17972 (let (level)
17973 (save-excursion
17974 (goto-char beg)
17975 (when (or (looking-at outline-regexp)
17976 (re-search-forward (concat "^" outline-regexp) end t))
17977 (setq level (org-outline-level)))
17978 (goto-char end)
17979 (skip-chars-forward " \t\r\n\v\f")
17980 (if (or (eobp)
17981 (and (bolp) (looking-at org-outline-regexp)
17982 (<= (org-outline-level) level)))
17983 nil ; Nothing would be swallowed
17984 t)))) ; something would swallow
17986 (define-key org-mode-map "\C-y" 'org-yank)
17988 (defun org-invisible-p ()
17989 "Check if point is at a character currently not visible."
17990 ;; Early versions of noutline don't have `outline-invisible-p'.
17991 (if (fboundp 'outline-invisible-p)
17992 (outline-invisible-p)
17993 (get-char-property (point) 'invisible)))
17995 (defun org-invisible-p2 ()
17996 "Check if point is at a character currently not visible."
17997 (save-excursion
17998 (if (and (eolp) (not (bobp))) (backward-char 1))
17999 ;; Early versions of noutline don't have `outline-invisible-p'.
18000 (if (fboundp 'outline-invisible-p)
18001 (outline-invisible-p)
18002 (get-char-property (point) 'invisible))))
18004 (defun org-back-to-heading (&optional invisible-ok)
18005 "Call `outline-back-to-heading', but provide a better error message."
18006 (condition-case nil
18007 (outline-back-to-heading invisible-ok)
18008 (error (error "Before first headline at position %d in buffer %s"
18009 (point) (current-buffer)))))
18011 (defun org-before-first-heading-p ()
18012 "Before first heading?"
18013 (save-excursion
18014 (null (re-search-backward "^\\*+ " nil t))))
18016 (defun org-on-heading-p (&optional ignored)
18017 (outline-on-heading-p t))
18018 (defun org-at-heading-p (&optional ignored)
18019 (outline-on-heading-p t))
18021 (defun org-point-at-end-of-empty-headline ()
18022 "If point is at the end of an empty headline, return t, else nil.
18023 If the heading only contains a TODO keyword, it is still still considered
18024 empty."
18025 (and (looking-at "[ \t]*$")
18026 (save-excursion
18027 (beginning-of-line 1)
18028 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18029 "\\)?[ \t]*$")))))
18030 (defun org-at-heading-or-item-p ()
18031 (or (org-on-heading-p) (org-at-item-p)))
18033 (defun org-on-target-p ()
18034 (or (org-in-regexp org-radio-target-regexp)
18035 (org-in-regexp org-target-regexp)))
18037 (defun org-up-heading-all (arg)
18038 "Move to the heading line of which the present line is a subheading.
18039 This function considers both visible and invisible heading lines.
18040 With argument, move up ARG levels."
18041 (if (fboundp 'outline-up-heading-all)
18042 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18043 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18045 (defun org-up-heading-safe ()
18046 "Move to the heading line of which the present line is a subheading.
18047 This version will not throw an error. It will return the level of the
18048 headline found, or nil if no higher level is found.
18050 Also, this function will be a lot faster than `outline-up-heading',
18051 because it relies on stars being the outline starters. This can really
18052 make a significant difference in outlines with very many siblings."
18053 (let (start-level re)
18054 (org-back-to-heading t)
18055 (setq start-level (funcall outline-level))
18056 (if (equal start-level 1)
18058 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18059 (if (re-search-backward re nil t)
18060 (funcall outline-level)))))
18062 (defun org-first-sibling-p ()
18063 "Is this heading the first child of its parents?"
18064 (interactive)
18065 (let ((re (concat "^" outline-regexp))
18066 level l)
18067 (unless (org-at-heading-p t)
18068 (error "Not at a heading"))
18069 (setq level (funcall outline-level))
18070 (save-excursion
18071 (if (not (re-search-backward re nil t))
18073 (setq l (funcall outline-level))
18074 (< l level)))))
18076 (defun org-goto-sibling (&optional previous)
18077 "Goto the next sibling, even if it is invisible.
18078 When PREVIOUS is set, go to the previous sibling instead. Returns t
18079 when a sibling was found. When none is found, return nil and don't
18080 move point."
18081 (let ((fun (if previous 're-search-backward 're-search-forward))
18082 (pos (point))
18083 (re (concat "^" outline-regexp))
18084 level l)
18085 (when (condition-case nil (org-back-to-heading t) (error nil))
18086 (setq level (funcall outline-level))
18087 (catch 'exit
18088 (or previous (forward-char 1))
18089 (while (funcall fun re nil t)
18090 (setq l (funcall outline-level))
18091 (when (< l level) (goto-char pos) (throw 'exit nil))
18092 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18093 (goto-char pos)
18094 nil))))
18096 (defun org-show-siblings ()
18097 "Show all siblings of the current headline."
18098 (save-excursion
18099 (while (org-goto-sibling) (org-flag-heading nil)))
18100 (save-excursion
18101 (while (org-goto-sibling 'previous)
18102 (org-flag-heading nil))))
18104 (defun org-show-hidden-entry ()
18105 "Show an entry where even the heading is hidden."
18106 (save-excursion
18107 (org-show-entry)))
18109 (defun org-flag-heading (flag &optional entry)
18110 "Flag the current heading. FLAG non-nil means make invisible.
18111 When ENTRY is non-nil, show the entire entry."
18112 (save-excursion
18113 (org-back-to-heading t)
18114 ;; Check if we should show the entire entry
18115 (if entry
18116 (progn
18117 (org-show-entry)
18118 (save-excursion
18119 (and (outline-next-heading)
18120 (org-flag-heading nil))))
18121 (outline-flag-region (max (point-min) (1- (point)))
18122 (save-excursion (outline-end-of-heading) (point))
18123 flag))))
18125 (defun org-get-next-sibling ()
18126 "Move to next heading of the same level, and return point.
18127 If there is no such heading, return nil.
18128 This is like outline-next-sibling, but invisible headings are ok."
18129 (let ((level (funcall outline-level)))
18130 (outline-next-heading)
18131 (while (and (not (eobp)) (> (funcall outline-level) level))
18132 (outline-next-heading))
18133 (if (or (eobp) (< (funcall outline-level) level))
18135 (point))))
18137 (defun org-get-last-sibling ()
18138 "Move to previous heading of the same level, and return point.
18139 If there is no such heading, return nil."
18140 (let ((opoint (point))
18141 (level (funcall outline-level)))
18142 (outline-previous-heading)
18143 (when (and (/= (point) opoint) (outline-on-heading-p t))
18144 (while (and (> (funcall outline-level) level)
18145 (not (bobp)))
18146 (outline-previous-heading))
18147 (if (< (funcall outline-level) level)
18149 (point)))))
18151 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18152 ;; This contains an exact copy of the original function, but it uses
18153 ;; `org-back-to-heading', to make it work also in invisible
18154 ;; trees. And is uses an invisible-OK argument.
18155 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18156 ;; Furthermore, when used inside Org, finding the end of a large subtree
18157 ;; with many children and grandchildren etc, this can be much faster
18158 ;; than the outline version.
18159 (org-back-to-heading invisible-OK)
18160 (let ((first t)
18161 (level (funcall outline-level)))
18162 (if (and (org-mode-p) (< level 1000))
18163 ;; A true heading (not a plain list item), in Org-mode
18164 ;; This means we can easily find the end by looking
18165 ;; only for the right number of stars. Using a regexp to do
18166 ;; this is so much faster than using a Lisp loop.
18167 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18168 (forward-char 1)
18169 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18170 ;; something else, do it the slow way
18171 (while (and (not (eobp))
18172 (or first (> (funcall outline-level) level)))
18173 (setq first nil)
18174 (outline-next-heading)))
18175 (unless to-heading
18176 (if (memq (preceding-char) '(?\n ?\^M))
18177 (progn
18178 ;; Go to end of line before heading
18179 (forward-char -1)
18180 (if (memq (preceding-char) '(?\n ?\^M))
18181 ;; leave blank line before heading
18182 (forward-char -1))))))
18183 (point))
18185 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18186 "Use Org version in org-mode, for dramatic speed-up."
18187 (if (eq major-mode 'org-mode)
18188 (progn
18189 (org-end-of-subtree nil t)
18190 (unless (eobp) (backward-char 1)))
18191 ad-do-it))
18193 (defun org-forward-same-level (arg &optional invisible-ok)
18194 "Move forward to the arg'th subheading at same level as this one.
18195 Stop at the first and last subheadings of a superior heading."
18196 (interactive "p")
18197 (org-back-to-heading invisible-ok)
18198 (org-on-heading-p)
18199 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18200 (re (format "^\\*\\{1,%d\\} " level))
18202 (forward-char 1)
18203 (while (> arg 0)
18204 (while (and (re-search-forward re nil 'move)
18205 (setq l (- (match-end 0) (match-beginning 0) 1))
18206 (= l level)
18207 (not invisible-ok)
18208 (progn (backward-char 1) (org-invisible-p)))
18209 (if (< l level) (setq arg 1)))
18210 (setq arg (1- arg)))
18211 (beginning-of-line 1)))
18213 (defun org-backward-same-level (arg &optional invisible-ok)
18214 "Move backward to the arg'th subheading at same level as this one.
18215 Stop at the first and last subheadings of a superior heading."
18216 (interactive "p")
18217 (org-back-to-heading)
18218 (org-on-heading-p)
18219 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18220 (re (format "^\\*\\{1,%d\\} " level))
18222 (while (> arg 0)
18223 (while (and (re-search-backward re nil 'move)
18224 (setq l (- (match-end 0) (match-beginning 0) 1))
18225 (= l level)
18226 (not invisible-ok)
18227 (org-invisible-p))
18228 (if (< l level) (setq arg 1)))
18229 (setq arg (1- arg)))))
18231 (defun org-show-subtree ()
18232 "Show everything after this heading at deeper levels."
18233 (outline-flag-region
18234 (point)
18235 (save-excursion
18236 (org-end-of-subtree t t))
18237 nil))
18239 (defun org-show-entry ()
18240 "Show the body directly following this heading.
18241 Show the heading too, if it is currently invisible."
18242 (interactive)
18243 (save-excursion
18244 (condition-case nil
18245 (progn
18246 (org-back-to-heading t)
18247 (outline-flag-region
18248 (max (point-min) (1- (point)))
18249 (save-excursion
18250 (if (re-search-forward
18251 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18252 (match-beginning 1)
18253 (point-max)))
18254 nil)
18255 (org-cycle-hide-drawers 'children))
18256 (error nil))))
18258 (defun org-make-options-regexp (kwds &optional extra)
18259 "Make a regular expression for keyword lines."
18260 (concat
18262 "#?[ \t]*\\+\\("
18263 (mapconcat 'regexp-quote kwds "\\|")
18264 (if extra (concat "\\|" extra))
18265 "\\):[ \t]*"
18266 "\\(.*\\)"))
18268 ;; Make isearch reveal the necessary context
18269 (defun org-isearch-end ()
18270 "Reveal context after isearch exits."
18271 (when isearch-success ; only if search was successful
18272 (if (featurep 'xemacs)
18273 ;; Under XEmacs, the hook is run in the correct place,
18274 ;; we directly show the context.
18275 (org-show-context 'isearch)
18276 ;; In Emacs the hook runs *before* restoring the overlays.
18277 ;; So we have to use a one-time post-command-hook to do this.
18278 ;; (Emacs 22 has a special variable, see function `org-mode')
18279 (unless (and (boundp 'isearch-mode-end-hook-quit)
18280 isearch-mode-end-hook-quit)
18281 ;; Only when the isearch was not quitted.
18282 (org-add-hook 'post-command-hook 'org-isearch-post-command
18283 'append 'local)))))
18285 (defun org-isearch-post-command ()
18286 "Remove self from hook, and show context."
18287 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18288 (org-show-context 'isearch))
18291 ;;;; Integration with and fixes for other packages
18293 ;;; Imenu support
18295 (defvar org-imenu-markers nil
18296 "All markers currently used by Imenu.")
18297 (make-variable-buffer-local 'org-imenu-markers)
18299 (defun org-imenu-new-marker (&optional pos)
18300 "Return a new marker for use by Imenu, and remember the marker."
18301 (let ((m (make-marker)))
18302 (move-marker m (or pos (point)))
18303 (push m org-imenu-markers)
18306 (defun org-imenu-get-tree ()
18307 "Produce the index for Imenu."
18308 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18309 (setq org-imenu-markers nil)
18310 (let* ((n org-imenu-depth)
18311 (re (concat "^" outline-regexp))
18312 (subs (make-vector (1+ n) nil))
18313 (last-level 0)
18314 m level head)
18315 (save-excursion
18316 (save-restriction
18317 (widen)
18318 (goto-char (point-max))
18319 (while (re-search-backward re nil t)
18320 (setq level (org-reduced-level (funcall outline-level)))
18321 (when (<= level n)
18322 (looking-at org-complex-heading-regexp)
18323 (setq head (org-link-display-format
18324 (org-match-string-no-properties 4))
18325 m (org-imenu-new-marker))
18326 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18327 (if (>= level last-level)
18328 (push (cons head m) (aref subs level))
18329 (push (cons head (aref subs (1+ level))) (aref subs level))
18330 (loop for i from (1+ level) to n do (aset subs i nil)))
18331 (setq last-level level)))))
18332 (aref subs 1)))
18334 (eval-after-load "imenu"
18335 '(progn
18336 (add-hook 'imenu-after-jump-hook
18337 (lambda ()
18338 (if (eq major-mode 'org-mode)
18339 (org-show-context 'org-goto))))))
18341 (defun org-link-display-format (link)
18342 "Replace a link with either the description, or the link target
18343 if no description is present"
18344 (save-match-data
18345 (if (string-match org-bracket-link-analytic-regexp link)
18346 (replace-match (if (match-end 5)
18347 (match-string 5 link)
18348 (concat (match-string 1 link)
18349 (match-string 3 link)))
18350 nil t link)
18351 link)))
18353 ;; Speedbar support
18355 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18356 "Overlay marking the agenda restriction line in speedbar.")
18357 (org-overlay-put org-speedbar-restriction-lock-overlay
18358 'face 'org-agenda-restriction-lock)
18359 (org-overlay-put org-speedbar-restriction-lock-overlay
18360 'help-echo "Agendas are currently limited to this item.")
18361 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18363 (defun org-speedbar-set-agenda-restriction ()
18364 "Restrict future agenda commands to the location at point in speedbar.
18365 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18366 (interactive)
18367 (require 'org-agenda)
18368 (let (p m tp np dir txt)
18369 (cond
18370 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18371 'org-imenu t))
18372 (setq m (get-text-property p 'org-imenu-marker))
18373 (with-current-buffer (marker-buffer m)
18374 (goto-char m)
18375 (org-agenda-set-restriction-lock 'subtree)))
18376 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18377 'speedbar-function 'speedbar-find-file))
18378 (setq tp (previous-single-property-change
18379 (1+ p) 'speedbar-function)
18380 np (next-single-property-change
18381 tp 'speedbar-function)
18382 dir (speedbar-line-directory)
18383 txt (buffer-substring-no-properties (or tp (point-min))
18384 (or np (point-max))))
18385 (with-current-buffer (find-file-noselect
18386 (let ((default-directory dir))
18387 (expand-file-name txt)))
18388 (unless (org-mode-p)
18389 (error "Cannot restrict to non-Org-mode file"))
18390 (org-agenda-set-restriction-lock 'file)))
18391 (t (error "Don't know how to restrict Org-mode's agenda")))
18392 (org-move-overlay org-speedbar-restriction-lock-overlay
18393 (point-at-bol) (point-at-eol))
18394 (setq current-prefix-arg nil)
18395 (org-agenda-maybe-redo)))
18397 (eval-after-load "speedbar"
18398 '(progn
18399 (speedbar-add-supported-extension ".org")
18400 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18401 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18402 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18403 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18404 (add-hook 'speedbar-visiting-tag-hook
18405 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18408 ;;; Fixes and Hacks for problems with other packages
18410 ;; Make flyspell not check words in links, to not mess up our keymap
18411 (defun org-mode-flyspell-verify ()
18412 "Don't let flyspell put overlays at active buttons."
18413 (and (not (get-text-property (point) 'keymap))
18414 (not (get-text-property (point) 'org-no-flyspell))))
18416 (defun org-remove-flyspell-overlays-in (beg end)
18417 "Remove flyspell overlays in region."
18418 (and (org-bound-and-true-p flyspell-mode)
18419 (fboundp 'flyspell-delete-region-overlays)
18420 (flyspell-delete-region-overlays beg end))
18421 (add-text-properties beg end '(org-no-flyspell t)))
18423 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18424 (eval-after-load "bookmark"
18425 '(if (boundp 'bookmark-after-jump-hook)
18426 ;; We can use the hook
18427 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18428 ;; Hook not available, use advice
18429 (defadvice bookmark-jump (after org-make-visible activate)
18430 "Make the position visible."
18431 (org-bookmark-jump-unhide))))
18433 ;; Make sure saveplace shows the location if it was hidden
18434 (eval-after-load "saveplace"
18435 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18436 "Make the position visible."
18437 (org-bookmark-jump-unhide)))
18439 ;; Make sure ecb shows the location if it was hidden
18440 (eval-after-load "ecb"
18441 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18442 "Make hierarchy visible when jumping into location from ECB tree buffer."
18443 (if (eq major-mode 'org-mode)
18444 (org-show-context))))
18446 (defun org-bookmark-jump-unhide ()
18447 "Unhide the current position, to show the bookmark location."
18448 (and (org-mode-p)
18449 (or (org-invisible-p)
18450 (save-excursion (goto-char (max (point-min) (1- (point))))
18451 (org-invisible-p)))
18452 (org-show-context 'bookmark-jump)))
18454 ;; Make session.el ignore our circular variable
18455 (eval-after-load "session"
18456 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18458 ;;;; Experimental code
18460 (defun org-closed-in-range ()
18461 "Sparse tree of items closed in a certain time range.
18462 Still experimental, may disappear in the future."
18463 (interactive)
18464 ;; Get the time interval from the user.
18465 (let* ((time1 (org-float-time
18466 (org-read-date nil 'to-time nil "Starting date: ")))
18467 (time2 (org-float-time
18468 (org-read-date nil 'to-time nil "End date:")))
18469 ;; callback function
18470 (callback (lambda ()
18471 (let ((time
18472 (org-float-time
18473 (apply 'encode-time
18474 (org-parse-time-string
18475 (match-string 1))))))
18476 ;; check if time in interval
18477 (and (>= time time1) (<= time time2))))))
18478 ;; make tree, check each match with the callback
18479 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18481 ;;;; Finish up
18483 (provide 'org)
18485 (run-hooks 'org-load-hook)
18487 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18489 ;;; org.el ends here