Release 6.35f
[org-mode/org-tableheadings.git] / lisp / org.el
blob2fea170a34693aaead179ba2e989d3c99344f513
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.35f
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.35f"
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 \[PACKAGES]
2915 \[DEFAULT-PACKAGES]
2916 % The settings below are copied from fullpage.sty
2917 \\setlength{\\textwidth}{\\paperwidth}
2918 \\addtolength{\\textwidth}{-3cm}
2919 \\setlength{\\oddsidemargin}{1.5cm}
2920 \\addtolength{\\oddsidemargin}{-2.54cm}
2921 \\setlength{\\evensidemargin}{\\oddsidemargin}
2922 \\setlength{\\textheight}{\\paperheight}
2923 \\addtolength{\\textheight}{-\\headheight}
2924 \\addtolength{\\textheight}{-\\headsep}
2925 \\addtolength{\\textheight}{-\\footskip}
2926 \\addtolength{\\textheight}{-3cm}
2927 \\setlength{\\topmargin}{1.5cm}
2928 \\addtolength{\\topmargin}{-2.54cm}"
2929 "The document header used for processing LaTeX fragments.
2930 It is imperative that this header make sure that no page number
2931 appears on the page. The package defined in the variables
2932 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
2933 will either replace the placeholder \"[PACKAGES]\" in this header, or they
2934 will be appended."
2935 :group 'org-latex
2936 :type 'string)
2938 (defvar org-format-latex-header-extra nil)
2940 ;; The following variables are defined here because is it also used
2941 ;; when formatting latex fragments. Originally it was part of the
2942 ;; LaTeX exporter, which is why the name includes "export".
2943 (defcustom org-export-latex-default-packages-alist
2944 '(("AUTO" "inputenc")
2945 ("T1" "fontenc")
2946 ("" "fixltx2e")
2947 ("" "graphicx")
2948 ("" "longtable")
2949 ("" "float")
2950 ("" "wrapfig")
2951 ("" "soul")
2952 ("" "t1enc")
2953 ("" "textcomp")
2954 ("" "marvosym")
2955 ("" "wasysym")
2956 ("" "latexsym")
2957 ("" "amssymb")
2958 ("" "microtype")
2959 ("" "hyperref")
2960 "\\tolerance=1000"
2962 "Alist of default packages to be inserted in the header.
2963 Change this only if one of the packages here causes an incompatibility
2964 with another package you are using.
2965 The packages in this list are needed by one part or another of Org-mode
2966 to function properly.
2968 - inputenc, fontenc, t1enc: for basic font and character selection
2969 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
2970 for interpreting the entities in `org-entities'. You can skip some of these
2971 packages if you don't use any of the symbols in it.
2972 - graphicx: for including images
2973 - float, wrapfig: for figure placement
2974 - longtable: for long tables
2975 - hyperref: for cross references
2977 Therefore you should not modify this variable unless you know what you
2978 are doing. The one reason to change it anyway is that you might be loading
2979 some other package that conflicts with one of the default packages.
2980 Each cell is of the format \( \"options\" \"package\" \)."
2981 :group 'org-export-latex
2982 :type '(repeat
2983 (choice
2984 (string :tag "A line of LaTeX")
2985 (list :tag "options/package pair"
2986 (string :tag "options")
2987 (string :tag "package")))))
2989 (defcustom org-export-latex-packages-alist nil
2990 "Alist of packages to be inserted in every LaTeX the header.
2991 These will be inserted after `org-export-latex-default-packages-alist'.
2992 Each cell is of the format \( \"options\" \"package\" \).
2993 Make sure that you only lis packages here which:
2994 - you want in every file
2995 - do not conflict with the default packages in
2996 `org-export-latex-default-packages-alist'
2997 - do not conflict with the setup in `org-format-latex-header'."
2998 :group 'org-export-latex
2999 :type '(repeat
3000 (choice
3001 (string :tag "A line of LaTeX")
3002 (list :tag "options/package pair"
3003 (string :tag "options")
3004 (string :tag "package")))))
3006 (defgroup org-appearance nil
3007 "Settings for Org-mode appearance."
3008 :tag "Org Appearance"
3009 :group 'org)
3011 (defcustom org-level-color-stars-only nil
3012 "Non-nil means fontify only the stars in each headline.
3013 When nil, the entire headline is fontified.
3014 Changing it requires restart of `font-lock-mode' to become effective
3015 also in regions already fontified."
3016 :group 'org-appearance
3017 :type 'boolean)
3019 (defcustom org-hide-leading-stars nil
3020 "Non-nil means hide the first N-1 stars in a headline.
3021 This works by using the face `org-hide' for these stars. This
3022 face is white for a light background, and black for a dark
3023 background. You may have to customize the face `org-hide' to
3024 make this work.
3025 Changing it requires restart of `font-lock-mode' to become effective
3026 also in regions already fontified.
3027 You may also set this on a per-file basis by adding one of the following
3028 lines to the buffer:
3030 #+STARTUP: hidestars
3031 #+STARTUP: showstars"
3032 :group 'org-appearance
3033 :type 'boolean)
3035 (defcustom org-hidden-keywords nil
3036 "List of keywords that should be hidden when typed in the org buffer.
3037 For example, add #+TITLE to this list in order to make the
3038 document title appear in the buffer without the initial #+TITLE:
3039 keyword."
3040 :group 'org-appearance
3041 :type '(set (const :tag "#+AUTHOR" author)
3042 (const :tag "#+DATE" date)
3043 (const :tag "#+EMAIL" email)
3044 (const :tag "#+TITLE" title)))
3046 (defcustom org-fontify-done-headline nil
3047 "Non-nil means change the face of a headline if it is marked DONE.
3048 Normally, only the TODO/DONE keyword indicates the state of a headline.
3049 When this is non-nil, the headline after the keyword is set to the
3050 `org-headline-done' as an additional indication."
3051 :group 'org-appearance
3052 :type 'boolean)
3054 (defcustom org-fontify-emphasized-text t
3055 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3056 Changing this variable requires a restart of Emacs to take effect."
3057 :group 'org-appearance
3058 :type 'boolean)
3060 (defcustom org-fontify-whole-heading-line nil
3061 "Non-nil means fontify the whole line for headings.
3062 This is useful when setting a background color for the
3063 org-level-* faces."
3064 :group 'org-appearance
3065 :type 'boolean)
3067 (defcustom org-highlight-latex-fragments-and-specials nil
3068 "Non-nil means fontify what is treated specially by the exporters."
3069 :group 'org-appearance
3070 :type 'boolean)
3072 (defcustom org-hide-emphasis-markers nil
3073 "Non-nil mean font-lock should hide the emphasis marker characters."
3074 :group 'org-appearance
3075 :type 'boolean)
3077 (defvar org-emph-re nil
3078 "Regular expression for matching emphasis.")
3079 (defvar org-verbatim-re nil
3080 "Regular expression for matching verbatim text.")
3081 (defvar org-emphasis-regexp-components) ; defined just below
3082 (defvar org-emphasis-alist) ; defined just below
3083 (defun org-set-emph-re (var val)
3084 "Set variable and compute the emphasis regular expression."
3085 (set var val)
3086 (when (and (boundp 'org-emphasis-alist)
3087 (boundp 'org-emphasis-regexp-components)
3088 org-emphasis-alist org-emphasis-regexp-components)
3089 (let* ((e org-emphasis-regexp-components)
3090 (pre (car e))
3091 (post (nth 1 e))
3092 (border (nth 2 e))
3093 (body (nth 3 e))
3094 (nl (nth 4 e))
3095 (body1 (concat body "*?"))
3096 (markers (mapconcat 'car org-emphasis-alist ""))
3097 (vmarkers (mapconcat
3098 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3099 org-emphasis-alist "")))
3100 ;; make sure special characters appear at the right position in the class
3101 (if (string-match "\\^" markers)
3102 (setq markers (concat (replace-match "" t t markers) "^")))
3103 (if (string-match "-" markers)
3104 (setq markers (concat (replace-match "" t t markers) "-")))
3105 (if (string-match "\\^" vmarkers)
3106 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3107 (if (string-match "-" vmarkers)
3108 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3109 (if (> nl 0)
3110 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3111 (int-to-string nl) "\\}")))
3112 ;; Make the regexp
3113 (setq org-emph-re
3114 (concat "\\([" pre "]\\|^\\)"
3115 "\\("
3116 "\\([" markers "]\\)"
3117 "\\("
3118 "[^" border "]\\|"
3119 "[^" border "]"
3120 body1
3121 "[^" border "]"
3122 "\\)"
3123 "\\3\\)"
3124 "\\([" post "]\\|$\\)"))
3125 (setq org-verbatim-re
3126 (concat "\\([" pre "]\\|^\\)"
3127 "\\("
3128 "\\([" vmarkers "]\\)"
3129 "\\("
3130 "[^" border "]\\|"
3131 "[^" border "]"
3132 body1
3133 "[^" border "]"
3134 "\\)"
3135 "\\3\\)"
3136 "\\([" post "]\\|$\\)")))))
3138 (defcustom org-emphasis-regexp-components
3139 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3140 "Components used to build the regular expression for emphasis.
3141 This is a list with 6 entries. Terminology: In an emphasis string
3142 like \" *strong word* \", we call the initial space PREMATCH, the final
3143 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3144 and \"trong wor\" is the body. The different components in this variable
3145 specify what is allowed/forbidden in each part:
3147 pre Chars allowed as prematch. Beginning of line will be allowed too.
3148 post Chars allowed as postmatch. End of line will be allowed too.
3149 border The chars *forbidden* as border characters.
3150 body-regexp A regexp like \".\" to match a body character. Don't use
3151 non-shy groups here, and don't allow newline here.
3152 newline The maximum number of newlines allowed in an emphasis exp.
3154 Use customize to modify this, or restart Emacs after changing it."
3155 :group 'org-appearance
3156 :set 'org-set-emph-re
3157 :type '(list
3158 (sexp :tag "Allowed chars in pre ")
3159 (sexp :tag "Allowed chars in post ")
3160 (sexp :tag "Forbidden chars in border ")
3161 (sexp :tag "Regexp for body ")
3162 (integer :tag "number of newlines allowed")
3163 (option (boolean :tag "Please ignore this button"))))
3165 (defcustom org-emphasis-alist
3166 `(("*" bold "<b>" "</b>")
3167 ("/" italic "<i>" "</i>")
3168 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3169 ("=" org-code "<code>" "</code>" verbatim)
3170 ("~" org-verbatim "<code>" "</code>" verbatim)
3171 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3172 "<del>" "</del>")
3174 "Special syntax for emphasized text.
3175 Text starting and ending with a special character will be emphasized, for
3176 example *bold*, _underlined_ and /italic/. This variable sets the marker
3177 characters, the face to be used by font-lock for highlighting in Org-mode
3178 Emacs buffers, and the HTML tags to be used for this.
3179 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3180 Use customize to modify this, or restart Emacs after changing it."
3181 :group 'org-appearance
3182 :set 'org-set-emph-re
3183 :type '(repeat
3184 (list
3185 (string :tag "Marker character")
3186 (choice
3187 (face :tag "Font-lock-face")
3188 (plist :tag "Face property list"))
3189 (string :tag "HTML start tag")
3190 (string :tag "HTML end tag")
3191 (option (const verbatim)))))
3193 (defvar org-protecting-blocks
3194 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3195 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3196 This is needed for font-lock setup.")
3198 ;;; Miscellaneous options
3200 (defgroup org-completion nil
3201 "Completion in Org-mode."
3202 :tag "Org Completion"
3203 :group 'org)
3205 (defcustom org-completion-use-ido nil
3206 "Non-nil means use ido completion wherever possible.
3207 Note that `ido-mode' must be active for this variable to be relevant.
3208 If you decide to turn this variable on, you might well want to turn off
3209 `org-outline-path-complete-in-steps'.
3210 See also `org-completion-use-iswitchb'."
3211 :group 'org-completion
3212 :type 'boolean)
3214 (defcustom org-completion-use-iswitchb nil
3215 "Non-nil means use iswitchb completion wherever possible.
3216 Note that `iswitchb-mode' must be active for this variable to be relevant.
3217 If you decide to turn this variable on, you might well want to turn off
3218 `org-outline-path-complete-in-steps'.
3219 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3220 :group 'org-completion
3221 :type 'boolean)
3223 (defcustom org-completion-fallback-command 'hippie-expand
3224 "The expansion command called by \\[org-complete] in normal context.
3225 Normal means no org-mode-specific context."
3226 :group 'org-completion
3227 :type 'function)
3229 ;;; Functions and variables from their packages
3230 ;; Declared here to avoid compiler warnings
3232 ;; XEmacs only
3233 (defvar outline-mode-menu-heading)
3234 (defvar outline-mode-menu-show)
3235 (defvar outline-mode-menu-hide)
3236 (defvar zmacs-regions) ; XEmacs regions
3238 ;; Emacs only
3239 (defvar mark-active)
3241 ;; Various packages
3242 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3243 (declare-function calendar-forward-day "cal-move" (arg))
3244 (declare-function calendar-goto-date "cal-move" (date))
3245 (declare-function calendar-goto-today "cal-move" ())
3246 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3247 (defvar calc-embedded-close-formula)
3248 (defvar calc-embedded-open-formula)
3249 (declare-function cdlatex-tab "ext:cdlatex" ())
3250 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3251 (defvar font-lock-unfontify-region-function)
3252 (declare-function iswitchb-read-buffer "iswitchb"
3253 (prompt &optional default require-match start matches-set))
3254 (defvar iswitchb-temp-buflist)
3255 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3256 (defvar org-agenda-tags-todo-honor-ignore-options)
3257 (declare-function org-agenda-skip "org-agenda" ())
3258 (declare-function
3259 org-format-agenda-item "org-agenda"
3260 (extra txt &optional category tags dotime noprefix remove-re habitp))
3261 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3262 (declare-function org-agenda-change-all-lines "org-agenda"
3263 (newhead hdmarker &optional fixface just-this))
3264 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3265 (declare-function org-agenda-maybe-redo "org-agenda" ())
3266 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3267 (beg end))
3268 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3269 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3270 "org-agenda" (&optional end))
3271 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3272 (declare-function org-indent-mode "org-indent" (&optional arg))
3273 (declare-function parse-time-string "parse-time" (string))
3274 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3275 (defvar remember-data-file)
3276 (defvar texmathp-why)
3277 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3278 (declare-function table--at-cell-p "table" (position &optional object at-column))
3280 (defvar w3m-current-url)
3281 (defvar w3m-current-title)
3283 (defvar org-latex-regexps)
3285 ;;; Autoload and prepare some org modules
3287 ;; Some table stuff that needs to be defined here, because it is used
3288 ;; by the functions setting up org-mode or checking for table context.
3290 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3291 "Detects an org-type or table-type table.")
3292 (defconst org-table-line-regexp "^[ \t]*|"
3293 "Detects an org-type table line.")
3294 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3295 "Detects an org-type table line.")
3296 (defconst org-table-hline-regexp "^[ \t]*|-"
3297 "Detects an org-type table hline.")
3298 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3299 "Detects a table-type table hline.")
3300 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3301 "Searching from within a table (any type) this finds the first line
3302 outside the table.")
3304 ;; Autoload the functions in org-table.el that are needed by functions here.
3306 (eval-and-compile
3307 (org-autoload "org-table"
3308 '(org-table-align org-table-begin org-table-blank-field
3309 org-table-convert org-table-convert-region org-table-copy-down
3310 org-table-copy-region org-table-create
3311 org-table-create-or-convert-from-region
3312 org-table-create-with-table.el org-table-current-dline
3313 org-table-cut-region org-table-delete-column org-table-edit-field
3314 org-table-edit-formulas org-table-end org-table-eval-formula
3315 org-table-export org-table-field-info
3316 org-table-get-stored-formulas org-table-goto-column
3317 org-table-hline-and-move org-table-import org-table-insert-column
3318 org-table-insert-hline org-table-insert-row org-table-iterate
3319 org-table-justify-field-maybe org-table-kill-row
3320 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3321 org-table-move-column org-table-move-column-left
3322 org-table-move-column-right org-table-move-row
3323 org-table-move-row-down org-table-move-row-up
3324 org-table-next-field org-table-next-row org-table-paste-rectangle
3325 org-table-previous-field org-table-recalculate
3326 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3327 org-table-toggle-coordinate-overlays
3328 org-table-toggle-formula-debugger org-table-wrap-region
3329 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3331 (defun org-at-table-p (&optional table-type)
3332 "Return t if the cursor is inside an org-type table.
3333 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3334 (if org-enable-table-editor
3335 (save-excursion
3336 (beginning-of-line 1)
3337 (looking-at (if table-type org-table-any-line-regexp
3338 org-table-line-regexp)))
3339 nil))
3340 (defsubst org-table-p () (org-at-table-p))
3342 (defun org-at-table.el-p ()
3343 "Return t if and only if we are at a table.el table."
3344 (and (org-at-table-p 'any)
3345 (save-excursion
3346 (goto-char (org-table-begin 'any))
3347 (looking-at org-table1-hline-regexp))))
3348 (defun org-table-recognize-table.el ()
3349 "If there is a table.el table nearby, recognize it and move into it."
3350 (if org-table-tab-recognizes-table.el
3351 (if (org-at-table.el-p)
3352 (progn
3353 (beginning-of-line 1)
3354 (if (looking-at org-table-dataline-regexp)
3356 (if (looking-at org-table1-hline-regexp)
3357 (progn
3358 (beginning-of-line 2)
3359 (if (looking-at org-table-any-border-regexp)
3360 (beginning-of-line -1)))))
3361 (if (re-search-forward "|" (org-table-end t) t)
3362 (progn
3363 (require 'table)
3364 (if (table--at-cell-p (point))
3366 (message "recognizing table.el table...")
3367 (table-recognize-table)
3368 (message "recognizing table.el table...done")))
3369 (error "This should not happen..."))
3371 nil)
3372 nil))
3374 (defun org-at-table-hline-p ()
3375 "Return t if the cursor is inside a hline in a table."
3376 (if org-enable-table-editor
3377 (save-excursion
3378 (beginning-of-line 1)
3379 (looking-at org-table-hline-regexp))
3380 nil))
3382 (defvar org-table-clean-did-remove-column nil)
3384 (defun org-table-map-tables (function)
3385 "Apply FUNCTION to the start of all tables in the buffer."
3386 (save-excursion
3387 (save-restriction
3388 (widen)
3389 (goto-char (point-min))
3390 (while (re-search-forward org-table-any-line-regexp nil t)
3391 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3392 (beginning-of-line 1)
3393 (when (looking-at org-table-line-regexp)
3394 (save-excursion (funcall function))
3395 (or (looking-at org-table-line-regexp)
3396 (forward-char 1)))
3397 (re-search-forward org-table-any-border-regexp nil 1))))
3398 (message "Mapping tables: done"))
3400 ;; Declare and autoload functions from org-exp.el & Co
3402 (declare-function org-default-export-plist "org-exp")
3403 (declare-function org-infile-export-plist "org-exp")
3404 (declare-function org-get-current-options "org-exp")
3405 (eval-and-compile
3406 (org-autoload "org-exp"
3407 '(org-export org-export-visible
3408 org-insert-export-options-template
3409 org-table-clean-before-export))
3410 (org-autoload "org-ascii"
3411 '(org-export-as-ascii org-export-ascii-preprocess
3412 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3413 org-export-region-as-ascii))
3414 (org-autoload "org-latex"
3415 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3416 org-replace-region-by-latex org-export-region-as-latex
3417 org-export-as-latex org-export-as-pdf
3418 org-export-as-pdf-and-open))
3419 (org-autoload "org-html"
3420 '(org-export-as-html-and-open
3421 org-export-as-html-batch org-export-as-html-to-buffer
3422 org-replace-region-by-html org-export-region-as-html
3423 org-export-as-html))
3424 (org-autoload "org-docbook"
3425 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3426 org-replace-region-by-docbook org-export-region-as-docbook
3427 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3428 org-export-as-docbook))
3429 (org-autoload "org-icalendar"
3430 '(org-export-icalendar-this-file
3431 org-export-icalendar-all-agenda-files
3432 org-export-icalendar-combine-agenda-files))
3433 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3434 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3436 ;; Declare and autoload functions from org-agenda.el
3438 (eval-and-compile
3439 (org-autoload "org-agenda"
3440 '(org-agenda org-agenda-list org-search-view
3441 org-todo-list org-tags-view org-agenda-list-stuck-projects
3442 org-diary org-agenda-to-appt
3443 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3445 ;; Autoload org-remember
3447 (eval-and-compile
3448 (org-autoload "org-remember"
3449 '(org-remember-insinuate org-remember-annotation
3450 org-remember-apply-template org-remember org-remember-handler)))
3452 ;; Autoload org-clock.el
3455 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3456 (beg end))
3457 (declare-function org-clock-update-mode-line "org-clock" ())
3458 (declare-function org-resolve-clocks "org-clock"
3459 (&optional also-non-dangling-p prompt last-valid))
3460 (defvar org-clock-start-time)
3461 (defvar org-clock-marker (make-marker)
3462 "Marker recording the last clock-in.")
3463 (defvar org-clock-hd-marker (make-marker)
3464 "Marker recording the last clock-in, but the headline position.")
3465 (defvar org-clock-heading ""
3466 "The heading of the current clock entry.")
3467 (defun org-clock-is-active ()
3468 "Return non-nil if clock is currently running.
3469 The return value is actually the clock marker."
3470 (marker-buffer org-clock-marker))
3472 (eval-and-compile
3473 (org-autoload
3474 "org-clock"
3475 '(org-clock-in org-clock-out org-clock-cancel
3476 org-clock-goto org-clock-sum org-clock-display
3477 org-clock-remove-overlays org-clock-report
3478 org-clocktable-shift org-dblock-write:clocktable
3479 org-get-clocktable org-resolve-clocks)))
3481 (defun org-clock-update-time-maybe ()
3482 "If this is a CLOCK line, update it and return t.
3483 Otherwise, return nil."
3484 (interactive)
3485 (save-excursion
3486 (beginning-of-line 1)
3487 (skip-chars-forward " \t")
3488 (when (looking-at org-clock-string)
3489 (let ((re (concat "[ \t]*" org-clock-string
3490 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3491 "\\([ \t]*=>.*\\)?\\)?"))
3492 ts te h m s neg)
3493 (cond
3494 ((not (looking-at re))
3495 nil)
3496 ((not (match-end 2))
3497 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3498 (> org-clock-marker (point))
3499 (<= org-clock-marker (point-at-eol)))
3500 ;; The clock is running here
3501 (setq org-clock-start-time
3502 (apply 'encode-time
3503 (org-parse-time-string (match-string 1))))
3504 (org-clock-update-mode-line)))
3506 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3507 (end-of-line 1)
3508 (setq ts (match-string 1)
3509 te (match-string 3))
3510 (setq s (- (org-float-time
3511 (apply 'encode-time (org-parse-time-string te)))
3512 (org-float-time
3513 (apply 'encode-time (org-parse-time-string ts))))
3514 neg (< s 0)
3515 s (abs s)
3516 h (floor (/ s 3600))
3517 s (- s (* 3600 h))
3518 m (floor (/ s 60))
3519 s (- s (* 60 s)))
3520 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3521 t))))))
3523 (defun org-check-running-clock ()
3524 "Check if the current buffer contains the running clock.
3525 If yes, offer to stop it and to save the buffer with the changes."
3526 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3527 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3528 (buffer-name))))
3529 (org-clock-out)
3530 (when (y-or-n-p "Save changed buffer?")
3531 (save-buffer))))
3533 (defun org-clocktable-try-shift (dir n)
3534 "Check if this line starts a clock table, if yes, shift the time block."
3535 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3536 (org-clocktable-shift dir n)))
3538 ;; Autoload org-timer.el
3540 (eval-and-compile
3541 (org-autoload
3542 "org-timer"
3543 '(org-timer-start org-timer org-timer-item
3544 org-timer-change-times-in-region
3545 org-timer-set-timer
3546 org-timer-reset-timers
3547 org-timer-show-remaining-time)))
3549 ;; Autoload org-feed.el
3551 (eval-and-compile
3552 (org-autoload
3553 "org-feed"
3554 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3557 ;; Autoload org-indent.el
3559 ;; Define the variable already here, to make sure we have it.
3560 (defvar org-indent-mode nil
3561 "Non-nil if Org-Indent mode is enabled.
3562 Use the command `org-indent-mode' to change this variable.")
3564 (eval-and-compile
3565 (org-autoload
3566 "org-indent"
3567 '(org-indent-mode)))
3569 ;; Autoload org-mobile.el
3571 (eval-and-compile
3572 (org-autoload
3573 "org-mobile"
3574 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3576 ;; Autoload archiving code
3577 ;; The stuff that is needed for cycling and tags has to be defined here.
3579 (defgroup org-archive nil
3580 "Options concerning archiving in Org-mode."
3581 :tag "Org Archive"
3582 :group 'org-structure)
3584 (defcustom org-archive-location "%s_archive::"
3585 "The location where subtrees should be archived.
3587 The value of this variable is a string, consisting of two parts,
3588 separated by a double-colon. The first part is a filename and
3589 the second part is a headline.
3591 When the filename is omitted, archiving happens in the same file.
3592 %s in the filename will be replaced by the current file
3593 name (without the directory part). Archiving to a different file
3594 is useful to keep archived entries from contributing to the
3595 Org-mode Agenda.
3597 The archived entries will be filed as subtrees of the specified
3598 headline. When the headline is omitted, the subtrees are simply
3599 filed away at the end of the file, as top-level entries. Also in
3600 the heading you can use %s to represent the file name, this can be
3601 useful when using the same archive for a number of different files.
3603 Here are a few examples:
3604 \"%s_archive::\"
3605 If the current file is Projects.org, archive in file
3606 Projects.org_archive, as top-level trees. This is the default.
3608 \"::* Archived Tasks\"
3609 Archive in the current file, under the top-level headline
3610 \"* Archived Tasks\".
3612 \"~/org/archive.org::\"
3613 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3615 \"~/org/archive.org::From %s\"
3616 Archive in file ~/org/archive.org (absolute path), under headlines
3617 \"From FILENAME\" where file name is the current file name.
3619 \"basement::** Finished Tasks\"
3620 Archive in file ./basement (relative path), as level 3 trees
3621 below the level 2 heading \"** Finished Tasks\".
3623 You may set this option on a per-file basis by adding to the buffer a
3624 line like
3626 #+ARCHIVE: basement::** Finished Tasks
3628 You may also define it locally for a subtree by setting an ARCHIVE property
3629 in the entry. If such a property is found in an entry, or anywhere up
3630 the hierarchy, it will be used."
3631 :group 'org-archive
3632 :type 'string)
3634 (defcustom org-archive-tag "ARCHIVE"
3635 "The tag that marks a subtree as archived.
3636 An archived subtree does not open during visibility cycling, and does
3637 not contribute to the agenda listings.
3638 After changing this, font-lock must be restarted in the relevant buffers to
3639 get the proper fontification."
3640 :group 'org-archive
3641 :group 'org-keywords
3642 :type 'string)
3644 (defcustom org-agenda-skip-archived-trees t
3645 "Non-nil means the agenda will skip any items located in archived trees.
3646 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3647 variable is no longer recommended, you should leave it at the value t.
3648 Instead, use the key `v' to cycle the archives-mode in the agenda."
3649 :group 'org-archive
3650 :group 'org-agenda-skip
3651 :type 'boolean)
3653 (defcustom org-columns-skip-archived-trees t
3654 "Non-nil means ignore archived trees when creating column view."
3655 :group 'org-archive
3656 :group 'org-properties
3657 :type 'boolean)
3659 (defcustom org-cycle-open-archived-trees nil
3660 "Non-nil means `org-cycle' will open archived trees.
3661 An archived tree is a tree marked with the tag ARCHIVE.
3662 When nil, archived trees will stay folded. You can still open them with
3663 normal outline commands like `show-all', but not with the cycling commands."
3664 :group 'org-archive
3665 :group 'org-cycle
3666 :type 'boolean)
3668 (defcustom org-sparse-tree-open-archived-trees nil
3669 "Non-nil means sparse tree construction shows matches in archived trees.
3670 When nil, matches in these trees are highlighted, but the trees are kept in
3671 collapsed state."
3672 :group 'org-archive
3673 :group 'org-sparse-trees
3674 :type 'boolean)
3676 (defun org-cycle-hide-archived-subtrees (state)
3677 "Re-hide all archived subtrees after a visibility state change."
3678 (when (and (not org-cycle-open-archived-trees)
3679 (not (memq state '(overview folded))))
3680 (save-excursion
3681 (let* ((globalp (memq state '(contents all)))
3682 (beg (if globalp (point-min) (point)))
3683 (end (if globalp (point-max) (org-end-of-subtree t))))
3684 (org-hide-archived-subtrees beg end)
3685 (goto-char beg)
3686 (if (looking-at (concat ".*:" org-archive-tag ":"))
3687 (message "%s" (substitute-command-keys
3688 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3690 (defun org-force-cycle-archived ()
3691 "Cycle subtree even if it is archived."
3692 (interactive)
3693 (setq this-command 'org-cycle)
3694 (let ((org-cycle-open-archived-trees t))
3695 (call-interactively 'org-cycle)))
3697 (defun org-hide-archived-subtrees (beg end)
3698 "Re-hide all archived subtrees after a visibility state change."
3699 (save-excursion
3700 (let* ((re (concat ":" org-archive-tag ":")))
3701 (goto-char beg)
3702 (while (re-search-forward re end t)
3703 (when (org-on-heading-p)
3704 (org-flag-subtree t)
3705 (org-end-of-subtree t))))))
3707 (defun org-flag-subtree (flag)
3708 (save-excursion
3709 (org-back-to-heading t)
3710 (outline-end-of-heading)
3711 (outline-flag-region (point)
3712 (progn (org-end-of-subtree t) (point))
3713 flag)))
3715 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3717 (eval-and-compile
3718 (org-autoload "org-archive"
3719 '(org-add-archive-files org-archive-subtree
3720 org-archive-to-archive-sibling org-toggle-archive-tag
3721 org-archive-subtree-default
3722 org-archive-subtree-default-with-confirmation)))
3724 ;; Autoload Column View Code
3726 (declare-function org-columns-number-to-string "org-colview")
3727 (declare-function org-columns-get-format-and-top-level "org-colview")
3728 (declare-function org-columns-compute "org-colview")
3730 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3731 '(org-columns-number-to-string org-columns-get-format-and-top-level
3732 org-columns-compute org-agenda-columns org-columns-remove-overlays
3733 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3735 ;; Autoload ID code
3737 (declare-function org-id-store-link "org-id")
3738 (declare-function org-id-locations-load "org-id")
3739 (declare-function org-id-locations-save "org-id")
3740 (defvar org-id-track-globally)
3741 (org-autoload "org-id"
3742 '(org-id-get-create org-id-new org-id-copy org-id-get
3743 org-id-get-with-outline-path-completion
3744 org-id-get-with-outline-drilling
3745 org-id-goto org-id-find org-id-store-link))
3747 ;; Autoload Plotting Code
3749 (org-autoload "org-plot"
3750 '(org-plot/gnuplot))
3752 ;;; Variables for pre-computed regular expressions, all buffer local
3754 (defvar org-drawer-regexp nil
3755 "Matches first line of a hidden block.")
3756 (make-variable-buffer-local 'org-drawer-regexp)
3757 (defvar org-todo-regexp nil
3758 "Matches any of the TODO state keywords.")
3759 (make-variable-buffer-local 'org-todo-regexp)
3760 (defvar org-not-done-regexp nil
3761 "Matches any of the TODO state keywords except the last one.")
3762 (make-variable-buffer-local 'org-not-done-regexp)
3763 (defvar org-not-done-heading-regexp nil
3764 "Matches a TODO headline that is not done.")
3765 (make-variable-buffer-local 'org-not-done-regexp)
3766 (defvar org-todo-line-regexp nil
3767 "Matches a headline and puts TODO state into group 2 if present.")
3768 (make-variable-buffer-local 'org-todo-line-regexp)
3769 (defvar org-complex-heading-regexp nil
3770 "Matches a headline and puts everything into groups:
3771 group 1: the stars
3772 group 2: The todo keyword, maybe
3773 group 3: Priority cookie
3774 group 4: True headline
3775 group 5: Tags")
3776 (make-variable-buffer-local 'org-complex-heading-regexp)
3777 (defvar org-complex-heading-regexp-format nil)
3778 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3779 (defvar org-todo-line-tags-regexp nil
3780 "Matches a headline and puts TODO state into group 2 if present.
3781 Also put tags into group 4 if tags are present.")
3782 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3783 (defvar org-nl-done-regexp nil
3784 "Matches newline followed by a headline with the DONE keyword.")
3785 (make-variable-buffer-local 'org-nl-done-regexp)
3786 (defvar org-looking-at-done-regexp nil
3787 "Matches the DONE keyword a point.")
3788 (make-variable-buffer-local 'org-looking-at-done-regexp)
3789 (defvar org-ds-keyword-length 12
3790 "Maximum length of the Deadline and SCHEDULED keywords.")
3791 (make-variable-buffer-local 'org-ds-keyword-length)
3792 (defvar org-deadline-regexp nil
3793 "Matches the DEADLINE keyword.")
3794 (make-variable-buffer-local 'org-deadline-regexp)
3795 (defvar org-deadline-time-regexp nil
3796 "Matches the DEADLINE keyword together with a time stamp.")
3797 (make-variable-buffer-local 'org-deadline-time-regexp)
3798 (defvar org-deadline-line-regexp nil
3799 "Matches the DEADLINE keyword and the rest of the line.")
3800 (make-variable-buffer-local 'org-deadline-line-regexp)
3801 (defvar org-scheduled-regexp nil
3802 "Matches the SCHEDULED keyword.")
3803 (make-variable-buffer-local 'org-scheduled-regexp)
3804 (defvar org-scheduled-time-regexp nil
3805 "Matches the SCHEDULED keyword together with a time stamp.")
3806 (make-variable-buffer-local 'org-scheduled-time-regexp)
3807 (defvar org-closed-time-regexp nil
3808 "Matches the CLOSED keyword together with a time stamp.")
3809 (make-variable-buffer-local 'org-closed-time-regexp)
3811 (defvar org-keyword-time-regexp nil
3812 "Matches any of the 4 keywords, together with the time stamp.")
3813 (make-variable-buffer-local 'org-keyword-time-regexp)
3814 (defvar org-keyword-time-not-clock-regexp nil
3815 "Matches any of the 3 keywords, together with the time stamp.")
3816 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3817 (defvar org-maybe-keyword-time-regexp nil
3818 "Matches a timestamp, possibly preceeded by a keyword.")
3819 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3820 (defvar org-planning-or-clock-line-re nil
3821 "Matches a line with planning or clock info.")
3822 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3823 (defvar org-all-time-keywords nil
3824 "List of time keywords.")
3825 (make-variable-buffer-local 'org-all-time-keywords)
3827 (defconst org-plain-time-of-day-regexp
3828 (concat
3829 "\\(\\<[012]?[0-9]"
3830 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3831 "\\(--?"
3832 "\\(\\<[012]?[0-9]"
3833 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3834 "\\)?")
3835 "Regular expression to match a plain time or time range.
3836 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3837 groups carry important information:
3838 0 the full match
3839 1 the first time, range or not
3840 8 the second time, if it is a range.")
3842 (defconst org-plain-time-extension-regexp
3843 (concat
3844 "\\(\\<[012]?[0-9]"
3845 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3846 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3847 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3848 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3849 groups carry important information:
3850 0 the full match
3851 7 hours of duration
3852 9 minutes of duration")
3854 (defconst org-stamp-time-of-day-regexp
3855 (concat
3856 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3857 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3858 "\\(--?"
3859 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3860 "Regular expression to match a timestamp time or time range.
3861 After a match, the following groups carry important information:
3862 0 the full match
3863 1 date plus weekday, for back referencing to make sure both times are on the same day
3864 2 the first time, range or not
3865 4 the second time, if it is a range.")
3867 (defconst org-startup-options
3868 '(("fold" org-startup-folded t)
3869 ("overview" org-startup-folded t)
3870 ("nofold" org-startup-folded nil)
3871 ("showall" org-startup-folded nil)
3872 ("showeverything" org-startup-folded showeverything)
3873 ("content" org-startup-folded content)
3874 ("indent" org-startup-indented t)
3875 ("noindent" org-startup-indented nil)
3876 ("hidestars" org-hide-leading-stars t)
3877 ("showstars" org-hide-leading-stars nil)
3878 ("odd" org-odd-levels-only t)
3879 ("oddeven" org-odd-levels-only nil)
3880 ("align" org-startup-align-all-tables t)
3881 ("noalign" org-startup-align-all-tables nil)
3882 ("customtime" org-display-custom-times t)
3883 ("logdone" org-log-done time)
3884 ("lognotedone" org-log-done note)
3885 ("nologdone" org-log-done nil)
3886 ("lognoteclock-out" org-log-note-clock-out t)
3887 ("nolognoteclock-out" org-log-note-clock-out nil)
3888 ("logrepeat" org-log-repeat state)
3889 ("lognoterepeat" org-log-repeat note)
3890 ("nologrepeat" org-log-repeat nil)
3891 ("logreschedule" org-log-reschedule time)
3892 ("lognotereschedule" org-log-reschedule note)
3893 ("nologreschedule" org-log-reschedule nil)
3894 ("logredeadline" org-log-redeadline time)
3895 ("lognoteredeadline" org-log-redeadline note)
3896 ("nologredeadline" org-log-redeadline nil)
3897 ("logrefile" org-log-refile time)
3898 ("lognoterefile" org-log-refile note)
3899 ("nologrefile" org-log-refile nil)
3900 ("fninline" org-footnote-define-inline t)
3901 ("nofninline" org-footnote-define-inline nil)
3902 ("fnlocal" org-footnote-section nil)
3903 ("fnauto" org-footnote-auto-label t)
3904 ("fnprompt" org-footnote-auto-label nil)
3905 ("fnconfirm" org-footnote-auto-label confirm)
3906 ("fnplain" org-footnote-auto-label plain)
3907 ("fnadjust" org-footnote-auto-adjust t)
3908 ("nofnadjust" org-footnote-auto-adjust nil)
3909 ("constcgs" constants-unit-system cgs)
3910 ("constSI" constants-unit-system SI)
3911 ("noptag" org-tag-persistent-alist nil)
3912 ("hideblocks" org-hide-block-startup t)
3913 ("nohideblocks" org-hide-block-startup nil)
3914 ("beamer" org-startup-with-beamer-mode t))
3915 "Variable associated with STARTUP options for org-mode.
3916 Each element is a list of three items: The startup options as written
3917 in the #+STARTUP line, the corresponding variable, and the value to
3918 set this variable to if the option is found. An optional forth element PUSH
3919 means to push this value onto the list in the variable.")
3921 (defun org-set-regexps-and-options ()
3922 "Precompute regular expressions for current buffer."
3923 (when (org-mode-p)
3924 (org-set-local 'org-todo-kwd-alist nil)
3925 (org-set-local 'org-todo-key-alist nil)
3926 (org-set-local 'org-todo-key-trigger nil)
3927 (org-set-local 'org-todo-keywords-1 nil)
3928 (org-set-local 'org-done-keywords nil)
3929 (org-set-local 'org-todo-heads nil)
3930 (org-set-local 'org-todo-sets nil)
3931 (org-set-local 'org-todo-log-states nil)
3932 (org-set-local 'org-file-properties nil)
3933 (org-set-local 'org-file-tags nil)
3934 (let ((re (org-make-options-regexp
3935 '("CATEGORY" "TODO" "COLUMNS"
3936 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3937 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3938 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3939 (splitre "[ \t]+")
3940 kwds kws0 kwsa key log value cat arch tags const links hw dws
3941 tail sep kws1 prio props ftags drawers beamer-p
3942 ext-setup-or-nil setup-contents (start 0))
3943 (save-excursion
3944 (save-restriction
3945 (widen)
3946 (goto-char (point-min))
3947 (while (or (and ext-setup-or-nil
3948 (string-match re ext-setup-or-nil start)
3949 (setq start (match-end 0)))
3950 (and (setq ext-setup-or-nil nil start 0)
3951 (re-search-forward re nil t)))
3952 (setq key (upcase (match-string 1 ext-setup-or-nil))
3953 value (org-match-string-no-properties 2 ext-setup-or-nil))
3954 (cond
3955 ((equal key "CATEGORY")
3956 (if (string-match "[ \t]+$" value)
3957 (setq value (replace-match "" t t value)))
3958 (setq cat value))
3959 ((member key '("SEQ_TODO" "TODO"))
3960 (push (cons 'sequence (org-split-string value splitre)) kwds))
3961 ((equal key "TYP_TODO")
3962 (push (cons 'type (org-split-string value splitre)) kwds))
3963 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3964 ;; general TODO-like setup
3965 (push (cons (intern (downcase (match-string 1 key)))
3966 (org-split-string value splitre)) kwds))
3967 ((equal key "TAGS")
3968 (setq tags (append tags (if tags '("\\n") nil)
3969 (org-split-string value splitre))))
3970 ((equal key "COLUMNS")
3971 (org-set-local 'org-columns-default-format value))
3972 ((equal key "LINK")
3973 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3974 (push (cons (match-string 1 value)
3975 (org-trim (match-string 2 value)))
3976 links)))
3977 ((equal key "PRIORITIES")
3978 (setq prio (org-split-string value " +")))
3979 ((equal key "PROPERTY")
3980 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3981 (push (cons (match-string 1 value) (match-string 2 value))
3982 props)))
3983 ((equal key "FILETAGS")
3984 (when (string-match "\\S-" value)
3985 (setq ftags
3986 (append
3987 ftags
3988 (apply 'append
3989 (mapcar (lambda (x) (org-split-string x ":"))
3990 (org-split-string value)))))))
3991 ((equal key "DRAWERS")
3992 (setq drawers (org-split-string value splitre)))
3993 ((equal key "CONSTANTS")
3994 (setq const (append const (org-split-string value splitre))))
3995 ((equal key "STARTUP")
3996 (let ((opts (org-split-string value splitre))
3997 l var val)
3998 (while (setq l (pop opts))
3999 (when (setq l (assoc l org-startup-options))
4000 (setq var (nth 1 l) val (nth 2 l))
4001 (if (not (nth 3 l))
4002 (set (make-local-variable var) val)
4003 (if (not (listp (symbol-value var)))
4004 (set (make-local-variable var) nil))
4005 (set (make-local-variable var) (symbol-value var))
4006 (add-to-list var val))))))
4007 ((equal key "ARCHIVE")
4008 (string-match " *$" value)
4009 (setq arch (replace-match "" t t value))
4010 (remove-text-properties 0 (length arch)
4011 '(face t fontified t) arch))
4012 ((equal key "LATEX_CLASS")
4013 (setq beamer-p (equal value "beamer")))
4014 ((equal key "SETUPFILE")
4015 (setq setup-contents (org-file-contents
4016 (expand-file-name
4017 (org-remove-double-quotes value))
4018 'noerror))
4019 (if (not ext-setup-or-nil)
4020 (setq ext-setup-or-nil setup-contents start 0)
4021 (setq ext-setup-or-nil
4022 (concat (substring ext-setup-or-nil 0 start)
4023 "\n" setup-contents "\n"
4024 (substring ext-setup-or-nil start)))))
4025 ))))
4026 (when cat
4027 (org-set-local 'org-category (intern cat))
4028 (push (cons "CATEGORY" cat) props))
4029 (when prio
4030 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4031 (setq prio (mapcar 'string-to-char prio))
4032 (org-set-local 'org-highest-priority (nth 0 prio))
4033 (org-set-local 'org-lowest-priority (nth 1 prio))
4034 (org-set-local 'org-default-priority (nth 2 prio)))
4035 (and props (org-set-local 'org-file-properties (nreverse props)))
4036 (and ftags (org-set-local 'org-file-tags
4037 (mapcar 'org-add-prop-inherited ftags)))
4038 (and drawers (org-set-local 'org-drawers drawers))
4039 (and arch (org-set-local 'org-archive-location arch))
4040 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4041 ;; Process the TODO keywords
4042 (unless kwds
4043 ;; Use the global values as if they had been given locally.
4044 (setq kwds (default-value 'org-todo-keywords))
4045 (if (stringp (car kwds))
4046 (setq kwds (list (cons org-todo-interpretation
4047 (default-value 'org-todo-keywords)))))
4048 (setq kwds (reverse kwds)))
4049 (setq kwds (nreverse kwds))
4050 (let (inter kws kw)
4051 (while (setq kws (pop kwds))
4052 (let ((kws (or
4053 (run-hook-with-args-until-success
4054 'org-todo-setup-filter-hook kws)
4055 kws)))
4056 (setq inter (pop kws) sep (member "|" kws)
4057 kws0 (delete "|" (copy-sequence kws))
4058 kwsa nil
4059 kws1 (mapcar
4060 (lambda (x)
4061 ;; 1 2
4062 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4063 (progn
4064 (setq kw (match-string 1 x)
4065 key (and (match-end 2) (match-string 2 x))
4066 log (org-extract-log-state-settings x))
4067 (push (cons kw (and key (string-to-char key))) kwsa)
4068 (and log (push log org-todo-log-states))
4070 (error "Invalid TODO keyword %s" x)))
4071 kws0)
4072 kwsa (if kwsa (append '((:startgroup))
4073 (nreverse kwsa)
4074 '((:endgroup))))
4075 hw (car kws1)
4076 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4077 tail (list inter hw (car dws) (org-last dws))))
4078 (add-to-list 'org-todo-heads hw 'append)
4079 (push kws1 org-todo-sets)
4080 (setq org-done-keywords (append org-done-keywords dws nil))
4081 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4082 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4083 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4084 (setq org-todo-sets (nreverse org-todo-sets)
4085 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4086 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4087 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4088 ;; Process the constants
4089 (when const
4090 (let (e cst)
4091 (while (setq e (pop const))
4092 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4093 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4094 (setq org-table-formula-constants-local cst)))
4096 ;; Process the tags.
4097 (when tags
4098 (let (e tgs)
4099 (while (setq e (pop tags))
4100 (cond
4101 ((equal e "{") (push '(:startgroup) tgs))
4102 ((equal e "}") (push '(:endgroup) tgs))
4103 ((equal e "\\n") (push '(:newline) tgs))
4104 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4105 (push (cons (match-string 1 e)
4106 (string-to-char (match-string 2 e)))
4107 tgs))
4108 (t (push (list e) tgs))))
4109 (org-set-local 'org-tag-alist nil)
4110 (while (setq e (pop tgs))
4111 (or (and (stringp (car e))
4112 (assoc (car e) org-tag-alist))
4113 (push e org-tag-alist)))))
4115 ;; Compute the regular expressions and other local variables
4116 (if (not org-done-keywords)
4117 (setq org-done-keywords (and org-todo-keywords-1
4118 (list (org-last org-todo-keywords-1)))))
4119 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4120 (length org-scheduled-string)
4121 (length org-clock-string)
4122 (length org-closed-string)))
4123 org-drawer-regexp
4124 (concat "^[ \t]*:\\("
4125 (mapconcat 'regexp-quote org-drawers "\\|")
4126 "\\):[ \t]*$")
4127 org-not-done-keywords
4128 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4129 org-todo-regexp
4130 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4131 "\\|") "\\)\\>")
4132 org-not-done-regexp
4133 (concat "\\<\\("
4134 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4135 "\\)\\>")
4136 org-not-done-heading-regexp
4137 (concat "^\\(\\*+\\)[ \t]+\\("
4138 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4139 "\\)\\>")
4140 org-todo-line-regexp
4141 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4142 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4143 "\\)\\>\\)?[ \t]*\\(.*\\)")
4144 org-complex-heading-regexp
4145 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4146 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4147 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4148 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4149 org-complex-heading-regexp-format
4150 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4151 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4152 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4153 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4154 org-nl-done-regexp
4155 (concat "\n\\*+[ \t]+"
4156 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4157 "\\)" "\\>")
4158 org-todo-line-tags-regexp
4159 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4160 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4161 (org-re
4162 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4163 org-looking-at-done-regexp
4164 (concat "^" "\\(?:"
4165 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4166 "\\>")
4167 org-deadline-regexp (concat "\\<" org-deadline-string)
4168 org-deadline-time-regexp
4169 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4170 org-deadline-line-regexp
4171 (concat "\\<\\(" org-deadline-string "\\).*")
4172 org-scheduled-regexp
4173 (concat "\\<" org-scheduled-string)
4174 org-scheduled-time-regexp
4175 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4176 org-closed-time-regexp
4177 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4178 org-keyword-time-regexp
4179 (concat "\\<\\(" org-scheduled-string
4180 "\\|" org-deadline-string
4181 "\\|" org-closed-string
4182 "\\|" org-clock-string "\\)"
4183 " *[[<]\\([^]>]+\\)[]>]")
4184 org-keyword-time-not-clock-regexp
4185 (concat "\\<\\(" org-scheduled-string
4186 "\\|" org-deadline-string
4187 "\\|" org-closed-string
4188 "\\)"
4189 " *[[<]\\([^]>]+\\)[]>]")
4190 org-maybe-keyword-time-regexp
4191 (concat "\\(\\<\\(" org-scheduled-string
4192 "\\|" org-deadline-string
4193 "\\|" org-closed-string
4194 "\\|" org-clock-string "\\)\\)?"
4195 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4196 org-planning-or-clock-line-re
4197 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4198 "\\|" org-deadline-string
4199 "\\|" org-closed-string "\\|" org-clock-string
4200 "\\)\\>\\)")
4201 org-all-time-keywords
4202 (mapcar (lambda (w) (substring w 0 -1))
4203 (list org-scheduled-string org-deadline-string
4204 org-clock-string org-closed-string))
4206 (org-compute-latex-and-specials-regexp)
4207 (org-set-font-lock-defaults))))
4209 (defun org-file-contents (file &optional noerror)
4210 "Return the contents of FILE, as a string."
4211 (if (or (not file)
4212 (not (file-readable-p file)))
4213 (if noerror
4214 (progn
4215 (message "Cannot read file %s" file)
4216 (ding) (sit-for 2)
4218 (error "Cannot read file %s" file))
4219 (with-temp-buffer
4220 (insert-file-contents file)
4221 (buffer-string))))
4223 (defun org-extract-log-state-settings (x)
4224 "Extract the log state setting from a TODO keyword string.
4225 This will extract info from a string like \"WAIT(w@/!)\"."
4226 (let (kw key log1 log2)
4227 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4228 (setq kw (match-string 1 x)
4229 key (and (match-end 2) (match-string 2 x))
4230 log1 (and (match-end 3) (match-string 3 x))
4231 log2 (and (match-end 4) (match-string 4 x)))
4232 (and (or log1 log2)
4233 (list kw
4234 (and log1 (if (equal log1 "!") 'time 'note))
4235 (and log2 (if (equal log2 "!") 'time 'note)))))))
4237 (defun org-remove-keyword-keys (list)
4238 "Remove a pair of parenthesis at the end of each string in LIST."
4239 (mapcar (lambda (x)
4240 (if (string-match "(.*)$" x)
4241 (substring x 0 (match-beginning 0))
4243 list))
4245 (defun org-assign-fast-keys (alist)
4246 "Assign fast keys to a keyword-key alist.
4247 Respect keys that are already there."
4248 (let (new e (alt ?0))
4249 (while (setq e (pop alist))
4250 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4251 (cdr e)) ;; Key already assigned.
4252 (push e new)
4253 (let ((clist (string-to-list (downcase (car e))))
4254 (used (append new alist)))
4255 (when (= (car clist) ?@)
4256 (pop clist))
4257 (while (and clist (rassoc (car clist) used))
4258 (pop clist))
4259 (unless clist
4260 (while (rassoc alt used)
4261 (incf alt)))
4262 (push (cons (car e) (or (car clist) alt)) new))))
4263 (nreverse new)))
4265 ;;; Some variables used in various places
4267 (defvar org-window-configuration nil
4268 "Used in various places to store a window configuration.")
4269 (defvar org-selected-window nil
4270 "Used in various places to store a window configuration.")
4271 (defvar org-finish-function nil
4272 "Function to be called when `C-c C-c' is used.
4273 This is for getting out of special buffers like remember.")
4276 ;; FIXME: Occasionally check by commenting these, to make sure
4277 ;; no other functions uses these, forgetting to let-bind them.
4278 (defvar entry)
4279 (defvar last-state)
4280 (defvar date)
4282 ;; Defined somewhere in this file, but used before definition.
4283 (defvar org-entities) ;; defined in org-entities.el
4284 (defvar org-struct-menu)
4285 (defvar org-org-menu)
4286 (defvar org-tbl-menu)
4288 ;;;; Define the Org-mode
4290 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4291 (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."))
4294 ;; We use a before-change function to check if a table might need
4295 ;; an update.
4296 (defvar org-table-may-need-update t
4297 "Indicates that a table might need an update.
4298 This variable is set by `org-before-change-function'.
4299 `org-table-align' sets it back to nil.")
4300 (defun org-before-change-function (beg end)
4301 "Every change indicates that a table might need an update."
4302 (setq org-table-may-need-update t))
4303 (defvar org-mode-map)
4304 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4305 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4306 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4307 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4308 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4309 (defvar org-table-buffer-is-an nil)
4310 (defconst org-outline-regexp "\\*+ ")
4312 ;;;###autoload
4313 (define-derived-mode org-mode outline-mode "Org"
4314 "Outline-based notes management and organizer, alias
4315 \"Carsten's outline-mode for keeping track of everything.\"
4317 Org-mode develops organizational tasks around a NOTES file which
4318 contains information about projects as plain text. Org-mode is
4319 implemented on top of outline-mode, which is ideal to keep the content
4320 of large files well structured. It supports ToDo items, deadlines and
4321 time stamps, which magically appear in the diary listing of the Emacs
4322 calendar. Tables are easily created with a built-in table editor.
4323 Plain text URL-like links connect to websites, emails (VM), Usenet
4324 messages (Gnus), BBDB entries, and any files related to the project.
4325 For printing and sharing of notes, an Org-mode file (or a part of it)
4326 can be exported as a structured ASCII or HTML file.
4328 The following commands are available:
4330 \\{org-mode-map}"
4332 ;; Get rid of Outline menus, they are not needed
4333 ;; Need to do this here because define-derived-mode sets up
4334 ;; the keymap so late. Still, it is a waste to call this each time
4335 ;; we switch another buffer into org-mode.
4336 (if (featurep 'xemacs)
4337 (when (boundp 'outline-mode-menu-heading)
4338 ;; Assume this is Greg's port, it used easymenu
4339 (easy-menu-remove outline-mode-menu-heading)
4340 (easy-menu-remove outline-mode-menu-show)
4341 (easy-menu-remove outline-mode-menu-hide))
4342 (define-key org-mode-map [menu-bar headings] 'undefined)
4343 (define-key org-mode-map [menu-bar hide] 'undefined)
4344 (define-key org-mode-map [menu-bar show] 'undefined))
4346 (org-load-modules-maybe)
4347 (easy-menu-add org-org-menu)
4348 (easy-menu-add org-tbl-menu)
4349 (org-install-agenda-files-menu)
4350 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4351 (org-add-to-invisibility-spec '(org-cwidth))
4352 (org-add-to-invisibility-spec '(org-hide-block . t))
4353 (when (featurep 'xemacs)
4354 (org-set-local 'line-move-ignore-invisible t))
4355 (org-set-local 'outline-regexp org-outline-regexp)
4356 (org-set-local 'outline-level 'org-outline-level)
4357 (when (and org-ellipsis
4358 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4359 (fboundp 'make-glyph-code))
4360 (unless org-display-table
4361 (setq org-display-table (make-display-table)))
4362 (set-display-table-slot
4363 org-display-table 4
4364 (vconcat (mapcar
4365 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4366 org-ellipsis)))
4367 (if (stringp org-ellipsis) org-ellipsis "..."))))
4368 (setq buffer-display-table org-display-table))
4369 (org-set-regexps-and-options)
4370 (when (and org-tag-faces (not org-tags-special-faces-re))
4371 ;; tag faces set outside customize.... force initialization.
4372 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4373 ;; Calc embedded
4374 (org-set-local 'calc-embedded-open-mode "# ")
4375 (modify-syntax-entry ?# "<")
4376 (modify-syntax-entry ?@ "w")
4377 (if org-startup-truncated (setq truncate-lines t))
4378 (org-set-local 'font-lock-unfontify-region-function
4379 'org-unfontify-region)
4380 ;; Activate before-change-function
4381 (org-set-local 'org-table-may-need-update t)
4382 (org-add-hook 'before-change-functions 'org-before-change-function nil
4383 'local)
4384 ;; Check for running clock before killing a buffer
4385 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4386 ;; Paragraphs and auto-filling
4387 (org-set-autofill-regexps)
4388 (setq indent-line-function 'org-indent-line-function)
4389 (org-update-radio-target-regexp)
4390 ;; Make sure dependence stuff works reliably, even for users who set it
4391 ;; too late :-(
4392 (if org-enforce-todo-dependencies
4393 (add-hook 'org-blocker-hook
4394 'org-block-todo-from-children-or-siblings-or-parent)
4395 (remove-hook 'org-blocker-hook
4396 'org-block-todo-from-children-or-siblings-or-parent))
4397 (if org-enforce-todo-checkbox-dependencies
4398 (add-hook 'org-blocker-hook
4399 'org-block-todo-from-checkboxes)
4400 (remove-hook 'org-blocker-hook
4401 'org-block-todo-from-checkboxes))
4403 ;; Comment characters
4404 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4405 (org-set-local 'comment-padding " ")
4407 ;; Align options lines
4408 (org-set-local
4409 'align-mode-rules-list
4410 '((org-in-buffer-settings
4411 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4412 (modes . '(org-mode)))))
4414 ;; Imenu
4415 (org-set-local 'imenu-create-index-function
4416 'org-imenu-get-tree)
4418 ;; Make isearch reveal context
4419 (if (or (featurep 'xemacs)
4420 (not (boundp 'outline-isearch-open-invisible-function)))
4421 ;; Emacs 21 and XEmacs make use of the hook
4422 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4423 ;; Emacs 22 deals with this through a special variable
4424 (org-set-local 'outline-isearch-open-invisible-function
4425 (lambda (&rest ignore) (org-show-context 'isearch))))
4427 ;; Turn on org-beamer-mode?
4428 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4430 ;; If empty file that did not turn on org-mode automatically, make it to.
4431 (if (and org-insert-mode-line-in-empty-file
4432 (interactive-p)
4433 (= (point-min) (point-max)))
4434 (insert "# -*- mode: org -*-\n\n"))
4435 (unless org-inhibit-startup
4436 (when org-startup-align-all-tables
4437 (let ((bmp (buffer-modified-p)))
4438 (org-table-map-tables 'org-table-align)
4439 (set-buffer-modified-p bmp)))
4440 (when org-startup-indented
4441 (require 'org-indent)
4442 (org-indent-mode 1))
4443 (unless org-inhibit-startup-visibility-stuff
4444 (org-set-startup-visibility))))
4446 (when (fboundp 'abbrev-table-put)
4447 (abbrev-table-put org-mode-abbrev-table
4448 :parents (list text-mode-abbrev-table)))
4450 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4452 (defun org-current-time ()
4453 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4454 (if (> (car org-time-stamp-rounding-minutes) 1)
4455 (let ((r (car org-time-stamp-rounding-minutes))
4456 (time (decode-time)))
4457 (apply 'encode-time
4458 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4459 (nthcdr 2 time))))
4460 (current-time)))
4462 ;;;; Font-Lock stuff, including the activators
4464 (defvar org-mouse-map (make-sparse-keymap))
4465 (org-defkey org-mouse-map
4466 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4467 (org-defkey org-mouse-map
4468 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4469 (when org-mouse-1-follows-link
4470 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4471 (when org-tab-follows-link
4472 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4473 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4475 (require 'font-lock)
4477 (defconst org-non-link-chars "]\t\n\r<>")
4478 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4479 "shell" "elisp"))
4480 (defvar org-link-types-re nil
4481 "Matches a link that has a url-like prefix like \"http:\"")
4482 (defvar org-link-re-with-space nil
4483 "Matches a link with spaces, optional angular brackets around it.")
4484 (defvar org-link-re-with-space2 nil
4485 "Matches a link with spaces, optional angular brackets around it.")
4486 (defvar org-link-re-with-space3 nil
4487 "Matches a link with spaces, only for internal part in bracket links.")
4488 (defvar org-angle-link-re nil
4489 "Matches link with angular brackets, spaces are allowed.")
4490 (defvar org-plain-link-re nil
4491 "Matches plain link, without spaces.")
4492 (defvar org-bracket-link-regexp nil
4493 "Matches a link in double brackets.")
4494 (defvar org-bracket-link-analytic-regexp nil
4495 "Regular expression used to analyze links.
4496 Here is what the match groups contain after a match:
4497 1: http:
4498 2: http
4499 3: path
4500 4: [desc]
4501 5: desc")
4502 (defvar org-bracket-link-analytic-regexp++ nil
4503 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4504 (defvar org-any-link-re nil
4505 "Regular expression matching any link.")
4507 (defun org-make-link-regexps ()
4508 "Update the link regular expressions.
4509 This should be called after the variable `org-link-types' has changed."
4510 (setq org-link-types-re
4511 (concat
4512 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4513 org-link-re-with-space
4514 (concat
4515 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4516 "\\([^" org-non-link-chars " ]"
4517 "[^" org-non-link-chars "]*"
4518 "[^" org-non-link-chars " ]\\)>?")
4519 org-link-re-with-space2
4520 (concat
4521 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4522 "\\([^" org-non-link-chars " ]"
4523 "[^\t\n\r]*"
4524 "[^" org-non-link-chars " ]\\)>?")
4525 org-link-re-with-space3
4526 (concat
4527 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4528 "\\([^" org-non-link-chars " ]"
4529 "[^\t\n\r]*\\)")
4530 org-angle-link-re
4531 (concat
4532 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4533 "\\([^" org-non-link-chars " ]"
4534 "[^" org-non-link-chars "]*"
4535 "\\)>")
4536 org-plain-link-re
4537 (concat
4538 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4539 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4540 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4541 org-bracket-link-regexp
4542 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4543 org-bracket-link-analytic-regexp
4544 (concat
4545 "\\[\\["
4546 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4547 "\\([^]]+\\)"
4548 "\\]"
4549 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4550 "\\]")
4551 org-bracket-link-analytic-regexp++
4552 (concat
4553 "\\[\\["
4554 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4555 "\\([^]]+\\)"
4556 "\\]"
4557 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4558 "\\]")
4559 org-any-link-re
4560 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4561 org-angle-link-re "\\)\\|\\("
4562 org-plain-link-re "\\)")))
4564 (org-make-link-regexps)
4566 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4567 "Regular expression for fast time stamp matching.")
4568 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4569 "Regular expression for fast time stamp matching.")
4570 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4571 "Regular expression matching time strings for analysis.
4572 This one does not require the space after the date, so it can be used
4573 on a string that terminates immediately after the date.")
4574 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4575 "Regular expression matching time strings for analysis.")
4576 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4577 "Regular expression matching time stamps, with groups.")
4578 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4579 "Regular expression matching time stamps (also [..]), with groups.")
4580 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4581 "Regular expression matching a time stamp range.")
4582 (defconst org-tr-regexp-both
4583 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4584 "Regular expression matching a time stamp range.")
4585 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4586 org-ts-regexp "\\)?")
4587 "Regular expression matching a time stamp or time stamp range.")
4588 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4589 org-ts-regexp-both "\\)?")
4590 "Regular expression matching a time stamp or time stamp range.
4591 The time stamps may be either active or inactive.")
4593 (defvar org-emph-face nil)
4595 (defun org-do-emphasis-faces (limit)
4596 "Run through the buffer and add overlays to links."
4597 (let (rtn a)
4598 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4599 (if (not (= (char-after (match-beginning 3))
4600 (char-after (match-beginning 4))))
4601 (progn
4602 (setq rtn t)
4603 (setq a (assoc (match-string 3) org-emphasis-alist))
4604 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4605 'face
4606 (nth 1 a))
4607 (and (nth 4 a)
4608 (org-remove-flyspell-overlays-in
4609 (match-beginning 0) (match-end 0)))
4610 (add-text-properties (match-beginning 2) (match-end 2)
4611 '(font-lock-multiline t))
4612 (when org-hide-emphasis-markers
4613 (add-text-properties (match-end 4) (match-beginning 5)
4614 '(invisible org-link))
4615 (add-text-properties (match-beginning 3) (match-end 3)
4616 '(invisible org-link)))))
4617 (backward-char 1))
4618 rtn))
4620 (defun org-emphasize (&optional char)
4621 "Insert or change an emphasis, i.e. a font like bold or italic.
4622 If there is an active region, change that region to a new emphasis.
4623 If there is no region, just insert the marker characters and position
4624 the cursor between them.
4625 CHAR should be either the marker character, or the first character of the
4626 HTML tag associated with that emphasis. If CHAR is a space, the means
4627 to remove the emphasis of the selected region.
4628 If char is not given (for example in an interactive call) it
4629 will be prompted for."
4630 (interactive)
4631 (let ((eal org-emphasis-alist) e det
4632 (erc org-emphasis-regexp-components)
4633 (prompt "")
4634 (string "") beg end move tag c s)
4635 (if (org-region-active-p)
4636 (setq beg (region-beginning) end (region-end)
4637 string (buffer-substring beg end))
4638 (setq move t))
4640 (while (setq e (pop eal))
4641 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4642 c (aref tag 0))
4643 (push (cons c (string-to-char (car e))) det)
4644 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4645 (substring tag 1)))))
4646 (setq det (nreverse det))
4647 (unless char
4648 (message "%s" (concat "Emphasis marker or tag:" prompt))
4649 (setq char (read-char-exclusive)))
4650 (setq char (or (cdr (assoc char det)) char))
4651 (if (equal char ?\ )
4652 (setq s "" move nil)
4653 (unless (assoc (char-to-string char) org-emphasis-alist)
4654 (error "No such emphasis marker: \"%c\"" char))
4655 (setq s (char-to-string char)))
4656 (while (and (> (length string) 1)
4657 (equal (substring string 0 1) (substring string -1))
4658 (assoc (substring string 0 1) org-emphasis-alist))
4659 (setq string (substring string 1 -1)))
4660 (setq string (concat s string s))
4661 (if beg (delete-region beg end))
4662 (unless (or (bolp)
4663 (string-match (concat "[" (nth 0 erc) "\n]")
4664 (char-to-string (char-before (point)))))
4665 (insert " "))
4666 (unless (or (eobp)
4667 (string-match (concat "[" (nth 1 erc) "\n]")
4668 (char-to-string (char-after (point)))))
4669 (insert " ") (backward-char 1))
4670 (insert string)
4671 (and move (backward-char 1))))
4673 (defconst org-nonsticky-props
4674 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4676 (defsubst org-rear-nonsticky-at (pos)
4677 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4679 (defun org-activate-plain-links (limit)
4680 "Run through the buffer and add overlays to links."
4681 (catch 'exit
4682 (let (f)
4683 (if (re-search-forward org-plain-link-re limit t)
4684 (progn
4685 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4686 (setq f (get-text-property (match-beginning 0) 'face))
4687 (if (or (eq f 'org-tag)
4688 (and (listp f) (memq 'org-tag f)))
4690 (add-text-properties (match-beginning 0) (match-end 0)
4691 (list 'mouse-face 'highlight
4692 'face 'org-link
4693 'keymap org-mouse-map))
4694 (org-rear-nonsticky-at (match-end 0)))
4695 t)))))
4697 (defun org-activate-code (limit)
4698 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4699 (progn
4700 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4701 (remove-text-properties (match-beginning 0) (match-end 0)
4702 '(display t invisible t intangible t))
4703 t)))
4705 (defun org-fontify-meta-lines-and-blocks (limit)
4706 "Fontify #+ lines and blocks, in the correct ways."
4707 (let ((case-fold-search t))
4708 (if (re-search-forward
4709 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4710 limit t)
4711 (let ((beg (match-beginning 0))
4712 (beg1 (line-beginning-position 2))
4713 (dc1 (downcase (match-string 2)))
4714 (dc3 (downcase (match-string 3)))
4715 end end1 quoting block-type)
4716 (cond
4717 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4718 ;; a single line of backend-specific content
4719 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4720 (remove-text-properties (match-beginning 0) (match-end 0)
4721 '(display t invisible t intangible t))
4722 (add-text-properties (match-beginning 1) (match-end 3)
4723 '(font-lock-fontified t face org-meta-line))
4724 (add-text-properties (match-beginning 6) (match-end 6)
4725 '(font-lock-fontified t face org-block))
4727 ((and (match-end 4) (equal dc3 "begin"))
4728 ;; Truely a block
4729 (setq block-type (downcase (match-string 5))
4730 quoting (member block-type org-protecting-blocks))
4731 (when (re-search-forward
4732 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4733 nil t) ;; on purpose, we look further than LIMIT
4734 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4735 (when quoting
4736 (remove-text-properties beg end
4737 '(display t invisible t intangible t)))
4738 (add-text-properties
4739 beg end
4740 '(font-lock-fontified t font-lock-multiline t))
4741 (add-text-properties beg beg1 '(face org-meta-line))
4742 (add-text-properties end1 end '(face org-meta-line))
4743 (cond
4744 (quoting
4745 (add-text-properties beg1 end1 '(face org-block)))
4746 ((not org-fontify-quote-and-verse-blocks))
4747 ((string= block-type "quote")
4748 (add-text-properties beg1 end1 '(face org-quote)))
4749 ((string= block-type "verse")
4750 (add-text-properties beg1 end1 '(face org-verse))))
4752 ((member dc1 '("title:" "author:" "email:" "date:"))
4753 (add-text-properties
4754 beg (match-end 3)
4755 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4756 '(font-lock-fontified t invisible t)
4757 '(font-lock-fontified t face org-document-info-keyword)))
4758 (add-text-properties
4759 (match-beginning 6) (match-end 6)
4760 (if (string-equal dc1 "title:")
4761 '(font-lock-fontified t face org-document-title)
4762 '(font-lock-fontified t face org-document-info))))
4763 ((not (member (char-after beg) '(?\ ?\t)))
4764 ;; just any other in-buffer setting, but not indented
4765 (add-text-properties
4766 beg (match-end 0)
4767 '(font-lock-fontified t face org-meta-line))
4769 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4770 "orgtbl:" "tblfm:" "tblname:"))
4771 (and (match-end 4) (equal dc3 "attr")))
4772 (add-text-properties
4773 beg (match-end 0)
4774 '(font-lock-fontified t face org-meta-line))
4776 ((member dc3 '(" " ""))
4777 (add-text-properties
4778 beg (match-end 0)
4779 '(font-lock-fontified t face font-lock-comment-face)))
4780 (t nil))))))
4782 (defun org-activate-angle-links (limit)
4783 "Run through the buffer and add overlays to links."
4784 (if (re-search-forward org-angle-link-re limit t)
4785 (progn
4786 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4787 (add-text-properties (match-beginning 0) (match-end 0)
4788 (list 'mouse-face 'highlight
4789 'keymap org-mouse-map))
4790 (org-rear-nonsticky-at (match-end 0))
4791 t)))
4793 (defun org-activate-footnote-links (limit)
4794 "Run through the buffer and add overlays to links."
4795 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4796 limit t)
4797 (progn
4798 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4799 (add-text-properties (match-beginning 2) (match-end 2)
4800 (list 'mouse-face 'highlight
4801 'keymap org-mouse-map
4802 'help-echo
4803 (if (= (point-at-bol) (match-beginning 2))
4804 "Footnote definition"
4805 "Footnote reference")
4807 (org-rear-nonsticky-at (match-end 2))
4808 t)))
4810 (defun org-activate-bracket-links (limit)
4811 "Run through the buffer and add overlays to bracketed links."
4812 (if (re-search-forward org-bracket-link-regexp limit t)
4813 (let* ((help (concat "LINK: "
4814 (org-match-string-no-properties 1)))
4815 ;; FIXME: above we should remove the escapes.
4816 ;; but that requires another match, protecting match data,
4817 ;; a lot of overhead for font-lock.
4818 (ip (org-maybe-intangible
4819 (list 'invisible 'org-link
4820 'keymap org-mouse-map 'mouse-face 'highlight
4821 'font-lock-multiline t 'help-echo help)))
4822 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4823 'font-lock-multiline t 'help-echo help)))
4824 ;; We need to remove the invisible property here. Table narrowing
4825 ;; may have made some of this invisible.
4826 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4827 (remove-text-properties (match-beginning 0) (match-end 0)
4828 '(invisible nil))
4829 (if (match-end 3)
4830 (progn
4831 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4832 (org-rear-nonsticky-at (match-beginning 3))
4833 (add-text-properties (match-beginning 3) (match-end 3) vp)
4834 (org-rear-nonsticky-at (match-end 3))
4835 (add-text-properties (match-end 3) (match-end 0) ip)
4836 (org-rear-nonsticky-at (match-end 0)))
4837 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4838 (org-rear-nonsticky-at (match-beginning 1))
4839 (add-text-properties (match-beginning 1) (match-end 1) vp)
4840 (org-rear-nonsticky-at (match-end 1))
4841 (add-text-properties (match-end 1) (match-end 0) ip)
4842 (org-rear-nonsticky-at (match-end 0)))
4843 t)))
4845 (defun org-activate-dates (limit)
4846 "Run through the buffer and add overlays to dates."
4847 (if (re-search-forward org-tsr-regexp-both limit t)
4848 (progn
4849 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4850 (add-text-properties (match-beginning 0) (match-end 0)
4851 (list 'mouse-face 'highlight
4852 'keymap org-mouse-map))
4853 (org-rear-nonsticky-at (match-end 0))
4854 (when org-display-custom-times
4855 (if (match-end 3)
4856 (org-display-custom-time (match-beginning 3) (match-end 3)))
4857 (org-display-custom-time (match-beginning 1) (match-end 1)))
4858 t)))
4860 (defvar org-target-link-regexp nil
4861 "Regular expression matching radio targets in plain text.")
4862 (make-variable-buffer-local 'org-target-link-regexp)
4863 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4864 "Regular expression matching a link target.")
4865 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4866 "Regular expression matching a radio target.")
4867 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4868 "Regular expression matching any target.")
4870 (defun org-activate-target-links (limit)
4871 "Run through the buffer and add overlays to target matches."
4872 (when org-target-link-regexp
4873 (let ((case-fold-search t))
4874 (if (re-search-forward org-target-link-regexp limit t)
4875 (progn
4876 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4877 (add-text-properties (match-beginning 0) (match-end 0)
4878 (list 'mouse-face 'highlight
4879 'keymap org-mouse-map
4880 'help-echo "Radio target link"
4881 'org-linked-text t))
4882 (org-rear-nonsticky-at (match-end 0))
4883 t)))))
4885 (defun org-update-radio-target-regexp ()
4886 "Find all radio targets in this file and update the regular expression."
4887 (interactive)
4888 (when (memq 'radio org-activate-links)
4889 (setq org-target-link-regexp
4890 (org-make-target-link-regexp (org-all-targets 'radio)))
4891 (org-restart-font-lock)))
4893 (defun org-hide-wide-columns (limit)
4894 (let (s e)
4895 (setq s (text-property-any (point) (or limit (point-max))
4896 'org-cwidth t))
4897 (when s
4898 (setq e (next-single-property-change s 'org-cwidth))
4899 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4900 (goto-char e)
4901 t)))
4903 (defvar org-latex-and-specials-regexp nil
4904 "Regular expression for highlighting export special stuff.")
4905 (defvar org-match-substring-regexp)
4906 (defvar org-match-substring-with-braces-regexp)
4908 ;; This should be with the exporter code, but we also use if for font-locking
4909 (defconst org-export-html-special-string-regexps
4910 '(("\\\\-" . "&shy;")
4911 ("---\\([^-]\\)" . "&mdash;\\1")
4912 ("--\\([^-]\\)" . "&ndash;\\1")
4913 ("\\.\\.\\." . "&hellip;"))
4914 "Regular expressions for special string conversion.")
4917 (defun org-compute-latex-and-specials-regexp ()
4918 "Compute regular expression for stuff treated specially by exporters."
4919 (if (not org-highlight-latex-fragments-and-specials)
4920 (org-set-local 'org-latex-and-specials-regexp nil)
4921 (require 'org-exp)
4922 (let*
4923 ((matchers (plist-get org-format-latex-options :matchers))
4924 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4925 org-latex-regexps)))
4926 (org-export-allow-BIND nil)
4927 (options (org-combine-plists (org-default-export-plist)
4928 (org-infile-export-plist)))
4929 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4930 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4931 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4932 (org-export-html-expand (plist-get options :expand-quoted-html))
4933 (org-export-with-special-strings (plist-get options :special-strings))
4934 (re-sub
4935 (cond
4936 ((equal org-export-with-sub-superscripts '{})
4937 (list org-match-substring-with-braces-regexp))
4938 (org-export-with-sub-superscripts
4939 (list org-match-substring-regexp))
4940 (t nil)))
4941 (re-latex
4942 (if org-export-with-LaTeX-fragments
4943 (mapcar (lambda (x) (nth 1 x)) latexs)))
4944 (re-macros
4945 (if org-export-with-TeX-macros
4946 (list (concat "\\\\"
4947 (regexp-opt
4948 (append (mapcar 'car (append org-entities-user
4949 org-entities))
4950 (if (boundp 'org-latex-entities)
4951 (mapcar (lambda (x)
4952 (or (car-safe x) x))
4953 org-latex-entities)
4954 nil))
4955 'words))) ; FIXME
4957 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4958 (re-special (if org-export-with-special-strings
4959 (mapcar (lambda (x) (car x))
4960 org-export-html-special-string-regexps)))
4961 (re-rest
4962 (delq nil
4963 (list
4964 (if org-export-html-expand "@<[^>\n]+>")
4965 ))))
4966 (org-set-local
4967 'org-latex-and-specials-regexp
4968 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4969 re-rest) "\\|")))))
4971 (defun org-do-latex-and-special-faces (limit)
4972 "Run through the buffer and add overlays to links."
4973 (when org-latex-and-specials-regexp
4974 (let (rtn d)
4975 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4976 limit t))
4977 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4978 'face))
4979 '(org-code org-verbatim underline)))
4980 (progn
4981 (setq rtn t
4982 d (cond ((member (char-after (1+ (match-beginning 0)))
4983 '(?_ ?^)) 1)
4984 (t 0)))
4985 (font-lock-prepend-text-property
4986 (+ d (match-beginning 0)) (match-end 0)
4987 'face 'org-latex-and-export-specials)
4988 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4989 '(font-lock-multiline t)))))
4990 rtn)))
4992 (defun org-restart-font-lock ()
4993 "Restart font-lock-mode, to force refontification."
4994 (when (and (boundp 'font-lock-mode) font-lock-mode)
4995 (font-lock-mode -1)
4996 (font-lock-mode 1)))
4998 (defun org-all-targets (&optional radio)
4999 "Return a list of all targets in this file.
5000 With optional argument RADIO, only find radio targets."
5001 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5002 rtn)
5003 (save-excursion
5004 (goto-char (point-min))
5005 (while (re-search-forward re nil t)
5006 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5007 rtn)))
5009 (defun org-make-target-link-regexp (targets)
5010 "Make regular expression matching all strings in TARGETS.
5011 The regular expression finds the targets also if there is a line break
5012 between words."
5013 (and targets
5014 (concat
5015 "\\<\\("
5016 (mapconcat
5017 (lambda (x)
5018 (while (string-match " +" x)
5019 (setq x (replace-match "\\s-+" t t x)))
5021 targets
5022 "\\|")
5023 "\\)\\>")))
5025 (defun org-activate-tags (limit)
5026 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5027 (progn
5028 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5029 (add-text-properties (match-beginning 1) (match-end 1)
5030 (list 'mouse-face 'highlight
5031 'keymap org-mouse-map))
5032 (org-rear-nonsticky-at (match-end 1))
5033 t)))
5035 (defun org-outline-level ()
5036 "Compute the outline level of the heading at point.
5037 This function assumes that the cursor is at the beginning of a line matched
5038 by outline-regexp. Otherwise it returns garbage.
5039 If this is called at a normal headline, the level is the number of stars.
5040 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5041 For plain list items, if they are matched by `outline-regexp', this returns
5042 1000 plus the line indentation."
5043 (save-excursion
5044 (looking-at outline-regexp)
5045 (if (match-beginning 1)
5046 (+ (org-get-string-indentation (match-string 1)) 1000)
5047 (1- (- (match-end 0) (match-beginning 0))))))
5049 (defvar org-font-lock-keywords nil)
5051 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5052 "Regular expression matching a property line.")
5054 (defvar org-font-lock-hook nil
5055 "Functions to be called for special font lock stuff.")
5057 (defun org-font-lock-hook (limit)
5058 (run-hook-with-args 'org-font-lock-hook limit))
5060 (defun org-set-font-lock-defaults ()
5061 (let* ((em org-fontify-emphasized-text)
5062 (lk org-activate-links)
5063 (org-font-lock-extra-keywords
5064 (list
5065 ;; Call the hook
5066 '(org-font-lock-hook)
5067 ;; Headlines
5068 `(,(if org-fontify-whole-heading-line
5069 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5070 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5071 (1 (org-get-level-face 1))
5072 (2 (org-get-level-face 2))
5073 (3 (org-get-level-face 3)))
5074 ;; Table lines
5075 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5076 (1 'org-table t))
5077 ;; Table internals
5078 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5079 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5080 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5081 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5082 ;; Drawers
5083 (list org-drawer-regexp '(0 'org-special-keyword t))
5084 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5085 ;; Properties
5086 (list org-property-re
5087 '(1 'org-special-keyword t)
5088 '(3 'org-property-value t))
5089 ;; Links
5090 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5091 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5092 (if (memq 'plain lk) '(org-activate-plain-links))
5093 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5094 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5095 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5096 (if (memq 'footnote lk) '(org-activate-footnote-links
5097 (2 'org-footnote t)))
5098 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5099 '(org-hide-wide-columns (0 nil append))
5100 ;; TODO lines
5101 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5102 '(1 (org-get-todo-face 1) t))
5103 ;; DONE
5104 (if org-fontify-done-headline
5105 (list (concat "^[*]+ +\\<\\("
5106 (mapconcat 'regexp-quote org-done-keywords "\\|")
5107 "\\)\\(.*\\)")
5108 '(2 'org-headline-done t))
5109 nil)
5110 ;; Priorities
5111 '(org-font-lock-add-priority-faces)
5112 ;; Tags
5113 '(org-font-lock-add-tag-faces)
5114 ;; Special keywords
5115 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5116 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5117 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5118 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5119 ;; Emphasis
5120 (if em
5121 (if (featurep 'xemacs)
5122 '(org-do-emphasis-faces (0 nil append))
5123 '(org-do-emphasis-faces)))
5124 ;; Checkboxes
5125 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5126 2 'org-checkbox prepend)
5127 (if org-provide-checkbox-statistics
5128 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5129 (0 (org-get-checkbox-statistics-face) t)))
5130 ;; Description list items
5131 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5132 2 'bold prepend)
5133 ;; ARCHIVEd headings
5134 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5135 '(1 'org-archived prepend))
5136 ;; Specials
5137 '(org-do-latex-and-special-faces)
5138 ;; Code
5139 '(org-activate-code (1 'org-code t))
5140 ;; COMMENT
5141 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5142 "\\|" org-quote-string "\\)\\>")
5143 '(1 'org-special-keyword t))
5144 '("^#.*" (0 'font-lock-comment-face t))
5145 ;; Blocks and meta lines
5146 '(org-fontify-meta-lines-and-blocks)
5148 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5149 ;; Now set the full font-lock-keywords
5150 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5151 (org-set-local 'font-lock-defaults
5152 '(org-font-lock-keywords t nil nil backward-paragraph))
5153 (kill-local-variable 'font-lock-keywords) nil))
5155 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5156 "Fontify string S like in Org-mode"
5157 (with-temp-buffer
5158 (insert s)
5159 (let ((org-odd-levels-only odd-levels))
5160 (org-mode)
5161 (font-lock-fontify-buffer)
5162 (buffer-string))))
5164 (defvar org-m nil)
5165 (defvar org-l nil)
5166 (defvar org-f nil)
5167 (defun org-get-level-face (n)
5168 "Get the right face for match N in font-lock matching of headlines."
5169 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5170 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5171 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5172 (cond
5173 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5174 ((eq n 2) org-f)
5175 (t (if org-level-color-stars-only nil org-f))))
5177 (defun org-get-todo-face (kwd)
5178 "Get the right face for a TODO keyword KWD.
5179 If KWD is a number, get the corresponding match group."
5180 (if (numberp kwd) (setq kwd (match-string kwd)))
5181 (or (org-face-from-face-or-color
5182 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5183 (and (member kwd org-done-keywords) 'org-done)
5184 'org-todo))
5186 (defun org-face-from-face-or-color (context inherit face-or-color)
5187 "Create a face list that inherits INHERIT, but sets the foreground color.
5188 When FACE-OR-COLOR is not a string, just return it."
5189 (if (stringp face-or-color)
5190 (list :inherit inherit
5191 (cdr (assoc context org-faces-easy-properties))
5192 face-or-color)
5193 face-or-color))
5195 (defun org-font-lock-add-tag-faces (limit)
5196 "Add the special tag faces."
5197 (when (and org-tag-faces org-tags-special-faces-re)
5198 (while (re-search-forward org-tags-special-faces-re limit t)
5199 (add-text-properties (match-beginning 1) (match-end 1)
5200 (list 'face (org-get-tag-face 1)
5201 'font-lock-fontified t))
5202 (backward-char 1))))
5204 (defun org-font-lock-add-priority-faces (limit)
5205 "Add the special priority faces."
5206 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5207 (add-text-properties
5208 (match-beginning 0) (match-end 0)
5209 (list 'face (or (org-face-from-face-or-color
5210 'priority 'org-special-keyword
5211 (cdr (assoc (char-after (match-beginning 1))
5212 org-priority-faces)))
5213 'org-special-keyword)
5214 'font-lock-fontified t))))
5216 (defun org-get-tag-face (kwd)
5217 "Get the right face for a TODO keyword KWD.
5218 If KWD is a number, get the corresponding match group."
5219 (if (numberp kwd) (setq kwd (match-string kwd)))
5220 (or (org-face-from-face-or-color
5221 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5222 'org-tag))
5224 (defun org-unfontify-region (beg end &optional maybe_loudly)
5225 "Remove fontification and activation overlays from links."
5226 (font-lock-default-unfontify-region beg end)
5227 (let* ((buffer-undo-list t)
5228 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5229 (inhibit-modification-hooks t)
5230 deactivate-mark buffer-file-name buffer-file-truename)
5231 (remove-text-properties
5232 beg end
5233 (if org-indent-mode
5234 ;; also remove line-prefix and wrap-prefix properties
5235 '(mouse-face t keymap t org-linked-text t
5236 invisible t intangible t
5237 line-prefix t wrap-prefix t
5238 org-no-flyspell t)
5239 '(mouse-face t keymap t org-linked-text t
5240 invisible t intangible t
5241 org-no-flyspell t)))))
5243 ;;;; Visibility cycling, including org-goto and indirect buffer
5245 ;;; Cycling
5247 (defvar org-cycle-global-status nil)
5248 (make-variable-buffer-local 'org-cycle-global-status)
5249 (defvar org-cycle-subtree-status nil)
5250 (make-variable-buffer-local 'org-cycle-subtree-status)
5252 ;;;###autoload
5254 (defvar org-inlinetask-min-level)
5256 (defun org-cycle (&optional arg)
5257 "TAB-action and visibility cycling for Org-mode.
5259 This is the command invoked in Org-mode by the TAB key. Its main purpose
5260 is outline visibility cycling, but it also invokes other actions
5261 in special contexts.
5263 - When this function is called with a prefix argument, rotate the entire
5264 buffer through 3 states (global cycling)
5265 1. OVERVIEW: Show only top-level headlines.
5266 2. CONTENTS: Show all headlines of all levels, but no body text.
5267 3. SHOW ALL: Show everything.
5268 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5269 determined by the variable `org-startup-folded', and by any VISIBILITY
5270 properties in the buffer.
5271 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5272 including any drawers.
5274 - When inside a table, re-align the table and move to the next field.
5276 - When point is at the beginning of a headline, rotate the subtree started
5277 by this line through 3 different states (local cycling)
5278 1. FOLDED: Only the main headline is shown.
5279 2. CHILDREN: The main headline and the direct children are shown.
5280 From this state, you can move to one of the children
5281 and zoom in further.
5282 3. SUBTREE: Show the entire subtree, including body text.
5283 If there is no subtree, switch directly from CHILDREN to FOLDED.
5285 - When point is at the beginning of an empty headline and the variable
5286 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5287 of the headline by demoting and promoting it to likely levels. This
5288 speeds up creation document structure by presing TAB once or several
5289 times right after creating a new headline.
5291 - When there is a numeric prefix, go up to a heading with level ARG, do
5292 a `show-subtree' and return to the previous cursor position. If ARG
5293 is negative, go up that many levels.
5295 - When point is not at the beginning of a headline, execute the global
5296 binding for TAB, which is re-indenting the line. See the option
5297 `org-cycle-emulate-tab' for details.
5299 - Special case: if point is at the beginning of the buffer and there is
5300 no headline in line 1, this function will act as if called with prefix arg.
5301 But only if also the variable `org-cycle-global-at-bob' is t."
5302 (interactive "P")
5303 (org-load-modules-maybe)
5304 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5305 (and org-cycle-level-after-item/entry-creation
5306 (or (org-cycle-level)
5307 (org-cycle-item-indentation))))
5308 (let* ((limit-level
5309 (or org-cycle-max-level
5310 (and (boundp 'org-inlinetask-min-level)
5311 org-inlinetask-min-level
5312 (1- org-inlinetask-min-level))))
5313 (nstars (and limit-level
5314 (if org-odd-levels-only
5315 (and limit-level (1- (* limit-level 2)))
5316 limit-level)))
5317 (outline-regexp
5318 (cond
5319 ((not (org-mode-p)) outline-regexp)
5320 ((or (eq org-cycle-include-plain-lists 'integrate)
5321 (and org-cycle-include-plain-lists (org-at-item-p)))
5322 (concat "\\(?:\\*"
5323 (if nstars (format "\\{1,%d\\}" nstars) "+")
5324 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5325 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5326 (bob-special (and org-cycle-global-at-bob (bobp)
5327 (not (looking-at outline-regexp))))
5328 (org-cycle-hook
5329 (if bob-special
5330 (delq 'org-optimize-window-after-visibility-change
5331 (copy-sequence org-cycle-hook))
5332 org-cycle-hook))
5333 (pos (point)))
5335 (if (or bob-special (equal arg '(4)))
5336 ;; special case: use global cycling
5337 (setq arg t))
5339 (cond
5341 ((equal arg '(16))
5342 (org-set-startup-visibility)
5343 (message "Startup visibility, plus VISIBILITY properties"))
5345 ((equal arg '(64))
5346 (show-all)
5347 (message "Entire buffer visible, including drawers"))
5349 ((org-at-table-p 'any)
5350 ;; Enter the table or move to the next field in the table
5351 (if (org-at-table.el-p)
5352 (message "Use C-c ' to edit table.el tables")
5353 (if arg (org-table-edit-field t)
5354 (org-table-justify-field-maybe)
5355 (call-interactively 'org-table-next-field))))
5357 ((run-hook-with-args-until-success
5358 'org-tab-after-check-for-table-hook))
5360 ((eq arg t) ;; Global cycling
5361 (org-cycle-internal-global))
5363 ((and org-drawers org-drawer-regexp
5364 (save-excursion
5365 (beginning-of-line 1)
5366 (looking-at org-drawer-regexp)))
5367 ;; Toggle block visibility
5368 (org-flag-drawer
5369 (not (get-char-property (match-end 0) 'invisible))))
5371 ((integerp arg)
5372 ;; Show-subtree, ARG levels up from here.
5373 (save-excursion
5374 (org-back-to-heading)
5375 (outline-up-heading (if (< arg 0) (- arg)
5376 (- (funcall outline-level) arg)))
5377 (org-show-subtree)))
5379 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5380 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5382 (org-cycle-internal-local))
5384 ;; TAB emulation and template completion
5385 (buffer-read-only (org-back-to-heading))
5387 ((run-hook-with-args-until-success
5388 'org-tab-after-check-for-cycling-hook))
5390 ((org-try-structure-completion))
5392 ((org-try-cdlatex-tab))
5394 ((run-hook-with-args-until-success
5395 'org-tab-before-tab-emulation-hook))
5397 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5398 (or (not (bolp))
5399 (not (looking-at outline-regexp))))
5400 (call-interactively (global-key-binding "\t")))
5402 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5403 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5404 (or (and (eq org-cycle-emulate-tab 'white)
5405 (= (match-end 0) (point-at-eol)))
5406 (and (eq org-cycle-emulate-tab 'whitestart)
5407 (>= (match-end 0) pos))))
5409 (eq org-cycle-emulate-tab t))
5410 (call-interactively (global-key-binding "\t")))
5412 (t (save-excursion
5413 (org-back-to-heading)
5414 (org-cycle)))))))
5416 (defun org-cycle-internal-global ()
5417 "Do the global cycling action."
5418 (cond
5419 ((and (eq last-command this-command)
5420 (eq org-cycle-global-status 'overview))
5421 ;; We just created the overview - now do table of contents
5422 ;; This can be slow in very large buffers, so indicate action
5423 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5424 (message "CONTENTS...")
5425 (org-content)
5426 (message "CONTENTS...done")
5427 (setq org-cycle-global-status 'contents)
5428 (run-hook-with-args 'org-cycle-hook 'contents))
5430 ((and (eq last-command this-command)
5431 (eq org-cycle-global-status 'contents))
5432 ;; We just showed the table of contents - now show everything
5433 (run-hook-with-args 'org-pre-cycle-hook 'all)
5434 (show-all)
5435 (message "SHOW ALL")
5436 (setq org-cycle-global-status 'all)
5437 (run-hook-with-args 'org-cycle-hook 'all))
5440 ;; Default action: go to overview
5441 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5442 (org-overview)
5443 (message "OVERVIEW")
5444 (setq org-cycle-global-status 'overview)
5445 (run-hook-with-args 'org-cycle-hook 'overview))))
5447 (defun org-cycle-internal-local ()
5448 "Do the local cycling action."
5449 (org-back-to-heading)
5450 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5451 ;; First, some boundaries
5452 (save-excursion
5453 (org-back-to-heading)
5454 (setq level (funcall outline-level))
5455 (save-excursion
5456 (beginning-of-line 2)
5457 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5458 ; XEmacs does not have `next-single-char-property-change'
5459 ; I'm not sure about Emacs 21.
5460 (while (and (not (eobp)) ;; this is like `next-line'
5461 (get-char-property (1- (point)) 'invisible))
5462 (beginning-of-line 2))
5463 (while (and (not (eobp)) ;; this is like `next-line'
5464 (get-char-property (1- (point)) 'invisible))
5465 (goto-char (next-single-char-property-change (point) 'invisible))
5466 ;;;??? (or (bolp) (beginning-of-line 2))))
5467 (and (eolp) (beginning-of-line 2))))
5468 (setq eol (point)))
5469 (outline-end-of-heading) (setq eoh (point))
5470 (save-excursion
5471 (outline-next-heading)
5472 (setq has-children (and (org-at-heading-p t)
5473 (> (funcall outline-level) level))))
5474 (org-end-of-subtree t)
5475 (unless (eobp)
5476 (skip-chars-forward " \t\n")
5477 (beginning-of-line 1) ; in case this is an item
5479 (setq eos (if (eobp) (point) (1- (point)))))
5480 ;; Find out what to do next and set `this-command'
5481 (cond
5482 ((= eos eoh)
5483 ;; Nothing is hidden behind this heading
5484 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5485 (message "EMPTY ENTRY")
5486 (setq org-cycle-subtree-status nil)
5487 (save-excursion
5488 (goto-char eos)
5489 (outline-next-heading)
5490 (if (org-invisible-p) (org-flag-heading nil))))
5491 ((and (or (>= eol eos)
5492 (not (string-match "\\S-" (buffer-substring eol eos))))
5493 (or has-children
5494 (not (setq children-skipped
5495 org-cycle-skip-children-state-if-no-children))))
5496 ;; Entire subtree is hidden in one line: children view
5497 (run-hook-with-args 'org-pre-cycle-hook 'children)
5498 (org-show-entry)
5499 (show-children)
5500 (message "CHILDREN")
5501 (save-excursion
5502 (goto-char eos)
5503 (outline-next-heading)
5504 (if (org-invisible-p) (org-flag-heading nil)))
5505 (setq org-cycle-subtree-status 'children)
5506 (run-hook-with-args 'org-cycle-hook 'children))
5507 ((or children-skipped
5508 (and (eq last-command this-command)
5509 (eq org-cycle-subtree-status 'children)))
5510 ;; We just showed the children, or no children are there,
5511 ;; now show everything.
5512 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5513 (org-show-subtree)
5514 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5515 (setq org-cycle-subtree-status 'subtree)
5516 (run-hook-with-args 'org-cycle-hook 'subtree))
5518 ;; Default action: hide the subtree.
5519 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5520 (hide-subtree)
5521 (message "FOLDED")
5522 (setq org-cycle-subtree-status 'folded)
5523 (run-hook-with-args 'org-cycle-hook 'folded)))))
5525 ;;;###autoload
5526 (defun org-global-cycle (&optional arg)
5527 "Cycle the global visibility. For details see `org-cycle'.
5528 With C-u prefix arg, switch to startup visibility.
5529 With a numeric prefix, show all headlines up to that level."
5530 (interactive "P")
5531 (let ((org-cycle-include-plain-lists
5532 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5533 (cond
5534 ((integerp arg)
5535 (show-all)
5536 (hide-sublevels arg)
5537 (setq org-cycle-global-status 'contents))
5538 ((equal arg '(4))
5539 (org-set-startup-visibility)
5540 (message "Startup visibility, plus VISIBILITY properties."))
5542 (org-cycle '(4))))))
5544 (defun org-set-startup-visibility ()
5545 "Set the visibility required by startup options and properties."
5546 (cond
5547 ((eq org-startup-folded t)
5548 (org-cycle '(4)))
5549 ((eq org-startup-folded 'content)
5550 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5551 (org-cycle '(4)) (org-cycle '(4)))))
5552 (unless (eq org-startup-folded 'showeverything)
5553 (if org-hide-block-startup (org-hide-block-all))
5554 (org-set-visibility-according-to-property 'no-cleanup)
5555 (org-cycle-hide-archived-subtrees 'all)
5556 (org-cycle-hide-drawers 'all)
5557 (org-cycle-show-empty-lines 'all)))
5559 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5560 "Switch subtree visibilities according to :VISIBILITY: property."
5561 (interactive)
5562 (let (org-show-entry-below state)
5563 (save-excursion
5564 (goto-char (point-min))
5565 (while (re-search-forward
5566 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5567 nil t)
5568 (setq state (match-string 1))
5569 (save-excursion
5570 (org-back-to-heading t)
5571 (hide-subtree)
5572 (org-reveal)
5573 (cond
5574 ((equal state '("fold" "folded"))
5575 (hide-subtree))
5576 ((equal state "children")
5577 (org-show-hidden-entry)
5578 (show-children))
5579 ((equal state "content")
5580 (save-excursion
5581 (save-restriction
5582 (org-narrow-to-subtree)
5583 (org-content))))
5584 ((member state '("all" "showall"))
5585 (show-subtree)))))
5586 (unless no-cleanup
5587 (org-cycle-hide-archived-subtrees 'all)
5588 (org-cycle-hide-drawers 'all)
5589 (org-cycle-show-empty-lines 'all)))))
5591 (defun org-overview ()
5592 "Switch to overview mode, showing only top-level headlines.
5593 Really, this shows all headlines with level equal or greater than the level
5594 of the first headline in the buffer. This is important, because if the
5595 first headline is not level one, then (hide-sublevels 1) gives confusing
5596 results."
5597 (interactive)
5598 (let ((level (save-excursion
5599 (goto-char (point-min))
5600 (if (re-search-forward (concat "^" outline-regexp) nil t)
5601 (progn
5602 (goto-char (match-beginning 0))
5603 (funcall outline-level))))))
5604 (and level (hide-sublevels level))))
5606 (defun org-content (&optional arg)
5607 "Show all headlines in the buffer, like a table of contents.
5608 With numerical argument N, show content up to level N."
5609 (interactive "P")
5610 (save-excursion
5611 ;; Visit all headings and show their offspring
5612 (and (integerp arg) (org-overview))
5613 (goto-char (point-max))
5614 (catch 'exit
5615 (while (and (progn (condition-case nil
5616 (outline-previous-visible-heading 1)
5617 (error (goto-char (point-min))))
5619 (looking-at outline-regexp))
5620 (if (integerp arg)
5621 (show-children (1- arg))
5622 (show-branches))
5623 (if (bobp) (throw 'exit nil))))))
5626 (defun org-optimize-window-after-visibility-change (state)
5627 "Adjust the window after a change in outline visibility.
5628 This function is the default value of the hook `org-cycle-hook'."
5629 (when (get-buffer-window (current-buffer))
5630 (cond
5631 ((eq state 'content) nil)
5632 ((eq state 'all) nil)
5633 ((eq state 'folded) nil)
5634 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5635 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5637 (defun org-remove-empty-overlays-at (pos)
5638 "Remove outline overlays that do not contain non-white stuff."
5639 (mapc
5640 (lambda (o)
5641 (and (eq 'outline (org-overlay-get o 'invisible))
5642 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5643 (org-overlay-end o))))
5644 (org-delete-overlay o)))
5645 (org-overlays-at pos)))
5647 (defun org-clean-visibility-after-subtree-move ()
5648 "Fix visibility issues after moving a subtree."
5649 ;; First, find a reasonable region to look at:
5650 ;; Start two siblings above, end three below
5651 (let* ((beg (save-excursion
5652 (and (org-get-last-sibling)
5653 (org-get-last-sibling))
5654 (point)))
5655 (end (save-excursion
5656 (and (org-get-next-sibling)
5657 (org-get-next-sibling)
5658 (org-get-next-sibling))
5659 (if (org-at-heading-p)
5660 (point-at-eol)
5661 (point))))
5662 (level (looking-at "\\*+"))
5663 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5664 (save-excursion
5665 (save-restriction
5666 (narrow-to-region beg end)
5667 (when re
5668 ;; Properly fold already folded siblings
5669 (goto-char (point-min))
5670 (while (re-search-forward re nil t)
5671 (if (and (not (org-invisible-p))
5672 (save-excursion
5673 (goto-char (point-at-eol)) (org-invisible-p)))
5674 (hide-entry))))
5675 (org-cycle-show-empty-lines 'overview)
5676 (org-cycle-hide-drawers 'overview)))))
5678 (defun org-cycle-show-empty-lines (state)
5679 "Show empty lines above all visible headlines.
5680 The region to be covered depends on STATE when called through
5681 `org-cycle-hook'. Lisp program can use t for STATE to get the
5682 entire buffer covered. Note that an empty line is only shown if there
5683 are at least `org-cycle-separator-lines' empty lines before the headline."
5684 (when (not (= org-cycle-separator-lines 0))
5685 (save-excursion
5686 (let* ((n (abs org-cycle-separator-lines))
5687 (re (cond
5688 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5689 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5690 (t (let ((ns (number-to-string (- n 2))))
5691 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5692 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5693 beg end b e)
5694 (cond
5695 ((memq state '(overview contents t))
5696 (setq beg (point-min) end (point-max)))
5697 ((memq state '(children folded))
5698 (setq beg (point) end (progn (org-end-of-subtree t t)
5699 (beginning-of-line 2)
5700 (point)))))
5701 (when beg
5702 (goto-char beg)
5703 (while (re-search-forward re end t)
5704 (unless (get-char-property (match-end 1) 'invisible)
5705 (setq e (match-end 1))
5706 (if (< org-cycle-separator-lines 0)
5707 (setq b (save-excursion
5708 (goto-char (match-beginning 0))
5709 (org-back-over-empty-lines)
5710 (if (save-excursion
5711 (goto-char (max (point-min) (1- (point))))
5712 (org-on-heading-p))
5713 (1- (point))
5714 (point))))
5715 (setq b (match-beginning 1)))
5716 (outline-flag-region b e nil)))))))
5717 ;; Never hide empty lines at the end of the file.
5718 (save-excursion
5719 (goto-char (point-max))
5720 (outline-previous-heading)
5721 (outline-end-of-heading)
5722 (if (and (looking-at "[ \t\n]+")
5723 (= (match-end 0) (point-max)))
5724 (outline-flag-region (point) (match-end 0) nil))))
5726 (defun org-show-empty-lines-in-parent ()
5727 "Move to the parent and re-show empty lines before visible headlines."
5728 (save-excursion
5729 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5730 (org-cycle-show-empty-lines context))))
5732 (defun org-files-list ()
5733 "Return `org-agenda-files' list, plus all open org-mode files.
5734 This is useful for operations that need to scan all of a user's
5735 open and agenda-wise Org files."
5736 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5737 (dolist (buf (buffer-list))
5738 (with-current-buffer buf
5739 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5740 (let ((file (expand-file-name (buffer-file-name))))
5741 (unless (member file files)
5742 (push file files))))))
5743 files))
5745 (defsubst org-entry-beginning-position ()
5746 "Return the beginning position of the current entry."
5747 (save-excursion (outline-back-to-heading t) (point)))
5749 (defsubst org-entry-end-position ()
5750 "Return the end position of the current entry."
5751 (save-excursion (outline-next-heading) (point)))
5753 (defun org-cycle-hide-drawers (state)
5754 "Re-hide all drawers after a visibility state change."
5755 (when (and (org-mode-p)
5756 (not (memq state '(overview folded contents))))
5757 (save-excursion
5758 (let* ((globalp (memq state '(contents all)))
5759 (beg (if globalp (point-min) (point)))
5760 (end (if globalp (point-max)
5761 (if (eq state 'children)
5762 (save-excursion (outline-next-heading) (point))
5763 (org-end-of-subtree t)))))
5764 (goto-char beg)
5765 (while (re-search-forward org-drawer-regexp end t)
5766 (org-flag-drawer t))))))
5768 (defun org-flag-drawer (flag)
5769 (save-excursion
5770 (beginning-of-line 1)
5771 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5772 (let ((b (match-end 0))
5773 (outline-regexp org-outline-regexp))
5774 (if (re-search-forward
5775 "^[ \t]*:END:"
5776 (save-excursion (outline-next-heading) (point)) t)
5777 (outline-flag-region b (point-at-eol) flag)
5778 (error ":END: line missing at position %s" b))))))
5780 (defun org-subtree-end-visible-p ()
5781 "Is the end of the current subtree visible?"
5782 (pos-visible-in-window-p
5783 (save-excursion (org-end-of-subtree t) (point))))
5785 (defun org-first-headline-recenter (&optional N)
5786 "Move cursor to the first headline and recenter the headline.
5787 Optional argument N means put the headline into the Nth line of the window."
5788 (goto-char (point-min))
5789 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5790 (beginning-of-line)
5791 (recenter (prefix-numeric-value N))))
5793 ;;; Saving and restoring visibility
5795 (defun org-outline-overlay-data (&optional use-markers)
5796 "Return a list of the locations of all outline overlays.
5797 The are overlays with the `invisible' property value `outline'.
5798 The return valus is a list of cons cells, with start and stop
5799 positions for each overlay.
5800 If USE-MARKERS is set, return the positions as markers."
5801 (let (beg end)
5802 (save-excursion
5803 (save-restriction
5804 (widen)
5805 (delq nil
5806 (mapcar (lambda (o)
5807 (when (eq (org-overlay-get o 'invisible) 'outline)
5808 (setq beg (org-overlay-start o)
5809 end (org-overlay-end o))
5810 (and beg end (> end beg)
5811 (if use-markers
5812 (cons (move-marker (make-marker) beg)
5813 (move-marker (make-marker) end))
5814 (cons beg end)))))
5815 (org-overlays-in (point-min) (point-max))))))))
5817 (defun org-set-outline-overlay-data (data)
5818 "Create visibility overlays for all positions in DATA.
5819 DATA should have been made by `org-outline-overlay-data'."
5820 (let (o)
5821 (save-excursion
5822 (save-restriction
5823 (widen)
5824 (show-all)
5825 (mapc (lambda (c)
5826 (setq o (org-make-overlay (car c) (cdr c)))
5827 (org-overlay-put o 'invisible 'outline))
5828 data)))))
5830 (defmacro org-save-outline-visibility (use-markers &rest body)
5831 "Save and restore outline visibility around BODY.
5832 If USE-MARKERS is non-nil, use markers for the positions.
5833 This means that the buffer may change while running BODY,
5834 but it also means that the buffer should stay alive
5835 during the operation, because otherwise all these markers will
5836 point nowhere."
5837 `(let ((data (org-outline-overlay-data ,use-markers)))
5838 (unwind-protect
5839 (progn
5840 ,@body
5841 (org-set-outline-overlay-data data))
5842 (when ,use-markers
5843 (mapc (lambda (c)
5844 (and (markerp (car c)) (move-marker (car c) nil))
5845 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5846 data)))))
5849 ;;; Folding of blocks
5851 (defconst org-block-regexp
5853 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5854 "Regular expression for hiding blocks.")
5856 (defvar org-hide-block-overlays nil
5857 "Overlays hiding blocks.")
5858 (make-variable-buffer-local 'org-hide-block-overlays)
5860 (defun org-block-map (function &optional start end)
5861 "Call func at the head of all source blocks in the current
5862 buffer. Optional arguments START and END can be used to limit
5863 the range."
5864 (let ((start (or start (point-min)))
5865 (end (or end (point-max))))
5866 (save-excursion
5867 (goto-char start)
5868 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5869 (save-excursion
5870 (save-match-data
5871 (goto-char (match-beginning 0))
5872 (funcall function)))))))
5874 (defun org-hide-block-toggle-all ()
5875 "Toggle the visibility of all blocks in the current buffer."
5876 (org-block-map #'org-hide-block-toggle))
5878 (defun org-hide-block-all ()
5879 "Fold all blocks in the current buffer."
5880 (interactive)
5881 (org-show-block-all)
5882 (org-block-map #'org-hide-block-toggle-maybe))
5884 (defun org-show-block-all ()
5885 "Unfold all blocks in the current buffer."
5886 (mapc 'org-delete-overlay org-hide-block-overlays)
5887 (setq org-hide-block-overlays nil))
5889 (defun org-hide-block-toggle-maybe ()
5890 "Toggle visibility of block at point."
5891 (interactive)
5892 (let ((case-fold-search t))
5893 (if (save-excursion
5894 (beginning-of-line 1)
5895 (looking-at org-block-regexp))
5896 (progn (org-hide-block-toggle)
5897 t) ;; to signal that we took action
5898 nil))) ;; to signal that we did not
5900 (defun org-hide-block-toggle (&optional force)
5901 "Toggle the visibility of the current block."
5902 (interactive)
5903 (save-excursion
5904 (beginning-of-line)
5905 (if (re-search-forward org-block-regexp nil t)
5906 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5907 (end (match-end 0)) ;; end of entire body
5909 (if (memq t (mapcar (lambda (overlay)
5910 (eq (org-overlay-get overlay 'invisible)
5911 'org-hide-block))
5912 (org-overlays-at start)))
5913 (if (or (not force) (eq force 'off))
5914 (mapc (lambda (ov)
5915 (when (member ov org-hide-block-overlays)
5916 (setq org-hide-block-overlays
5917 (delq ov org-hide-block-overlays)))
5918 (when (eq (org-overlay-get ov 'invisible)
5919 'org-hide-block)
5920 (org-delete-overlay ov)))
5921 (org-overlays-at start)))
5922 (setq ov (org-make-overlay start end))
5923 (org-overlay-put ov 'invisible 'org-hide-block)
5924 ;; make the block accessible to isearch
5925 (org-overlay-put
5926 ov 'isearch-open-invisible
5927 (lambda (ov)
5928 (when (member ov org-hide-block-overlays)
5929 (setq org-hide-block-overlays
5930 (delq ov org-hide-block-overlays)))
5931 (when (eq (org-overlay-get ov 'invisible)
5932 'org-hide-block)
5933 (org-delete-overlay ov))))
5934 (push ov org-hide-block-overlays)))
5935 (error "Not looking at a source block"))))
5937 ;; org-tab-after-check-for-cycling-hook
5938 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5939 ;; Remove overlays when changing major mode
5940 (add-hook 'org-mode-hook
5941 (lambda () (org-add-hook 'change-major-mode-hook
5942 'org-show-block-all 'append 'local)))
5944 ;;; Org-goto
5946 (defvar org-goto-window-configuration nil)
5947 (defvar org-goto-marker nil)
5948 (defvar org-goto-map
5949 (let ((map (make-sparse-keymap)))
5950 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5951 (while (setq cmd (pop cmds))
5952 (substitute-key-definition cmd cmd map global-map)))
5953 (suppress-keymap map)
5954 (org-defkey map "\C-m" 'org-goto-ret)
5955 (org-defkey map [(return)] 'org-goto-ret)
5956 (org-defkey map [(left)] 'org-goto-left)
5957 (org-defkey map [(right)] 'org-goto-right)
5958 (org-defkey map [(control ?g)] 'org-goto-quit)
5959 (org-defkey map "\C-i" 'org-cycle)
5960 (org-defkey map [(tab)] 'org-cycle)
5961 (org-defkey map [(down)] 'outline-next-visible-heading)
5962 (org-defkey map [(up)] 'outline-previous-visible-heading)
5963 (if org-goto-auto-isearch
5964 (if (fboundp 'define-key-after)
5965 (define-key-after map [t] 'org-goto-local-auto-isearch)
5966 nil)
5967 (org-defkey map "q" 'org-goto-quit)
5968 (org-defkey map "n" 'outline-next-visible-heading)
5969 (org-defkey map "p" 'outline-previous-visible-heading)
5970 (org-defkey map "f" 'outline-forward-same-level)
5971 (org-defkey map "b" 'outline-backward-same-level)
5972 (org-defkey map "u" 'outline-up-heading))
5973 (org-defkey map "/" 'org-occur)
5974 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5975 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5976 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5977 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5978 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5979 map))
5981 (defconst org-goto-help
5982 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5983 RET=jump to location [Q]uit and return to previous location
5984 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5986 (defvar org-goto-start-pos) ; dynamically scoped parameter
5988 ;; FIXME: Docstring does not mention both interfaces
5989 (defun org-goto (&optional alternative-interface)
5990 "Look up a different location in the current file, keeping current visibility.
5992 When you want look-up or go to a different location in a document, the
5993 fastest way is often to fold the entire buffer and then dive into the tree.
5994 This method has the disadvantage, that the previous location will be folded,
5995 which may not be what you want.
5997 This command works around this by showing a copy of the current buffer
5998 in an indirect buffer, in overview mode. You can dive into the tree in
5999 that copy, use org-occur and incremental search to find a location.
6000 When pressing RET or `Q', the command returns to the original buffer in
6001 which the visibility is still unchanged. After RET is will also jump to
6002 the location selected in the indirect buffer and expose the
6003 the headline hierarchy above."
6004 (interactive "P")
6005 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6006 (org-refile-use-outline-path t)
6007 (org-refile-target-verify-function nil)
6008 (interface
6009 (if (not alternative-interface)
6010 org-goto-interface
6011 (if (eq org-goto-interface 'outline)
6012 'outline-path-completion
6013 'outline)))
6014 (org-goto-start-pos (point))
6015 (selected-point
6016 (if (eq interface 'outline)
6017 (car (org-get-location (current-buffer) org-goto-help))
6018 (nth 3 (org-refile-get-location "Goto: ")))))
6019 (if selected-point
6020 (progn
6021 (org-mark-ring-push org-goto-start-pos)
6022 (goto-char selected-point)
6023 (if (or (org-invisible-p) (org-invisible-p2))
6024 (org-show-context 'org-goto)))
6025 (message "Quit"))))
6027 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6028 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6029 (defvar org-goto-local-auto-isearch-map) ; defined below
6031 (defun org-get-location (buf help)
6032 "Let the user select a location in the Org-mode buffer BUF.
6033 This function uses a recursive edit. It returns the selected position
6034 or nil."
6035 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6036 (isearch-hide-immediately nil)
6037 (isearch-search-fun-function
6038 (lambda () 'org-goto-local-search-headings))
6039 (org-goto-selected-point org-goto-exit-command)
6040 (pop-up-frames nil)
6041 (special-display-buffer-names nil)
6042 (special-display-regexps nil)
6043 (special-display-function nil))
6044 (save-excursion
6045 (save-window-excursion
6046 (delete-other-windows)
6047 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6048 (switch-to-buffer
6049 (condition-case nil
6050 (make-indirect-buffer (current-buffer) "*org-goto*")
6051 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6052 (with-output-to-temp-buffer "*Help*"
6053 (princ help))
6054 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6055 (setq buffer-read-only nil)
6056 (let ((org-startup-truncated t)
6057 (org-startup-folded nil)
6058 (org-startup-align-all-tables nil))
6059 (org-mode)
6060 (org-overview))
6061 (setq buffer-read-only t)
6062 (if (and (boundp 'org-goto-start-pos)
6063 (integer-or-marker-p org-goto-start-pos))
6064 (let ((org-show-hierarchy-above t)
6065 (org-show-siblings t)
6066 (org-show-following-heading t))
6067 (goto-char org-goto-start-pos)
6068 (and (org-invisible-p) (org-show-context)))
6069 (goto-char (point-min)))
6070 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6071 (message "Select location and press RET")
6072 (use-local-map org-goto-map)
6073 (recursive-edit)
6075 (kill-buffer "*org-goto*")
6076 (cons org-goto-selected-point org-goto-exit-command)))
6078 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6079 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6080 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6081 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6083 (defun org-goto-local-search-headings (string bound noerror)
6084 "Search and make sure that any matches are in headlines."
6085 (catch 'return
6086 (while (if isearch-forward
6087 (search-forward string bound noerror)
6088 (search-backward string bound noerror))
6089 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6090 (and (member :headline context)
6091 (not (member :tags context))))
6092 (throw 'return (point))))))
6094 (defun org-goto-local-auto-isearch ()
6095 "Start isearch."
6096 (interactive)
6097 (goto-char (point-min))
6098 (let ((keys (this-command-keys)))
6099 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6100 (isearch-mode t)
6101 (isearch-process-search-char (string-to-char keys)))))
6103 (defun org-goto-ret (&optional arg)
6104 "Finish `org-goto' by going to the new location."
6105 (interactive "P")
6106 (setq org-goto-selected-point (point)
6107 org-goto-exit-command 'return)
6108 (throw 'exit nil))
6110 (defun org-goto-left ()
6111 "Finish `org-goto' by going to the new location."
6112 (interactive)
6113 (if (org-on-heading-p)
6114 (progn
6115 (beginning-of-line 1)
6116 (setq org-goto-selected-point (point)
6117 org-goto-exit-command 'left)
6118 (throw 'exit nil))
6119 (error "Not on a heading")))
6121 (defun org-goto-right ()
6122 "Finish `org-goto' by going to the new location."
6123 (interactive)
6124 (if (org-on-heading-p)
6125 (progn
6126 (setq org-goto-selected-point (point)
6127 org-goto-exit-command 'right)
6128 (throw 'exit nil))
6129 (error "Not on a heading")))
6131 (defun org-goto-quit ()
6132 "Finish `org-goto' without cursor motion."
6133 (interactive)
6134 (setq org-goto-selected-point nil)
6135 (setq org-goto-exit-command 'quit)
6136 (throw 'exit nil))
6138 ;;; Indirect buffer display of subtrees
6140 (defvar org-indirect-dedicated-frame nil
6141 "This is the frame being used for indirect tree display.")
6142 (defvar org-last-indirect-buffer nil)
6144 (defun org-tree-to-indirect-buffer (&optional arg)
6145 "Create indirect buffer and narrow it to current subtree.
6146 With numerical prefix ARG, go up to this level and then take that tree.
6147 If ARG is negative, go up that many levels.
6148 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6149 indirect buffer previously made with this command, to avoid proliferation of
6150 indirect buffers. However, when you call the command with a `C-u' prefix, or
6151 when `org-indirect-buffer-display' is `new-frame', the last buffer
6152 is kept so that you can work with several indirect buffers at the same time.
6153 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6154 requests that a new frame be made for the new buffer, so that the dedicated
6155 frame is not changed."
6156 (interactive "P")
6157 (let ((cbuf (current-buffer))
6158 (cwin (selected-window))
6159 (pos (point))
6160 beg end level heading ibuf)
6161 (save-excursion
6162 (org-back-to-heading t)
6163 (when (numberp arg)
6164 (setq level (org-outline-level))
6165 (if (< arg 0) (setq arg (+ level arg)))
6166 (while (> (setq level (org-outline-level)) arg)
6167 (outline-up-heading 1 t)))
6168 (setq beg (point)
6169 heading (org-get-heading))
6170 (org-end-of-subtree t t)
6171 (if (org-on-heading-p) (backward-char 1))
6172 (setq end (point)))
6173 (if (and (buffer-live-p org-last-indirect-buffer)
6174 (not (eq org-indirect-buffer-display 'new-frame))
6175 (not arg))
6176 (kill-buffer org-last-indirect-buffer))
6177 (setq ibuf (org-get-indirect-buffer cbuf)
6178 org-last-indirect-buffer ibuf)
6179 (cond
6180 ((or (eq org-indirect-buffer-display 'new-frame)
6181 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6182 (select-frame (make-frame))
6183 (delete-other-windows)
6184 (switch-to-buffer ibuf)
6185 (org-set-frame-title heading))
6186 ((eq org-indirect-buffer-display 'dedicated-frame)
6187 (raise-frame
6188 (select-frame (or (and org-indirect-dedicated-frame
6189 (frame-live-p org-indirect-dedicated-frame)
6190 org-indirect-dedicated-frame)
6191 (setq org-indirect-dedicated-frame (make-frame)))))
6192 (delete-other-windows)
6193 (switch-to-buffer ibuf)
6194 (org-set-frame-title (concat "Indirect: " heading)))
6195 ((eq org-indirect-buffer-display 'current-window)
6196 (switch-to-buffer ibuf))
6197 ((eq org-indirect-buffer-display 'other-window)
6198 (pop-to-buffer ibuf))
6199 (t (error "Invalid value")))
6200 (if (featurep 'xemacs)
6201 (save-excursion (org-mode) (turn-on-font-lock)))
6202 (narrow-to-region beg end)
6203 (show-all)
6204 (goto-char pos)
6205 (and (window-live-p cwin) (select-window cwin))))
6207 (defun org-get-indirect-buffer (&optional buffer)
6208 (setq buffer (or buffer (current-buffer)))
6209 (let ((n 1) (base (buffer-name buffer)) bname)
6210 (while (buffer-live-p
6211 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6212 (setq n (1+ n)))
6213 (condition-case nil
6214 (make-indirect-buffer buffer bname 'clone)
6215 (error (make-indirect-buffer buffer bname)))))
6217 (defun org-set-frame-title (title)
6218 "Set the title of the current frame to the string TITLE."
6219 ;; FIXME: how to name a single frame in XEmacs???
6220 (unless (featurep 'xemacs)
6221 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6223 ;;;; Structure editing
6225 ;;; Inserting headlines
6227 (defun org-previous-line-empty-p ()
6228 (save-excursion
6229 (and (not (bobp))
6230 (or (beginning-of-line 0) t)
6231 (save-match-data
6232 (looking-at "[ \t]*$")))))
6234 (defun org-insert-heading (&optional force-heading invisible-ok)
6235 "Insert a new heading or item with same depth at point.
6236 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6237 If point is at the beginning of a headline, insert a sibling before the
6238 current headline. If point is not at the beginning, do not split the line,
6239 but create the new headline after the current line.
6240 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6241 This is important for non-interactive uses of the command."
6242 (interactive "P")
6243 (if (or (= (buffer-size) 0)
6244 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6245 (org-on-heading-p))))
6246 (not (org-in-item-p))))
6247 (insert "\n* ")
6248 (when (or force-heading (not (org-insert-item)))
6249 (let* ((empty-line-p nil)
6250 (head (save-excursion
6251 (condition-case nil
6252 (progn
6253 (org-back-to-heading invisible-ok)
6254 (setq empty-line-p (org-previous-line-empty-p))
6255 (match-string 0))
6256 (error "*"))))
6257 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6258 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6259 pos hide-previous previous-pos)
6260 (cond
6261 ((and (org-on-heading-p) (bolp)
6262 (or (bobp)
6263 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6264 ;; insert before the current line
6265 (open-line (if blank 2 1)))
6266 ((and (bolp)
6267 (not org-insert-heading-respect-content)
6268 (or (bobp)
6269 (save-excursion
6270 (backward-char 1) (not (org-invisible-p)))))
6271 ;; insert right here
6272 nil)
6274 ;; somewhere in the line
6275 (save-excursion
6276 (setq previous-pos (point-at-bol))
6277 (end-of-line)
6278 (setq hide-previous (org-invisible-p)))
6279 (and org-insert-heading-respect-content (org-show-subtree))
6280 (let ((split
6281 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6282 (save-excursion
6283 (let ((p (point)))
6284 (goto-char (point-at-bol))
6285 (and (looking-at org-complex-heading-regexp)
6286 (> p (match-beginning 4)))))))
6287 tags pos)
6288 (cond
6289 (org-insert-heading-respect-content
6290 (org-end-of-subtree nil t)
6291 (or (bolp) (newline))
6292 (or (org-previous-line-empty-p)
6293 (and blank (newline)))
6294 (open-line 1))
6295 ((org-on-heading-p)
6296 (when hide-previous
6297 (show-children)
6298 (org-show-entry))
6299 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6300 (setq tags (and (match-end 2) (match-string 2)))
6301 (and (match-end 1)
6302 (delete-region (match-beginning 1) (match-end 1)))
6303 (setq pos (point-at-bol))
6304 (or split (end-of-line 1))
6305 (delete-horizontal-space)
6306 (if (string-match "\\`\\*+\\'"
6307 (buffer-substring (point-at-bol) (point)))
6308 (insert " "))
6309 (newline (if blank 2 1))
6310 (when tags
6311 (save-excursion
6312 (goto-char pos)
6313 (end-of-line 1)
6314 (insert " " tags)
6315 (org-set-tags nil 'align))))
6317 (or split (end-of-line 1))
6318 (newline (if blank 2 1)))))))
6319 (insert head) (just-one-space)
6320 (setq pos (point))
6321 (end-of-line 1)
6322 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6323 (when (and org-insert-heading-respect-content hide-previous)
6324 (save-excursion
6325 (goto-char previous-pos)
6326 (hide-subtree)))
6327 (run-hooks 'org-insert-heading-hook)))))
6329 (defun org-get-heading (&optional no-tags)
6330 "Return the heading of the current entry, without the stars."
6331 (save-excursion
6332 (org-back-to-heading t)
6333 (if (looking-at
6334 (if no-tags
6335 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6336 "\\*+[ \t]+\\([^\r\n]*\\)"))
6337 (match-string 1) "")))
6339 (defun org-heading-components ()
6340 "Return the components of the current heading.
6341 This is a list with the following elements:
6342 - the level as an integer
6343 - the reduced level, different if `org-odd-levels-only' is set.
6344 - the TODO keyword, or nil
6345 - the priority character, like ?A, or nil if no priority is given
6346 - the headline text itself, or the tags string if no headline text
6347 - the tags string, or nil."
6348 (save-excursion
6349 (org-back-to-heading t)
6350 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6351 (list (length (match-string 1))
6352 (org-reduced-level (length (match-string 1)))
6353 (org-match-string-no-properties 2)
6354 (and (match-end 3) (aref (match-string 3) 2))
6355 (org-match-string-no-properties 4)
6356 (org-match-string-no-properties 5)))))
6358 (defun org-get-entry ()
6359 "Get the entry text, after heading, entire subtree."
6360 (save-excursion
6361 (org-back-to-heading t)
6362 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6364 (defun org-insert-heading-after-current ()
6365 "Insert a new heading with same level as current, after current subtree."
6366 (interactive)
6367 (org-back-to-heading)
6368 (org-insert-heading)
6369 (org-move-subtree-down)
6370 (end-of-line 1))
6372 (defun org-insert-heading-respect-content ()
6373 (interactive)
6374 (let ((org-insert-heading-respect-content t))
6375 (org-insert-heading t)))
6377 (defun org-insert-todo-heading-respect-content (&optional force-state)
6378 (interactive "P")
6379 (let ((org-insert-heading-respect-content t))
6380 (org-insert-todo-heading force-state t)))
6382 (defun org-insert-todo-heading (arg &optional force-heading)
6383 "Insert a new heading with the same level and TODO state as current heading.
6384 If the heading has no TODO state, or if the state is DONE, use the first
6385 state (TODO by default). Also with prefix arg, force first state."
6386 (interactive "P")
6387 (when (or force-heading (not (org-insert-item 'checkbox)))
6388 (org-insert-heading force-heading)
6389 (save-excursion
6390 (org-back-to-heading)
6391 (outline-previous-heading)
6392 (looking-at org-todo-line-regexp))
6393 (let*
6394 ((new-mark-x
6395 (if (or arg
6396 (not (match-beginning 2))
6397 (member (match-string 2) org-done-keywords))
6398 (car org-todo-keywords-1)
6399 (match-string 2)))
6400 (new-mark
6402 (run-hook-with-args-until-success
6403 'org-todo-get-default-hook new-mark-x nil)
6404 new-mark-x)))
6405 (beginning-of-line 1)
6406 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6407 (if org-treat-insert-todo-heading-as-state-change
6408 (org-todo new-mark)
6409 (insert new-mark " "))))
6410 (when org-provide-todo-statistics
6411 (org-update-parent-todo-statistics))))
6413 (defun org-insert-subheading (arg)
6414 "Insert a new subheading and demote it.
6415 Works for outline headings and for plain lists alike."
6416 (interactive "P")
6417 (org-insert-heading arg)
6418 (cond
6419 ((org-on-heading-p) (org-do-demote))
6420 ((org-at-item-p) (org-indent-item 1))))
6422 (defun org-insert-todo-subheading (arg)
6423 "Insert a new subheading with TODO keyword or checkbox and demote it.
6424 Works for outline headings and for plain lists alike."
6425 (interactive "P")
6426 (org-insert-todo-heading arg)
6427 (cond
6428 ((org-on-heading-p) (org-do-demote))
6429 ((org-at-item-p) (org-indent-item 1))))
6431 ;;; Promotion and Demotion
6433 (defvar org-after-demote-entry-hook nil
6434 "Hook run after an entry has been demoted.
6435 The cursor will be at the beginning of the entry.
6436 When a subtree is being demoted, the hook will be called for each node.")
6438 (defvar org-after-promote-entry-hook nil
6439 "Hook run after an entry has been promoted.
6440 The cursor will be at the beginning of the entry.
6441 When a subtree is being promoted, the hook will be called for each node.")
6443 (defun org-promote-subtree ()
6444 "Promote the entire subtree.
6445 See also `org-promote'."
6446 (interactive)
6447 (save-excursion
6448 (org-map-tree 'org-promote))
6449 (org-fix-position-after-promote))
6451 (defun org-demote-subtree ()
6452 "Demote the entire subtree. See `org-demote'.
6453 See also `org-promote'."
6454 (interactive)
6455 (save-excursion
6456 (org-map-tree 'org-demote))
6457 (org-fix-position-after-promote))
6460 (defun org-do-promote ()
6461 "Promote the current heading higher up the tree.
6462 If the region is active in `transient-mark-mode', promote all headings
6463 in the region."
6464 (interactive)
6465 (save-excursion
6466 (if (org-region-active-p)
6467 (org-map-region 'org-promote (region-beginning) (region-end))
6468 (org-promote)))
6469 (org-fix-position-after-promote))
6471 (defun org-do-demote ()
6472 "Demote the current heading lower down the tree.
6473 If the region is active in `transient-mark-mode', demote all headings
6474 in the region."
6475 (interactive)
6476 (save-excursion
6477 (if (org-region-active-p)
6478 (org-map-region 'org-demote (region-beginning) (region-end))
6479 (org-demote)))
6480 (org-fix-position-after-promote))
6482 (defun org-fix-position-after-promote ()
6483 "Make sure that after pro/demotion cursor position is right."
6484 (let ((pos (point)))
6485 (when (save-excursion
6486 (beginning-of-line 1)
6487 (looking-at org-todo-line-regexp)
6488 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6489 (cond ((eobp) (insert " "))
6490 ((eolp) (insert " "))
6491 ((equal (char-after) ?\ ) (forward-char 1))))))
6493 (defun org-current-level ()
6494 "Return the level of the current entry, or nil if before the first headline.
6495 The level is the number of stars at the beginning of the headline."
6496 (save-excursion
6497 (condition-case nil
6498 (progn
6499 (org-back-to-heading t)
6500 (funcall outline-level))
6501 (error nil))))
6503 (defun org-get-previous-line-level ()
6504 "Return the outline depth of the last headline before the current line.
6505 Returns 0 for the first headline in the buffer, and nil if before the
6506 first headline."
6507 (let ((current-level (org-current-level))
6508 (prev-level (when (> (line-number-at-pos) 1)
6509 (save-excursion
6510 (beginning-of-line 0)
6511 (org-current-level)))))
6512 (cond ((null current-level) nil) ; Before first headline
6513 ((null prev-level) 0) ; At first headline
6514 (prev-level))))
6516 (defun org-reduced-level (l)
6517 "Compute the effective level of a heading.
6518 This takes into account the setting of `org-odd-levels-only'."
6519 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6521 (defun org-level-increment ()
6522 "Return the number of stars that will be added or removed at a
6523 time to headlines when structure editing, based on the value of
6524 `org-odd-levels-only'."
6525 (if org-odd-levels-only 2 1))
6527 (defun org-get-valid-level (level &optional change)
6528 "Rectify a level change under the influence of `org-odd-levels-only'
6529 LEVEL is a current level, CHANGE is by how much the level should be
6530 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6531 even level numbers will become the next higher odd number."
6532 (if org-odd-levels-only
6533 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6534 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6535 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6536 (max 1 (+ level (or change 0)))))
6538 (if (boundp 'define-obsolete-function-alias)
6539 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6540 (define-obsolete-function-alias 'org-get-legal-level
6541 'org-get-valid-level)
6542 (define-obsolete-function-alias 'org-get-legal-level
6543 'org-get-valid-level "23.1")))
6545 (defun org-promote ()
6546 "Promote the current heading higher up the tree.
6547 If the region is active in `transient-mark-mode', promote all headings
6548 in the region."
6549 (org-back-to-heading t)
6550 (let* ((level (save-match-data (funcall outline-level)))
6551 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6552 (diff (abs (- level (length up-head) -1))))
6553 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6554 (replace-match up-head nil t)
6555 ;; Fixup tag positioning
6556 (and org-auto-align-tags (org-set-tags nil t))
6557 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6558 (run-hooks 'org-after-promote-entry-hook)))
6560 (defun org-demote ()
6561 "Demote the current heading lower down the tree.
6562 If the region is active in `transient-mark-mode', demote all headings
6563 in the region."
6564 (org-back-to-heading t)
6565 (let* ((level (save-match-data (funcall outline-level)))
6566 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6567 (diff (abs (- level (length down-head) -1))))
6568 (replace-match down-head nil t)
6569 ;; Fixup tag positioning
6570 (and org-auto-align-tags (org-set-tags nil t))
6571 (if org-adapt-indentation (org-fixup-indentation diff))
6572 (run-hooks 'org-after-demote-entry-hook)))
6574 (defun org-cycle-level ()
6575 "Cycle the level of an empty headline through possible states.
6576 This goes first to child, then to parent, level, then up the hierarchy.
6577 After top level, it switches back to sibling level."
6578 (interactive)
6579 (let ((org-adapt-indentation nil))
6580 (when (org-point-at-end-of-empty-headline)
6581 (setq this-command 'org-cycle-level) ; Only needed for caching
6582 (let ((cur-level (org-current-level))
6583 (prev-level (org-get-previous-line-level)))
6584 (cond
6585 ;; If first headline in file, promote to top-level.
6586 ((= prev-level 0)
6587 (loop repeat (/ (- cur-level 1) (org-level-increment))
6588 do (org-do-promote)))
6589 ;; If same level as prev, demote one.
6590 ((= prev-level cur-level)
6591 (org-do-demote))
6592 ;; If parent is top-level, promote to top level if not already.
6593 ((= prev-level 1)
6594 (loop repeat (/ (- cur-level 1) (org-level-increment))
6595 do (org-do-promote)))
6596 ;; If top-level, return to prev-level.
6597 ((= cur-level 1)
6598 (loop repeat (/ (- prev-level 1) (org-level-increment))
6599 do (org-do-demote)))
6600 ;; If less than prev-level, promote one.
6601 ((< cur-level prev-level)
6602 (org-do-promote))
6603 ;; If deeper than prev-level, promote until higher than
6604 ;; prev-level.
6605 ((> cur-level prev-level)
6606 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6607 do (org-do-promote))))
6608 t))))
6610 (defun org-map-tree (fun)
6611 "Call FUN for every heading underneath the current one."
6612 (org-back-to-heading)
6613 (let ((level (funcall outline-level)))
6614 (save-excursion
6615 (funcall fun)
6616 (while (and (progn
6617 (outline-next-heading)
6618 (> (funcall outline-level) level))
6619 (not (eobp)))
6620 (funcall fun)))))
6622 (defun org-map-region (fun beg end)
6623 "Call FUN for every heading between BEG and END."
6624 (let ((org-ignore-region t))
6625 (save-excursion
6626 (setq end (copy-marker end))
6627 (goto-char beg)
6628 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6629 (< (point) end))
6630 (funcall fun))
6631 (while (and (progn
6632 (outline-next-heading)
6633 (< (point) end))
6634 (not (eobp)))
6635 (funcall fun)))))
6637 (defun org-fixup-indentation (diff)
6638 "Change the indentation in the current entry by DIFF
6639 However, if any line in the current entry has no indentation, or if it
6640 would end up with no indentation after the change, nothing at all is done."
6641 (save-excursion
6642 (let ((end (save-excursion (outline-next-heading)
6643 (point-marker)))
6644 (prohibit (if (> diff 0)
6645 "^\\S-"
6646 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6647 col)
6648 (unless (save-excursion (end-of-line 1)
6649 (re-search-forward prohibit end t))
6650 (while (and (< (point) end)
6651 (re-search-forward "^[ \t]+" end t))
6652 (goto-char (match-end 0))
6653 (setq col (current-column))
6654 (if (< diff 0) (replace-match ""))
6655 (org-indent-to-column (+ diff col))))
6656 (move-marker end nil))))
6658 (defun org-convert-to-odd-levels ()
6659 "Convert an org-mode file with all levels allowed to one with odd levels.
6660 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6661 level 5 etc."
6662 (interactive)
6663 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6664 (let ((outline-regexp org-outline-regexp)
6665 (outline-level 'org-outline-level)
6666 (org-odd-levels-only nil) n)
6667 (save-excursion
6668 (goto-char (point-min))
6669 (while (re-search-forward "^\\*\\*+ " nil t)
6670 (setq n (- (length (match-string 0)) 2))
6671 (while (>= (setq n (1- n)) 0)
6672 (org-demote))
6673 (end-of-line 1))))))
6675 (defun org-convert-to-oddeven-levels ()
6676 "Convert an org-mode file with only odd levels to one with odd and even levels.
6677 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6678 section with an even level, conversion would destroy the structure of the file. An error
6679 is signaled in this case."
6680 (interactive)
6681 (goto-char (point-min))
6682 ;; First check if there are no even levels
6683 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6684 (org-show-context t)
6685 (error "Not all levels are odd in this file. Conversion not possible"))
6686 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6687 (let ((outline-regexp org-outline-regexp)
6688 (outline-level 'org-outline-level)
6689 (org-odd-levels-only nil) n)
6690 (save-excursion
6691 (goto-char (point-min))
6692 (while (re-search-forward "^\\*\\*+ " nil t)
6693 (setq n (/ (1- (length (match-string 0))) 2))
6694 (while (>= (setq n (1- n)) 0)
6695 (org-promote))
6696 (end-of-line 1))))))
6698 (defun org-tr-level (n)
6699 "Make N odd if required."
6700 (if org-odd-levels-only (1+ (/ n 2)) n))
6702 ;;; Vertical tree motion, cutting and pasting of subtrees
6704 (defun org-move-subtree-up (&optional arg)
6705 "Move the current subtree up past ARG headlines of the same level."
6706 (interactive "p")
6707 (org-move-subtree-down (- (prefix-numeric-value arg))))
6709 (defun org-move-subtree-down (&optional arg)
6710 "Move the current subtree down past ARG headlines of the same level."
6711 (interactive "p")
6712 (setq arg (prefix-numeric-value arg))
6713 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6714 'org-get-last-sibling))
6715 (ins-point (make-marker))
6716 (cnt (abs arg))
6717 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6718 ;; Select the tree
6719 (org-back-to-heading)
6720 (setq beg0 (point))
6721 (save-excursion
6722 (setq ne-beg (org-back-over-empty-lines))
6723 (setq beg (point)))
6724 (save-match-data
6725 (save-excursion (outline-end-of-heading)
6726 (setq folded (org-invisible-p)))
6727 (outline-end-of-subtree))
6728 (outline-next-heading)
6729 (setq ne-end (org-back-over-empty-lines))
6730 (setq end (point))
6731 (goto-char beg0)
6732 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6733 ;; include less whitespace
6734 (save-excursion
6735 (goto-char beg)
6736 (forward-line (- ne-beg ne-end))
6737 (setq beg (point))))
6738 ;; Find insertion point, with error handling
6739 (while (> cnt 0)
6740 (or (and (funcall movfunc) (looking-at outline-regexp))
6741 (progn (goto-char beg0)
6742 (error "Cannot move past superior level or buffer limit")))
6743 (setq cnt (1- cnt)))
6744 (if (> arg 0)
6745 ;; Moving forward - still need to move over subtree
6746 (progn (org-end-of-subtree t t)
6747 (save-excursion
6748 (org-back-over-empty-lines)
6749 (or (bolp) (newline)))))
6750 (setq ne-ins (org-back-over-empty-lines))
6751 (move-marker ins-point (point))
6752 (setq txt (buffer-substring beg end))
6753 (org-save-markers-in-region beg end)
6754 (delete-region beg end)
6755 (org-remove-empty-overlays-at beg)
6756 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6757 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6758 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6759 (let ((bbb (point)))
6760 (insert-before-markers txt)
6761 (org-reinstall-markers-in-region bbb)
6762 (move-marker ins-point bbb))
6763 (or (bolp) (insert "\n"))
6764 (setq ins-end (point))
6765 (goto-char ins-point)
6766 (org-skip-whitespace)
6767 (when (and (< arg 0)
6768 (org-first-sibling-p)
6769 (> ne-ins ne-beg))
6770 ;; Move whitespace back to beginning
6771 (save-excursion
6772 (goto-char ins-end)
6773 (let ((kill-whole-line t))
6774 (kill-line (- ne-ins ne-beg)) (point)))
6775 (insert (make-string (- ne-ins ne-beg) ?\n)))
6776 (move-marker ins-point nil)
6777 (if folded
6778 (hide-subtree)
6779 (org-show-entry)
6780 (show-children)
6781 (org-cycle-hide-drawers 'children))
6782 (org-clean-visibility-after-subtree-move)))
6784 (defvar org-subtree-clip ""
6785 "Clipboard for cut and paste of subtrees.
6786 This is actually only a copy of the kill, because we use the normal kill
6787 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6789 (defvar org-subtree-clip-folded nil
6790 "Was the last copied subtree folded?
6791 This is used to fold the tree back after pasting.")
6793 (defun org-cut-subtree (&optional n)
6794 "Cut the current subtree into the clipboard.
6795 With prefix arg N, cut this many sequential subtrees.
6796 This is a short-hand for marking the subtree and then cutting it."
6797 (interactive "p")
6798 (org-copy-subtree n 'cut))
6800 (defun org-copy-subtree (&optional n cut force-store-markers)
6801 "Cut the current subtree into the clipboard.
6802 With prefix arg N, cut this many sequential subtrees.
6803 This is a short-hand for marking the subtree and then copying it.
6804 If CUT is non-nil, actually cut the subtree.
6805 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6806 of some markers in the region, even if CUT is non-nil. This is
6807 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6808 (interactive "p")
6809 (let (beg end folded (beg0 (point)))
6810 (if (interactive-p)
6811 (org-back-to-heading nil) ; take what looks like a subtree
6812 (org-back-to-heading t)) ; take what is really there
6813 (org-back-over-empty-lines)
6814 (setq beg (point))
6815 (skip-chars-forward " \t\r\n")
6816 (save-match-data
6817 (save-excursion (outline-end-of-heading)
6818 (setq folded (org-invisible-p)))
6819 (condition-case nil
6820 (org-forward-same-level (1- n) t)
6821 (error nil))
6822 (org-end-of-subtree t t))
6823 (org-back-over-empty-lines)
6824 (setq end (point))
6825 (goto-char beg0)
6826 (when (> end beg)
6827 (setq org-subtree-clip-folded folded)
6828 (when (or cut force-store-markers)
6829 (org-save-markers-in-region beg end))
6830 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6831 (setq org-subtree-clip (current-kill 0))
6832 (message "%s: Subtree(s) with %d characters"
6833 (if cut "Cut" "Copied")
6834 (length org-subtree-clip)))))
6836 (defun org-paste-subtree (&optional level tree for-yank)
6837 "Paste the clipboard as a subtree, with modification of headline level.
6838 The entire subtree is promoted or demoted in order to match a new headline
6839 level.
6841 If the cursor is at the beginning of a headline, the same level as
6842 that headline is used to paste the tree
6844 If not, the new level is derived from the *visible* headings
6845 before and after the insertion point, and taken to be the inferior headline
6846 level of the two. So if the previous visible heading is level 3 and the
6847 next is level 4 (or vice versa), level 4 will be used for insertion.
6848 This makes sure that the subtree remains an independent subtree and does
6849 not swallow low level entries.
6851 You can also force a different level, either by using a numeric prefix
6852 argument, or by inserting the heading marker by hand. For example, if the
6853 cursor is after \"*****\", then the tree will be shifted to level 5.
6855 If optional TREE is given, use this text instead of the kill ring.
6857 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6858 move back over whitespace before inserting, and move point to the end of
6859 the inserted text when done."
6860 (interactive "P")
6861 (setq tree (or tree (and kill-ring (current-kill 0))))
6862 (unless (org-kill-is-subtree-p tree)
6863 (error "%s"
6864 (substitute-command-keys
6865 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6866 (let* ((visp (not (org-invisible-p)))
6867 (txt tree)
6868 (^re (concat "^\\(" outline-regexp "\\)"))
6869 (re (concat "\\(" outline-regexp "\\)"))
6870 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6872 (old-level (if (string-match ^re txt)
6873 (- (match-end 0) (match-beginning 0) 1)
6874 -1))
6875 (force-level (cond (level (prefix-numeric-value level))
6876 ((and (looking-at "[ \t]*$")
6877 (string-match
6878 ^re_ (buffer-substring
6879 (point-at-bol) (point))))
6880 (- (match-end 1) (match-beginning 1)))
6881 ((and (bolp)
6882 (looking-at org-outline-regexp))
6883 (- (match-end 0) (point) 1))
6884 (t nil)))
6885 (previous-level (save-excursion
6886 (condition-case nil
6887 (progn
6888 (outline-previous-visible-heading 1)
6889 (if (looking-at re)
6890 (- (match-end 0) (match-beginning 0) 1)
6892 (error 1))))
6893 (next-level (save-excursion
6894 (condition-case nil
6895 (progn
6896 (or (looking-at outline-regexp)
6897 (outline-next-visible-heading 1))
6898 (if (looking-at re)
6899 (- (match-end 0) (match-beginning 0) 1)
6901 (error 1))))
6902 (new-level (or force-level (max previous-level next-level)))
6903 (shift (if (or (= old-level -1)
6904 (= new-level -1)
6905 (= old-level new-level))
6907 (- new-level old-level)))
6908 (delta (if (> shift 0) -1 1))
6909 (func (if (> shift 0) 'org-demote 'org-promote))
6910 (org-odd-levels-only nil)
6911 beg end newend)
6912 ;; Remove the forced level indicator
6913 (if force-level
6914 (delete-region (point-at-bol) (point)))
6915 ;; Paste
6916 (beginning-of-line 1)
6917 (unless for-yank (org-back-over-empty-lines))
6918 (setq beg (point))
6919 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6920 (insert-before-markers txt)
6921 (unless (string-match "\n\\'" txt) (insert "\n"))
6922 (setq newend (point))
6923 (org-reinstall-markers-in-region beg)
6924 (setq end (point))
6925 (goto-char beg)
6926 (skip-chars-forward " \t\n\r")
6927 (setq beg (point))
6928 (if (and (org-invisible-p) visp)
6929 (save-excursion (outline-show-heading)))
6930 ;; Shift if necessary
6931 (unless (= shift 0)
6932 (save-restriction
6933 (narrow-to-region beg end)
6934 (while (not (= shift 0))
6935 (org-map-region func (point-min) (point-max))
6936 (setq shift (+ delta shift)))
6937 (goto-char (point-min))
6938 (setq newend (point-max))))
6939 (when (or (interactive-p) for-yank)
6940 (message "Clipboard pasted as level %d subtree" new-level))
6941 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6942 kill-ring
6943 (eq org-subtree-clip (current-kill 0))
6944 org-subtree-clip-folded)
6945 ;; The tree was folded before it was killed/copied
6946 (hide-subtree))
6947 (and for-yank (goto-char newend))))
6949 (defun org-kill-is-subtree-p (&optional txt)
6950 "Check if the current kill is an outline subtree, or a set of trees.
6951 Returns nil if kill does not start with a headline, or if the first
6952 headline level is not the largest headline level in the tree.
6953 So this will actually accept several entries of equal levels as well,
6954 which is OK for `org-paste-subtree'.
6955 If optional TXT is given, check this string instead of the current kill."
6956 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6957 (start-level (and kill
6958 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6959 org-outline-regexp "\\)")
6960 kill)
6961 (- (match-end 2) (match-beginning 2) 1)))
6962 (re (concat "^" org-outline-regexp))
6963 (start (1+ (or (match-beginning 2) -1))))
6964 (if (not start-level)
6965 (progn
6966 nil) ;; does not even start with a heading
6967 (catch 'exit
6968 (while (setq start (string-match re kill (1+ start)))
6969 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6970 (throw 'exit nil)))
6971 t))))
6973 (defvar org-markers-to-move nil
6974 "Markers that should be moved with a cut-and-paste operation.
6975 Those markers are stored together with their positions relative to
6976 the start of the region.")
6978 (defun org-save-markers-in-region (beg end)
6979 "Check markers in region.
6980 If these markers are between BEG and END, record their position relative
6981 to BEG, so that after moving the block of text, we can put the markers back
6982 into place.
6983 This function gets called just before an entry or tree gets cut from the
6984 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6985 called immediately, to move the markers with the entries."
6986 (setq org-markers-to-move nil)
6987 (when (featurep 'org-clock)
6988 (org-clock-save-markers-for-cut-and-paste beg end))
6989 (when (featurep 'org-agenda)
6990 (org-agenda-save-markers-for-cut-and-paste beg end)))
6992 (defun org-check-and-save-marker (marker beg end)
6993 "Check if MARKER is between BEG and END.
6994 If yes, remember the marker and the distance to BEG."
6995 (when (and (marker-buffer marker)
6996 (equal (marker-buffer marker) (current-buffer)))
6997 (if (and (>= marker beg) (< marker end))
6998 (push (cons marker (- marker beg)) org-markers-to-move))))
7000 (defun org-reinstall-markers-in-region (beg)
7001 "Move all remembered markers to their position relative to BEG."
7002 (mapc (lambda (x)
7003 (move-marker (car x) (+ beg (cdr x))))
7004 org-markers-to-move)
7005 (setq org-markers-to-move nil))
7007 (defun org-narrow-to-subtree ()
7008 "Narrow buffer to the current subtree."
7009 (interactive)
7010 (save-excursion
7011 (save-match-data
7012 (narrow-to-region
7013 (progn (org-back-to-heading t) (point))
7014 (progn (org-end-of-subtree t t)
7015 (if (org-on-heading-p) (backward-char 1))
7016 (point))))))
7018 (defun org-clone-subtree-with-time-shift (n &optional shift)
7019 "Clone the task (subtree) at point N times.
7020 The clones will be inserted as siblings.
7022 In interactive use, the user will be prompted for the number of clones
7023 to be produced, and for a time SHIFT, which may be a repeater as used
7024 in time stamps, for example `+3d'.
7026 When a valid repeater is given and the entry contains any time stamps,
7027 the clones will become a sequence in time, with time stamps in the
7028 subtree shifted for each clone produced. If SHIFT is nil or the
7029 empty string, time stamps will be left alone.
7031 If the original subtree did contain time stamps with a repeater,
7032 the following will happen:
7033 - the repeater will be removed in each clone
7034 - an additional clone will be produced, with the current, unshifted
7035 date(s) in the entry.
7036 - the original entry will be placed *after* all the clones, with
7037 repeater intact.
7038 - the start days in the repeater in the original entry will be shifted
7039 to past the last clone.
7040 I this way you can spell out a number of instances of a repeating task,
7041 and still retain the repeater to cover future instances of the task."
7042 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7043 (let (beg end template task
7044 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7045 (if (not (and (integerp n) (> n 0)))
7046 (error "Invalid number of replications %s" n))
7047 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7048 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7049 shift)))
7050 (error "Invalid shift specification %s" shift))
7051 (when doshift
7052 (setq shift-n (string-to-number (match-string 1 shift))
7053 shift-what (cdr (assoc (match-string 2 shift)
7054 '(("d" . day) ("w" . week)
7055 ("m" . month) ("y" . year))))))
7056 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7057 (setq nmin 1 nmax n)
7058 (org-back-to-heading t)
7059 (setq beg (point))
7060 (org-end-of-subtree t t)
7061 (or (bolp) (insert "\n"))
7062 (setq end (point))
7063 (setq template (buffer-substring beg end))
7064 (when (and doshift
7065 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7066 (delete-region beg end)
7067 (setq end beg)
7068 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7069 (goto-char end)
7070 (loop for n from nmin to nmax do
7071 (if (not doshift)
7072 (setq task template)
7073 (with-temp-buffer
7074 (insert template)
7075 (org-mode)
7076 (goto-char (point-min))
7077 (while (re-search-forward org-ts-regexp-both nil t)
7078 (org-timestamp-change (* n shift-n) shift-what))
7079 (unless (= n n-no-remove)
7080 (goto-char (point-min))
7081 (while (re-search-forward org-ts-regexp nil t)
7082 (save-excursion
7083 (goto-char (match-beginning 0))
7084 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7085 (delete-region (match-beginning 1) (match-end 1))))))
7086 (setq task (buffer-string))))
7087 (insert task))
7088 (goto-char beg)))
7090 ;;; Outline Sorting
7092 (defun org-sort (with-case)
7093 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7094 Optional argument WITH-CASE means sort case-sensitively.
7095 With a double prefix argument, also remove duplicate entries."
7096 (interactive "P")
7097 (if (org-at-table-p)
7098 (org-call-with-arg 'org-table-sort-lines with-case)
7099 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7101 (defun org-sort-remove-invisible (s)
7102 (remove-text-properties 0 (length s) org-rm-props s)
7103 (while (string-match org-bracket-link-regexp s)
7104 (setq s (replace-match (if (match-end 2)
7105 (match-string 3 s)
7106 (match-string 1 s)) t t s)))
7109 (defvar org-priority-regexp) ; defined later in the file
7111 (defvar org-after-sorting-entries-or-items-hook nil
7112 "Hook that is run after a bunch of entries or items have been sorted.
7113 When children are sorted, the cursor is in the parent line when this
7114 hook gets called. When a region or a plain list is sorted, the cursor
7115 will be in the first entry of the sorted region/list.")
7117 (defun org-sort-entries-or-items
7118 (&optional with-case sorting-type getkey-func compare-func property)
7119 "Sort entries on a certain level of an outline tree, or plain list items.
7120 If there is an active region, the entries in the region are sorted.
7121 Else, if the cursor is before the first entry, sort the top-level items.
7122 Else, the children of the entry at point are sorted.
7123 If the cursor is at the first item in a plain list, the list items will be
7124 sorted.
7126 Sorting can be alphabetically, numerically, by date/time as given by
7127 a time stamp, by a property or by priority.
7129 The command prompts for the sorting type unless it has been given to the
7130 function through the SORTING-TYPE argument, which needs to a character,
7131 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7132 precise meaning of each character:
7134 n Numerically, by converting the beginning of the entry/item to a number.
7135 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7136 t By date/time, either the first active time stamp in the entry, or, if
7137 none exist, by the first inactive one.
7138 In items, only the first line will be checked.
7139 s By the scheduled date/time.
7140 d By deadline date/time.
7141 c By creation time, which is assumed to be the first inactive time stamp
7142 at the beginning of a line.
7143 p By priority according to the cookie.
7144 r By the value of a property.
7146 Capital letters will reverse the sort order.
7148 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7149 called with point at the beginning of the record. It must return either
7150 a string or a number that should serve as the sorting key for that record.
7152 Comparing entries ignores case by default. However, with an optional argument
7153 WITH-CASE, the sorting considers case as well."
7154 (interactive "P")
7155 (let ((case-func (if with-case 'identity 'downcase))
7156 start beg end stars re re2
7157 txt what tmp plain-list-p)
7158 ;; Find beginning and end of region to sort
7159 (cond
7160 ((org-region-active-p)
7161 ;; we will sort the region
7162 (setq end (region-end)
7163 what "region")
7164 (goto-char (region-beginning))
7165 (if (not (org-on-heading-p)) (outline-next-heading))
7166 (setq start (point)))
7167 ((org-at-item-p)
7168 ;; we will sort this plain list
7169 (org-beginning-of-item-list) (setq start (point))
7170 (org-end-of-item-list)
7171 (or (bolp) (insert "\n"))
7172 (setq end (point))
7173 (goto-char start)
7174 (setq plain-list-p t
7175 what "plain list"))
7176 ((or (org-on-heading-p)
7177 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7178 ;; we will sort the children of the current headline
7179 (org-back-to-heading)
7180 (setq start (point)
7181 end (progn (org-end-of-subtree t t)
7182 (or (bolp) (insert "\n"))
7183 (org-back-over-empty-lines)
7184 (point))
7185 what "children")
7186 (goto-char start)
7187 (show-subtree)
7188 (outline-next-heading))
7190 ;; we will sort the top-level entries in this file
7191 (goto-char (point-min))
7192 (or (org-on-heading-p) (outline-next-heading))
7193 (setq start (point))
7194 (goto-char (point-max))
7195 (beginning-of-line 1)
7196 (when (looking-at ".*?\\S-")
7197 ;; File ends in a non-white line
7198 (end-of-line 1)
7199 (insert "\n"))
7200 (setq end (point-max))
7201 (setq what "top-level")
7202 (goto-char start)
7203 (show-all)))
7205 (setq beg (point))
7206 (if (>= beg end) (error "Nothing to sort"))
7208 (unless plain-list-p
7209 (looking-at "\\(\\*+\\)")
7210 (setq stars (match-string 1)
7211 re (concat "^" (regexp-quote stars) " +")
7212 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7213 txt (buffer-substring beg end))
7214 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7215 (if (and (not (equal stars "*")) (string-match re2 txt))
7216 (error "Region to sort contains a level above the first entry")))
7218 (unless sorting-type
7219 (message
7220 (if plain-list-p
7221 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7222 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7223 [t]ime [s]cheduled [d]eadline [c]reated
7224 A/N/T/S/D/C/P/O/F means reversed:")
7225 what)
7226 (setq sorting-type (read-char-exclusive))
7228 (and (= (downcase sorting-type) ?f)
7229 (setq getkey-func
7230 (org-icompleting-read "Sort using function: "
7231 obarray 'fboundp t nil nil))
7232 (setq getkey-func (intern getkey-func)))
7234 (and (= (downcase sorting-type) ?r)
7235 (setq property
7236 (org-icompleting-read "Property: "
7237 (mapcar 'list (org-buffer-property-keys t))
7238 nil t))))
7240 (message "Sorting entries...")
7242 (save-restriction
7243 (narrow-to-region start end)
7245 (let ((dcst (downcase sorting-type))
7246 (case-fold-search nil)
7247 (now (current-time)))
7248 (sort-subr
7249 (/= dcst sorting-type)
7250 ;; This function moves to the beginning character of the "record" to
7251 ;; be sorted.
7252 (if plain-list-p
7253 (lambda nil
7254 (if (org-at-item-p) t (goto-char (point-max))))
7255 (lambda nil
7256 (if (re-search-forward re nil t)
7257 (goto-char (match-beginning 0))
7258 (goto-char (point-max)))))
7259 ;; This function moves to the last character of the "record" being
7260 ;; sorted.
7261 (if plain-list-p
7262 'org-end-of-item
7263 (lambda nil
7264 (save-match-data
7265 (condition-case nil
7266 (outline-forward-same-level 1)
7267 (error
7268 (goto-char (point-max)))))))
7270 ;; This function returns the value that gets sorted against.
7271 (if plain-list-p
7272 (lambda nil
7273 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7274 (cond
7275 ((= dcst ?n)
7276 (string-to-number (buffer-substring (match-end 0)
7277 (point-at-eol))))
7278 ((= dcst ?a)
7279 (buffer-substring (match-end 0) (point-at-eol)))
7280 ((= dcst ?t)
7281 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7282 (re-search-forward org-ts-regexp-both
7283 (point-at-eol) t))
7284 (org-time-string-to-seconds (match-string 0))
7285 (org-float-time now)))
7286 ((= dcst ?f)
7287 (if getkey-func
7288 (progn
7289 (setq tmp (funcall getkey-func))
7290 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7291 tmp)
7292 (error "Invalid key function `%s'" getkey-func)))
7293 (t (error "Invalid sorting type `%c'" sorting-type)))))
7294 (lambda nil
7295 (cond
7296 ((= dcst ?n)
7297 (if (looking-at org-complex-heading-regexp)
7298 (string-to-number (match-string 4))
7299 nil))
7300 ((= dcst ?a)
7301 (if (looking-at org-complex-heading-regexp)
7302 (funcall case-func (match-string 4))
7303 nil))
7304 ((= dcst ?t)
7305 (let ((end (save-excursion (outline-next-heading) (point))))
7306 (if (or (re-search-forward org-ts-regexp end t)
7307 (re-search-forward org-ts-regexp-both end t))
7308 (org-time-string-to-seconds (match-string 0))
7309 (org-float-time now))))
7310 ((= dcst ?c)
7311 (let ((end (save-excursion (outline-next-heading) (point))))
7312 (if (re-search-forward
7313 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7314 end t)
7315 (org-time-string-to-seconds (match-string 0))
7316 (org-float-time now))))
7317 ((= dcst ?s)
7318 (let ((end (save-excursion (outline-next-heading) (point))))
7319 (if (re-search-forward org-scheduled-time-regexp end t)
7320 (org-time-string-to-seconds (match-string 1))
7321 (org-float-time now))))
7322 ((= dcst ?d)
7323 (let ((end (save-excursion (outline-next-heading) (point))))
7324 (if (re-search-forward org-deadline-time-regexp end t)
7325 (org-time-string-to-seconds (match-string 1))
7326 (org-float-time now))))
7327 ((= dcst ?p)
7328 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7329 (string-to-char (match-string 2))
7330 org-default-priority))
7331 ((= dcst ?r)
7332 (or (org-entry-get nil property) ""))
7333 ((= dcst ?o)
7334 (if (looking-at org-complex-heading-regexp)
7335 (- 9999 (length (member (match-string 2)
7336 org-todo-keywords-1)))))
7337 ((= dcst ?f)
7338 (if getkey-func
7339 (progn
7340 (setq tmp (funcall getkey-func))
7341 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7342 tmp)
7343 (error "Invalid key function `%s'" getkey-func)))
7344 (t (error "Invalid sorting type `%c'" sorting-type)))))
7346 (cond
7347 ((= dcst ?a) 'string<)
7348 ((= dcst ?f) compare-func)
7349 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7350 (t nil)))))
7351 (run-hooks 'org-after-sorting-entries-or-items-hook)
7352 (message "Sorting entries...done")))
7354 (defun org-do-sort (table what &optional with-case sorting-type)
7355 "Sort TABLE of WHAT according to SORTING-TYPE.
7356 The user will be prompted for the SORTING-TYPE if the call to this
7357 function does not specify it. WHAT is only for the prompt, to indicate
7358 what is being sorted. The sorting key will be extracted from
7359 the car of the elements of the table.
7360 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7361 (unless sorting-type
7362 (message
7363 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7364 what)
7365 (setq sorting-type (read-char-exclusive)))
7366 (let ((dcst (downcase sorting-type))
7367 extractfun comparefun)
7368 ;; Define the appropriate functions
7369 (cond
7370 ((= dcst ?n)
7371 (setq extractfun 'string-to-number
7372 comparefun (if (= dcst sorting-type) '< '>)))
7373 ((= dcst ?a)
7374 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7375 (lambda(x) (downcase (org-sort-remove-invisible x))))
7376 comparefun (if (= dcst sorting-type)
7377 'string<
7378 (lambda (a b) (and (not (string< a b))
7379 (not (string= a b)))))))
7380 ((= dcst ?t)
7381 (setq extractfun
7382 (lambda (x)
7383 (if (or (string-match org-ts-regexp x)
7384 (string-match org-ts-regexp-both x))
7385 (org-float-time
7386 (org-time-string-to-time (match-string 0 x)))
7388 comparefun (if (= dcst sorting-type) '< '>)))
7389 (t (error "Invalid sorting type `%c'" sorting-type)))
7391 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7392 table)
7393 (lambda (a b) (funcall comparefun (car a) (car b))))))
7396 ;;; The orgstruct minor mode
7398 ;; Define a minor mode which can be used in other modes in order to
7399 ;; integrate the org-mode structure editing commands.
7401 ;; This is really a hack, because the org-mode structure commands use
7402 ;; keys which normally belong to the major mode. Here is how it
7403 ;; works: The minor mode defines all the keys necessary to operate the
7404 ;; structure commands, but wraps the commands into a function which
7405 ;; tests if the cursor is currently at a headline or a plain list
7406 ;; item. If that is the case, the structure command is used,
7407 ;; temporarily setting many Org-mode variables like regular
7408 ;; expressions for filling etc. However, when any of those keys is
7409 ;; used at a different location, function uses `key-binding' to look
7410 ;; up if the key has an associated command in another currently active
7411 ;; keymap (minor modes, major mode, global), and executes that
7412 ;; command. There might be problems if any of the keys is otherwise
7413 ;; used as a prefix key.
7415 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7416 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7417 ;; addresses this by checking explicitly for both bindings.
7419 (defvar orgstruct-mode-map (make-sparse-keymap)
7420 "Keymap for the minor `orgstruct-mode'.")
7422 (defvar org-local-vars nil
7423 "List of local variables, for use by `orgstruct-mode'")
7425 ;;;###autoload
7426 (define-minor-mode orgstruct-mode
7427 "Toggle the minor more `orgstruct-mode'.
7428 This mode is for using Org-mode structure commands in other modes.
7429 The following key behave as if Org-mode was active, if the cursor
7430 is on a headline, or on a plain list item (both in the definition
7431 of Org-mode).
7433 M-up Move entry/item up
7434 M-down Move entry/item down
7435 M-left Promote
7436 M-right Demote
7437 M-S-up Move entry/item up
7438 M-S-down Move entry/item down
7439 M-S-left Promote subtree
7440 M-S-right Demote subtree
7441 M-q Fill paragraph and items like in Org-mode
7442 C-c ^ Sort entries
7443 C-c - Cycle list bullet
7444 TAB Cycle item visibility
7445 M-RET Insert new heading/item
7446 S-M-RET Insert new TODO heading / Checkbox item
7447 C-c C-c Set tags / toggle checkbox"
7448 nil " OrgStruct" nil
7449 (org-load-modules-maybe)
7450 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7452 ;;;###autoload
7453 (defun turn-on-orgstruct ()
7454 "Unconditionally turn on `orgstruct-mode'."
7455 (orgstruct-mode 1))
7457 (defun orgstruct++-mode (&optional arg)
7458 "Toggle `orgstruct-mode', the enhanced version of it.
7459 In addition to setting orgstruct-mode, this also exports all indentation
7460 and autofilling variables from org-mode into the buffer. It will also
7461 recognize item context in multiline items.
7462 Note that turning off orgstruct-mode will *not* remove the
7463 indentation/paragraph settings. This can only be done by refreshing the
7464 major mode, for example with \\[normal-mode]."
7465 (interactive "P")
7466 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7467 (if (< arg 1)
7468 (orgstruct-mode -1)
7469 (orgstruct-mode 1)
7470 (let (var val)
7471 (mapc
7472 (lambda (x)
7473 (when (string-match
7474 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7475 (symbol-name (car x)))
7476 (setq var (car x) val (nth 1 x))
7477 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7478 org-local-vars)
7479 (org-set-local 'orgstruct-is-++ t))))
7481 (defvar orgstruct-is-++ nil
7482 "Is orgstruct-mode in ++ version in the current-buffer?")
7483 (make-variable-buffer-local 'orgstruct-is-++)
7485 ;;;###autoload
7486 (defun turn-on-orgstruct++ ()
7487 "Unconditionally turn on `orgstruct++-mode'."
7488 (orgstruct++-mode 1))
7490 (defun orgstruct-error ()
7491 "Error when there is no default binding for a structure key."
7492 (interactive)
7493 (error "This key has no function outside structure elements"))
7495 (defun orgstruct-setup ()
7496 "Setup orgstruct keymaps."
7497 (let ((nfunc 0)
7498 (bindings
7499 (list
7500 '([(meta up)] org-metaup)
7501 '([(meta down)] org-metadown)
7502 '([(meta left)] org-metaleft)
7503 '([(meta right)] org-metaright)
7504 '([(meta shift up)] org-shiftmetaup)
7505 '([(meta shift down)] org-shiftmetadown)
7506 '([(meta shift left)] org-shiftmetaleft)
7507 '([(meta shift right)] org-shiftmetaright)
7508 '([?\e (up)] org-metaup)
7509 '([?\e (down)] org-metadown)
7510 '([?\e (left)] org-metaleft)
7511 '([?\e (right)] org-metaright)
7512 '([?\e (shift up)] org-shiftmetaup)
7513 '([?\e (shift down)] org-shiftmetadown)
7514 '([?\e (shift left)] org-shiftmetaleft)
7515 '([?\e (shift right)] org-shiftmetaright)
7516 '([(shift up)] org-shiftup)
7517 '([(shift down)] org-shiftdown)
7518 '([(shift left)] org-shiftleft)
7519 '([(shift right)] org-shiftright)
7520 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7521 '("\M-q" fill-paragraph)
7522 '("\C-c^" org-sort)
7523 '("\C-c-" org-cycle-list-bullet)))
7524 elt key fun cmd)
7525 (while (setq elt (pop bindings))
7526 (setq nfunc (1+ nfunc))
7527 (setq key (org-key (car elt))
7528 fun (nth 1 elt)
7529 cmd (orgstruct-make-binding fun nfunc key))
7530 (org-defkey orgstruct-mode-map key cmd))
7532 ;; Special treatment needed for TAB and RET
7533 (org-defkey orgstruct-mode-map [(tab)]
7534 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7535 (org-defkey orgstruct-mode-map "\C-i"
7536 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7538 (org-defkey orgstruct-mode-map "\M-\C-m"
7539 (orgstruct-make-binding 'org-insert-heading 105
7540 "\M-\C-m" [(meta return)]))
7541 (org-defkey orgstruct-mode-map [(meta return)]
7542 (orgstruct-make-binding 'org-insert-heading 106
7543 [(meta return)] "\M-\C-m"))
7545 (org-defkey orgstruct-mode-map [(shift meta return)]
7546 (orgstruct-make-binding 'org-insert-todo-heading 107
7547 [(meta return)] "\M-\C-m"))
7549 (org-defkey orgstruct-mode-map "\e\C-m"
7550 (orgstruct-make-binding 'org-insert-heading 108
7551 "\e\C-m" [?\e (return)]))
7552 (org-defkey orgstruct-mode-map [?\e (return)]
7553 (orgstruct-make-binding 'org-insert-heading 109
7554 [?\e (return)] "\e\C-m"))
7555 (org-defkey orgstruct-mode-map [?\e (shift return)]
7556 (orgstruct-make-binding 'org-insert-todo-heading 110
7557 [?\e (return)] "\e\C-m"))
7559 (unless org-local-vars
7560 (setq org-local-vars (org-get-local-variables)))
7564 (defun orgstruct-make-binding (fun n &rest keys)
7565 "Create a function for binding in the structure minor mode.
7566 FUN is the command to call inside a table. N is used to create a unique
7567 command name. KEYS are keys that should be checked in for a command
7568 to execute outside of tables."
7569 (eval
7570 (list 'defun
7571 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7572 '(arg)
7573 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7574 "Outside of structure, run the binding of `"
7575 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7576 "'.")
7577 '(interactive "p")
7578 (list 'if
7579 `(org-context-p 'headline 'item
7580 (and orgstruct-is-++
7581 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7582 'item-body))
7583 (list 'org-run-like-in-org-mode (list 'quote fun))
7584 (list 'let '(orgstruct-mode)
7585 (list 'call-interactively
7586 (append '(or)
7587 (mapcar (lambda (k)
7588 (list 'key-binding k))
7589 keys)
7590 '('orgstruct-error))))))))
7592 (defun org-context-p (&rest contexts)
7593 "Check if local context is any of CONTEXTS.
7594 Possible values in the list of contexts are `table', `headline', and `item'."
7595 (let ((pos (point)))
7596 (goto-char (point-at-bol))
7597 (prog1 (or (and (memq 'table contexts)
7598 (looking-at "[ \t]*|"))
7599 (and (memq 'headline contexts)
7600 ;;????????? (looking-at "\\*+"))
7601 (looking-at outline-regexp))
7602 (and (memq 'item contexts)
7603 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7604 (and (memq 'item-body contexts)
7605 (org-in-item-p)))
7606 (goto-char pos))))
7608 (defun org-get-local-variables ()
7609 "Return a list of all local variables in an org-mode buffer."
7610 (let (varlist)
7611 (with-current-buffer (get-buffer-create "*Org tmp*")
7612 (erase-buffer)
7613 (org-mode)
7614 (setq varlist (buffer-local-variables)))
7615 (kill-buffer "*Org tmp*")
7616 (delq nil
7617 (mapcar
7618 (lambda (x)
7619 (setq x
7620 (if (symbolp x)
7621 (list x)
7622 (list (car x) (list 'quote (cdr x)))))
7623 (if (string-match
7624 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7625 (symbol-name (car x)))
7626 x nil))
7627 varlist))))
7629 ;;;###autoload
7630 (defun org-run-like-in-org-mode (cmd)
7631 "Run a command, pretending that the current buffer is in Org-mode.
7632 This will temporarily bind local variables that are typically bound in
7633 Org-mode to the values they have in Org-mode, and then interactively
7634 call CMD."
7635 (org-load-modules-maybe)
7636 (unless org-local-vars
7637 (setq org-local-vars (org-get-local-variables)))
7638 (eval (list 'let org-local-vars
7639 (list 'call-interactively (list 'quote cmd)))))
7641 ;;;; Archiving
7643 (defun org-get-category (&optional pos)
7644 "Get the category applying to position POS."
7645 (get-text-property (or pos (point)) 'org-category))
7647 (defun org-refresh-category-properties ()
7648 "Refresh category text properties in the buffer."
7649 (let ((def-cat (cond
7650 ((null org-category)
7651 (if buffer-file-name
7652 (file-name-sans-extension
7653 (file-name-nondirectory buffer-file-name))
7654 "???"))
7655 ((symbolp org-category) (symbol-name org-category))
7656 (t org-category)))
7657 beg end cat pos optionp)
7658 (org-unmodified
7659 (save-excursion
7660 (save-restriction
7661 (widen)
7662 (goto-char (point-min))
7663 (put-text-property (point) (point-max) 'org-category def-cat)
7664 (while (re-search-forward
7665 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7666 (setq pos (match-end 0)
7667 optionp (equal (char-after (match-beginning 0)) ?#)
7668 cat (org-trim (match-string 2)))
7669 (if optionp
7670 (setq beg (point-at-bol) end (point-max))
7671 (org-back-to-heading t)
7672 (setq beg (point) end (org-end-of-subtree t t)))
7673 (put-text-property beg end 'org-category cat)
7674 (goto-char pos)))))))
7677 ;;;; Link Stuff
7679 ;;; Link abbreviations
7681 (defun org-link-expand-abbrev (link)
7682 "Apply replacements as defined in `org-link-abbrev-alist."
7683 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7684 (let* ((key (match-string 1 link))
7685 (as (or (assoc key org-link-abbrev-alist-local)
7686 (assoc key org-link-abbrev-alist)))
7687 (tag (and (match-end 2) (match-string 3 link)))
7688 rpl)
7689 (if (not as)
7690 link
7691 (setq rpl (cdr as))
7692 (cond
7693 ((symbolp rpl) (funcall rpl tag))
7694 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7695 ((string-match "%h" rpl)
7696 (replace-match (url-hexify-string (or tag "")) t t rpl))
7697 (t (concat rpl tag)))))
7698 link))
7700 ;;; Storing and inserting links
7702 (defvar org-insert-link-history nil
7703 "Minibuffer history for links inserted with `org-insert-link'.")
7705 (defvar org-stored-links nil
7706 "Contains the links stored with `org-store-link'.")
7708 (defvar org-store-link-plist nil
7709 "Plist with info about the most recently link created with `org-store-link'.")
7711 (defvar org-link-protocols nil
7712 "Link protocols added to Org-mode using `org-add-link-type'.")
7714 (defvar org-store-link-functions nil
7715 "List of functions that are called to create and store a link.
7716 Each function will be called in turn until one returns a non-nil
7717 value. Each function should check if it is responsible for creating
7718 this link (for example by looking at the major mode).
7719 If not, it must exit and return nil.
7720 If yes, it should return a non-nil value after a calling
7721 `org-store-link-props' with a list of properties and values.
7722 Special properties are:
7724 :type The link prefix. like \"http\". This must be given.
7725 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7726 This is obligatory as well.
7727 :description Optional default description for the second pair
7728 of brackets in an Org-mode link. The user can still change
7729 this when inserting this link into an Org-mode buffer.
7731 In addition to these, any additional properties can be specified
7732 and then used in remember templates.")
7734 (defun org-add-link-type (type &optional follow export)
7735 "Add TYPE to the list of `org-link-types'.
7736 Re-compute all regular expressions depending on `org-link-types'
7738 FOLLOW and EXPORT are two functions.
7740 FOLLOW should take the link path as the single argument and do whatever
7741 is necessary to follow the link, for example find a file or display
7742 a mail message.
7744 EXPORT should format the link path for export to one of the export formats.
7745 It should be a function accepting three arguments:
7747 path the path of the link, the text after the prefix (like \"http:\")
7748 desc the description of the link, if any, nil if there was no description
7749 format the export format, a symbol like `html' or `latex'.
7751 The function may use the FORMAT information to return different values
7752 depending on the format. The return value will be put literally into
7753 the exported file.
7754 Org-mode has a built-in default for exporting links. If you are happy with
7755 this default, there is no need to define an export function for the link
7756 type. For a simple example of an export function, see `org-bbdb.el'."
7757 (add-to-list 'org-link-types type t)
7758 (org-make-link-regexps)
7759 (if (assoc type org-link-protocols)
7760 (setcdr (assoc type org-link-protocols) (list follow export))
7761 (push (list type follow export) org-link-protocols)))
7763 (defvar org-agenda-buffer-name)
7765 ;;;###autoload
7766 (defun org-store-link (arg)
7767 "\\<org-mode-map>Store an org-link to the current location.
7768 This link is added to `org-stored-links' and can later be inserted
7769 into an org-buffer with \\[org-insert-link].
7771 For some link types, a prefix arg is interpreted:
7772 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7773 For file links, arg negates `org-context-in-file-links'."
7774 (interactive "P")
7775 (org-load-modules-maybe)
7776 (setq org-store-link-plist nil) ; reset
7777 (let ((outline-regexp (org-get-limited-outline-regexp))
7778 link cpltxt desc description search txt custom-id)
7779 (cond
7781 ((run-hook-with-args-until-success 'org-store-link-functions)
7782 (setq link (plist-get org-store-link-plist :link)
7783 desc (or (plist-get org-store-link-plist :description) link)))
7785 ((equal (buffer-name) "*Org Edit Src Example*")
7786 (let (label gc)
7787 (while (or (not label)
7788 (save-excursion
7789 (save-restriction
7790 (widen)
7791 (goto-char (point-min))
7792 (re-search-forward
7793 (regexp-quote (format org-coderef-label-format label))
7794 nil t))))
7795 (when label (message "Label exists already") (sit-for 2))
7796 (setq label (read-string "Code line label: " label)))
7797 (end-of-line 1)
7798 (setq link (format org-coderef-label-format label))
7799 (setq gc (- 79 (length link)))
7800 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7801 (insert link)
7802 (setq link (concat "(" label ")") desc nil)))
7804 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7805 ;; We are in the agenda, link to referenced location
7806 (let ((m (or (get-text-property (point) 'org-hd-marker)
7807 (get-text-property (point) 'org-marker))))
7808 (when m
7809 (org-with-point-at m
7810 (call-interactively 'org-store-link)))))
7812 ((eq major-mode 'calendar-mode)
7813 (let ((cd (calendar-cursor-to-date)))
7814 (setq link
7815 (format-time-string
7816 (car org-time-stamp-formats)
7817 (apply 'encode-time
7818 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7819 nil nil nil))))
7820 (org-store-link-props :type "calendar" :date cd)))
7822 ((eq major-mode 'w3-mode)
7823 (setq cpltxt (if (and (buffer-name)
7824 (not (string-match "Untitled" (buffer-name))))
7825 (buffer-name)
7826 (url-view-url t))
7827 link (org-make-link (url-view-url t)))
7828 (org-store-link-props :type "w3" :url (url-view-url t)))
7830 ((eq major-mode 'w3m-mode)
7831 (setq cpltxt (or w3m-current-title w3m-current-url)
7832 link (org-make-link w3m-current-url))
7833 (org-store-link-props :type "w3m" :url (url-view-url t)))
7835 ((setq search (run-hook-with-args-until-success
7836 'org-create-file-search-functions))
7837 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7838 "::" search))
7839 (setq cpltxt (or description link)))
7841 ((eq major-mode 'image-mode)
7842 (setq cpltxt (concat "file:"
7843 (abbreviate-file-name buffer-file-name))
7844 link (org-make-link cpltxt))
7845 (org-store-link-props :type "image" :file buffer-file-name))
7847 ((eq major-mode 'dired-mode)
7848 ;; link to the file in the current line
7849 (let ((file (dired-get-filename nil t)))
7850 (setq file (if file
7851 (abbreviate-file-name
7852 (expand-file-name (dired-get-filename nil t)))
7853 ;; otherwise, no file so use current directory.
7854 default-directory))
7855 (setq cpltxt (concat "file:" file)
7856 link (org-make-link cpltxt))))
7858 ((and buffer-file-name (org-mode-p))
7859 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7860 (cond
7861 ((org-in-regexp "<<\\(.*?\\)>>")
7862 (setq cpltxt
7863 (concat "file:"
7864 (abbreviate-file-name buffer-file-name)
7865 "::" (match-string 1))
7866 link (org-make-link cpltxt)))
7867 ((and (featurep 'org-id)
7868 (or (eq org-link-to-org-use-id t)
7869 (and (eq org-link-to-org-use-id 'create-if-interactive)
7870 (interactive-p))
7871 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7872 (interactive-p)
7873 (not custom-id))
7874 (and org-link-to-org-use-id
7875 (condition-case nil
7876 (org-entry-get nil "ID")
7877 (error nil)))))
7878 ;; We can make a link using the ID.
7879 (setq link (condition-case nil
7880 (prog1 (org-id-store-link)
7881 (setq desc (plist-get org-store-link-plist
7882 :description)))
7883 (error
7884 ;; probably before first headline, link to file only
7885 (concat "file:"
7886 (abbreviate-file-name buffer-file-name))))))
7888 ;; Just link to current headline
7889 (setq cpltxt (concat "file:"
7890 (abbreviate-file-name buffer-file-name)))
7891 ;; Add a context search string
7892 (when (org-xor org-context-in-file-links arg)
7893 (setq txt (cond
7894 ((org-on-heading-p) nil)
7895 ((org-region-active-p)
7896 (buffer-substring (region-beginning) (region-end)))
7897 (t nil)))
7898 (when (or (null txt) (string-match "\\S-" txt))
7899 (setq cpltxt
7900 (concat cpltxt "::"
7901 (condition-case nil
7902 (org-make-org-heading-search-string txt)
7903 (error "")))
7904 desc (or (nth 4 (ignore-errors
7905 (org-heading-components))) "NONE"))))
7906 (if (string-match "::\\'" cpltxt)
7907 (setq cpltxt (substring cpltxt 0 -2)))
7908 (setq link (org-make-link cpltxt)))))
7910 ((buffer-file-name (buffer-base-buffer))
7911 ;; Just link to this file here.
7912 (setq cpltxt (concat "file:"
7913 (abbreviate-file-name
7914 (buffer-file-name (buffer-base-buffer)))))
7915 ;; Add a context string
7916 (when (org-xor org-context-in-file-links arg)
7917 (setq txt (if (org-region-active-p)
7918 (buffer-substring (region-beginning) (region-end))
7919 (buffer-substring (point-at-bol) (point-at-eol))))
7920 ;; Only use search option if there is some text.
7921 (when (string-match "\\S-" txt)
7922 (setq cpltxt
7923 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7924 desc "NONE")))
7925 (setq link (org-make-link cpltxt)))
7927 ((interactive-p)
7928 (error "Cannot link to a buffer which is not visiting a file"))
7930 (t (setq link nil)))
7932 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7933 (setq link (or link cpltxt)
7934 desc (or desc cpltxt))
7935 (if (equal desc "NONE") (setq desc nil))
7937 (if (and (or (interactive-p) executing-kbd-macro) link)
7938 (progn
7939 (setq org-stored-links
7940 (cons (list link desc) org-stored-links))
7941 (message "Stored: %s" (or desc link))
7942 (when custom-id
7943 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7944 "::#" custom-id))
7945 (setq org-stored-links
7946 (cons (list link desc) org-stored-links))))
7947 (and link (org-make-link-string link desc)))))
7949 (defun org-store-link-props (&rest plist)
7950 "Store link properties, extract names and addresses."
7951 (let (x adr)
7952 (when (setq x (plist-get plist :from))
7953 (setq adr (mail-extract-address-components x))
7954 (setq plist (plist-put plist :fromname (car adr)))
7955 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7956 (when (setq x (plist-get plist :to))
7957 (setq adr (mail-extract-address-components x))
7958 (setq plist (plist-put plist :toname (car adr)))
7959 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7960 (let ((from (plist-get plist :from))
7961 (to (plist-get plist :to)))
7962 (when (and from to org-from-is-user-regexp)
7963 (setq plist
7964 (plist-put plist :fromto
7965 (if (string-match org-from-is-user-regexp from)
7966 (concat "to %t")
7967 (concat "from %f"))))))
7968 (setq org-store-link-plist plist))
7970 (defun org-add-link-props (&rest plist)
7971 "Add these properties to the link property list."
7972 (let (key value)
7973 (while plist
7974 (setq key (pop plist) value (pop plist))
7975 (setq org-store-link-plist
7976 (plist-put org-store-link-plist key value)))))
7978 (defun org-email-link-description (&optional fmt)
7979 "Return the description part of an email link.
7980 This takes information from `org-store-link-plist' and formats it
7981 according to FMT (default from `org-email-link-description-format')."
7982 (setq fmt (or fmt org-email-link-description-format))
7983 (let* ((p org-store-link-plist)
7984 (to (plist-get p :toaddress))
7985 (from (plist-get p :fromaddress))
7986 (table
7987 (list
7988 (cons "%c" (plist-get p :fromto))
7989 (cons "%F" (plist-get p :from))
7990 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7991 (cons "%T" (plist-get p :to))
7992 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7993 (cons "%s" (plist-get p :subject))
7994 (cons "%m" (plist-get p :message-id)))))
7995 (when (string-match "%c" fmt)
7996 ;; Check if the user wrote this message
7997 (if (and org-from-is-user-regexp from to
7998 (save-match-data (string-match org-from-is-user-regexp from)))
7999 (setq fmt (replace-match "to %t" t t fmt))
8000 (setq fmt (replace-match "from %f" t t fmt))))
8001 (org-replace-escapes fmt table)))
8003 (defun org-make-org-heading-search-string (&optional string heading)
8004 "Make search string for STRING or current headline."
8005 (interactive)
8006 (let ((s (or string (org-get-heading))))
8007 (unless (and string (not heading))
8008 ;; We are using a headline, clean up garbage in there.
8009 (if (string-match org-todo-regexp s)
8010 (setq s (replace-match "" t t s)))
8011 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8012 (setq s (replace-match "" t t s)))
8013 (setq s (org-trim s))
8014 (if (string-match (concat "^\\(" org-quote-string "\\|"
8015 org-comment-string "\\)") s)
8016 (setq s (replace-match "" t t s)))
8017 (while (string-match org-ts-regexp s)
8018 (setq s (replace-match "" t t s))))
8019 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8020 (setq s (replace-match " " t t s)))
8021 (or string (setq s (concat "*" s))) ; Add * for headlines
8022 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8024 (defun org-make-link (&rest strings)
8025 "Concatenate STRINGS."
8026 (apply 'concat strings))
8028 (defun org-make-link-string (link &optional description)
8029 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8030 (unless (string-match "\\S-" link)
8031 (error "Empty link"))
8032 (when (and description
8033 (stringp description)
8034 (not (string-match "\\S-" description)))
8035 (setq description nil))
8036 (when (stringp description)
8037 ;; Remove brackets from the description, they are fatal.
8038 (while (string-match "\\[" description)
8039 (setq description (replace-match "{" t t description)))
8040 (while (string-match "\\]" description)
8041 (setq description (replace-match "}" t t description))))
8042 (when (equal (org-link-escape link) description)
8043 ;; No description needed, it is identical
8044 (setq description nil))
8045 (when (and (not description)
8046 (not (equal link (org-link-escape link))))
8047 (setq description (org-extract-attributes link)))
8048 (concat "[[" (org-link-escape link) "]"
8049 (if description (concat "[" description "]") "")
8050 "]"))
8052 (defconst org-link-escape-chars
8053 '((?\ . "%20")
8054 (?\[ . "%5B")
8055 (?\] . "%5D")
8056 (?\340 . "%E0") ; `a
8057 (?\342 . "%E2") ; ^a
8058 (?\347 . "%E7") ; ,c
8059 (?\350 . "%E8") ; `e
8060 (?\351 . "%E9") ; 'e
8061 (?\352 . "%EA") ; ^e
8062 (?\356 . "%EE") ; ^i
8063 (?\364 . "%F4") ; ^o
8064 (?\371 . "%F9") ; `u
8065 (?\373 . "%FB") ; ^u
8066 (?\; . "%3B")
8067 ;; (?? . "%3F")
8068 (?= . "%3D")
8069 (?+ . "%2B")
8071 "Association list of escapes for some characters problematic in links.
8072 This is the list that is used for internal purposes.")
8074 (defvar org-url-encoding-use-url-hexify nil)
8076 (defconst org-link-escape-chars-browser
8077 '((?\ . "%20")) ; 32 for the SPC char
8078 "Association list of escapes for some characters problematic in links.
8079 This is the list that is used before handing over to the browser.")
8081 (defun org-link-escape (text &optional table)
8082 "Escape characters in TEXT that are problematic for links."
8083 (if (and org-url-encoding-use-url-hexify (not table))
8084 (url-hexify-string text)
8085 (setq table (or table org-link-escape-chars))
8086 (when text
8087 (let ((re (mapconcat (lambda (x) (regexp-quote
8088 (char-to-string (car x))))
8089 table "\\|")))
8090 (while (string-match re text)
8091 (setq text
8092 (replace-match
8093 (cdr (assoc (string-to-char (match-string 0 text))
8094 table))
8095 t t text)))
8096 text))))
8098 (defun org-link-unescape (text &optional table)
8099 "Reverse the action of `org-link-escape'."
8100 (if (and org-url-encoding-use-url-hexify (not table))
8101 (url-unhex-string text)
8102 (setq table (or table org-link-escape-chars))
8103 (when text
8104 (let ((case-fold-search t)
8105 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8106 table "\\|")))
8107 (while (string-match re text)
8108 (setq text
8109 (replace-match
8110 (char-to-string (car (rassoc (upcase (match-string 0 text))
8111 table)))
8112 t t text)))
8113 text))))
8115 (defun org-xor (a b)
8116 "Exclusive or."
8117 (if a (not b) b))
8119 (defun org-fixup-message-id-for-http (s)
8120 "Replace special characters in a message id, so it can be used in an http query."
8121 (while (string-match "<" s)
8122 (setq s (replace-match "%3C" t t s)))
8123 (while (string-match ">" s)
8124 (setq s (replace-match "%3E" t t s)))
8125 (while (string-match "@" s)
8126 (setq s (replace-match "%40" t t s)))
8129 ;;;###autoload
8130 (defun org-insert-link-global ()
8131 "Insert a link like Org-mode does.
8132 This command can be called in any mode to insert a link in Org-mode syntax."
8133 (interactive)
8134 (org-load-modules-maybe)
8135 (org-run-like-in-org-mode 'org-insert-link))
8137 (defun org-insert-link (&optional complete-file link-location)
8138 "Insert a link. At the prompt, enter the link.
8140 Completion can be used to insert any of the link protocol prefixes like
8141 http or ftp in use.
8143 The history can be used to select a link previously stored with
8144 `org-store-link'. When the empty string is entered (i.e. if you just
8145 press RET at the prompt), the link defaults to the most recently
8146 stored link. As SPC triggers completion in the minibuffer, you need to
8147 use M-SPC or C-q SPC to force the insertion of a space character.
8149 You will also be prompted for a description, and if one is given, it will
8150 be displayed in the buffer instead of the link.
8152 If there is already a link at point, this command will allow you to edit link
8153 and description parts.
8155 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8156 be selected using completion. The path to the file will be relative to the
8157 current directory if the file is in the current directory or a subdirectory.
8158 Otherwise, the link will be the absolute path as completed in the minibuffer
8159 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8160 option `org-link-file-path-type'.
8162 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8163 the current directory or below.
8165 With three \\[universal-argument] prefixes, negate the meaning of
8166 `org-keep-stored-link-after-insertion'.
8168 If `org-make-link-description-function' is non-nil, this function will be
8169 called with the link target, and the result will be the default
8170 link description.
8172 If the LINK-LOCATION parameter is non-nil, this value will be
8173 used as the link location instead of reading one interactively."
8174 (interactive "P")
8175 (let* ((wcf (current-window-configuration))
8176 (region (if (org-region-active-p)
8177 (buffer-substring (region-beginning) (region-end))))
8178 (remove (and region (list (region-beginning) (region-end))))
8179 (desc region)
8180 tmphist ; byte-compile incorrectly complains about this
8181 (link link-location)
8182 entry file all-prefixes)
8183 (cond
8184 (link-location) ; specified by arg, just use it.
8185 ((org-in-regexp org-bracket-link-regexp 1)
8186 ;; We do have a link at point, and we are going to edit it.
8187 (setq remove (list (match-beginning 0) (match-end 0)))
8188 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8189 (setq link (read-string "Link: "
8190 (org-link-unescape
8191 (org-match-string-no-properties 1)))))
8192 ((or (org-in-regexp org-angle-link-re)
8193 (org-in-regexp org-plain-link-re))
8194 ;; Convert to bracket link
8195 (setq remove (list (match-beginning 0) (match-end 0))
8196 link (read-string "Link: "
8197 (org-remove-angle-brackets (match-string 0)))))
8198 ((member complete-file '((4) (16)))
8199 ;; Completing read for file names.
8200 (setq link (org-file-complete-link complete-file)))
8202 ;; Read link, with completion for stored links.
8203 (with-output-to-temp-buffer "*Org Links*"
8204 (princ "Insert a link.
8205 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8206 (when org-stored-links
8207 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8208 (princ (mapconcat
8209 (lambda (x)
8210 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8211 (reverse org-stored-links) "\n"))))
8212 (let ((cw (selected-window)))
8213 (select-window (get-buffer-window "*Org Links*" 'visible))
8214 (setq truncate-lines t)
8215 (unless (pos-visible-in-window-p (point-max))
8216 (org-fit-window-to-buffer))
8217 (and (window-live-p cw) (select-window cw)))
8218 ;; Fake a link history, containing the stored links.
8219 (setq tmphist (append (mapcar 'car org-stored-links)
8220 org-insert-link-history))
8221 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8222 (mapcar 'car org-link-abbrev-alist)
8223 org-link-types))
8224 (unwind-protect
8225 (progn
8226 (setq link
8227 (let ((org-completion-use-ido nil)
8228 (org-completion-use-iswitchb nil))
8229 (org-completing-read
8230 "Link: "
8231 (append
8232 (mapcar (lambda (x) (list (concat x ":")))
8233 all-prefixes)
8234 (mapcar 'car org-stored-links))
8235 nil nil nil
8236 'tmphist
8237 (car (car org-stored-links)))))
8238 (if (not (string-match "\\S-" link))
8239 (error "No link selected"))
8240 (if (or (member link all-prefixes)
8241 (and (equal ":" (substring link -1))
8242 (member (substring link 0 -1) all-prefixes)
8243 (setq link (substring link 0 -1))))
8244 (setq link (org-link-try-special-completion link))))
8245 (set-window-configuration wcf)
8246 (kill-buffer "*Org Links*"))
8247 (setq entry (assoc link org-stored-links))
8248 (or entry (push link org-insert-link-history))
8249 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8250 (not org-keep-stored-link-after-insertion))
8251 (setq org-stored-links (delq (assoc link org-stored-links)
8252 org-stored-links)))
8253 (setq desc (or desc (nth 1 entry)))))
8255 (if (string-match org-plain-link-re link)
8256 ;; URL-like link, normalize the use of angular brackets.
8257 (setq link (org-make-link (org-remove-angle-brackets link))))
8259 ;; Check if we are linking to the current file with a search option
8260 ;; If yes, simplify the link by using only the search option.
8261 (when (and buffer-file-name
8262 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8263 (let* ((path (match-string 1 link))
8264 (case-fold-search nil)
8265 (search (match-string 2 link)))
8266 (save-match-data
8267 (if (equal (file-truename buffer-file-name) (file-truename path))
8268 ;; We are linking to this same file, with a search option
8269 (setq link search)))))
8271 ;; Check if we can/should use a relative path. If yes, simplify the link
8272 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8273 (let* ((type (match-string 1 link))
8274 (path (match-string 2 link))
8275 (origpath path)
8276 (case-fold-search nil))
8277 (cond
8278 ((or (eq org-link-file-path-type 'absolute)
8279 (equal complete-file '(16)))
8280 (setq path (abbreviate-file-name (expand-file-name path))))
8281 ((eq org-link-file-path-type 'noabbrev)
8282 (setq path (expand-file-name path)))
8283 ((eq org-link-file-path-type 'relative)
8284 (setq path (file-relative-name path)))
8286 (save-match-data
8287 (if (string-match (concat "^" (regexp-quote
8288 (file-name-as-directory
8289 (expand-file-name "."))))
8290 (expand-file-name path))
8291 ;; We are linking a file with relative path name.
8292 (setq path (substring (expand-file-name path)
8293 (match-end 0)))
8294 (setq path (abbreviate-file-name (expand-file-name path)))))))
8295 (setq link (concat type path))
8296 (if (equal desc origpath)
8297 (setq desc path))))
8299 (if org-make-link-description-function
8300 (setq desc (funcall org-make-link-description-function link desc)))
8302 (setq desc (read-string "Description: " desc))
8303 (unless (string-match "\\S-" desc) (setq desc nil))
8304 (if remove (apply 'delete-region remove))
8305 (insert (org-make-link-string link desc))))
8307 (defun org-link-try-special-completion (type)
8308 "If there is completion support for link type TYPE, offer it."
8309 (let ((fun (intern (concat "org-" type "-complete-link"))))
8310 (if (functionp fun)
8311 (funcall fun)
8312 (read-string "Link (no completion support): " (concat type ":")))))
8314 (defun org-file-complete-link (&optional arg)
8315 "Create a file link using completion."
8316 (let (file link)
8317 (setq file (read-file-name "File: "))
8318 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8319 (pwd1 (file-name-as-directory (abbreviate-file-name
8320 (expand-file-name ".")))))
8321 (cond
8322 ((equal arg '(16))
8323 (setq link (org-make-link
8324 "file:"
8325 (abbreviate-file-name (expand-file-name file)))))
8326 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8327 (setq link (org-make-link "file:" (match-string 1 file))))
8328 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8329 (expand-file-name file))
8330 (setq link (org-make-link
8331 "file:" (match-string 1 (expand-file-name file)))))
8332 (t (setq link (org-make-link "file:" file)))))
8333 link))
8335 (defun org-completing-read (&rest args)
8336 "Completing-read with SPACE being a normal character."
8337 (let ((minibuffer-local-completion-map
8338 (copy-keymap minibuffer-local-completion-map)))
8339 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8340 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8341 (apply 'org-icompleting-read args)))
8343 (defun org-completing-read-no-i (&rest args)
8344 (let (org-completion-use-ido org-completion-use-iswitchb)
8345 (apply 'org-completing-read args)))
8347 (defun org-iswitchb-completing-read (prompt choices &rest args)
8348 "Use iswitch as a completing-read replacement to choose from choices.
8349 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8350 from."
8351 (let* ((iswitchb-use-virtual-buffers nil)
8352 (iswitchb-make-buflist-hook
8353 (lambda ()
8354 (setq iswitchb-temp-buflist choices))))
8355 (iswitchb-read-buffer prompt)))
8357 (defun org-icompleting-read (&rest args)
8358 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8359 (org-without-partial-completion
8360 (if (and org-completion-use-ido
8361 (fboundp 'ido-completing-read)
8362 (boundp 'ido-mode) ido-mode
8363 (listp (second args)))
8364 (let ((ido-enter-matching-directory nil))
8365 (apply 'ido-completing-read (concat (car args))
8366 (if (consp (car (nth 1 args)))
8367 (mapcar (lambda (x) (car x)) (nth 1 args))
8368 (nth 1 args))
8369 (cddr args)))
8370 (if (and org-completion-use-iswitchb
8371 (boundp 'iswitchb-mode) iswitchb-mode
8372 (listp (second args)))
8373 (apply 'org-iswitchb-completing-read (concat (car args))
8374 (if (consp (car (nth 1 args)))
8375 (mapcar (lambda (x) (car x)) (nth 1 args))
8376 (nth 1 args))
8377 (cddr args))
8378 (apply 'completing-read args)))))
8380 (defun org-extract-attributes (s)
8381 "Extract the attributes cookie from a string and set as text property."
8382 (let (a attr (start 0) key value)
8383 (save-match-data
8384 (when (string-match "{{\\([^}]+\\)}}$" s)
8385 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8386 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8387 (setq key (match-string 1 a) value (match-string 2 a)
8388 start (match-end 0)
8389 attr (plist-put attr (intern key) value))))
8390 (org-add-props s nil 'org-attr attr))
8393 (defun org-extract-attributes-from-string (tag)
8394 (let (key value attr)
8395 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8396 (setq key (match-string 1 tag) value (match-string 2 tag)
8397 tag (replace-match "" t t tag)
8398 attr (plist-put attr (intern key) value)))
8399 (cons tag attr)))
8401 (defun org-attributes-to-string (plist)
8402 "Format a property list into an HTML attribute list."
8403 (let ((s "") key value)
8404 (while plist
8405 (setq key (pop plist) value (pop plist))
8406 (and value
8407 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8410 ;;; Opening/following a link
8412 (defvar org-link-search-failed nil)
8414 (defvar org-open-link-functions nil
8415 "Hook for functions finding a plain text link.
8416 These functions must take a single argument, the link content.
8417 They will be called for links that look like [[link text][description]]
8418 when LINK TEXT does not have a protocol like \"http:\" and does not look
8419 like a filename (e.g. \"./blue.png\").
8421 These functions will be called *before* Org attempts to resolve the
8422 link by doing text searches in the current buffer - so if you want a
8423 link \"[[target]]\" to still find \"<<target>>\", your function should
8424 handle this as a special case.
8426 When the function does handle the link, it must return a non-nil value.
8427 If it decides that it is not responsible for this link, it must return
8428 nil to indicate that that Org-mode can continue with other options
8429 like exact and fuzzy text search.")
8431 (defun org-next-link ()
8432 "Move forward to the next link.
8433 If the link is in hidden text, expose it."
8434 (interactive)
8435 (when (and org-link-search-failed (eq this-command last-command))
8436 (goto-char (point-min))
8437 (message "Link search wrapped back to beginning of buffer"))
8438 (setq org-link-search-failed nil)
8439 (let* ((pos (point))
8440 (ct (org-context))
8441 (a (assoc :link ct)))
8442 (if a (goto-char (nth 2 a)))
8443 (if (re-search-forward org-any-link-re nil t)
8444 (progn
8445 (goto-char (match-beginning 0))
8446 (if (org-invisible-p) (org-show-context)))
8447 (goto-char pos)
8448 (setq org-link-search-failed t)
8449 (error "No further link found"))))
8451 (defun org-previous-link ()
8452 "Move backward to the previous link.
8453 If the link is in hidden text, expose it."
8454 (interactive)
8455 (when (and org-link-search-failed (eq this-command last-command))
8456 (goto-char (point-max))
8457 (message "Link search wrapped back to end of buffer"))
8458 (setq org-link-search-failed nil)
8459 (let* ((pos (point))
8460 (ct (org-context))
8461 (a (assoc :link ct)))
8462 (if a (goto-char (nth 1 a)))
8463 (if (re-search-backward org-any-link-re nil t)
8464 (progn
8465 (goto-char (match-beginning 0))
8466 (if (org-invisible-p) (org-show-context)))
8467 (goto-char pos)
8468 (setq org-link-search-failed t)
8469 (error "No further link found"))))
8471 (defun org-translate-link (s)
8472 "Translate a link string if a translation function has been defined."
8473 (if (and org-link-translation-function
8474 (fboundp org-link-translation-function)
8475 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8476 (progn
8477 (setq s (funcall org-link-translation-function
8478 (match-string 1) (match-string 2)))
8479 (concat (car s) ":" (cdr s)))
8482 (defun org-translate-link-from-planner (type path)
8483 "Translate a link from Emacs Planner syntax so that Org can follow it.
8484 This is still an experimental function, your mileage may vary."
8485 (cond
8486 ((member type '("http" "https" "news" "ftp"))
8487 ;; standard Internet links are the same.
8488 nil)
8489 ((and (equal type "irc") (string-match "^//" path))
8490 ;; Planner has two / at the beginning of an irc link, we have 1.
8491 ;; We should have zero, actually....
8492 (setq path (substring path 1)))
8493 ((and (equal type "lisp") (string-match "^/" path))
8494 ;; Planner has a slash, we do not.
8495 (setq type "elisp" path (substring path 1)))
8496 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8497 ;; A typical message link. Planner has the id after the final slash,
8498 ;; we separate it with a hash mark
8499 (setq path (concat (match-string 1 path) "#"
8500 (org-remove-angle-brackets (match-string 2 path)))))
8502 (cons type path))
8504 (defun org-find-file-at-mouse (ev)
8505 "Open file link or URL at mouse."
8506 (interactive "e")
8507 (mouse-set-point ev)
8508 (org-open-at-point 'in-emacs))
8510 (defun org-open-at-mouse (ev)
8511 "Open file link or URL at mouse."
8512 (interactive "e")
8513 (mouse-set-point ev)
8514 (if (eq major-mode 'org-agenda-mode)
8515 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8516 (org-open-at-point))
8518 (defvar org-window-config-before-follow-link nil
8519 "The window configuration before following a link.
8520 This is saved in case the need arises to restore it.")
8522 (defvar org-open-link-marker (make-marker)
8523 "Marker pointing to the location where `org-open-at-point; was called.")
8525 ;;;###autoload
8526 (defun org-open-at-point-global ()
8527 "Follow a link like Org-mode does.
8528 This command can be called in any mode to follow a link that has
8529 Org-mode syntax."
8530 (interactive)
8531 (org-run-like-in-org-mode 'org-open-at-point))
8533 ;;;###autoload
8534 (defun org-open-link-from-string (s &optional arg reference-buffer)
8535 "Open a link in the string S, as if it was in Org-mode."
8536 (interactive "sLink: \nP")
8537 (let ((reference-buffer (or reference-buffer (current-buffer))))
8538 (with-temp-buffer
8539 (let ((org-inhibit-startup t))
8540 (org-mode)
8541 (insert s)
8542 (goto-char (point-min))
8543 (when reference-buffer
8544 (setq org-link-abbrev-alist-local
8545 (with-current-buffer reference-buffer
8546 org-link-abbrev-alist-local)))
8547 (org-open-at-point arg reference-buffer)))))
8549 (defun org-open-at-point (&optional in-emacs reference-buffer)
8550 "Open link at or after point.
8551 If there is no link at point, this function will search forward up to
8552 the end of the current line.
8553 Normally, files will be opened by an appropriate application. If the
8554 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8555 With a double prefix argument, try to open outside of Emacs, in the
8556 application the system uses for this file type."
8557 (interactive "P")
8558 (org-load-modules-maybe)
8559 (move-marker org-open-link-marker (point))
8560 (setq org-window-config-before-follow-link (current-window-configuration))
8561 (org-remove-occur-highlights nil nil t)
8562 (cond
8563 ((and (org-on-heading-p)
8564 (not (org-in-regexp
8565 (concat org-plain-link-re "\\|"
8566 org-bracket-link-regexp "\\|"
8567 org-angle-link-re "\\|"
8568 "[ \t]:[^ \t\n]+:[ \t]*$")))
8569 (not (get-text-property (point) 'org-linked-text)))
8570 (or (org-offer-links-in-entry in-emacs)
8571 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8572 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8573 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8574 (org-footnote-action))
8576 (let (type path link line search (pos (point)))
8577 (catch 'match
8578 (save-excursion
8579 (skip-chars-forward "^]\n\r")
8580 (when (org-in-regexp org-bracket-link-regexp 1)
8581 (setq link (org-extract-attributes
8582 (org-link-unescape (org-match-string-no-properties 1))))
8583 (while (string-match " *\n *" link)
8584 (setq link (replace-match " " t t link)))
8585 (setq link (org-link-expand-abbrev link))
8586 (cond
8587 ((or (file-name-absolute-p link)
8588 (string-match "^\\.\\.?/" link))
8589 (setq type "file" path link))
8590 ((string-match org-link-re-with-space3 link)
8591 (setq type (match-string 1 link) path (match-string 2 link)))
8592 (t (setq type "thisfile" path link)))
8593 (throw 'match t)))
8595 (when (get-text-property (point) 'org-linked-text)
8596 (setq type "thisfile"
8597 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8598 (1+ (point)) (point))
8599 path (buffer-substring
8600 (previous-single-property-change pos 'org-linked-text)
8601 (next-single-property-change pos 'org-linked-text)))
8602 (throw 'match t))
8604 (save-excursion
8605 (when (or (org-in-regexp org-angle-link-re)
8606 (org-in-regexp org-plain-link-re))
8607 (setq type (match-string 1) path (match-string 2))
8608 (throw 'match t)))
8609 (save-excursion
8610 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8611 (setq type "tags"
8612 path (match-string 1))
8613 (while (string-match ":" path)
8614 (setq path (replace-match "+" t t path)))
8615 (throw 'match t)))
8616 (when (org-in-regexp "<\\([^><\n]+\\)>")
8617 (setq type "tree-match"
8618 path (match-string 1))
8619 (throw 'match t)))
8620 (unless path
8621 (error "No link found"))
8623 ;; switch back to reference buffer
8624 ;; needed when if called in a temporary buffer through
8625 ;; org-open-link-from-string
8626 (with-current-buffer (or reference-buffer (current-buffer))
8628 ;; Remove any trailing spaces in path
8629 (if (string-match " +\\'" path)
8630 (setq path (replace-match "" t t path)))
8631 (if (and org-link-translation-function
8632 (fboundp org-link-translation-function))
8633 ;; Check if we need to translate the link
8634 (let ((tmp (funcall org-link-translation-function type path)))
8635 (setq type (car tmp) path (cdr tmp))))
8637 (cond
8639 ((assoc type org-link-protocols)
8640 (funcall (nth 1 (assoc type org-link-protocols)) path))
8642 ((equal type "mailto")
8643 (let ((cmd (car org-link-mailto-program))
8644 (args (cdr org-link-mailto-program)) args1
8645 (address path) (subject "") a)
8646 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8647 (setq address (match-string 1 path)
8648 subject (org-link-escape (match-string 2 path))))
8649 (while args
8650 (cond
8651 ((not (stringp (car args))) (push (pop args) args1))
8652 (t (setq a (pop args))
8653 (if (string-match "%a" a)
8654 (setq a (replace-match address t t a)))
8655 (if (string-match "%s" a)
8656 (setq a (replace-match subject t t a)))
8657 (push a args1))))
8658 (apply cmd (nreverse args1))))
8660 ((member type '("http" "https" "ftp" "news"))
8661 (browse-url (concat type ":" (org-link-escape
8662 path org-link-escape-chars-browser))))
8664 ((member type '("message"))
8665 (browse-url (concat type ":" path)))
8667 ((string= type "tags")
8668 (org-tags-view in-emacs path))
8670 ((string= type "tree-match")
8671 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8673 ((string= type "file")
8674 (if (string-match "::\\([0-9]+\\)\\'" path)
8675 (setq line (string-to-number (match-string 1 path))
8676 path (substring path 0 (match-beginning 0)))
8677 (if (string-match "::\\(.+\\)\\'" path)
8678 (setq search (match-string 1 path)
8679 path (substring path 0 (match-beginning 0)))))
8680 (if (string-match "[*?{]" (file-name-nondirectory path))
8681 (dired path)
8682 (org-open-file path in-emacs line search)))
8684 ((string= type "news")
8685 (require 'org-gnus)
8686 (org-gnus-follow-link path))
8688 ((string= type "shell")
8689 (let ((cmd path))
8690 (if (or (not org-confirm-shell-link-function)
8691 (funcall org-confirm-shell-link-function
8692 (format "Execute \"%s\" in shell? "
8693 (org-add-props cmd nil
8694 'face 'org-warning))))
8695 (progn
8696 (message "Executing %s" cmd)
8697 (shell-command cmd))
8698 (error "Abort"))))
8700 ((string= type "elisp")
8701 (let ((cmd path))
8702 (if (or (not org-confirm-elisp-link-function)
8703 (funcall org-confirm-elisp-link-function
8704 (format "Execute \"%s\" as elisp? "
8705 (org-add-props cmd nil
8706 'face 'org-warning))))
8707 (message "%s => %s" cmd
8708 (if (equal (string-to-char cmd) ?\()
8709 (eval (read cmd))
8710 (call-interactively (read cmd))))
8711 (error "Abort"))))
8713 ((and (string= type "thisfile")
8714 (run-hook-with-args-until-success
8715 'org-open-link-functions path)))
8717 ((string= type "thisfile")
8718 (if in-emacs
8719 (switch-to-buffer-other-window
8720 (org-get-buffer-for-internal-link (current-buffer)))
8721 (org-mark-ring-push))
8722 (let ((cmd `(org-link-search
8723 ,path
8724 ,(cond ((equal in-emacs '(4)) 'occur)
8725 ((equal in-emacs '(16)) 'org-occur)
8726 (t nil))
8727 ,pos)))
8728 (condition-case nil (eval cmd)
8729 (error (progn (widen) (eval cmd))))))
8732 (browse-url-at-point)))))))
8733 (move-marker org-open-link-marker nil)
8734 (run-hook-with-args 'org-follow-link-hook))
8736 (defun org-offer-links-in-entry (&optional nth zero)
8737 "Offer links in the current entry and follow the selected link.
8738 If there is only one link, follow it immediately as well.
8739 If NTH is an integer, immediately pick the NTH link found.
8740 If ZERO is a string, check also this string for a link, and if
8741 there is one, offer it as link number zero."
8742 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8743 "\\(" org-angle-link-re "\\)\\|"
8744 "\\(" org-plain-link-re "\\)"))
8745 (cnt ?0)
8746 (in-emacs (if (integerp nth) nil nth))
8747 have-zero end links link c)
8748 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8749 (push (match-string 0 zero) links)
8750 (setq cnt (1- cnt) have-zero t))
8751 (save-excursion
8752 (org-back-to-heading t)
8753 (setq end (save-excursion (outline-next-heading) (point)))
8754 (while (re-search-forward re end t)
8755 (push (match-string 0) links))
8756 (setq links (org-uniquify (reverse links))))
8758 (cond
8759 ((null links)
8760 (message "No links"))
8761 ((equal (length links) 1)
8762 (setq link (list (car links))))
8763 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8764 (setq link (nth (if have-zero nth (1- nth)) links)))
8765 (t ; we have to select a link
8766 (save-excursion
8767 (save-window-excursion
8768 (delete-other-windows)
8769 (with-output-to-temp-buffer "*Select Link*"
8770 (mapc (lambda (l)
8771 (if (not (string-match org-bracket-link-regexp l))
8772 (princ (format "[%c] %s\n" (incf cnt)
8773 (org-remove-angle-brackets l)))
8774 (if (match-end 3)
8775 (princ (format "[%c] %s (%s)\n" (incf cnt)
8776 (match-string 3 l) (match-string 1 l)))
8777 (princ (format "[%c] %s\n" (incf cnt)
8778 (match-string 1 l))))))
8779 links))
8780 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8781 (message "Select link to open, RET to open all:")
8782 (setq c (read-char-exclusive))
8783 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8784 (when (equal c ?q) (error "Abort"))
8785 (if (equal c ?\C-m)
8786 (setq link links)
8787 (setq nth (- c ?0))
8788 (if have-zero (setq nth (1+ nth)))
8789 (unless (and (integerp nth) (>= (length links) nth))
8790 (error "Invalid link selection"))
8791 (setq link (list (nth (1- nth) links))))))
8792 (if link
8793 (let ((buf (current-buffer)))
8794 (dolist (l link)
8795 (org-open-link-from-string l in-emacs buf))
8797 nil)))
8799 ;; Add special file links that specify the way of opening
8801 (org-add-link-type "file+sys" 'org-open-file-with-system)
8802 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8803 (defun org-open-file-with-system (path)
8804 "Open file at PATH using the system way of opeing it."
8805 (org-open-file path 'system))
8806 (defun org-open-file-with-emacs (path)
8807 "Open file at PATH in emacs."
8808 (org-open-file path 'emacs))
8809 (defun org-remove-file-link-modifiers ()
8810 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8811 (goto-char (point-min))
8812 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8813 (org-if-unprotected
8814 (replace-match "file:" t t))))
8815 (eval-after-load "org-exp"
8816 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8817 'org-remove-file-link-modifiers))
8819 ;;;; Time estimates
8821 (defun org-get-effort (&optional pom)
8822 "Get the effort estimate for the current entry."
8823 (org-entry-get pom org-effort-property))
8825 ;;; File search
8827 (defvar org-create-file-search-functions nil
8828 "List of functions to construct the right search string for a file link.
8829 These functions are called in turn with point at the location to
8830 which the link should point.
8832 A function in the hook should first test if it would like to
8833 handle this file type, for example by checking the major-mode or
8834 the file extension. If it decides not to handle this file, it
8835 should just return nil to give other functions a chance. If it
8836 does handle the file, it must return the search string to be used
8837 when following the link. The search string will be part of the
8838 file link, given after a double colon, and `org-open-at-point'
8839 will automatically search for it. If special measures must be
8840 taken to make the search successful, another function should be
8841 added to the companion hook `org-execute-file-search-functions',
8842 which see.
8844 A function in this hook may also use `setq' to set the variable
8845 `description' to provide a suggestion for the descriptive text to
8846 be used for this link when it gets inserted into an Org-mode
8847 buffer with \\[org-insert-link].")
8849 (defvar org-execute-file-search-functions nil
8850 "List of functions to execute a file search triggered by a link.
8852 Functions added to this hook must accept a single argument, the
8853 search string that was part of the file link, the part after the
8854 double colon. The function must first check if it would like to
8855 handle this search, for example by checking the major-mode or the
8856 file extension. If it decides not to handle this search, it
8857 should just return nil to give other functions a chance. If it
8858 does handle the search, it must return a non-nil value to keep
8859 other functions from trying.
8861 Each function can access the current prefix argument through the
8862 variable `current-prefix-argument'. Note that a single prefix is
8863 used to force opening a link in Emacs, so it may be good to only
8864 use a numeric or double prefix to guide the search function.
8866 In case this is needed, a function in this hook can also restore
8867 the window configuration before `org-open-at-point' was called using:
8869 (set-window-configuration org-window-config-before-follow-link)")
8871 (defun org-link-search (s &optional type avoid-pos)
8872 "Search for a link search option.
8873 If S is surrounded by forward slashes, it is interpreted as a
8874 regular expression. In org-mode files, this will create an `org-occur'
8875 sparse tree. In ordinary files, `occur' will be used to list matches.
8876 If the current buffer is in `dired-mode', grep will be used to search
8877 in all files. If AVOID-POS is given, ignore matches near that position."
8878 (let ((case-fold-search t)
8879 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8880 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8881 (append '(("") (" ") ("\t") ("\n"))
8882 org-emphasis-alist)
8883 "\\|") "\\)"))
8884 (pos (point))
8885 (pre nil) (post nil)
8886 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8887 (cond
8888 ;; First check if there are any special
8889 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8890 ;; Now try the builtin stuff
8891 ((and (equal (string-to-char s0) ?#)
8892 (> (length s0) 1)
8893 (save-excursion
8894 (goto-char (point-min))
8895 (and
8896 (re-search-forward
8897 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8898 (setq type 'dedicated
8899 pos (match-beginning 0))))
8900 ;; There is an exact target for this
8901 (goto-char pos)
8902 (org-back-to-heading t)))
8903 ((save-excursion
8904 (goto-char (point-min))
8905 (and
8906 (re-search-forward
8907 (concat "<<" (regexp-quote s0) ">>") nil t)
8908 (setq type 'dedicated
8909 pos (match-beginning 0))))
8910 ;; There is an exact target for this
8911 (goto-char pos))
8912 ((and (string-match "^(\\(.*\\))$" s0)
8913 (save-excursion
8914 (goto-char (point-min))
8915 (and
8916 (re-search-forward
8917 (concat "[^[]" (regexp-quote
8918 (format org-coderef-label-format
8919 (match-string 1 s0))))
8920 nil t)
8921 (setq type 'dedicated
8922 pos (1+ (match-beginning 0))))))
8923 ;; There is a coderef target for this
8924 (goto-char pos))
8925 ((string-match "^/\\(.*\\)/$" s)
8926 ;; A regular expression
8927 (cond
8928 ((org-mode-p)
8929 (org-occur (match-string 1 s)))
8930 ;;((eq major-mode 'dired-mode)
8931 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8932 (t (org-do-occur (match-string 1 s)))))
8934 ;; A normal search strings
8935 (when (equal (string-to-char s) ?*)
8936 ;; Anchor on headlines, post may include tags.
8937 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8938 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8939 s (substring s 1)))
8940 (remove-text-properties
8941 0 (length s)
8942 '(face nil mouse-face nil keymap nil fontified nil) s)
8943 ;; Make a series of regular expressions to find a match
8944 (setq words (org-split-string s "[ \n\r\t]+")
8946 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8947 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8948 "\\)" markers)
8949 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8950 re2a (concat "[ \t\r\n]" re2a_)
8951 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8952 re4 (concat "[^a-zA-Z_]" re4_)
8954 re1 (concat pre re2 post)
8955 re3 (concat pre (if pre re4_ re4) post)
8956 re5 (concat pre ".*" re4)
8957 re2 (concat pre re2)
8958 re2a (concat pre (if pre re2a_ re2a))
8959 re4 (concat pre (if pre re4_ re4))
8960 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8961 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8962 re5 "\\)"
8964 (cond
8965 ((eq type 'org-occur) (org-occur reall))
8966 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8967 (t (goto-char (point-min))
8968 (setq type 'fuzzy)
8969 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8970 (org-search-not-self 1 re1 nil t)
8971 (org-search-not-self 1 re2 nil t)
8972 (org-search-not-self 1 re2a nil t)
8973 (org-search-not-self 1 re3 nil t)
8974 (org-search-not-self 1 re4 nil t)
8975 (org-search-not-self 1 re5 nil t)
8977 (goto-char (match-beginning 1))
8978 (goto-char pos)
8979 (error "No match")))))
8981 ;; Normal string-search
8982 (goto-char (point-min))
8983 (if (search-forward s nil t)
8984 (goto-char (match-beginning 0))
8985 (error "No match"))))
8986 (and (org-mode-p) (org-show-context 'link-search))
8987 type))
8989 (defun org-search-not-self (group &rest args)
8990 "Execute `re-search-forward', but only accept matches that do not
8991 enclose the position of `org-open-link-marker'."
8992 (let ((m org-open-link-marker))
8993 (catch 'exit
8994 (while (apply 're-search-forward args)
8995 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8996 (goto-char (match-end group))
8997 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8998 (> (match-beginning 0) (marker-position m))
8999 (< (match-end 0) (marker-position m)))
9000 (save-match-data
9001 (or (not (org-in-regexp
9002 org-bracket-link-analytic-regexp 1))
9003 (not (match-end 4)) ; no description
9004 (and (<= (match-beginning 4) (point))
9005 (>= (match-end 4) (point))))))
9006 (throw 'exit (point))))))))
9008 (defun org-get-buffer-for-internal-link (buffer)
9009 "Return a buffer to be used for displaying the link target of internal links."
9010 (cond
9011 ((not org-display-internal-link-with-indirect-buffer)
9012 buffer)
9013 ((string-match "(Clone)$" (buffer-name buffer))
9014 (message "Buffer is already a clone, not making another one")
9015 ;; we also do not modify visibility in this case
9016 buffer)
9017 (t ; make a new indirect buffer for displaying the link
9018 (let* ((bn (buffer-name buffer))
9019 (ibn (concat bn "(Clone)"))
9020 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9021 (with-current-buffer ib (org-overview))
9022 ib))))
9024 (defun org-do-occur (regexp &optional cleanup)
9025 "Call the Emacs command `occur'.
9026 If CLEANUP is non-nil, remove the printout of the regular expression
9027 in the *Occur* buffer. This is useful if the regex is long and not useful
9028 to read."
9029 (occur regexp)
9030 (when cleanup
9031 (let ((cwin (selected-window)) win beg end)
9032 (when (setq win (get-buffer-window "*Occur*"))
9033 (select-window win))
9034 (goto-char (point-min))
9035 (when (re-search-forward "match[a-z]+" nil t)
9036 (setq beg (match-end 0))
9037 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9038 (setq end (1- (match-beginning 0)))))
9039 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9040 (goto-char (point-min))
9041 (select-window cwin))))
9043 ;;; The mark ring for links jumps
9045 (defvar org-mark-ring nil
9046 "Mark ring for positions before jumps in Org-mode.")
9047 (defvar org-mark-ring-last-goto nil
9048 "Last position in the mark ring used to go back.")
9049 ;; Fill and close the ring
9050 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9051 (loop for i from 1 to org-mark-ring-length do
9052 (push (make-marker) org-mark-ring))
9053 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9054 org-mark-ring)
9056 (defun org-mark-ring-push (&optional pos buffer)
9057 "Put the current position or POS into the mark ring and rotate it."
9058 (interactive)
9059 (setq pos (or pos (point)))
9060 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9061 (move-marker (car org-mark-ring)
9062 (or pos (point))
9063 (or buffer (current-buffer)))
9064 (message "%s"
9065 (substitute-command-keys
9066 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9068 (defun org-mark-ring-goto (&optional n)
9069 "Jump to the previous position in the mark ring.
9070 With prefix arg N, jump back that many stored positions. When
9071 called several times in succession, walk through the entire ring.
9072 Org-mode commands jumping to a different position in the current file,
9073 or to another Org-mode file, automatically push the old position
9074 onto the ring."
9075 (interactive "p")
9076 (let (p m)
9077 (if (eq last-command this-command)
9078 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9079 (setq p org-mark-ring))
9080 (setq org-mark-ring-last-goto p)
9081 (setq m (car p))
9082 (switch-to-buffer (marker-buffer m))
9083 (goto-char m)
9084 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9086 (defun org-remove-angle-brackets (s)
9087 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9088 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9090 (defun org-add-angle-brackets (s)
9091 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9092 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9094 (defun org-remove-double-quotes (s)
9095 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9096 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9099 ;;; Following specific links
9101 (defun org-follow-timestamp-link ()
9102 (cond
9103 ((org-at-date-range-p t)
9104 (let ((org-agenda-start-on-weekday)
9105 (t1 (match-string 1))
9106 (t2 (match-string 2)))
9107 (setq t1 (time-to-days (org-time-string-to-time t1))
9108 t2 (time-to-days (org-time-string-to-time t2)))
9109 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9110 ((org-at-timestamp-p t)
9111 (org-agenda-list nil (time-to-days (org-time-string-to-time
9112 (substring (match-string 1) 0 10)))
9114 (t (error "This should not happen"))))
9117 ;;; Following file links
9118 (defvar org-wait nil)
9119 (defun org-open-file (path &optional in-emacs line search)
9120 "Open the file at PATH.
9121 First, this expands any special file name abbreviations. Then the
9122 configuration variable `org-file-apps' is checked if it contains an
9123 entry for this file type, and if yes, the corresponding command is launched.
9125 If no application is found, Emacs simply visits the file.
9127 With optional prefix argument IN-EMACS, Emacs will visit the file.
9128 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9129 and to use an external application to visit the file.
9131 Optional LINE specifies a line to go to, optional SEARCH a string to
9132 search for. If LINE or SEARCH is given, but IN-EMACS is nil, it will
9133 be assumed that org-open-file was called to open a file: link, and the
9134 original link to match against org-file-apps will be reconstructed
9135 from PATH and whichever of LINE or SEARCH is given.
9137 If the file does not exist, an error is thrown."
9138 (let* ((file (if (equal path "")
9139 buffer-file-name
9140 (substitute-in-file-name (expand-file-name path))))
9141 (apps (append org-file-apps (org-default-apps)))
9142 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9143 (dirp (if remp nil (file-directory-p file)))
9144 (file (if (and dirp org-open-directory-means-index-dot-org)
9145 (concat (file-name-as-directory file) "index.org")
9146 file))
9147 (a-m-a-p (assq 'auto-mode apps))
9148 (dfile (downcase file))
9149 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9150 (link (cond ((and (eq line nil)
9151 (eq search nil))
9152 file)
9153 (line
9154 (concat file "::" (number-to-string line)))
9155 (search
9156 (concat file "::" search))))
9157 (dlink (downcase link))
9158 (old-buffer (current-buffer))
9159 (old-pos (point))
9160 (old-mode major-mode)
9161 ext cmd link-match-data)
9162 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9163 (setq ext (match-string 1 dfile))
9164 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9165 (setq ext (match-string 1 dfile))))
9166 (cond
9167 ((member in-emacs '((16) system))
9168 (setq cmd (cdr (assoc 'system apps))))
9169 (in-emacs (setq cmd 'emacs))
9171 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9172 (and dirp (cdr (assoc 'directory apps)))
9173 ;; if we find a match in org-file-apps, store the match
9174 ;; data for later
9175 (let ((match (assoc-default dlink (org-apps-regexp-alist
9176 apps a-m-a-p)
9177 'string-match)))
9178 (if match
9179 (progn (setq link-match-data (match-data))
9180 match)
9181 nil))
9182 (cdr (assoc ext apps))
9183 (cdr (assoc t apps))))))
9184 (when (eq cmd 'system)
9185 (setq cmd (cdr (assoc 'system apps))))
9186 (when (eq cmd 'default)
9187 (setq cmd (cdr (assoc t apps))))
9188 (when (eq cmd 'mailcap)
9189 (require 'mailcap)
9190 (mailcap-parse-mailcaps)
9191 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9192 (command (mailcap-mime-info mime-type)))
9193 (if (stringp command)
9194 (setq cmd command)
9195 (setq cmd 'emacs))))
9196 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9197 (not (file-exists-p file))
9198 (not org-open-non-existing-files))
9199 (error "No such file: %s" file))
9200 (cond
9201 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9202 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9203 (while (string-match "['\"]%s['\"]" cmd)
9204 (setq cmd (replace-match "%s" t t cmd)))
9205 (while (string-match "%s" cmd)
9206 (setq cmd (replace-match
9207 (save-match-data
9208 (shell-quote-argument
9209 (convert-standard-filename file)))
9210 t t cmd)))
9211 ;; Replace "%1", "%2" etc. in command with group matches from regex
9212 (save-match-data
9213 (let ((match-index 1)
9214 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9215 (set-match-data link-match-data)
9216 (while (<= match-index number-of-groups)
9217 (let ((regex (concat "%" (number-to-string match-index)))
9218 (replace-with (match-string match-index dlink)))
9219 (while (string-match regex cmd)
9220 (setq cmd (replace-match replace-with t t cmd))))
9221 (setq match-index (+ match-index 1)))))
9223 (save-window-excursion
9224 (start-process-shell-command cmd nil cmd)
9225 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9227 ((or (stringp cmd)
9228 (eq cmd 'emacs))
9229 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9230 (widen)
9231 (if line (org-goto-line line)
9232 (if search (org-link-search search))))
9233 ((consp cmd)
9234 (let ((file (convert-standard-filename file)))
9235 (save-match-data
9236 (set-match-data link-match-data)
9237 (eval cmd))))
9238 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9239 (and (org-mode-p) (eq old-mode 'org-mode)
9240 (or (not (equal old-buffer (current-buffer)))
9241 (not (equal old-pos (point))))
9242 (org-mark-ring-push old-pos old-buffer))))
9244 (defun org-default-apps ()
9245 "Return the default applications for this operating system."
9246 (cond
9247 ((eq system-type 'darwin)
9248 org-file-apps-defaults-macosx)
9249 ((eq system-type 'windows-nt)
9250 org-file-apps-defaults-windowsnt)
9251 (t org-file-apps-defaults-gnu)))
9253 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9254 "Convert extensions to regular expressions in the cars of LIST.
9255 Also, weed out any non-string entries, because the return value is used
9256 only for regexp matching.
9257 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9258 point to the symbol `emacs', indicating that the file should
9259 be opened in Emacs."
9260 (append
9261 (delq nil
9262 (mapcar (lambda (x)
9263 (if (not (stringp (car x)))
9265 (if (string-match "\\W" (car x))
9267 (cons (concat "\\." (car x) "\\(::.*\\)?\\'")
9268 (cdr x)))))
9269 list))
9270 (if add-auto-mode
9271 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9273 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9274 (defun org-file-remote-p (file)
9275 "Test whether FILE specifies a location on a remote system.
9276 Return non-nil if the location is indeed remote.
9278 For example, the filename \"/user@host:/foo\" specifies a location
9279 on the system \"/user@host:\"."
9280 (cond ((fboundp 'file-remote-p)
9281 (file-remote-p file))
9282 ((fboundp 'tramp-handle-file-remote-p)
9283 (tramp-handle-file-remote-p file))
9284 ((and (boundp 'ange-ftp-name-format)
9285 (string-match (car ange-ftp-name-format) file))
9287 (t nil)))
9290 ;;;; Refiling
9292 (defun org-get-org-file ()
9293 "Read a filename, with default directory `org-directory'."
9294 (let ((default (or org-default-notes-file remember-data-file)))
9295 (read-file-name (format "File name [%s]: " default)
9296 (file-name-as-directory org-directory)
9297 default)))
9299 (defun org-notes-order-reversed-p ()
9300 "Check if the current file should receive notes in reversed order."
9301 (cond
9302 ((not org-reverse-note-order) nil)
9303 ((eq t org-reverse-note-order) t)
9304 ((not (listp org-reverse-note-order)) nil)
9305 (t (catch 'exit
9306 (let ((all org-reverse-note-order)
9307 entry)
9308 (while (setq entry (pop all))
9309 (if (string-match (car entry) buffer-file-name)
9310 (throw 'exit (cdr entry))))
9311 nil)))))
9313 (defvar org-refile-target-table nil
9314 "The list of refile targets, created by `org-refile'.")
9316 (defvar org-agenda-new-buffers nil
9317 "Buffers created to visit agenda files.")
9319 (defun org-get-refile-targets (&optional default-buffer)
9320 "Produce a table with refile targets."
9321 (let ((case-fold-search nil)
9322 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9323 (entries (or org-refile-targets '((nil . (:level . 1)))))
9324 targets txt re files f desc descre fast-path-p level pos0)
9325 (message "Getting targets...")
9326 (with-current-buffer (or default-buffer (current-buffer))
9327 (while (setq entry (pop entries))
9328 (setq files (car entry) desc (cdr entry))
9329 (setq fast-path-p nil)
9330 (cond
9331 ((null files) (setq files (list (current-buffer))))
9332 ((eq files 'org-agenda-files)
9333 (setq files (org-agenda-files 'unrestricted)))
9334 ((and (symbolp files) (fboundp files))
9335 (setq files (funcall files)))
9336 ((and (symbolp files) (boundp files))
9337 (setq files (symbol-value files))))
9338 (if (stringp files) (setq files (list files)))
9339 (cond
9340 ((eq (car desc) :tag)
9341 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9342 ((eq (car desc) :todo)
9343 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9344 ((eq (car desc) :regexp)
9345 (setq descre (cdr desc)))
9346 ((eq (car desc) :level)
9347 (setq descre (concat "^\\*\\{" (number-to-string
9348 (if org-odd-levels-only
9349 (1- (* 2 (cdr desc)))
9350 (cdr desc)))
9351 "\\}[ \t]")))
9352 ((eq (car desc) :maxlevel)
9353 (setq fast-path-p t)
9354 (setq descre (concat "^\\*\\{1," (number-to-string
9355 (if org-odd-levels-only
9356 (1- (* 2 (cdr desc)))
9357 (cdr desc)))
9358 "\\}[ \t]")))
9359 (t (error "Bad refiling target description %s" desc)))
9360 (while (setq f (pop files))
9361 (with-current-buffer
9362 (if (bufferp f) f (org-get-agenda-file-buffer f))
9363 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9364 (setq f (and f (expand-file-name f)))
9365 (if (eq org-refile-use-outline-path 'file)
9366 (push (list (file-name-nondirectory f) f nil nil) targets))
9367 (save-excursion
9368 (save-restriction
9369 (widen)
9370 (goto-char (point-min))
9371 (while (re-search-forward descre nil t)
9372 (goto-char (setq pos0 (point-at-bol)))
9373 (catch 'next
9374 (when org-refile-target-verify-function
9375 (save-match-data
9376 (or (funcall org-refile-target-verify-function)
9377 (throw 'next t))))
9378 (when (looking-at org-complex-heading-regexp)
9379 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9380 txt (org-link-display-format (match-string 4))
9381 re (concat "^" (regexp-quote
9382 (buffer-substring (match-beginning 1)
9383 (match-end 4)))))
9384 (if (match-end 5) (setq re (concat re "[ \t]+"
9385 (regexp-quote
9386 (match-string 5)))))
9387 (setq re (concat re "[ \t]*$"))
9388 (when org-refile-use-outline-path
9389 (setq txt (mapconcat 'org-protect-slash
9390 (append
9391 (if (eq org-refile-use-outline-path 'file)
9392 (list (file-name-nondirectory
9393 (buffer-file-name (buffer-base-buffer))))
9394 (if (eq org-refile-use-outline-path 'full-file-path)
9395 (list (buffer-file-name (buffer-base-buffer)))))
9396 (org-get-outline-path fast-path-p level txt)
9397 (list txt))
9398 "/")))
9399 (push (list txt f re (point)) targets)))
9400 (when (= (point) pos0)
9401 ;; verification function has not moved point
9402 (goto-char (point-at-eol))))))))))
9403 (message "Getting targets...done")
9404 (nreverse targets)))
9406 (defun org-protect-slash (s)
9407 (while (string-match "/" s)
9408 (setq s (replace-match "\\" t t s)))
9411 (defvar org-olpa (make-vector 20 nil))
9413 (defun org-get-outline-path (&optional fastp level heading)
9414 "Return the outline path to the current entry, as a list.
9415 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9416 routine which makes outline path derivations for an entire file,
9417 avoiding backtracing."
9418 (if fastp
9419 (progn
9420 (if (> level 19)
9421 (error "Outline path failure, more than 19 levels."))
9422 (loop for i from level upto 19 do
9423 (aset org-olpa i nil))
9424 (prog1
9425 (delq nil (append org-olpa nil))
9426 (aset org-olpa level heading)))
9427 (let (rtn case-fold-search)
9428 (save-excursion
9429 (save-restriction
9430 (widen)
9431 (while (org-up-heading-safe)
9432 (when (looking-at org-complex-heading-regexp)
9433 (push (org-match-string-no-properties 4) rtn)))
9434 rtn)))))
9436 (defun org-format-outline-path (path &optional width prefix)
9437 "Format the outlie path PATH for display.
9438 Width is the maximum number of characters that is available.
9439 Prefix is a prefix to be included in the returned string,
9440 such as the file name."
9441 (setq width (or width 79))
9442 (if prefix (setq width (- width (length prefix))))
9443 (if (not path)
9444 (or prefix "")
9445 (let* ((nsteps (length path))
9446 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9447 (maxwidth (if (<= total-width width)
9448 10000 ;; everything fits
9449 ;; we need to shorten the level headings
9450 (/ (- width nsteps) nsteps)))
9451 (org-odd-levels-only nil)
9452 (n 0)
9453 (total (1+ (length prefix))))
9454 (setq maxwidth (max maxwidth 10))
9455 (concat prefix
9456 (mapconcat
9457 (lambda (h)
9458 (setq n (1+ n))
9459 (if (and (= n nsteps) (< maxwidth 10000))
9460 (setq maxwidth (- total-width total)))
9461 (if (< (length h) maxwidth)
9462 (progn (setq total (+ total (length h) 1)) h)
9463 (setq h (substring h 0 (- maxwidth 2))
9464 total (+ total maxwidth 1))
9465 (if (string-match "[ \t]+\\'" h)
9466 (setq h (substring h 0 (match-beginning 0))))
9467 (setq h (concat h "..")))
9468 (org-add-props h nil 'face
9469 (nth (% (1- n) org-n-level-faces)
9470 org-level-faces))
9472 path "/")))))
9474 (defun org-display-outline-path (&optional file current)
9475 "Display the current outline path in the echo area."
9476 (interactive "P")
9477 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9478 (case-fold-search nil)
9479 (path (and (org-mode-p) (org-get-outline-path))))
9480 (if current (setq path (append path
9481 (save-excursion
9482 (org-back-to-heading t)
9483 (if (looking-at org-complex-heading-regexp)
9484 (list (match-string 4)))))))
9485 (message "%s"
9486 (org-format-outline-path
9487 path
9488 (1- (frame-width))
9489 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9491 (defvar org-refile-history nil
9492 "History for refiling operations.")
9494 (defvar org-after-refile-insert-hook nil
9495 "Hook run after `org-refile' has inserted its stuff at the new location.
9496 Note that this is still *before* the stuff will be removed from
9497 the *old* location.")
9499 (defun org-refile (&optional goto default-buffer rfloc)
9500 "Move the entry at point to another heading.
9501 The list of target headings is compiled using the information in
9502 `org-refile-targets', which see. This list is created before each use
9503 and will therefore always be up-to-date.
9505 At the target location, the entry is filed as a subitem of the target heading.
9506 Depending on `org-reverse-note-order', the new subitem will either be the
9507 first or the last subitem.
9509 If there is an active region, all entries in that region will be moved.
9510 However, the region must fulfil the requirement that the first heading
9511 is the first one sets the top-level of the moved text - at most siblings
9512 below it are allowed.
9514 With prefix arg GOTO, the command will only visit the target location,
9515 not actually move anything.
9516 With a double prefix `C-u C-u', go to the location where the last refiling
9517 operation has put the subtree.
9518 With a prefix argument of `2', refile to the running clock.
9520 RFLOC can be a refile location obtained in a different way.
9522 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9523 (interactive "P")
9524 (let* ((cbuf (current-buffer))
9525 (regionp (org-region-active-p))
9526 (region-start (and regionp (region-beginning)))
9527 (region-end (and regionp (region-end)))
9528 (region-length (and regionp (- region-end region-start)))
9529 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9530 pos it nbuf file re level reversed)
9531 (setq last-command nil)
9532 (when regionp
9533 (goto-char region-start)
9534 (or (bolp) (goto-char (point-at-bol)))
9535 (setq region-start (point))
9536 (unless (org-kill-is-subtree-p
9537 (buffer-substring region-start region-end))
9538 (error "The region is not a (sequence of) subtree(s)")))
9539 (if (equal goto '(16))
9540 (org-refile-goto-last-stored)
9541 (when (or
9542 (and (equal goto 2)
9543 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9544 (prog1
9545 (setq it (list (or org-clock-heading "running clock")
9546 (buffer-file-name
9547 (marker-buffer org-clock-hd-marker))
9549 (marker-position org-clock-hd-marker)))
9550 (setq goto nil)))
9551 (setq it (or rfloc
9552 (save-excursion
9553 (org-refile-get-location
9554 (if goto "Goto: " "Refile to: ") default-buffer
9555 org-refile-allow-creating-parent-nodes)))))
9556 (setq file (nth 1 it)
9557 re (nth 2 it)
9558 pos (nth 3 it))
9559 (if (and (not goto)
9561 (equal (buffer-file-name) file)
9562 (if regionp
9563 (and (>= pos region-start)
9564 (<= pos region-end))
9565 (and (>= pos (point))
9566 (< pos (save-excursion
9567 (org-end-of-subtree t t))))))
9568 (error "Cannot refile to position inside the tree or region"))
9570 (setq nbuf (or (find-buffer-visiting file)
9571 (find-file-noselect file)))
9572 (if goto
9573 (progn
9574 (switch-to-buffer nbuf)
9575 (goto-char pos)
9576 (org-show-context 'org-goto))
9577 (if regionp
9578 (progn
9579 (org-kill-new (buffer-substring region-start region-end))
9580 (org-save-markers-in-region region-start region-end))
9581 (org-copy-subtree 1 nil t))
9582 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9583 (find-file-noselect file)))
9584 (setq reversed (org-notes-order-reversed-p))
9585 (save-excursion
9586 (save-restriction
9587 (widen)
9588 (if pos
9589 (progn
9590 (goto-char pos)
9591 (looking-at outline-regexp)
9592 (setq level (org-get-valid-level (funcall outline-level) 1))
9593 (goto-char
9594 (if reversed
9595 (or (outline-next-heading) (point-max))
9596 (or (save-excursion (org-get-next-sibling))
9597 (org-end-of-subtree t t)
9598 (point-max)))))
9599 (setq level 1)
9600 (if (not reversed)
9601 (goto-char (point-max))
9602 (goto-char (point-min))
9603 (or (outline-next-heading) (goto-char (point-max)))))
9604 (if (not (bolp)) (newline))
9605 (org-paste-subtree level)
9606 (when org-log-refile
9607 (org-add-log-setup 'refile nil nil 'findpos
9608 org-log-refile)
9609 (unless (eq org-log-refile 'note)
9610 (save-excursion (org-add-log-note))))
9611 (and org-auto-align-tags (org-set-tags nil t))
9612 (bookmark-set "org-refile-last-stored")
9613 (if (fboundp 'deactivate-mark) (deactivate-mark))
9614 (run-hooks 'org-after-refile-insert-hook))))
9615 (if regionp
9616 (delete-region (point) (+ (point) region-length))
9617 (org-cut-subtree))
9618 (when (featurep 'org-inlinetask)
9619 (org-inlinetask-remove-END-maybe))
9620 (setq org-markers-to-move nil)
9621 (message "Refiled to \"%s\"" (car it))))))
9622 (org-reveal))
9624 (defun org-refile-goto-last-stored ()
9625 "Go to the location where the last refile was stored."
9626 (interactive)
9627 (bookmark-jump "org-refile-last-stored")
9628 (message "This is the location of the last refile"))
9630 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9631 "Prompt the user for a refile location, using PROMPT."
9632 (let ((org-refile-targets org-refile-targets)
9633 (org-refile-use-outline-path org-refile-use-outline-path))
9634 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9635 (unless org-refile-target-table
9636 (error "No refile targets"))
9637 (let* ((cbuf (current-buffer))
9638 (partial-completion-mode nil)
9639 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9640 (cfunc (if (and org-refile-use-outline-path
9641 org-outline-path-complete-in-steps)
9642 'org-olpath-completing-read
9643 'org-icompleting-read))
9644 (extra (if org-refile-use-outline-path "/" ""))
9645 (filename (and cfn (expand-file-name cfn)))
9646 (tbl (mapcar
9647 (lambda (x)
9648 (if (and (not (member org-refile-use-outline-path
9649 '(file full-file-path)))
9650 (not (equal filename (nth 1 x))))
9651 (cons (concat (car x) extra " ("
9652 (file-name-nondirectory (nth 1 x)) ")")
9653 (cdr x))
9654 (cons (concat (car x) extra) (cdr x))))
9655 org-refile-target-table))
9656 (completion-ignore-case t)
9657 pa answ parent-target child parent old-hist)
9658 (setq old-hist org-refile-history)
9659 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9660 nil 'org-refile-history))
9661 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9662 (if pa
9663 (progn
9664 (when (or (not org-refile-history)
9665 (not (eq old-hist org-refile-history))
9666 (not (equal (car pa) (car org-refile-history))))
9667 (setq org-refile-history
9668 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9669 org-refile-history
9670 (cdr org-refile-history))))
9671 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9672 (pop org-refile-history)))
9674 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9675 (progn
9676 (setq parent (match-string 1 answ)
9677 child (match-string 2 answ))
9678 (setq parent-target (or (assoc parent tbl)
9679 (assoc (concat parent "/") tbl)))
9680 (when (and parent-target
9681 (or (eq new-nodes t)
9682 (and (eq new-nodes 'confirm)
9683 (y-or-n-p (format "Create new node \"%s\"? "
9684 child)))))
9685 (org-refile-new-child parent-target child)))
9686 (error "Invalid target location")))))
9688 (defun org-refile-new-child (parent-target child)
9689 "Use refile target PARENT-TARGET to add new CHILD below it."
9690 (unless parent-target
9691 (error "Cannot find parent for new node"))
9692 (let ((file (nth 1 parent-target))
9693 (pos (nth 3 parent-target))
9694 level)
9695 (with-current-buffer (or (find-buffer-visiting file)
9696 (find-file-noselect file))
9697 (save-excursion
9698 (save-restriction
9699 (widen)
9700 (if pos
9701 (goto-char pos)
9702 (goto-char (point-max))
9703 (if (not (bolp)) (newline)))
9704 (when (looking-at outline-regexp)
9705 (setq level (funcall outline-level))
9706 (org-end-of-subtree t t))
9707 (org-back-over-empty-lines)
9708 (insert "\n" (make-string
9709 (if pos (org-get-valid-level level 1) 1) ?*)
9710 " " child "\n")
9711 (beginning-of-line 0)
9712 (list (concat (car parent-target) "/" child) file "" (point)))))))
9714 (defun org-olpath-completing-read (prompt collection &rest args)
9715 "Read an outline path like a file name."
9716 (let ((thetable collection)
9717 (org-completion-use-ido nil) ; does not work with ido.
9718 (org-completion-use-iswitchb nil)) ; or iswitchb
9719 (apply
9720 'org-icompleting-read prompt
9721 (lambda (string predicate &optional flag)
9722 (let (rtn r f (l (length string)))
9723 (cond
9724 ((eq flag nil)
9725 ;; try completion
9726 (try-completion string thetable))
9727 ((eq flag t)
9728 ;; all-completions
9729 (setq rtn (all-completions string thetable predicate))
9730 (mapcar
9731 (lambda (x)
9732 (setq r (substring x l))
9733 (if (string-match " ([^)]*)$" x)
9734 (setq f (match-string 0 x))
9735 (setq f ""))
9736 (if (string-match "/" r)
9737 (concat string (substring r 0 (match-end 0)) f)
9739 rtn))
9740 ((eq flag 'lambda)
9741 ;; exact match?
9742 (assoc string thetable)))
9744 args)))
9746 ;;;; Dynamic blocks
9748 (defun org-find-dblock (name)
9749 "Find the first dynamic block with name NAME in the buffer.
9750 If not found, stay at current position and return nil."
9751 (let (pos)
9752 (save-excursion
9753 (goto-char (point-min))
9754 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9755 nil t)
9756 (match-beginning 0))))
9757 (if pos (goto-char pos))
9758 pos))
9760 (defconst org-dblock-start-re
9761 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9762 "Matches the start line of a dynamic block, with parameters.")
9764 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9765 "Matches the end of a dynamic block.")
9767 (defun org-create-dblock (plist)
9768 "Create a dynamic block section, with parameters taken from PLIST.
9769 PLIST must contain a :name entry which is used as name of the block."
9770 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9771 (end-of-line 1)
9772 (newline))
9773 (let ((col (current-column))
9774 (name (plist-get plist :name)))
9775 (insert "#+BEGIN: " name)
9776 (while plist
9777 (if (eq (car plist) :name)
9778 (setq plist (cddr plist))
9779 (insert " " (prin1-to-string (pop plist)))))
9780 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9781 (beginning-of-line -2)))
9783 (defun org-prepare-dblock ()
9784 "Prepare dynamic block for refresh.
9785 This empties the block, puts the cursor at the insert position and returns
9786 the property list including an extra property :name with the block name."
9787 (unless (looking-at org-dblock-start-re)
9788 (error "Not at a dynamic block"))
9789 (let* ((begdel (1+ (match-end 0)))
9790 (name (org-no-properties (match-string 1)))
9791 (params (append (list :name name)
9792 (read (concat "(" (match-string 3) ")")))))
9793 (save-excursion
9794 (beginning-of-line 1)
9795 (skip-chars-forward " \t")
9796 (setq params (plist-put params :indentation-column (current-column))))
9797 (unless (re-search-forward org-dblock-end-re nil t)
9798 (error "Dynamic block not terminated"))
9799 (setq params
9800 (append params
9801 (list :content (buffer-substring
9802 begdel (match-beginning 0)))))
9803 (delete-region begdel (match-beginning 0))
9804 (goto-char begdel)
9805 (open-line 1)
9806 params))
9808 (defun org-map-dblocks (&optional command)
9809 "Apply COMMAND to all dynamic blocks in the current buffer.
9810 If COMMAND is not given, use `org-update-dblock'."
9811 (let ((cmd (or command 'org-update-dblock)))
9812 (save-excursion
9813 (goto-char (point-min))
9814 (while (re-search-forward org-dblock-start-re nil t)
9815 (goto-char (match-beginning 0))
9816 (save-excursion
9817 (condition-case nil
9818 (funcall cmd)
9819 (error (message "Error during update of dynamic block"))))
9820 (unless (re-search-forward org-dblock-end-re nil t)
9821 (error "Dynamic block not terminated"))))))
9823 (defun org-dblock-update (&optional arg)
9824 "User command for updating dynamic blocks.
9825 Update the dynamic block at point. With prefix ARG, update all dynamic
9826 blocks in the buffer."
9827 (interactive "P")
9828 (if arg
9829 (org-update-all-dblocks)
9830 (or (looking-at org-dblock-start-re)
9831 (org-beginning-of-dblock))
9832 (org-update-dblock)))
9834 (defun org-update-dblock ()
9835 "Update the dynamic block at point
9836 This means to empty the block, parse for parameters and then call
9837 the correct writing function."
9838 (save-window-excursion
9839 (let* ((pos (point))
9840 (line (org-current-line))
9841 (params (org-prepare-dblock))
9842 (name (plist-get params :name))
9843 (indent (plist-get params :indentation-column))
9844 (cmd (intern (concat "org-dblock-write:" name))))
9845 (message "Updating dynamic block `%s' at line %d..." name line)
9846 (funcall cmd params)
9847 (message "Updating dynamic block `%s' at line %d...done" name line)
9848 (goto-char pos)
9849 (when (and indent (> indent 0))
9850 (setq indent (make-string indent ?\ ))
9851 (save-excursion
9852 (org-beginning-of-dblock)
9853 (forward-line 1)
9854 (while (not (looking-at org-dblock-end-re))
9855 (insert indent)
9856 (beginning-of-line 2))
9857 (when (looking-at org-dblock-end-re)
9858 (and (looking-at "[ \t]+")
9859 (replace-match ""))
9860 (insert indent)))))))
9862 (defun org-beginning-of-dblock ()
9863 "Find the beginning of the dynamic block at point.
9864 Error if there is no such block at point."
9865 (let ((pos (point))
9866 beg)
9867 (end-of-line 1)
9868 (if (and (re-search-backward org-dblock-start-re nil t)
9869 (setq beg (match-beginning 0))
9870 (re-search-forward org-dblock-end-re nil t)
9871 (> (match-end 0) pos))
9872 (goto-char beg)
9873 (goto-char pos)
9874 (error "Not in a dynamic block"))))
9876 (defun org-update-all-dblocks ()
9877 "Update all dynamic blocks in the buffer.
9878 This function can be used in a hook."
9879 (when (org-mode-p)
9880 (org-map-dblocks 'org-update-dblock)))
9883 ;;;; Completion
9885 (defconst org-additional-option-like-keywords
9886 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9887 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9888 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9889 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9890 "BEGIN:" "END:"
9891 "ORGTBL" "TBLFM:" "TBLNAME:"
9892 "BEGIN_EXAMPLE" "END_EXAMPLE"
9893 "BEGIN_QUOTE" "END_QUOTE"
9894 "BEGIN_VERSE" "END_VERSE"
9895 "BEGIN_CENTER" "END_CENTER"
9896 "BEGIN_SRC" "END_SRC"
9897 "CATEGORY" "COLUMNS"
9898 "CAPTION" "LABEL"
9899 "SETUPFILE"
9900 "BIND"
9901 "MACRO"))
9903 (defcustom org-structure-template-alist
9905 ("s" "#+begin_src ?\n\n#+end_src"
9906 "<src lang=\"?\">\n\n</src>")
9907 ("e" "#+begin_example\n?\n#+end_example"
9908 "<example>\n?\n</example>")
9909 ("q" "#+begin_quote\n?\n#+end_quote"
9910 "<quote>\n?\n</quote>")
9911 ("v" "#+begin_verse\n?\n#+end_verse"
9912 "<verse>\n?\n/verse>")
9913 ("c" "#+begin_center\n?\n#+end_center"
9914 "<center>\n?\n/center>")
9915 ("l" "#+begin_latex\n?\n#+end_latex"
9916 "<literal style=\"latex\">\n?\n</literal>")
9917 ("L" "#+latex: "
9918 "<literal style=\"latex\">?</literal>")
9919 ("h" "#+begin_html\n?\n#+end_html"
9920 "<literal style=\"html\">\n?\n</literal>")
9921 ("H" "#+html: "
9922 "<literal style=\"html\">?</literal>")
9923 ("a" "#+begin_ascii\n?\n#+end_ascii")
9924 ("A" "#+ascii: ")
9925 ("i" "#+include %file ?"
9926 "<include file=%file markup=\"?\">")
9928 "Structure completion elements.
9929 This is a list of abbreviation keys and values. The value gets inserted
9930 it you type @samp{.} followed by the key and then the completion key,
9931 usually `M-TAB'. %file will be replaced by a file name after prompting
9932 for the file using completion.
9933 There are two templates for each key, the first uses the original Org syntax,
9934 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9935 the default when the /org-mtags.el/ module has been loaded. See also the
9936 variable `org-mtags-prefer-muse-templates'.
9937 This is an experimental feature, it is undecided if it is going to stay in."
9938 :group 'org-completion
9939 :type '(repeat
9940 (string :tag "Key")
9941 (string :tag "Template")
9942 (string :tag "Muse Template")))
9944 (defun org-try-structure-completion ()
9945 "Try to complete a structure template before point.
9946 This looks for strings like \"<e\" on an otherwise empty line and
9947 expands them."
9948 (let ((l (buffer-substring (point-at-bol) (point)))
9950 (when (and (looking-at "[ \t]*$")
9951 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9952 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9953 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9954 (match-beginning 1)) a)
9955 t)))
9957 (defun org-complete-expand-structure-template (start cell)
9958 "Expand a structure template."
9959 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9960 (rpl (nth (if musep 2 1) cell))
9961 (ind ""))
9962 (delete-region start (point))
9963 (when (string-match "\\`#\\+" rpl)
9964 (cond
9965 ((bolp))
9966 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9967 (setq ind (buffer-substring (point-at-bol) (point))))
9968 (t (newline))))
9969 (setq start (point))
9970 (if (string-match "%file" rpl)
9971 (setq rpl (replace-match
9972 (concat
9973 "\""
9974 (save-match-data
9975 (abbreviate-file-name (read-file-name "Include file: ")))
9976 "\"")
9977 t t rpl)))
9978 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9979 (concat "\n" ind)))
9980 (insert rpl)
9981 (if (re-search-backward "\\?" start t) (delete-char 1))))
9984 (defun org-complete (&optional arg)
9985 "Perform completion on word at point.
9986 At the beginning of a headline, this completes TODO keywords as given in
9987 `org-todo-keywords'.
9988 If the current word is preceded by a backslash, completes the TeX symbols
9989 that are supported for HTML support.
9990 If the current word is preceded by \"#+\", completes special words for
9991 setting file options.
9992 In the line after \"#+STARTUP:, complete valid keywords.\"
9993 At all other locations, this simply calls the value of
9994 `org-completion-fallback-command'."
9995 (interactive "P")
9996 (org-without-partial-completion
9997 (catch 'exit
9998 (let* ((a nil)
9999 (end (point))
10000 (beg1 (save-excursion
10001 (skip-chars-backward (org-re "[:alnum:]_@"))
10002 (point)))
10003 (beg (save-excursion
10004 (skip-chars-backward "a-zA-Z0-9_:$")
10005 (point)))
10006 (confirm (lambda (x) (stringp (car x))))
10007 (searchhead (equal (char-before beg) ?*))
10008 (struct
10009 (when (and (member (char-before beg1) '(?. ?<))
10010 (setq a (assoc (buffer-substring beg1 (point))
10011 org-structure-template-alist)))
10012 (org-complete-expand-structure-template (1- beg1) a)
10013 (throw 'exit t)))
10014 (tag (and (equal (char-before beg1) ?:)
10015 (equal (char-after (point-at-bol)) ?*)))
10016 (prop (and (equal (char-before beg1) ?:)
10017 (not (equal (char-after (point-at-bol)) ?*))))
10018 (texp (equal (char-before beg) ?\\))
10019 (link (equal (char-before beg) ?\[))
10020 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10021 beg)
10022 "#+"))
10023 (startup (string-match "^#\\+STARTUP:.*"
10024 (buffer-substring (point-at-bol) (point))))
10025 (completion-ignore-case opt)
10026 (type nil)
10027 (tbl nil)
10028 (table (cond
10029 (opt
10030 (setq type :opt)
10031 (require 'org-exp)
10032 (append
10033 (delq nil
10034 (mapcar
10035 (lambda (x)
10036 (if (string-match
10037 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10038 (cons (match-string 2 x)
10039 (match-string 1 x))))
10040 (org-split-string (org-get-current-options) "\n")))
10041 (mapcar 'list org-additional-option-like-keywords)))
10042 (startup
10043 (setq type :startup)
10044 org-startup-options)
10045 (link (append org-link-abbrev-alist-local
10046 org-link-abbrev-alist))
10047 (texp
10048 (setq type :tex)
10049 (append org-entities-user org-entities))
10050 ((string-match "\\`\\*+[ \t]+\\'"
10051 (buffer-substring (point-at-bol) beg))
10052 (setq type :todo)
10053 (mapcar 'list org-todo-keywords-1))
10054 (searchhead
10055 (setq type :searchhead)
10056 (save-excursion
10057 (goto-char (point-min))
10058 (while (re-search-forward org-todo-line-regexp nil t)
10059 (push (list
10060 (org-make-org-heading-search-string
10061 (match-string 3) t))
10062 tbl)))
10063 tbl)
10064 (tag (setq type :tag beg beg1)
10065 (or org-tag-alist (org-get-buffer-tags)))
10066 (prop (setq type :prop beg beg1)
10067 (mapcar 'list (org-buffer-property-keys nil t t)))
10068 (t (progn
10069 (call-interactively org-completion-fallback-command)
10070 (throw 'exit nil)))))
10071 (pattern (buffer-substring-no-properties beg end))
10072 (completion (try-completion pattern table confirm)))
10073 (cond ((eq completion t)
10074 (if (not (assoc (upcase pattern) table))
10075 (message "Already complete")
10076 (if (and (equal type :opt)
10077 (not (member (car (assoc (upcase pattern) table))
10078 org-additional-option-like-keywords)))
10079 (insert (substring (cdr (assoc (upcase pattern) table))
10080 (length pattern)))
10081 (if (memq type '(:tag :prop)) (insert ":")))))
10082 ((null completion)
10083 (message "Can't find completion for \"%s\"" pattern)
10084 (ding))
10085 ((not (string= pattern completion))
10086 (delete-region beg end)
10087 (if (string-match " +$" completion)
10088 (setq completion (replace-match "" t t completion)))
10089 (insert completion)
10090 (if (get-buffer-window "*Completions*")
10091 (delete-window (get-buffer-window "*Completions*")))
10092 (if (assoc completion table)
10093 (if (eq type :todo) (insert " ")
10094 (if (memq type '(:tag :prop)) (insert ":"))))
10095 (if (and (equal type :opt) (assoc completion table))
10096 (message "%s" (substitute-command-keys
10097 "Press \\[org-complete] again to insert example settings"))))
10099 (message "Making completion list...")
10100 (let ((list (sort (all-completions pattern table confirm)
10101 'string<)))
10102 (with-output-to-temp-buffer "*Completions*"
10103 (condition-case nil
10104 ;; Protection needed for XEmacs and emacs 21
10105 (display-completion-list list pattern)
10106 (error (display-completion-list list)))))
10107 (message "Making completion list...%s" "done")))))))
10109 ;;;; TODO, DEADLINE, Comments
10111 (defun org-toggle-comment ()
10112 "Change the COMMENT state of an entry."
10113 (interactive)
10114 (save-excursion
10115 (org-back-to-heading)
10116 (let (case-fold-search)
10117 (if (looking-at (concat outline-regexp
10118 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10119 (replace-match "" t t nil 1)
10120 (if (looking-at outline-regexp)
10121 (progn
10122 (goto-char (match-end 0))
10123 (insert org-comment-string " ")))))))
10125 (defvar org-last-todo-state-is-todo nil
10126 "This is non-nil when the last TODO state change led to a TODO state.
10127 If the last change removed the TODO tag or switched to DONE, then
10128 this is nil.")
10130 (defvar org-setting-tags nil) ; dynamically skipped
10132 (defun org-parse-local-options (string var)
10133 "Parse STRING for startup setting relevant for variable VAR."
10134 (let ((rtn (symbol-value var))
10135 e opts)
10136 (save-match-data
10137 (if (or (not string) (not (string-match "\\S-" string)))
10139 (setq opts (delq nil (mapcar (lambda (x)
10140 (setq e (assoc x org-startup-options))
10141 (if (eq (nth 1 e) var) e nil))
10142 (org-split-string string "[ \t]+"))))
10143 (if (not opts)
10145 (setq rtn nil)
10146 (while (setq e (pop opts))
10147 (if (not (nth 3 e))
10148 (setq rtn (nth 2 e))
10149 (if (not (listp rtn)) (setq rtn nil))
10150 (push (nth 2 e) rtn)))
10151 rtn)))))
10153 (defvar org-todo-setup-filter-hook nil
10154 "Hook for functions that pre-filter todo specs.
10156 Each function takes a todo spec and returns either `nil' or the spec
10157 transformed into canonical form." )
10159 (defvar org-todo-get-default-hook nil
10160 "Hook for functions that get a default item for todo.
10162 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10163 `nil' or a string to be used for the todo mark." )
10165 (defvar org-agenda-headline-snapshot-before-repeat)
10167 (defun org-todo (&optional arg)
10168 "Change the TODO state of an item.
10169 The state of an item is given by a keyword at the start of the heading,
10170 like
10171 *** TODO Write paper
10172 *** DONE Call mom
10174 The different keywords are specified in the variable `org-todo-keywords'.
10175 By default the available states are \"TODO\" and \"DONE\".
10176 So for this example: when the item starts with TODO, it is changed to DONE.
10177 When it starts with DONE, the DONE is removed. And when neither TODO nor
10178 DONE are present, add TODO at the beginning of the heading.
10180 With C-u prefix arg, use completion to determine the new state.
10181 With numeric prefix arg, switch to that state.
10182 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10183 With a triple C-u prefix, circumvent any state blocking.
10185 For calling through lisp, arg is also interpreted in the following way:
10186 'none -> empty state
10187 \"\"(empty string) -> switch to empty state
10188 'done -> switch to DONE
10189 'nextset -> switch to the next set of keywords
10190 'previousset -> switch to the previous set of keywords
10191 \"WAITING\" -> switch to the specified keyword, but only if it
10192 really is a member of `org-todo-keywords'."
10193 (interactive "P")
10194 (if (equal arg '(16)) (setq arg 'nextset))
10195 (let ((org-blocker-hook org-blocker-hook)
10196 (case-fold-search nil))
10197 (when (equal arg '(64))
10198 (setq arg nil org-blocker-hook nil))
10199 (when (and org-blocker-hook
10200 (or org-inhibit-blocking
10201 (org-entry-get nil "NOBLOCKING")))
10202 (setq org-blocker-hook nil))
10203 (save-excursion
10204 (catch 'exit
10205 (org-back-to-heading t)
10206 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10207 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10208 (looking-at " *"))
10209 (let* ((match-data (match-data))
10210 (startpos (point-at-bol))
10211 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10212 (org-log-done org-log-done)
10213 (org-log-repeat org-log-repeat)
10214 (org-todo-log-states org-todo-log-states)
10215 (this (match-string 1))
10216 (hl-pos (match-beginning 0))
10217 (head (org-get-todo-sequence-head this))
10218 (ass (assoc head org-todo-kwd-alist))
10219 (interpret (nth 1 ass))
10220 (done-word (nth 3 ass))
10221 (final-done-word (nth 4 ass))
10222 (last-state (or this ""))
10223 (completion-ignore-case t)
10224 (member (member this org-todo-keywords-1))
10225 (tail (cdr member))
10226 (state (cond
10227 ((and org-todo-key-trigger
10228 (or (and (equal arg '(4))
10229 (eq org-use-fast-todo-selection 'prefix))
10230 (and (not arg) org-use-fast-todo-selection
10231 (not (eq org-use-fast-todo-selection
10232 'prefix)))))
10233 ;; Use fast selection
10234 (org-fast-todo-selection))
10235 ((and (equal arg '(4))
10236 (or (not org-use-fast-todo-selection)
10237 (not org-todo-key-trigger)))
10238 ;; Read a state with completion
10239 (org-icompleting-read
10240 "State: " (mapcar (lambda(x) (list x))
10241 org-todo-keywords-1)
10242 nil t))
10243 ((eq arg 'right)
10244 (if this
10245 (if tail (car tail) nil)
10246 (car org-todo-keywords-1)))
10247 ((eq arg 'left)
10248 (if (equal member org-todo-keywords-1)
10250 (if this
10251 (nth (- (length org-todo-keywords-1)
10252 (length tail) 2)
10253 org-todo-keywords-1)
10254 (org-last org-todo-keywords-1))))
10255 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10256 (setq arg nil))) ; hack to fall back to cycling
10257 (arg
10258 ;; user or caller requests a specific state
10259 (cond
10260 ((equal arg "") nil)
10261 ((eq arg 'none) nil)
10262 ((eq arg 'done) (or done-word (car org-done-keywords)))
10263 ((eq arg 'nextset)
10264 (or (car (cdr (member head org-todo-heads)))
10265 (car org-todo-heads)))
10266 ((eq arg 'previousset)
10267 (let ((org-todo-heads (reverse org-todo-heads)))
10268 (or (car (cdr (member head org-todo-heads)))
10269 (car org-todo-heads))))
10270 ((car (member arg org-todo-keywords-1)))
10271 ((stringp arg)
10272 (error "State `%s' not valid in this file" arg))
10273 ((nth (1- (prefix-numeric-value arg))
10274 org-todo-keywords-1))))
10275 ((null member) (or head (car org-todo-keywords-1)))
10276 ((equal this final-done-word) nil) ;; -> make empty
10277 ((null tail) nil) ;; -> first entry
10278 ((memq interpret '(type priority))
10279 (if (eq this-command last-command)
10280 (car tail)
10281 (if (> (length tail) 0)
10282 (or done-word (car org-done-keywords))
10283 nil)))
10285 (car tail))))
10286 (state (or
10287 (run-hook-with-args-until-success
10288 'org-todo-get-default-hook state last-state)
10289 state))
10290 (next (if state (concat " " state " ") " "))
10291 (change-plist (list :type 'todo-state-change :from this :to state
10292 :position startpos))
10293 dolog now-done-p)
10294 (when org-blocker-hook
10295 (setq org-last-todo-state-is-todo
10296 (not (member this org-done-keywords)))
10297 (unless (save-excursion
10298 (save-match-data
10299 (run-hook-with-args-until-failure
10300 'org-blocker-hook change-plist)))
10301 (if (interactive-p)
10302 (error "TODO state change from %s to %s blocked" this state)
10303 ;; fail silently
10304 (message "TODO state change from %s to %s blocked" this state)
10305 (throw 'exit nil))))
10306 (store-match-data match-data)
10307 (replace-match next t t)
10308 (unless (pos-visible-in-window-p hl-pos)
10309 (message "TODO state changed to %s" (org-trim next)))
10310 (unless head
10311 (setq head (org-get-todo-sequence-head state)
10312 ass (assoc head org-todo-kwd-alist)
10313 interpret (nth 1 ass)
10314 done-word (nth 3 ass)
10315 final-done-word (nth 4 ass)))
10316 (when (memq arg '(nextset previousset))
10317 (message "Keyword-Set %d/%d: %s"
10318 (- (length org-todo-sets) -1
10319 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10320 (length org-todo-sets)
10321 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10322 (setq org-last-todo-state-is-todo
10323 (not (member state org-done-keywords)))
10324 (setq now-done-p (and (member state org-done-keywords)
10325 (not (member this org-done-keywords))))
10326 (and logging (org-local-logging logging))
10327 (when (and (or org-todo-log-states org-log-done)
10328 (not (eq org-inhibit-logging t))
10329 (not (memq arg '(nextset previousset))))
10330 ;; we need to look at recording a time and note
10331 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10332 (nth 2 (assoc this org-todo-log-states))))
10333 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10334 (setq dolog 'time))
10335 (when (and state
10336 (member state org-not-done-keywords)
10337 (not (member this org-not-done-keywords)))
10338 ;; This is now a todo state and was not one before
10339 ;; If there was a CLOSED time stamp, get rid of it.
10340 (org-add-planning-info nil nil 'closed))
10341 (when (and now-done-p org-log-done)
10342 ;; It is now done, and it was not done before
10343 (org-add-planning-info 'closed (org-current-time))
10344 (if (and (not dolog) (eq 'note org-log-done))
10345 (org-add-log-setup 'done state this 'findpos 'note)))
10346 (when (and state dolog)
10347 ;; This is a non-nil state, and we need to log it
10348 (org-add-log-setup 'state state this 'findpos dolog)))
10349 ;; Fixup tag positioning
10350 (org-todo-trigger-tag-changes state)
10351 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10352 (when org-provide-todo-statistics
10353 (org-update-parent-todo-statistics))
10354 (run-hooks 'org-after-todo-state-change-hook)
10355 (if (and arg (not (member state org-done-keywords)))
10356 (setq head (org-get-todo-sequence-head state)))
10357 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10358 ;; Do we need to trigger a repeat?
10359 (when now-done-p
10360 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10361 ;; This is for the agenda, take a snapshot of the headline.
10362 (save-match-data
10363 (setq org-agenda-headline-snapshot-before-repeat
10364 (org-get-heading))))
10365 (org-auto-repeat-maybe state))
10366 ;; Fixup cursor location if close to the keyword
10367 (if (and (outline-on-heading-p)
10368 (not (bolp))
10369 (save-excursion (beginning-of-line 1)
10370 (looking-at org-todo-line-regexp))
10371 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10372 (progn
10373 (goto-char (or (match-end 2) (match-end 1)))
10374 (and (looking-at " ") (just-one-space))))
10375 (when org-trigger-hook
10376 (save-excursion
10377 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10379 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10380 "Block turning an entry into a TODO, using the hierarchy.
10381 This checks whether the current task should be blocked from state
10382 changes. Such blocking occurs when:
10384 1. The task has children which are not all in a completed state.
10386 2. A task has a parent with the property :ORDERED:, and there
10387 are siblings prior to the current task with incomplete
10388 status.
10390 3. The parent of the task is blocked because it has siblings that should
10391 be done first, or is child of a block grandparent TODO entry."
10393 (if (not org-enforce-todo-dependencies)
10394 t ; if locally turned off don't block
10395 (catch 'dont-block
10396 ;; If this is not a todo state change, or if this entry is already DONE,
10397 ;; do not block
10398 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10399 (member (plist-get change-plist :from)
10400 (cons 'done org-done-keywords))
10401 (member (plist-get change-plist :to)
10402 (cons 'todo org-not-done-keywords))
10403 (not (plist-get change-plist :to)))
10404 (throw 'dont-block t))
10405 ;; If this task has children, and any are undone, it's blocked
10406 (save-excursion
10407 (org-back-to-heading t)
10408 (let ((this-level (funcall outline-level)))
10409 (outline-next-heading)
10410 (let ((child-level (funcall outline-level)))
10411 (while (and (not (eobp))
10412 (> child-level this-level))
10413 ;; this todo has children, check whether they are all
10414 ;; completed
10415 (if (and (not (org-entry-is-done-p))
10416 (org-entry-is-todo-p))
10417 (throw 'dont-block nil))
10418 (outline-next-heading)
10419 (setq child-level (funcall outline-level))))))
10420 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10421 ;; any previous siblings are undone, it's blocked
10422 (save-excursion
10423 (org-back-to-heading t)
10424 (let* ((pos (point))
10425 (parent-pos (and (org-up-heading-safe) (point))))
10426 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10427 (when (and (org-entry-get (point) "ORDERED")
10428 (forward-line 1)
10429 (re-search-forward org-not-done-heading-regexp pos t))
10430 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10431 ;; Search further up the hierarchy, to see if an anchestor is blocked
10432 (while t
10433 (goto-char parent-pos)
10434 (if (not (looking-at org-not-done-heading-regexp))
10435 (throw 'dont-block t)) ; do not block, parent is not a TODO
10436 (setq pos (point))
10437 (setq parent-pos (and (org-up-heading-safe) (point)))
10438 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10439 (when (and (org-entry-get (point) "ORDERED")
10440 (forward-line 1)
10441 (re-search-forward org-not-done-heading-regexp pos t))
10442 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10444 (defcustom org-track-ordered-property-with-tag nil
10445 "Should the ORDERED property also be shown as a tag?
10446 The ORDERED property decides if an entry should require subtasks to be
10447 completed in sequence. Since a property is not very visible, setting
10448 this option means that toggling the ORDERED property with the command
10449 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10450 not relevant for the behavior, but it makes things more visible.
10452 Note that toggling the tag with tags commands will not change the property
10453 and therefore not influence behavior!
10455 This can be t, meaning the tag ORDERED should be used, It can also be a
10456 string to select a different tag for this task."
10457 :group 'org-todo
10458 :type '(choice
10459 (const :tag "No tracking" nil)
10460 (const :tag "Track with ORDERED tag" t)
10461 (string :tag "Use other tag")))
10463 (defun org-toggle-ordered-property ()
10464 "Toggle the ORDERED property of the current entry.
10465 For better visibility, you can track the value of this property with a tag.
10466 See variable `org-track-ordered-property-with-tag'."
10467 (interactive)
10468 (let* ((t1 org-track-ordered-property-with-tag)
10469 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10470 (save-excursion
10471 (org-back-to-heading)
10472 (if (org-entry-get nil "ORDERED")
10473 (progn
10474 (org-delete-property "ORDERED")
10475 (and tag (org-toggle-tag tag 'off))
10476 (message "Subtasks can be completed in arbitrary order"))
10477 (org-entry-put nil "ORDERED" "t")
10478 (and tag (org-toggle-tag tag 'on))
10479 (message "Subtasks must be completed in sequence")))))
10481 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10482 (defun org-block-todo-from-checkboxes (change-plist)
10483 "Block turning an entry into a TODO, using checkboxes.
10484 This checks whether the current task should be blocked from state
10485 changes because there are unchecked boxes in this entry."
10486 (if (not org-enforce-todo-checkbox-dependencies)
10487 t ; if locally turned off don't block
10488 (catch 'dont-block
10489 ;; If this is not a todo state change, or if this entry is already DONE,
10490 ;; do not block
10491 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10492 (member (plist-get change-plist :from)
10493 (cons 'done org-done-keywords))
10494 (member (plist-get change-plist :to)
10495 (cons 'todo org-not-done-keywords))
10496 (not (plist-get change-plist :to)))
10497 (throw 'dont-block t))
10498 ;; If this task has checkboxes that are not checked, it's blocked
10499 (save-excursion
10500 (org-back-to-heading t)
10501 (let ((beg (point)) end)
10502 (outline-next-heading)
10503 (setq end (point))
10504 (goto-char beg)
10505 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10506 end t)
10507 (progn
10508 (if (boundp 'org-blocked-by-checkboxes)
10509 (setq org-blocked-by-checkboxes t))
10510 (throw 'dont-block nil)))))
10511 t))) ; do not block
10513 (defun org-entry-blocked-p ()
10514 "Is the current entry blocked?"
10515 (if (org-entry-get nil "NOBLOCKING")
10516 nil ;; Never block this entry
10517 (not
10518 (run-hook-with-args-until-failure
10519 'org-blocker-hook
10520 (list :type 'todo-state-change
10521 :position (point)
10522 :from 'todo
10523 :to 'done)))))
10525 (defun org-update-statistics-cookies (all)
10526 "Update the statistics cookie, either from TODO or from checkboxes.
10527 This should be called with the cursor in a line with a statistics cookie."
10528 (interactive "P")
10529 (if all
10530 (progn
10531 (org-update-checkbox-count 'all)
10532 (org-map-entries 'org-update-parent-todo-statistics))
10533 (if (not (org-on-heading-p))
10534 (org-update-checkbox-count)
10535 (let ((pos (move-marker (make-marker) (point)))
10536 end l1 l2)
10537 (ignore-errors (org-back-to-heading t))
10538 (if (not (org-on-heading-p))
10539 (org-update-checkbox-count)
10540 (setq l1 (org-outline-level))
10541 (setq end (save-excursion
10542 (outline-next-heading)
10543 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10544 (point)))
10545 (if (and (save-excursion
10546 (re-search-forward
10547 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10548 (not (save-excursion (re-search-forward
10549 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10550 (org-update-checkbox-count)
10551 (if (and l2 (> l2 l1))
10552 (progn
10553 (goto-char end)
10554 (org-update-parent-todo-statistics))
10555 (goto-char pos)
10556 (beginning-of-line 1)
10557 (while (re-search-forward
10558 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10559 (point-at-eol) t)
10560 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10561 (goto-char pos)
10562 (move-marker pos nil)))))
10564 (defvar org-entry-property-inherited-from) ;; defined below
10565 (defun org-update-parent-todo-statistics ()
10566 "Update any statistics cookie in the parent of the current headline.
10567 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10568 the entire subtree and this will travel up the hierarchy and update
10569 statistics everywhere."
10570 (interactive)
10571 (let* ((lim 0) prop
10572 (recursive (or (not org-hierarchical-todo-statistics)
10573 (string-match
10574 "\\<recursive\\>"
10575 (or (setq prop (org-entry-get
10576 nil "COOKIE_DATA" 'inherit)) ""))))
10577 (lim (or (and prop (marker-position
10578 org-entry-property-inherited-from))
10579 lim))
10580 (first t)
10581 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10582 level ltoggle l1 new ndel
10583 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10584 (catch 'exit
10585 (save-excursion
10586 (beginning-of-line 1)
10587 (if (org-at-heading-p)
10588 (setq ltoggle (funcall outline-level))
10589 (error "This should not happen"))
10590 (while (and (setq level (org-up-heading-safe))
10591 (or recursive first)
10592 (>= (point) lim))
10593 (setq first nil cookie-present nil)
10594 (unless (and level
10595 (not (string-match
10596 "\\<checkbox\\>"
10597 (downcase
10598 (or (org-entry-get
10599 nil "COOKIE_DATA")
10600 "")))))
10601 (throw 'exit nil))
10602 (while (re-search-forward box-re (point-at-eol) t)
10603 (setq cnt-all 0 cnt-done 0 cookie-present t)
10604 (setq is-percent (match-end 2))
10605 (save-match-data
10606 (unless (outline-next-heading) (throw 'exit nil))
10607 (while (and (looking-at org-complex-heading-regexp)
10608 (> (setq l1 (length (match-string 1))) level))
10609 (setq kwd (and (or recursive (= l1 ltoggle))
10610 (match-string 2)))
10611 (if (or (eq org-provide-todo-statistics 'all-headlines)
10612 (and (listp org-provide-todo-statistics)
10613 (or (member kwd org-provide-todo-statistics)
10614 (member kwd org-done-keywords))))
10615 (setq cnt-all (1+ cnt-all))
10616 (if (eq org-provide-todo-statistics t)
10617 (and kwd (setq cnt-all (1+ cnt-all)))))
10618 (and (member kwd org-done-keywords)
10619 (setq cnt-done (1+ cnt-done)))
10620 (outline-next-heading)))
10621 (setq new
10622 (if is-percent
10623 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10624 (format "[%d/%d]" cnt-done cnt-all))
10625 ndel (- (match-end 0) (match-beginning 0)))
10626 (goto-char (match-beginning 0))
10627 (insert new)
10628 (delete-region (point) (+ (point) ndel)))
10629 (when cookie-present
10630 (run-hook-with-args 'org-after-todo-statistics-hook
10631 cnt-done (- cnt-all cnt-done))))))
10632 (run-hooks 'org-todo-statistics-hook)))
10634 (defvar org-after-todo-statistics-hook nil
10635 "Hook that is called after a TODO statistics cookie has been updated.
10636 Each function is called with two arguments: the number of not-done entries
10637 and the number of done entries.
10639 For example, the following function, when added to this hook, will switch
10640 an entry to DONE when all children are done, and back to TODO when new
10641 entries are set to a TODO status. Note that this hook is only called
10642 when there is a statistics cookie in the headline!
10644 (defun org-summary-todo (n-done n-not-done)
10645 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10646 (let (org-log-done org-log-states) ; turn off logging
10647 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10650 (defvar org-todo-statistics-hook nil
10651 "Hook that is run whenever Org thinks TODO statistics should be updated.
10652 This hook runs even if there is no statistics cookie present, in which case
10653 `org-after-todo-statistics-hook' would not run.")
10655 (defun org-todo-trigger-tag-changes (state)
10656 "Apply the changes defined in `org-todo-state-tags-triggers'."
10657 (let ((l org-todo-state-tags-triggers)
10658 changes)
10659 (when (or (not state) (equal state ""))
10660 (setq changes (append changes (cdr (assoc "" l)))))
10661 (when (and (stringp state) (> (length state) 0))
10662 (setq changes (append changes (cdr (assoc state l)))))
10663 (when (member state org-not-done-keywords)
10664 (setq changes (append changes (cdr (assoc 'todo l)))))
10665 (when (member state org-done-keywords)
10666 (setq changes (append changes (cdr (assoc 'done l)))))
10667 (dolist (c changes)
10668 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10670 (defun org-local-logging (value)
10671 "Get logging settings from a property VALUE."
10672 (let* (words w a)
10673 ;; directly set the variables, they are already local.
10674 (setq org-log-done nil
10675 org-log-repeat nil
10676 org-todo-log-states nil)
10677 (setq words (org-split-string value))
10678 (while (setq w (pop words))
10679 (cond
10680 ((setq a (assoc w org-startup-options))
10681 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10682 (set (nth 1 a) (nth 2 a))))
10683 ((setq a (org-extract-log-state-settings w))
10684 (and (member (car a) org-todo-keywords-1)
10685 (push a org-todo-log-states)))))))
10687 (defun org-get-todo-sequence-head (kwd)
10688 "Return the head of the TODO sequence to which KWD belongs.
10689 If KWD is not set, check if there is a text property remembering the
10690 right sequence."
10691 (let (p)
10692 (cond
10693 ((not kwd)
10694 (or (get-text-property (point-at-bol) 'org-todo-head)
10695 (progn
10696 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10697 nil (point-at-eol)))
10698 (get-text-property p 'org-todo-head))))
10699 ((not (member kwd org-todo-keywords-1))
10700 (car org-todo-keywords-1))
10701 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10703 (defun org-fast-todo-selection ()
10704 "Fast TODO keyword selection with single keys.
10705 Returns the new TODO keyword, or nil if no state change should occur."
10706 (let* ((fulltable org-todo-key-alist)
10707 (done-keywords org-done-keywords) ;; needed for the faces.
10708 (maxlen (apply 'max (mapcar
10709 (lambda (x)
10710 (if (stringp (car x)) (string-width (car x)) 0))
10711 fulltable)))
10712 (expert nil)
10713 (fwidth (+ maxlen 3 1 3))
10714 (ncol (/ (- (window-width) 4) fwidth))
10715 tg cnt e c tbl
10716 groups ingroup)
10717 (save-excursion
10718 (save-window-excursion
10719 (if expert
10720 (set-buffer (get-buffer-create " *Org todo*"))
10721 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10722 (erase-buffer)
10723 (org-set-local 'org-done-keywords done-keywords)
10724 (setq tbl fulltable cnt 0)
10725 (while (setq e (pop tbl))
10726 (cond
10727 ((equal e '(:startgroup))
10728 (push '() groups) (setq ingroup t)
10729 (when (not (= cnt 0))
10730 (setq cnt 0)
10731 (insert "\n"))
10732 (insert "{ "))
10733 ((equal e '(:endgroup))
10734 (setq ingroup nil cnt 0)
10735 (insert "}\n"))
10736 ((equal e '(:newline))
10737 (when (not (= cnt 0))
10738 (setq cnt 0)
10739 (insert "\n")
10740 (setq e (car tbl))
10741 (while (equal (car tbl) '(:newline))
10742 (insert "\n")
10743 (setq tbl (cdr tbl)))))
10745 (setq tg (car e) c (cdr e))
10746 (if ingroup (push tg (car groups)))
10747 (setq tg (org-add-props tg nil 'face
10748 (org-get-todo-face tg)))
10749 (if (and (= cnt 0) (not ingroup)) (insert " "))
10750 (insert "[" c "] " tg (make-string
10751 (- fwidth 4 (length tg)) ?\ ))
10752 (when (= (setq cnt (1+ cnt)) ncol)
10753 (insert "\n")
10754 (if ingroup (insert " "))
10755 (setq cnt 0)))))
10756 (insert "\n")
10757 (goto-char (point-min))
10758 (if (not expert) (org-fit-window-to-buffer))
10759 (message "[a-z..]:Set [SPC]:clear")
10760 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10761 (cond
10762 ((or (= c ?\C-g)
10763 (and (= c ?q) (not (rassoc c fulltable))))
10764 (setq quit-flag t))
10765 ((= c ?\ ) nil)
10766 ((setq e (rassoc c fulltable) tg (car e))
10768 (t (setq quit-flag t)))))))
10770 (defun org-entry-is-todo-p ()
10771 (member (org-get-todo-state) org-not-done-keywords))
10773 (defun org-entry-is-done-p ()
10774 (member (org-get-todo-state) org-done-keywords))
10776 (defun org-get-todo-state ()
10777 (save-excursion
10778 (org-back-to-heading t)
10779 (and (looking-at org-todo-line-regexp)
10780 (match-end 2)
10781 (match-string 2))))
10783 (defun org-at-date-range-p (&optional inactive-ok)
10784 "Is the cursor inside a date range?"
10785 (interactive)
10786 (save-excursion
10787 (catch 'exit
10788 (let ((pos (point)))
10789 (skip-chars-backward "^[<\r\n")
10790 (skip-chars-backward "<[")
10791 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10792 (>= (match-end 0) pos)
10793 (throw 'exit t))
10794 (skip-chars-backward "^<[\r\n")
10795 (skip-chars-backward "<[")
10796 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10797 (>= (match-end 0) pos)
10798 (throw 'exit t)))
10799 nil)))
10801 (defun org-get-repeat (&optional tagline)
10802 "Check if there is a deadline/schedule with repeater in this entry."
10803 (save-match-data
10804 (save-excursion
10805 (org-back-to-heading t)
10806 (and (re-search-forward (if tagline
10807 (concat tagline "\\s-*" org-repeat-re)
10808 org-repeat-re)
10809 (org-entry-end-position) t)
10810 (match-string-no-properties 1)))))
10812 (defvar org-last-changed-timestamp)
10813 (defvar org-last-inserted-timestamp)
10814 (defvar org-log-post-message)
10815 (defvar org-log-note-purpose)
10816 (defvar org-log-note-how)
10817 (defvar org-log-note-extra)
10818 (defun org-auto-repeat-maybe (done-word)
10819 "Check if the current headline contains a repeated deadline/schedule.
10820 If yes, set TODO state back to what it was and change the base date
10821 of repeating deadline/scheduled time stamps to new date.
10822 This function is run automatically after each state change to a DONE state."
10823 ;; last-state is dynamically scoped into this function
10824 (let* ((repeat (org-get-repeat))
10825 (aa (assoc last-state org-todo-kwd-alist))
10826 (interpret (nth 1 aa))
10827 (head (nth 2 aa))
10828 (whata '(("d" . day) ("m" . month) ("y" . year)))
10829 (msg "Entry repeats: ")
10830 (org-log-done nil)
10831 (org-todo-log-states nil)
10832 (nshiftmax 10) (nshift 0)
10833 re type n what ts time)
10834 (when repeat
10835 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10836 (org-todo (if (eq interpret 'type) last-state head))
10837 (org-entry-put nil "LAST_REPEAT" (format-time-string
10838 (org-time-stamp-format t t)))
10839 (when org-log-repeat
10840 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10841 (memq 'org-add-log-note post-command-hook))
10842 ;; OK, we are already setup for some record
10843 (if (eq org-log-repeat 'note)
10844 ;; make sure we take a note, not only a time stamp
10845 (setq org-log-note-how 'note))
10846 ;; Set up for taking a record
10847 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10848 last-state
10849 'findpos org-log-repeat)))
10850 (org-back-to-heading t)
10851 (org-add-planning-info nil nil 'closed)
10852 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10853 org-deadline-time-regexp "\\)\\|\\("
10854 org-ts-regexp "\\)"))
10855 (while (re-search-forward
10856 re (save-excursion (outline-next-heading) (point)) t)
10857 (setq type (if (match-end 1) org-scheduled-string
10858 (if (match-end 3) org-deadline-string "Plain:"))
10859 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10860 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10861 (setq n (string-to-number (match-string 2 ts))
10862 what (match-string 3 ts))
10863 (if (equal what "w") (setq n (* n 7) what "d"))
10864 ;; Preparation, see if we need to modify the start date for the change
10865 (when (match-end 1)
10866 (setq time (save-match-data (org-time-string-to-time ts)))
10867 (cond
10868 ((equal (match-string 1 ts) ".")
10869 ;; Shift starting date to today
10870 (org-timestamp-change
10871 (- (time-to-days (current-time)) (time-to-days time))
10872 'day))
10873 ((equal (match-string 1 ts) "+")
10874 (while (or (= nshift 0)
10875 (<= (time-to-days time) (time-to-days (current-time))))
10876 (when (= (incf nshift) nshiftmax)
10877 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10878 (error "Abort")))
10879 (org-timestamp-change n (cdr (assoc what whata)))
10880 (org-at-timestamp-p t)
10881 (setq ts (match-string 1))
10882 (setq time (save-match-data (org-time-string-to-time ts))))
10883 (org-timestamp-change (- n) (cdr (assoc what whata)))
10884 ;; rematch, so that we have everything in place for the real shift
10885 (org-at-timestamp-p t)
10886 (setq ts (match-string 1))
10887 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10888 (org-timestamp-change n (cdr (assoc what whata)))
10889 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10890 (setq org-log-post-message msg)
10891 (message "%s" msg))))
10893 (defun org-show-todo-tree (arg)
10894 "Make a compact tree which shows all headlines marked with TODO.
10895 The tree will show the lines where the regexp matches, and all higher
10896 headlines above the match.
10897 With a \\[universal-argument] prefix, prompt for a regexp to match.
10898 With a numeric prefix N, construct a sparse tree for the Nth element
10899 of `org-todo-keywords-1'."
10900 (interactive "P")
10901 (let ((case-fold-search nil)
10902 (kwd-re
10903 (cond ((null arg) org-not-done-regexp)
10904 ((equal arg '(4))
10905 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10906 (mapcar 'list org-todo-keywords-1))))
10907 (concat "\\("
10908 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10909 "\\)\\>")))
10910 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10911 (regexp-quote (nth (1- (prefix-numeric-value arg))
10912 org-todo-keywords-1)))
10913 (t (error "Invalid prefix argument: %s" arg)))))
10914 (message "%d TODO entries found"
10915 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10917 (defun org-deadline (&optional remove time)
10918 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10919 With argument REMOVE, remove any deadline from the item.
10920 When TIME is set, it should be an internal time specification, and the
10921 scheduling will use the corresponding date."
10922 (interactive "P")
10923 (let* ((old-date (org-entry-get nil "DEADLINE"))
10924 (repeater (and old-date
10925 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10926 (match-string 1 old-date))))
10927 (if remove
10928 (progn
10929 (when (and old-date org-log-redeadline)
10930 (org-add-log-setup 'deldeadline nil old-date 'findpos
10931 org-log-redeadline))
10932 (org-remove-timestamp-with-keyword org-deadline-string)
10933 (message "Item no longer has a deadline."))
10934 (org-add-planning-info 'deadline time 'closed)
10935 (when (and old-date org-log-redeadline
10936 (not (equal old-date
10937 (substring org-last-inserted-timestamp 1 -1))))
10938 (org-add-log-setup 'redeadline nil old-date 'findpos
10939 org-log-redeadline))
10940 (when repeater
10941 (save-excursion
10942 (org-back-to-heading t)
10943 (when (re-search-forward (concat org-deadline-string " "
10944 org-last-inserted-timestamp)
10945 (save-excursion
10946 (outline-next-heading) (point)) t)
10947 (goto-char (1- (match-end 0)))
10948 (insert " " repeater)
10949 (setq org-last-inserted-timestamp
10950 (concat (substring org-last-inserted-timestamp 0 -1)
10951 " " repeater
10952 (substring org-last-inserted-timestamp -1))))))
10953 (message "Deadline on %s" org-last-inserted-timestamp))))
10955 (defun org-schedule (&optional remove time)
10956 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10957 With argument REMOVE, remove any scheduling date from the item.
10958 When TIME is set, it should be an internal time specification, and the
10959 scheduling will use the corresponding date."
10960 (interactive "P")
10961 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10962 (repeater (and old-date
10963 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10964 (match-string 1 old-date))))
10965 (if remove
10966 (progn
10967 (when (and old-date org-log-reschedule)
10968 (org-add-log-setup 'delschedule nil old-date 'findpos
10969 org-log-reschedule))
10970 (org-remove-timestamp-with-keyword org-scheduled-string)
10971 (message "Item is no longer scheduled."))
10972 (org-add-planning-info 'scheduled time 'closed)
10973 (when (and old-date org-log-reschedule
10974 (not (equal old-date
10975 (substring org-last-inserted-timestamp 1 -1))))
10976 (org-add-log-setup 'reschedule nil old-date 'findpos
10977 org-log-reschedule))
10978 (when repeater
10979 (save-excursion
10980 (org-back-to-heading t)
10981 (when (re-search-forward (concat org-scheduled-string " "
10982 org-last-inserted-timestamp)
10983 (save-excursion
10984 (outline-next-heading) (point)) t)
10985 (goto-char (1- (match-end 0)))
10986 (insert " " repeater)
10987 (setq org-last-inserted-timestamp
10988 (concat (substring org-last-inserted-timestamp 0 -1)
10989 " " repeater
10990 (substring org-last-inserted-timestamp -1))))))
10991 (message "Scheduled to %s" org-last-inserted-timestamp))))
10993 (defun org-get-scheduled-time (pom &optional inherit)
10994 "Get the scheduled time as a time tuple, of a format suitable
10995 for calling org-schedule with, or if there is no scheduling,
10996 returns nil."
10997 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10998 (when time
10999 (apply 'encode-time (org-parse-time-string time)))))
11001 (defun org-get-deadline-time (pom &optional inherit)
11002 "Get the deadine as a time tuple, of a format suitable for
11003 calling org-deadline with, or if there is no scheduling, returns
11004 nil."
11005 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11006 (when time
11007 (apply 'encode-time (org-parse-time-string time)))))
11009 (defun org-remove-timestamp-with-keyword (keyword)
11010 "Remove all time stamps with KEYWORD in the current entry."
11011 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11012 beg)
11013 (save-excursion
11014 (org-back-to-heading t)
11015 (setq beg (point))
11016 (outline-next-heading)
11017 (while (re-search-backward re beg t)
11018 (replace-match "")
11019 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11020 (equal (char-before) ?\ ))
11021 (backward-delete-char 1)
11022 (if (string-match "^[ \t]*$" (buffer-substring
11023 (point-at-bol) (point-at-eol)))
11024 (delete-region (point-at-bol)
11025 (min (point-max) (1+ (point-at-eol))))))))))
11027 (defun org-add-planning-info (what &optional time &rest remove)
11028 "Insert new timestamp with keyword in the line directly after the headline.
11029 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11030 If non is given, the user is prompted for a date.
11031 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11032 be removed."
11033 (interactive)
11034 (let (org-time-was-given org-end-time-was-given ts
11035 end default-time default-input)
11037 (catch 'exit
11038 (when (and (not time) (memq what '(scheduled deadline)))
11039 ;; Try to get a default date/time from existing timestamp
11040 (save-excursion
11041 (org-back-to-heading t)
11042 (setq end (save-excursion (outline-next-heading) (point)))
11043 (when (re-search-forward (if (eq what 'scheduled)
11044 org-scheduled-time-regexp
11045 org-deadline-time-regexp)
11046 end t)
11047 (setq ts (match-string 1)
11048 default-time
11049 (apply 'encode-time (org-parse-time-string ts))
11050 default-input (and ts (org-get-compact-tod ts))))))
11051 (when what
11052 ;; If necessary, get the time from the user
11053 (setq time (or time (org-read-date nil 'to-time nil nil
11054 default-time default-input))))
11056 (when (and org-insert-labeled-timestamps-at-point
11057 (member what '(scheduled deadline)))
11058 (insert
11059 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11060 (org-insert-time-stamp time org-time-was-given
11061 nil nil nil (list org-end-time-was-given))
11062 (setq what nil))
11063 (save-excursion
11064 (save-restriction
11065 (let (col list elt ts buffer-invisibility-spec)
11066 (org-back-to-heading t)
11067 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11068 (goto-char (match-end 1))
11069 (setq col (current-column))
11070 (goto-char (match-end 0))
11071 (if (eobp) (insert "\n") (forward-char 1))
11072 (when (and (not what)
11073 (not (looking-at
11074 (concat "[ \t]*"
11075 org-keyword-time-not-clock-regexp))))
11076 ;; Nothing to add, nothing to remove...... :-)
11077 (throw 'exit nil))
11078 (if (and (not (looking-at outline-regexp))
11079 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11080 "[^\r\n]*"))
11081 (not (equal (match-string 1) org-clock-string)))
11082 (narrow-to-region (match-beginning 0) (match-end 0))
11083 (insert-before-markers "\n")
11084 (backward-char 1)
11085 (narrow-to-region (point) (point))
11086 (and org-adapt-indentation (org-indent-to-column col)))
11087 ;; Check if we have to remove something.
11088 (setq list (cons what remove))
11089 (while list
11090 (setq elt (pop list))
11091 (goto-char (point-min))
11092 (when (or (and (eq elt 'scheduled)
11093 (re-search-forward org-scheduled-time-regexp nil t))
11094 (and (eq elt 'deadline)
11095 (re-search-forward org-deadline-time-regexp nil t))
11096 (and (eq elt 'closed)
11097 (re-search-forward org-closed-time-regexp nil t)))
11098 (replace-match "")
11099 (if (looking-at "--+<[^>]+>") (replace-match ""))
11100 (skip-chars-backward " ")
11101 (if (looking-at " +") (replace-match ""))))
11102 (goto-char (point-max))
11103 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11104 (when what
11105 (insert
11106 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11107 (cond ((eq what 'scheduled) org-scheduled-string)
11108 ((eq what 'deadline) org-deadline-string)
11109 ((eq what 'closed) org-closed-string))
11110 " ")
11111 (setq ts (org-insert-time-stamp
11112 time
11113 (or org-time-was-given
11114 (and (eq what 'closed) org-log-done-with-time))
11115 (eq what 'closed)
11116 nil nil (list org-end-time-was-given)))
11117 (end-of-line 1))
11118 (goto-char (point-min))
11119 (widen)
11120 (if (and (looking-at "[ \t]+\n")
11121 (equal (char-before) ?\n))
11122 (delete-region (1- (point)) (point-at-eol)))
11123 ts))))))
11125 (defvar org-log-note-marker (make-marker))
11126 (defvar org-log-note-purpose nil)
11127 (defvar org-log-note-state nil)
11128 (defvar org-log-note-previous-state nil)
11129 (defvar org-log-note-how nil)
11130 (defvar org-log-note-extra nil)
11131 (defvar org-log-note-window-configuration nil)
11132 (defvar org-log-note-return-to (make-marker))
11133 (defvar org-log-post-message nil
11134 "Message to be displayed after a log note has been stored.
11135 The auto-repeater uses this.")
11137 (defun org-add-note ()
11138 "Add a note to the current entry.
11139 This is done in the same way as adding a state change note."
11140 (interactive)
11141 (org-add-log-setup 'note nil nil 'findpos nil))
11143 (defvar org-property-end-re)
11144 (defun org-add-log-setup (&optional purpose state prev-state
11145 findpos how &optional extra)
11146 "Set up the post command hook to take a note.
11147 If this is about to TODO state change, the new state is expected in STATE.
11148 When FINDPOS is non-nil, find the correct position for the note in
11149 the current entry. If not, assume that it can be inserted at point.
11150 HOW is an indicator what kind of note should be created.
11151 EXTRA is additional text that will be inserted into the notes buffer."
11152 (let* ((org-log-into-drawer (org-log-into-drawer))
11153 (drawer (cond ((stringp org-log-into-drawer)
11154 org-log-into-drawer)
11155 (org-log-into-drawer "LOGBOOK")
11156 (t nil))))
11157 (save-restriction
11158 (save-excursion
11159 (when findpos
11160 (org-back-to-heading t)
11161 (narrow-to-region (point) (save-excursion
11162 (outline-next-heading) (point)))
11163 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11164 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11165 "[^\r\n]*\\)?"))
11166 (goto-char (match-end 0))
11167 (cond
11168 (drawer
11169 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11170 nil t)
11171 (progn
11172 (goto-char (match-end 0))
11173 (or org-log-states-order-reversed
11174 (and (re-search-forward org-property-end-re nil t)
11175 (goto-char (1- (match-beginning 0))))))
11176 (insert "\n:" drawer ":\n:END:")
11177 (beginning-of-line 0)
11178 (org-indent-line-function)
11179 (beginning-of-line 2)
11180 (org-indent-line-function)
11181 (end-of-line 0)))
11182 ((and org-log-state-notes-insert-after-drawers
11183 (save-excursion
11184 (forward-line) (looking-at org-drawer-regexp)))
11185 (forward-line)
11186 (while (looking-at org-drawer-regexp)
11187 (goto-char (match-end 0))
11188 (re-search-forward org-property-end-re (point-max) t)
11189 (forward-line))
11190 (forward-line -1)))
11191 (unless org-log-states-order-reversed
11192 (and (= (char-after) ?\n) (forward-char 1))
11193 (org-skip-over-state-notes)
11194 (skip-chars-backward " \t\n\r")))
11195 (move-marker org-log-note-marker (point))
11196 (setq org-log-note-purpose purpose
11197 org-log-note-state state
11198 org-log-note-previous-state prev-state
11199 org-log-note-how how
11200 org-log-note-extra extra)
11201 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11203 (defun org-skip-over-state-notes ()
11204 "Skip past the list of State notes in an entry."
11205 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11206 (while (looking-at "[ \t]*- State")
11207 (condition-case nil
11208 (org-next-item)
11209 (error (org-end-of-item)))))
11211 (defun org-add-log-note (&optional purpose)
11212 "Pop up a window for taking a note, and add this note later at point."
11213 (remove-hook 'post-command-hook 'org-add-log-note)
11214 (setq org-log-note-window-configuration (current-window-configuration))
11215 (delete-other-windows)
11216 (move-marker org-log-note-return-to (point))
11217 (switch-to-buffer (marker-buffer org-log-note-marker))
11218 (goto-char org-log-note-marker)
11219 (org-switch-to-buffer-other-window "*Org Note*")
11220 (erase-buffer)
11221 (if (memq org-log-note-how '(time state))
11222 (let (current-prefix-arg) (org-store-log-note))
11223 (let ((org-inhibit-startup t)) (org-mode))
11224 (insert (format "# Insert note for %s.
11225 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11226 (cond
11227 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11228 ((eq org-log-note-purpose 'done) "closed todo item")
11229 ((eq org-log-note-purpose 'state)
11230 (format "state change from \"%s\" to \"%s\""
11231 (or org-log-note-previous-state "")
11232 (or org-log-note-state "")))
11233 ((eq org-log-note-purpose 'reschedule)
11234 "rescheduling")
11235 ((eq org-log-note-purpose 'delschedule)
11236 "no longer scheduled")
11237 ((eq org-log-note-purpose 'redeadline)
11238 "changing deadline")
11239 ((eq org-log-note-purpose 'deldeadline)
11240 "removing deadline")
11241 ((eq org-log-note-purpose 'refile)
11242 "refiling")
11243 ((eq org-log-note-purpose 'note)
11244 "this entry")
11245 (t (error "This should not happen")))))
11246 (if org-log-note-extra (insert org-log-note-extra))
11247 (org-set-local 'org-finish-function 'org-store-log-note)))
11249 (defvar org-note-abort nil) ; dynamically scoped
11250 (defun org-store-log-note ()
11251 "Finish taking a log note, and insert it to where it belongs."
11252 (let ((txt (buffer-string))
11253 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11254 lines ind)
11255 (kill-buffer (current-buffer))
11256 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11257 (setq txt (replace-match "" t t txt)))
11258 (if (string-match "\\s-+\\'" txt)
11259 (setq txt (replace-match "" t t txt)))
11260 (setq lines (org-split-string txt "\n"))
11261 (when (and note (string-match "\\S-" note))
11262 (setq note
11263 (org-replace-escapes
11264 note
11265 (list (cons "%u" (user-login-name))
11266 (cons "%U" user-full-name)
11267 (cons "%t" (format-time-string
11268 (org-time-stamp-format 'long 'inactive)
11269 (current-time)))
11270 (cons "%s" (if org-log-note-state
11271 (concat "\"" org-log-note-state "\"")
11272 ""))
11273 (cons "%S" (if org-log-note-previous-state
11274 (concat "\"" org-log-note-previous-state "\"")
11275 "\"\"")))))
11276 (if lines (setq note (concat note " \\\\")))
11277 (push note lines))
11278 (when (or current-prefix-arg org-note-abort)
11279 (when org-log-into-drawer
11280 (org-remove-empty-drawer-at
11281 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11282 org-log-note-marker))
11283 (setq lines nil))
11284 (when lines
11285 (with-current-buffer (marker-buffer org-log-note-marker)
11286 (save-excursion
11287 (goto-char org-log-note-marker)
11288 (move-marker org-log-note-marker nil)
11289 (end-of-line 1)
11290 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11291 (insert "- " (pop lines))
11292 (org-indent-line-function)
11293 (beginning-of-line 1)
11294 (looking-at "[ \t]*")
11295 (setq ind (concat (match-string 0) " "))
11296 (end-of-line 1)
11297 (while lines (insert "\n" ind (pop lines)))
11298 (message "Note stored")
11299 (org-back-to-heading t)
11300 (org-cycle-hide-drawers 'children)))))
11301 (set-window-configuration org-log-note-window-configuration)
11302 (with-current-buffer (marker-buffer org-log-note-return-to)
11303 (goto-char org-log-note-return-to))
11304 (move-marker org-log-note-return-to nil)
11305 (and org-log-post-message (message "%s" org-log-post-message)))
11307 (defun org-remove-empty-drawer-at (drawer pos)
11308 "Remove an empty drawer DRAWER at position POS.
11309 POS may also be a marker."
11310 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11311 (save-excursion
11312 (save-restriction
11313 (widen)
11314 (goto-char pos)
11315 (if (org-in-regexp
11316 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11317 (replace-match ""))))))
11319 (defun org-sparse-tree (&optional arg)
11320 "Create a sparse tree, prompt for the details.
11321 This command can create sparse trees. You first need to select the type
11322 of match used to create the tree:
11324 t Show entries with a specific TODO keyword.
11325 m Show entries selected by a tags/property match.
11326 p Enter a property name and its value (both with completion on existing
11327 names/values) and show entries with that property.
11328 / Show entries matching a regular expression (`r' can be used as well)
11329 d Show deadlines due within `org-deadline-warning-days'.
11330 b Show deadlines and scheduled items before a date.
11331 a Show deadlines and scheduled items after a date."
11332 (interactive "P")
11333 (let (ans kwd value)
11334 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11335 (setq ans (read-char-exclusive))
11336 (cond
11337 ((equal ans ?d)
11338 (call-interactively 'org-check-deadlines))
11339 ((equal ans ?b)
11340 (call-interactively 'org-check-before-date))
11341 ((equal ans ?a)
11342 (call-interactively 'org-check-after-date))
11343 ((equal ans ?t)
11344 (org-show-todo-tree '(4)))
11345 ((member ans '(?T ?m))
11346 (call-interactively 'org-match-sparse-tree))
11347 ((member ans '(?p ?P))
11348 (setq kwd (org-icompleting-read "Property: "
11349 (mapcar 'list (org-buffer-property-keys))))
11350 (setq value (org-icompleting-read "Value: "
11351 (mapcar 'list (org-property-values kwd))))
11352 (unless (string-match "\\`{.*}\\'" value)
11353 (setq value (concat "\"" value "\"")))
11354 (org-match-sparse-tree arg (concat kwd "=" value)))
11355 ((member ans '(?r ?R ?/))
11356 (call-interactively 'org-occur))
11357 (t (error "No such sparse tree command \"%c\"" ans)))))
11359 (defvar org-occur-highlights nil
11360 "List of overlays used for occur matches.")
11361 (make-variable-buffer-local 'org-occur-highlights)
11362 (defvar org-occur-parameters nil
11363 "Parameters of the active org-occur calls.
11364 This is a list, each call to org-occur pushes as cons cell,
11365 containing the regular expression and the callback, onto the list.
11366 The list can contain several entries if `org-occur' has been called
11367 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11368 will only contain one set of parameters. When the highlights are
11369 removed (for example with `C-c C-c', or with the next edit (depending
11370 on `org-remove-highlights-with-change'), this variable is emptied
11371 as well.")
11372 (make-variable-buffer-local 'org-occur-parameters)
11374 (defun org-occur (regexp &optional keep-previous callback)
11375 "Make a compact tree which shows all matches of REGEXP.
11376 The tree will show the lines where the regexp matches, and all higher
11377 headlines above the match. It will also show the heading after the match,
11378 to make sure editing the matching entry is easy.
11379 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11380 call to `org-occur' will be kept, to allow stacking of calls to this
11381 command.
11382 If CALLBACK is non-nil, it is a function which is called to confirm
11383 that the match should indeed be shown."
11384 (interactive "sRegexp: \nP")
11385 (when (equal regexp "")
11386 (error "Regexp cannot be empty"))
11387 (unless keep-previous
11388 (org-remove-occur-highlights nil nil t))
11389 (push (cons regexp callback) org-occur-parameters)
11390 (let ((cnt 0))
11391 (save-excursion
11392 (goto-char (point-min))
11393 (if (or (not keep-previous) ; do not want to keep
11394 (not org-occur-highlights)) ; no previous matches
11395 ;; hide everything
11396 (org-overview))
11397 (while (re-search-forward regexp nil t)
11398 (when (or (not callback)
11399 (save-match-data (funcall callback)))
11400 (setq cnt (1+ cnt))
11401 (when org-highlight-sparse-tree-matches
11402 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11403 (org-show-context 'occur-tree))))
11404 (when org-remove-highlights-with-change
11405 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11406 nil 'local))
11407 (unless org-sparse-tree-open-archived-trees
11408 (org-hide-archived-subtrees (point-min) (point-max)))
11409 (run-hooks 'org-occur-hook)
11410 (if (interactive-p)
11411 (message "%d match(es) for regexp %s" cnt regexp))
11412 cnt))
11414 (defun org-show-context (&optional key)
11415 "Make sure point and context and visible.
11416 How much context is shown depends upon the variables
11417 `org-show-hierarchy-above', `org-show-following-heading'. and
11418 `org-show-siblings'."
11419 (let ((heading-p (org-on-heading-p t))
11420 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11421 (following-p (org-get-alist-option org-show-following-heading key))
11422 (entry-p (org-get-alist-option org-show-entry-below key))
11423 (siblings-p (org-get-alist-option org-show-siblings key)))
11424 (catch 'exit
11425 ;; Show heading or entry text
11426 (if (and heading-p (not entry-p))
11427 (org-flag-heading nil) ; only show the heading
11428 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11429 (org-show-hidden-entry))) ; show entire entry
11430 (when following-p
11431 ;; Show next sibling, or heading below text
11432 (save-excursion
11433 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11434 (org-flag-heading nil))))
11435 (when siblings-p (org-show-siblings))
11436 (when hierarchy-p
11437 ;; show all higher headings, possibly with siblings
11438 (save-excursion
11439 (while (and (condition-case nil
11440 (progn (org-up-heading-all 1) t)
11441 (error nil))
11442 (not (bobp)))
11443 (org-flag-heading nil)
11444 (when siblings-p (org-show-siblings))))))))
11446 (defvar org-reveal-start-hook nil
11447 "Hook run before revealing a location.")
11449 (defun org-reveal (&optional siblings)
11450 "Show current entry, hierarchy above it, and the following headline.
11451 This can be used to show a consistent set of context around locations
11452 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11453 not t for the search context.
11455 With optional argument SIBLINGS, on each level of the hierarchy all
11456 siblings are shown. This repairs the tree structure to what it would
11457 look like when opened with hierarchical calls to `org-cycle'.
11458 With double optional argument `C-u C-u', go to the parent and show the
11459 entire tree."
11460 (interactive "P")
11461 (run-hooks 'org-reveal-start-hook)
11462 (let ((org-show-hierarchy-above t)
11463 (org-show-following-heading t)
11464 (org-show-siblings (if siblings t org-show-siblings)))
11465 (org-show-context nil))
11466 (when (equal siblings '(16))
11467 (save-excursion
11468 (when (org-up-heading-safe)
11469 (org-show-subtree)
11470 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11472 (defun org-highlight-new-match (beg end)
11473 "Highlight from BEG to END and mark the highlight is an occur headline."
11474 (let ((ov (org-make-overlay beg end)))
11475 (org-overlay-put ov 'face 'secondary-selection)
11476 (push ov org-occur-highlights)))
11478 (defun org-remove-occur-highlights (&optional beg end noremove)
11479 "Remove the occur highlights from the buffer.
11480 BEG and END are ignored. If NOREMOVE is nil, remove this function
11481 from the `before-change-functions' in the current buffer."
11482 (interactive)
11483 (unless org-inhibit-highlight-removal
11484 (mapc 'org-delete-overlay org-occur-highlights)
11485 (setq org-occur-highlights nil)
11486 (setq org-occur-parameters nil)
11487 (unless noremove
11488 (remove-hook 'before-change-functions
11489 'org-remove-occur-highlights 'local))))
11491 ;;;; Priorities
11493 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11494 "Regular expression matching the priority indicator.")
11496 (defvar org-remove-priority-next-time nil)
11498 (defun org-priority-up ()
11499 "Increase the priority of the current item."
11500 (interactive)
11501 (org-priority 'up))
11503 (defun org-priority-down ()
11504 "Decrease the priority of the current item."
11505 (interactive)
11506 (org-priority 'down))
11508 (defun org-priority (&optional action)
11509 "Change the priority of an item by ARG.
11510 ACTION can be `set', `up', `down', or a character."
11511 (interactive)
11512 (unless org-enable-priority-commands
11513 (error "Priority commands are disabled"))
11514 (setq action (or action 'set))
11515 (let (current new news have remove)
11516 (save-excursion
11517 (org-back-to-heading t)
11518 (if (looking-at org-priority-regexp)
11519 (setq current (string-to-char (match-string 2))
11520 have t)
11521 (setq current org-default-priority))
11522 (cond
11523 ((eq action 'remove)
11524 (setq remove t new ?\ ))
11525 ((or (eq action 'set)
11526 (if (featurep 'xemacs) (characterp action) (integerp action)))
11527 (if (not (eq action 'set))
11528 (setq new action)
11529 (message "Priority %c-%c, SPC to remove: "
11530 org-highest-priority org-lowest-priority)
11531 (setq new (read-char-exclusive)))
11532 (if (and (= (upcase org-highest-priority) org-highest-priority)
11533 (= (upcase org-lowest-priority) org-lowest-priority))
11534 (setq new (upcase new)))
11535 (cond ((equal new ?\ ) (setq remove t))
11536 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11537 (error "Priority must be between `%c' and `%c'"
11538 org-highest-priority org-lowest-priority))))
11539 ((eq action 'up)
11540 (if (and (not have) (eq last-command this-command))
11541 (setq new org-lowest-priority)
11542 (setq new (if (and org-priority-start-cycle-with-default (not have))
11543 org-default-priority (1- current)))))
11544 ((eq action 'down)
11545 (if (and (not have) (eq last-command this-command))
11546 (setq new org-highest-priority)
11547 (setq new (if (and org-priority-start-cycle-with-default (not have))
11548 org-default-priority (1+ current)))))
11549 (t (error "Invalid action")))
11550 (if (or (< (upcase new) org-highest-priority)
11551 (> (upcase new) org-lowest-priority))
11552 (setq remove t))
11553 (setq news (format "%c" new))
11554 (if have
11555 (if remove
11556 (replace-match "" t t nil 1)
11557 (replace-match news t t nil 2))
11558 (if remove
11559 (error "No priority cookie found in line")
11560 (let ((case-fold-search nil))
11561 (looking-at org-todo-line-regexp))
11562 (if (match-end 2)
11563 (progn
11564 (goto-char (match-end 2))
11565 (insert " [#" news "]"))
11566 (goto-char (match-beginning 3))
11567 (insert "[#" news "] "))))
11568 (org-preserve-lc (org-set-tags nil 'align)))
11569 (if remove
11570 (message "Priority removed")
11571 (message "Priority of current item set to %s" news))))
11573 (defun org-get-priority (s)
11574 "Find priority cookie and return priority."
11575 (save-match-data
11576 (if (not (string-match org-priority-regexp s))
11577 (* 1000 (- org-lowest-priority org-default-priority))
11578 (* 1000 (- org-lowest-priority
11579 (string-to-char (match-string 2 s)))))))
11581 ;;;; Tags
11583 (defvar org-agenda-archives-mode)
11584 (defvar org-map-continue-from nil
11585 "Position from where mapping should continue.
11586 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11588 (defvar org-scanner-tags nil
11589 "The current tag list while the tags scanner is running.")
11590 (defvar org-trust-scanner-tags nil
11591 "Should `org-get-tags-at' use the tags fro the scanner.
11592 This is for internal dynamical scoping only.
11593 When this is non-nil, the function `org-get-tags-at' will return the value
11594 of `org-scanner-tags' instead of building the list by itself. This
11595 can lead to large speed-ups when the tags scanner is used in a file with
11596 many entries, and when the list of tags is retrieved, for example to
11597 obtain a list of properties. Building the tags list for each entry in such
11598 a file becomes an N^2 operation - but with this variable set, it scales
11599 as N.")
11601 (defun org-scan-tags (action matcher &optional todo-only)
11602 "Scan headline tags with inheritance and produce output ACTION.
11604 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11605 or `agenda' to produce an entry list for an agenda view. It can also be
11606 a Lisp form or a function that should be called at each matched headline, in
11607 this case the return value is a list of all return values from these calls.
11609 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11610 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11611 only lines with a TODO keyword are included in the output."
11612 (require 'org-agenda)
11613 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11614 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11615 (org-re
11616 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11617 (props (list 'face 'default
11618 'done-face 'org-agenda-done
11619 'undone-face 'default
11620 'mouse-face 'highlight
11621 'org-not-done-regexp org-not-done-regexp
11622 'org-todo-regexp org-todo-regexp
11623 'help-echo
11624 (format "mouse-2 or RET jump to org file %s"
11625 (abbreviate-file-name
11626 (or (buffer-file-name (buffer-base-buffer))
11627 (buffer-name (buffer-base-buffer)))))))
11628 (case-fold-search nil)
11629 (org-map-continue-from nil)
11630 lspos tags tags-list
11631 (tags-alist (list (cons 0 org-file-tags)))
11632 (llast 0) rtn rtn1 level category i txt
11633 todo marker entry priority)
11634 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11635 (setq action (list 'lambda nil action)))
11636 (save-excursion
11637 (goto-char (point-min))
11638 (when (eq action 'sparse-tree)
11639 (org-overview)
11640 (org-remove-occur-highlights))
11641 (while (re-search-forward re nil t)
11642 (catch :skip
11643 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11644 tags (if (match-end 4) (org-match-string-no-properties 4)))
11645 (goto-char (setq lspos (match-beginning 0)))
11646 (setq level (org-reduced-level (funcall outline-level))
11647 category (org-get-category))
11648 (setq i llast llast level)
11649 ;; remove tag lists from same and sublevels
11650 (while (>= i level)
11651 (when (setq entry (assoc i tags-alist))
11652 (setq tags-alist (delete entry tags-alist)))
11653 (setq i (1- i)))
11654 ;; add the next tags
11655 (when tags
11656 (setq tags (org-split-string tags ":")
11657 tags-alist
11658 (cons (cons level tags) tags-alist)))
11659 ;; compile tags for current headline
11660 (setq tags-list
11661 (if org-use-tag-inheritance
11662 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11663 tags)
11664 org-scanner-tags tags-list)
11665 (when org-use-tag-inheritance
11666 (setcdr (car tags-alist)
11667 (mapcar (lambda (x)
11668 (setq x (copy-sequence x))
11669 (org-add-prop-inherited x))
11670 (cdar tags-alist))))
11671 (when (and tags org-use-tag-inheritance
11672 (or (not (eq t org-use-tag-inheritance))
11673 org-tags-exclude-from-inheritance))
11674 ;; selective inheritance, remove uninherited ones
11675 (setcdr (car tags-alist)
11676 (org-remove-uniherited-tags (cdar tags-alist))))
11677 (when (and (or (not todo-only)
11678 (and (member todo org-not-done-keywords)
11679 (or (not org-agenda-tags-todo-honor-ignore-options)
11680 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11681 (let ((case-fold-search t)) (eval matcher))
11683 (not (member org-archive-tag tags-list))
11684 ;; we have an archive tag, should we use this anyway?
11685 (or (not org-agenda-skip-archived-trees)
11686 (and (eq action 'agenda) org-agenda-archives-mode))))
11687 (unless (eq action 'sparse-tree) (org-agenda-skip))
11689 ;; select this headline
11691 (cond
11692 ((eq action 'sparse-tree)
11693 (and org-highlight-sparse-tree-matches
11694 (org-get-heading) (match-end 0)
11695 (org-highlight-new-match
11696 (match-beginning 0) (match-beginning 1)))
11697 (org-show-context 'tags-tree))
11698 ((eq action 'agenda)
11699 (setq txt (org-format-agenda-item
11701 (concat
11702 (if (eq org-tags-match-list-sublevels 'indented)
11703 (make-string (1- level) ?.) "")
11704 (org-get-heading))
11705 category
11706 tags-list
11708 priority (org-get-priority txt))
11709 (goto-char lspos)
11710 (setq marker (org-agenda-new-marker))
11711 (org-add-props txt props
11712 'org-marker marker 'org-hd-marker marker 'org-category category
11713 'todo-state todo
11714 'priority priority 'type "tagsmatch")
11715 (push txt rtn))
11716 ((functionp action)
11717 (setq org-map-continue-from nil)
11718 (save-excursion
11719 (setq rtn1 (funcall action))
11720 (push rtn1 rtn)))
11721 (t (error "Invalid action")))
11723 ;; if we are to skip sublevels, jump to end of subtree
11724 (unless org-tags-match-list-sublevels
11725 (org-end-of-subtree t)
11726 (backward-char 1))))
11727 ;; Get the correct position from where to continue
11728 (if org-map-continue-from
11729 (goto-char org-map-continue-from)
11730 (and (= (point) lspos) (end-of-line 1)))))
11731 (when (and (eq action 'sparse-tree)
11732 (not org-sparse-tree-open-archived-trees))
11733 (org-hide-archived-subtrees (point-min) (point-max)))
11734 (nreverse rtn)))
11736 (defun org-remove-uniherited-tags (tags)
11737 "Remove all tags that are not inherited from the list TAGS."
11738 (cond
11739 ((eq org-use-tag-inheritance t)
11740 (if org-tags-exclude-from-inheritance
11741 (org-delete-all org-tags-exclude-from-inheritance tags)
11742 tags))
11743 ((not org-use-tag-inheritance) nil)
11744 ((stringp org-use-tag-inheritance)
11745 (delq nil (mapcar
11746 (lambda (x)
11747 (if (and (string-match org-use-tag-inheritance x)
11748 (not (member x org-tags-exclude-from-inheritance)))
11749 x nil))
11750 tags)))
11751 ((listp org-use-tag-inheritance)
11752 (delq nil (mapcar
11753 (lambda (x)
11754 (if (member x org-use-tag-inheritance) x nil))
11755 tags)))))
11757 (defvar todo-only) ;; dynamically scoped
11759 (defun org-match-sparse-tree (&optional todo-only match)
11760 "Create a sparse tree according to tags string MATCH.
11761 MATCH can contain positive and negative selection of tags, like
11762 \"+WORK+URGENT-WITHBOSS\".
11763 If optional argument TODO-ONLY is non-nil, only select lines that are
11764 also TODO lines."
11765 (interactive "P")
11766 (org-prepare-agenda-buffers (list (current-buffer)))
11767 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11769 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11771 (defvar org-cached-props nil)
11772 (defun org-cached-entry-get (pom property)
11773 (if (or (eq t org-use-property-inheritance)
11774 (and (stringp org-use-property-inheritance)
11775 (string-match org-use-property-inheritance property))
11776 (and (listp org-use-property-inheritance)
11777 (member property org-use-property-inheritance)))
11778 ;; Caching is not possible, check it directly
11779 (org-entry-get pom property 'inherit)
11780 ;; Get all properties, so that we can do complicated checks easily
11781 (cdr (assoc property (or org-cached-props
11782 (setq org-cached-props
11783 (org-entry-properties pom)))))))
11785 (defun org-global-tags-completion-table (&optional files)
11786 "Return the list of all tags in all agenda buffer/files."
11787 (save-excursion
11788 (org-uniquify
11789 (delq nil
11790 (apply 'append
11791 (mapcar
11792 (lambda (file)
11793 (set-buffer (find-file-noselect file))
11794 (append (org-get-buffer-tags)
11795 (mapcar (lambda (x) (if (stringp (car-safe x))
11796 (list (car-safe x)) nil))
11797 org-tag-alist)))
11798 (if (and files (car files))
11799 files
11800 (org-agenda-files))))))))
11802 (defun org-make-tags-matcher (match)
11803 "Create the TAGS//TODO matcher form for the selection string MATCH."
11804 ;; todo-only is scoped dynamically into this function, and the function
11805 ;; may change it if the matcher asks for it.
11806 (unless match
11807 ;; Get a new match request, with completion
11808 (let ((org-last-tags-completion-table
11809 (org-global-tags-completion-table)))
11810 (setq match (org-completing-read-no-i
11811 "Match: " 'org-tags-completion-function nil nil nil
11812 'org-tags-history))))
11814 ;; Parse the string and create a lisp form
11815 (let ((match0 match)
11816 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11817 minus tag mm
11818 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11819 orterms term orlist re-p str-p level-p level-op time-p
11820 prop-p pn pv po cat-p gv rest)
11821 (if (string-match "/+" match)
11822 ;; match contains also a todo-matching request
11823 (progn
11824 (setq tagsmatch (substring match 0 (match-beginning 0))
11825 todomatch (substring match (match-end 0)))
11826 (if (string-match "^!" todomatch)
11827 (setq todo-only t todomatch (substring todomatch 1)))
11828 (if (string-match "^\\s-*$" todomatch)
11829 (setq todomatch nil)))
11830 ;; only matching tags
11831 (setq tagsmatch match todomatch nil))
11833 ;; Make the tags matcher
11834 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11835 (setq tagsmatcher t)
11836 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11837 (while (setq term (pop orterms))
11838 (while (and (equal (substring term -1) "\\") orterms)
11839 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11840 (while (string-match re term)
11841 (setq rest (substring term (match-end 0))
11842 minus (and (match-end 1)
11843 (equal (match-string 1 term) "-"))
11844 tag (match-string 2 term)
11845 re-p (equal (string-to-char tag) ?{)
11846 level-p (match-end 4)
11847 prop-p (match-end 5)
11848 mm (cond
11849 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11850 (level-p
11851 (setq level-op (org-op-to-function (match-string 3 term)))
11852 `(,level-op level ,(string-to-number
11853 (match-string 4 term))))
11854 (prop-p
11855 (setq pn (match-string 5 term)
11856 po (match-string 6 term)
11857 pv (match-string 7 term)
11858 cat-p (equal pn "CATEGORY")
11859 re-p (equal (string-to-char pv) ?{)
11860 str-p (equal (string-to-char pv) ?\")
11861 time-p (save-match-data
11862 (string-match "^\"[[<].*[]>]\"$" pv))
11863 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11864 (if time-p (setq pv (org-matcher-time pv)))
11865 (setq po (org-op-to-function po (if time-p 'time str-p)))
11866 (cond
11867 ((equal pn "CATEGORY")
11868 (setq gv '(get-text-property (point) 'org-category)))
11869 ((equal pn "TODO")
11870 (setq gv 'todo))
11872 (setq gv `(org-cached-entry-get nil ,pn))))
11873 (if re-p
11874 (if (eq po 'org<>)
11875 `(not (string-match ,pv (or ,gv "")))
11876 `(string-match ,pv (or ,gv "")))
11877 (if str-p
11878 `(,po (or ,gv "") ,pv)
11879 `(,po (string-to-number (or ,gv ""))
11880 ,(string-to-number pv) ))))
11881 (t `(member ,tag tags-list)))
11882 mm (if minus (list 'not mm) mm)
11883 term rest)
11884 (push mm tagsmatcher))
11885 (push (if (> (length tagsmatcher) 1)
11886 (cons 'and tagsmatcher)
11887 (car tagsmatcher))
11888 orlist)
11889 (setq tagsmatcher nil))
11890 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11891 (setq tagsmatcher
11892 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11893 ;; Make the todo matcher
11894 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11895 (setq todomatcher t)
11896 (setq orterms (org-split-string todomatch "|") orlist nil)
11897 (while (setq term (pop orterms))
11898 (while (string-match re term)
11899 (setq minus (and (match-end 1)
11900 (equal (match-string 1 term) "-"))
11901 kwd (match-string 2 term)
11902 re-p (equal (string-to-char kwd) ?{)
11903 term (substring term (match-end 0))
11904 mm (if re-p
11905 `(string-match ,(substring kwd 1 -1) todo)
11906 (list 'equal 'todo kwd))
11907 mm (if minus (list 'not mm) mm))
11908 (push mm todomatcher))
11909 (push (if (> (length todomatcher) 1)
11910 (cons 'and todomatcher)
11911 (car todomatcher))
11912 orlist)
11913 (setq todomatcher nil))
11914 (setq todomatcher (if (> (length orlist) 1)
11915 (cons 'or orlist) (car orlist))))
11917 ;; Return the string and lisp forms of the matcher
11918 (setq matcher (if todomatcher
11919 (list 'and tagsmatcher todomatcher)
11920 tagsmatcher))
11921 (cons match0 matcher)))
11923 (defun org-op-to-function (op &optional stringp)
11924 "Turn an operator into the appropriate function."
11925 (setq op
11926 (cond
11927 ((equal op "<" ) '(< string< org-time<))
11928 ((equal op ">" ) '(> org-string> org-time>))
11929 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11930 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11931 ((member op '("=" "==")) '(= string= org-time=))
11932 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11933 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11935 (defun org<> (a b) (not (= a b)))
11936 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11937 (defun org-string>= (a b) (not (string< a b)))
11938 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11939 (defun org-string<> (a b) (not (string= a b)))
11940 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11941 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11942 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11943 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11944 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11945 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11946 (defun org-2ft (s)
11947 "Convert S to a floating point time.
11948 If S is already a number, just return it. If it is a string, parse
11949 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11950 (cond
11951 ((numberp s) s)
11952 ((stringp s)
11953 (condition-case nil
11954 (float-time (apply 'encode-time (org-parse-time-string s)))
11955 (error 0.)))
11956 (t 0.)))
11958 (defun org-time-today ()
11959 "Time in seconds today at 0:00.
11960 Returns the float number of seconds since the beginning of the
11961 epoch to the beginning of today (00:00)."
11962 (float-time (apply 'encode-time
11963 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11965 (defun org-matcher-time (s)
11966 "Interpret a time comparison value."
11967 (save-match-data
11968 (cond
11969 ((string= s "<now>") (float-time))
11970 ((string= s "<today>") (org-time-today))
11971 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11972 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11973 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11974 (+ (org-time-today)
11975 (* (string-to-number (match-string 1 s))
11976 (cdr (assoc (match-string 2 s)
11977 '(("d" . 86400.0) ("w" . 604800.0)
11978 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11979 (t (org-2ft s)))))
11981 (defun org-match-any-p (re list)
11982 "Does re match any element of list?"
11983 (setq list (mapcar (lambda (x) (string-match re x)) list))
11984 (delq nil list))
11986 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11987 (defvar org-tags-overlay (org-make-overlay 1 1))
11988 (org-detach-overlay org-tags-overlay)
11990 (defun org-get-local-tags-at (&optional pos)
11991 "Get a list of tags defined in the current headline."
11992 (org-get-tags-at pos 'local))
11994 (defun org-get-local-tags ()
11995 "Get a list of tags defined in the current headline."
11996 (org-get-tags-at nil 'local))
11998 (defun org-get-tags-at (&optional pos local)
11999 "Get a list of all headline tags applicable at POS.
12000 POS defaults to point. If tags are inherited, the list contains
12001 the targets in the same sequence as the headlines appear, i.e.
12002 the tags of the current headline come last.
12003 When LOCAL is non-nil, only return tags from the current headline,
12004 ignore inherited ones."
12005 (interactive)
12006 (if (and org-trust-scanner-tags
12007 (or (not pos) (equal pos (point)))
12008 (not local))
12009 org-scanner-tags
12010 (let (tags ltags lastpos parent)
12011 (save-excursion
12012 (save-restriction
12013 (widen)
12014 (goto-char (or pos (point)))
12015 (save-match-data
12016 (catch 'done
12017 (condition-case nil
12018 (progn
12019 (org-back-to-heading t)
12020 (while (not (equal lastpos (point)))
12021 (setq lastpos (point))
12022 (when (looking-at
12023 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12024 (setq ltags (org-split-string
12025 (org-match-string-no-properties 1) ":"))
12026 (when parent
12027 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12028 (setq tags (append
12029 (if parent
12030 (org-remove-uniherited-tags ltags)
12031 ltags)
12032 tags)))
12033 (or org-use-tag-inheritance (throw 'done t))
12034 (if local (throw 'done t))
12035 (or (org-up-heading-safe) (error nil))
12036 (setq parent t)))
12037 (error nil)))))
12038 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12040 (defun org-add-prop-inherited (s)
12041 (add-text-properties 0 (length s) '(inherited t) s)
12044 (defun org-toggle-tag (tag &optional onoff)
12045 "Toggle the tag TAG for the current line.
12046 If ONOFF is `on' or `off', don't toggle but set to this state."
12047 (let (res current)
12048 (save-excursion
12049 (org-back-to-heading t)
12050 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12051 (point-at-eol) t)
12052 (progn
12053 (setq current (match-string 1))
12054 (replace-match ""))
12055 (setq current ""))
12056 (setq current (nreverse (org-split-string current ":")))
12057 (cond
12058 ((eq onoff 'on)
12059 (setq res t)
12060 (or (member tag current) (push tag current)))
12061 ((eq onoff 'off)
12062 (or (not (member tag current)) (setq current (delete tag current))))
12063 (t (if (member tag current)
12064 (setq current (delete tag current))
12065 (setq res t)
12066 (push tag current))))
12067 (end-of-line 1)
12068 (if current
12069 (progn
12070 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12071 (org-set-tags nil t))
12072 (delete-horizontal-space))
12073 (run-hooks 'org-after-tags-change-hook))
12074 res))
12076 (defun org-align-tags-here (to-col)
12077 ;; Assumes that this is a headline
12078 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12079 (beginning-of-line 1)
12080 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12081 (< pos (match-beginning 2)))
12082 (progn
12083 (setq tags-l (- (match-end 2) (match-beginning 2)))
12084 (goto-char (match-beginning 1))
12085 (insert " ")
12086 (delete-region (point) (1+ (match-beginning 2)))
12087 (setq ncol (max (1+ (current-column))
12088 (1+ col)
12089 (if (> to-col 0)
12090 to-col
12091 (- (abs to-col) tags-l))))
12092 (setq p (point))
12093 (insert (make-string (- ncol (current-column)) ?\ ))
12094 (setq ncol (current-column))
12095 (when indent-tabs-mode (tabify p (point-at-eol)))
12096 (org-move-to-column (min ncol col) t))
12097 (goto-char pos))))
12099 (defun org-set-tags-command (&optional arg just-align)
12100 "Call the set-tags command for the current entry."
12101 (interactive "P")
12102 (if (org-on-heading-p)
12103 (org-set-tags arg just-align)
12104 (save-excursion
12105 (org-back-to-heading t)
12106 (org-set-tags arg just-align))))
12108 (defun org-set-tags-to (data)
12109 "Set the tags of the current entry to DATA, replacing the current tags.
12110 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12111 If DATA is nil or the empty string, any tags will be removed."
12112 (interactive "sTags: ")
12113 (setq data
12114 (cond
12115 ((eq data nil) "")
12116 ((equal data "") "")
12117 ((stringp data)
12118 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12119 ":"))
12120 ((listp data)
12121 (concat ":" (mapconcat 'identity data ":") ":"))
12122 (t nil)))
12123 (when data
12124 (save-excursion
12125 (org-back-to-heading t)
12126 (when (looking-at org-complex-heading-regexp)
12127 (if (match-end 5)
12128 (progn
12129 (goto-char (match-beginning 5))
12130 (insert data)
12131 (delete-region (point) (point-at-eol))
12132 (org-set-tags nil 'align))
12133 (goto-char (point-at-eol))
12134 (insert " " data)
12135 (org-set-tags nil 'align)))
12136 (beginning-of-line 1)
12137 (if (looking-at ".*?\\([ \t]+\\)$")
12138 (delete-region (match-beginning 1) (match-end 1))))))
12140 (defun org-set-tags (&optional arg just-align)
12141 "Set the tags for the current headline.
12142 With prefix ARG, realign all tags in headings in the current buffer."
12143 (interactive "P")
12144 (let* ((re (concat "^" outline-regexp))
12145 (current (org-get-tags-string))
12146 (col (current-column))
12147 (org-setting-tags t)
12148 table current-tags inherited-tags ; computed below when needed
12149 tags p0 c0 c1 rpl)
12150 (if arg
12151 (save-excursion
12152 (goto-char (point-min))
12153 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12154 (while (re-search-forward re nil t)
12155 (org-set-tags nil t)
12156 (end-of-line 1)))
12157 (message "All tags realigned to column %d" org-tags-column))
12158 (if just-align
12159 (setq tags current)
12160 ;; Get a new set of tags from the user
12161 (save-excursion
12162 (setq table (append org-tag-persistent-alist
12163 (or org-tag-alist (org-get-buffer-tags))
12164 (and org-complete-tags-always-offer-all-agenda-tags
12165 (org-global-tags-completion-table (org-agenda-files))))
12166 org-last-tags-completion-table table
12167 current-tags (org-split-string current ":")
12168 inherited-tags (nreverse
12169 (nthcdr (length current-tags)
12170 (nreverse (org-get-tags-at))))
12171 tags
12172 (if (or (eq t org-use-fast-tag-selection)
12173 (and org-use-fast-tag-selection
12174 (delq nil (mapcar 'cdr table))))
12175 (org-fast-tag-selection
12176 current-tags inherited-tags table
12177 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12178 (let ((org-add-colon-after-tag-completion t))
12179 (org-trim
12180 (org-without-partial-completion
12181 (org-icompleting-read "Tags: " 'org-tags-completion-function
12182 nil nil current 'org-tags-history)))))))
12183 (while (string-match "[-+&]+" tags)
12184 ;; No boolean logic, just a list
12185 (setq tags (replace-match ":" t t tags))))
12187 (if org-tags-sort-function
12188 (setq tags (mapconcat 'identity
12189 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12190 org-tags-sort-function) ":")))
12192 (if (string-match "\\`[\t ]*\\'" tags)
12193 (setq tags "")
12194 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12195 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12197 ;; Insert new tags at the correct column
12198 (beginning-of-line 1)
12199 (cond
12200 ((and (equal current "") (equal tags "")))
12201 ((re-search-forward
12202 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12203 (point-at-eol) t)
12204 (if (equal tags "")
12205 (setq rpl "")
12206 (goto-char (match-beginning 0))
12207 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12208 (1+ (point)) (point))
12209 c1 (max (1+ c0) (if (> org-tags-column 0)
12210 org-tags-column
12211 (- (- org-tags-column) (length tags))))
12212 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12213 (replace-match rpl t t)
12214 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12215 tags)
12216 (t (error "Tags alignment failed")))
12217 (org-move-to-column col)
12218 (unless just-align
12219 (run-hooks 'org-after-tags-change-hook)))))
12221 (defun org-change-tag-in-region (beg end tag off)
12222 "Add or remove TAG for each entry in the region.
12223 This works in the agenda, and also in an org-mode buffer."
12224 (interactive
12225 (list (region-beginning) (region-end)
12226 (let ((org-last-tags-completion-table
12227 (if (org-mode-p)
12228 (org-get-buffer-tags)
12229 (org-global-tags-completion-table))))
12230 (org-icompleting-read
12231 "Tag: " 'org-tags-completion-function nil nil nil
12232 'org-tags-history))
12233 (progn
12234 (message "[s]et or [r]emove? ")
12235 (equal (read-char-exclusive) ?r))))
12236 (if (fboundp 'deactivate-mark) (deactivate-mark))
12237 (let ((agendap (equal major-mode 'org-agenda-mode))
12238 l1 l2 m buf pos newhead (cnt 0))
12239 (goto-char end)
12240 (setq l2 (1- (org-current-line)))
12241 (goto-char beg)
12242 (setq l1 (org-current-line))
12243 (loop for l from l1 to l2 do
12244 (org-goto-line l)
12245 (setq m (get-text-property (point) 'org-hd-marker))
12246 (when (or (and (org-mode-p) (org-on-heading-p))
12247 (and agendap m))
12248 (setq buf (if agendap (marker-buffer m) (current-buffer))
12249 pos (if agendap m (point)))
12250 (with-current-buffer buf
12251 (save-excursion
12252 (save-restriction
12253 (goto-char pos)
12254 (setq cnt (1+ cnt))
12255 (org-toggle-tag tag (if off 'off 'on))
12256 (setq newhead (org-get-heading)))))
12257 (and agendap (org-agenda-change-all-lines newhead m))))
12258 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12260 (defun org-tags-completion-function (string predicate &optional flag)
12261 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12262 (confirm (lambda (x) (stringp (car x)))))
12263 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12264 (setq s1 (match-string 1 string)
12265 s2 (match-string 2 string))
12266 (setq s1 "" s2 string))
12267 (cond
12268 ((eq flag nil)
12269 ;; try completion
12270 (setq rtn (try-completion s2 ctable confirm))
12271 (if (stringp rtn)
12272 (setq rtn
12273 (concat s1 s2 (substring rtn (length s2))
12274 (if (and org-add-colon-after-tag-completion
12275 (assoc rtn ctable))
12276 ":" ""))))
12277 rtn)
12278 ((eq flag t)
12279 ;; all-completions
12280 (all-completions s2 ctable confirm)
12282 ((eq flag 'lambda)
12283 ;; exact match?
12284 (assoc s2 ctable)))
12287 (defun org-fast-tag-insert (kwd tags face &optional end)
12288 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12289 (insert (format "%-12s" (concat kwd ":"))
12290 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12291 (or end "")))
12293 (defun org-fast-tag-show-exit (flag)
12294 (save-excursion
12295 (org-goto-line 3)
12296 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12297 (replace-match ""))
12298 (when flag
12299 (end-of-line 1)
12300 (org-move-to-column (- (window-width) 19) t)
12301 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12303 (defun org-set-current-tags-overlay (current prefix)
12304 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12305 (if (featurep 'xemacs)
12306 (org-overlay-display org-tags-overlay (concat prefix s)
12307 'secondary-selection)
12308 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12309 (org-overlay-display org-tags-overlay (concat prefix s)))))
12311 (defvar org-last-tag-selection-key nil)
12312 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12313 "Fast tag selection with single keys.
12314 CURRENT is the current list of tags in the headline, INHERITED is the
12315 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12316 possibly with grouping information. TODO-TABLE is a similar table with
12317 TODO keywords, should these have keys assigned to them.
12318 If the keys are nil, a-z are automatically assigned.
12319 Returns the new tags string, or nil to not change the current settings."
12320 (let* ((fulltable (append table todo-table))
12321 (maxlen (apply 'max (mapcar
12322 (lambda (x)
12323 (if (stringp (car x)) (string-width (car x)) 0))
12324 fulltable)))
12325 (buf (current-buffer))
12326 (expert (eq org-fast-tag-selection-single-key 'expert))
12327 (buffer-tags nil)
12328 (fwidth (+ maxlen 3 1 3))
12329 (ncol (/ (- (window-width) 4) fwidth))
12330 (i-face 'org-done)
12331 (c-face 'org-todo)
12332 tg cnt e c char c1 c2 ntable tbl rtn
12333 ov-start ov-end ov-prefix
12334 (exit-after-next org-fast-tag-selection-single-key)
12335 (done-keywords org-done-keywords)
12336 groups ingroup)
12337 (save-excursion
12338 (beginning-of-line 1)
12339 (if (looking-at
12340 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12341 (setq ov-start (match-beginning 1)
12342 ov-end (match-end 1)
12343 ov-prefix "")
12344 (setq ov-start (1- (point-at-eol))
12345 ov-end (1+ ov-start))
12346 (skip-chars-forward "^\n\r")
12347 (setq ov-prefix
12348 (concat
12349 (buffer-substring (1- (point)) (point))
12350 (if (> (current-column) org-tags-column)
12352 (make-string (- org-tags-column (current-column)) ?\ ))))))
12353 (org-move-overlay org-tags-overlay ov-start ov-end)
12354 (save-window-excursion
12355 (if expert
12356 (set-buffer (get-buffer-create " *Org tags*"))
12357 (delete-other-windows)
12358 (split-window-vertically)
12359 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12360 (erase-buffer)
12361 (org-set-local 'org-done-keywords done-keywords)
12362 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12363 (org-fast-tag-insert "Current" current c-face "\n\n")
12364 (org-fast-tag-show-exit exit-after-next)
12365 (org-set-current-tags-overlay current ov-prefix)
12366 (setq tbl fulltable char ?a cnt 0)
12367 (while (setq e (pop tbl))
12368 (cond
12369 ((equal (car e) :startgroup)
12370 (push '() groups) (setq ingroup t)
12371 (when (not (= cnt 0))
12372 (setq cnt 0)
12373 (insert "\n"))
12374 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12375 ((equal (car e) :endgroup)
12376 (setq ingroup nil cnt 0)
12377 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12378 ((equal e '(:newline))
12379 (when (not (= cnt 0))
12380 (setq cnt 0)
12381 (insert "\n")
12382 (setq e (car tbl))
12383 (while (equal (car tbl) '(:newline))
12384 (insert "\n")
12385 (setq tbl (cdr tbl)))))
12387 (setq tg (copy-sequence (car e)) c2 nil)
12388 (if (cdr e)
12389 (setq c (cdr e))
12390 ;; automatically assign a character.
12391 (setq c1 (string-to-char
12392 (downcase (substring
12393 tg (if (= (string-to-char tg) ?@) 1 0)))))
12394 (if (or (rassoc c1 ntable) (rassoc c1 table))
12395 (while (or (rassoc char ntable) (rassoc char table))
12396 (setq char (1+ char)))
12397 (setq c2 c1))
12398 (setq c (or c2 char)))
12399 (if ingroup (push tg (car groups)))
12400 (setq tg (org-add-props tg nil 'face
12401 (cond
12402 ((not (assoc tg table))
12403 (org-get-todo-face tg))
12404 ((member tg current) c-face)
12405 ((member tg inherited) i-face)
12406 (t nil))))
12407 (if (and (= cnt 0) (not ingroup)) (insert " "))
12408 (insert "[" c "] " tg (make-string
12409 (- fwidth 4 (length tg)) ?\ ))
12410 (push (cons tg c) ntable)
12411 (when (= (setq cnt (1+ cnt)) ncol)
12412 (insert "\n")
12413 (if ingroup (insert " "))
12414 (setq cnt 0)))))
12415 (setq ntable (nreverse ntable))
12416 (insert "\n")
12417 (goto-char (point-min))
12418 (if (not expert) (org-fit-window-to-buffer))
12419 (setq rtn
12420 (catch 'exit
12421 (while t
12422 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12423 (if (not groups) "no " "")
12424 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12425 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12426 (setq org-last-tag-selection-key c)
12427 (cond
12428 ((= c ?\r) (throw 'exit t))
12429 ((= c ?!)
12430 (setq groups (not groups))
12431 (goto-char (point-min))
12432 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12433 ((= c ?\C-c)
12434 (if (not expert)
12435 (org-fast-tag-show-exit
12436 (setq exit-after-next (not exit-after-next)))
12437 (setq expert nil)
12438 (delete-other-windows)
12439 (split-window-vertically)
12440 (org-switch-to-buffer-other-window " *Org tags*")
12441 (org-fit-window-to-buffer)))
12442 ((or (= c ?\C-g)
12443 (and (= c ?q) (not (rassoc c ntable))))
12444 (org-detach-overlay org-tags-overlay)
12445 (setq quit-flag t))
12446 ((= c ?\ )
12447 (setq current nil)
12448 (if exit-after-next (setq exit-after-next 'now)))
12449 ((= c ?\t)
12450 (condition-case nil
12451 (setq tg (org-icompleting-read
12452 "Tag: "
12453 (or buffer-tags
12454 (with-current-buffer buf
12455 (org-get-buffer-tags)))))
12456 (quit (setq tg "")))
12457 (when (string-match "\\S-" tg)
12458 (add-to-list 'buffer-tags (list tg))
12459 (if (member tg current)
12460 (setq current (delete tg current))
12461 (push tg current)))
12462 (if exit-after-next (setq exit-after-next 'now)))
12463 ((setq e (rassoc c todo-table) tg (car e))
12464 (with-current-buffer buf
12465 (save-excursion (org-todo tg)))
12466 (if exit-after-next (setq exit-after-next 'now)))
12467 ((setq e (rassoc c ntable) tg (car e))
12468 (if (member tg current)
12469 (setq current (delete tg current))
12470 (loop for g in groups do
12471 (if (member tg g)
12472 (mapc (lambda (x)
12473 (setq current (delete x current)))
12474 g)))
12475 (push tg current))
12476 (if exit-after-next (setq exit-after-next 'now))))
12478 ;; Create a sorted list
12479 (setq current
12480 (sort current
12481 (lambda (a b)
12482 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12483 (if (eq exit-after-next 'now) (throw 'exit t))
12484 (goto-char (point-min))
12485 (beginning-of-line 2)
12486 (delete-region (point) (point-at-eol))
12487 (org-fast-tag-insert "Current" current c-face)
12488 (org-set-current-tags-overlay current ov-prefix)
12489 (while (re-search-forward
12490 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12491 (setq tg (match-string 1))
12492 (add-text-properties
12493 (match-beginning 1) (match-end 1)
12494 (list 'face
12495 (cond
12496 ((member tg current) c-face)
12497 ((member tg inherited) i-face)
12498 (t (get-text-property (match-beginning 1) 'face))))))
12499 (goto-char (point-min)))))
12500 (org-detach-overlay org-tags-overlay)
12501 (if rtn
12502 (mapconcat 'identity current ":")
12503 nil))))
12505 (defun org-get-tags-string ()
12506 "Get the TAGS string in the current headline."
12507 (unless (org-on-heading-p t)
12508 (error "Not on a heading"))
12509 (save-excursion
12510 (beginning-of-line 1)
12511 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12512 (org-match-string-no-properties 1)
12513 "")))
12515 (defun org-get-tags ()
12516 "Get the list of tags specified in the current headline."
12517 (org-split-string (org-get-tags-string) ":"))
12519 (defun org-get-buffer-tags ()
12520 "Get a table of all tags used in the buffer, for completion."
12521 (let (tags)
12522 (save-excursion
12523 (goto-char (point-min))
12524 (while (re-search-forward
12525 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12526 (when (equal (char-after (point-at-bol 0)) ?*)
12527 (mapc (lambda (x) (add-to-list 'tags x))
12528 (org-split-string (org-match-string-no-properties 1) ":")))))
12529 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12530 (mapcar 'list tags)))
12532 ;;;; The mapping API
12534 ;;;###autoload
12535 (defun org-map-entries (func &optional match scope &rest skip)
12536 "Call FUNC at each headline selected by MATCH in SCOPE.
12538 FUNC is a function or a lisp form. The function will be called without
12539 arguments, with the cursor positioned at the beginning of the headline.
12540 The return values of all calls to the function will be collected and
12541 returned as a list.
12543 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12544 does not need to preserve point. After evaluation, the cursor will be
12545 moved to the end of the line (presumably of the headline of the
12546 processed entry) and search continues from there. Under some
12547 circumstances, this may not produce the wanted results. For example,
12548 if you have removed (e.g. archived) the current (sub)tree it could
12549 mean that the next entry will be skipped entirely. In such cases, you
12550 can specify the position from where search should continue by making
12551 FUNC set the variable `org-map-continue-from' to the desired buffer
12552 position.
12554 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12555 Only headlines that are matched by this query will be considered during
12556 the iteration. When MATCH is nil or t, all headlines will be
12557 visited by the iteration.
12559 SCOPE determines the scope of this command. It can be any of:
12561 nil The current buffer, respecting the restriction if any
12562 tree The subtree started with the entry at point
12563 file The current buffer, without restriction
12564 file-with-archives
12565 The current buffer, and any archives associated with it
12566 agenda All agenda files
12567 agenda-with-archives
12568 All agenda files with any archive files associated with them
12569 \(file1 file2 ...)
12570 If this is a list, all files in the list will be scanned
12572 The remaining args are treated as settings for the skipping facilities of
12573 the scanner. The following items can be given here:
12575 archive skip trees with the archive tag.
12576 comment skip trees with the COMMENT keyword
12577 function or Emacs Lisp form:
12578 will be used as value for `org-agenda-skip-function', so whenever
12579 the function returns t, FUNC will not be called for that
12580 entry and search will continue from the point where the
12581 function leaves it.
12583 If your function needs to retrieve the tags including inherited tags
12584 at the *current* entry, you can use the value of the variable
12585 `org-scanner-tags' which will be much faster than getting the value
12586 with `org-get-tags-at'. If your function gets properties with
12587 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12588 to t around the call to `org-entry-properties' to get the same speedup.
12589 Note that if your function moves around to retrieve tags and properties at
12590 a *different* entry, you cannot use these techniques."
12591 (let* ((org-agenda-archives-mode nil) ; just to make sure
12592 (org-agenda-skip-archived-trees (memq 'archive skip))
12593 (org-agenda-skip-comment-trees (memq 'comment skip))
12594 (org-agenda-skip-function
12595 (car (org-delete-all '(comment archive) skip)))
12596 (org-tags-match-list-sublevels t)
12597 matcher file res
12598 org-todo-keywords-for-agenda
12599 org-done-keywords-for-agenda
12600 org-todo-keyword-alist-for-agenda
12601 org-drawers-for-agenda
12602 org-tag-alist-for-agenda)
12604 (cond
12605 ((eq match t) (setq matcher t))
12606 ((eq match nil) (setq matcher t))
12607 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12609 (save-excursion
12610 (save-restriction
12611 (when (eq scope 'tree)
12612 (org-back-to-heading t)
12613 (org-narrow-to-subtree)
12614 (setq scope nil))
12616 (if (not scope)
12617 (progn
12618 (org-prepare-agenda-buffers
12619 (list (buffer-file-name (current-buffer))))
12620 (setq res (org-scan-tags func matcher)))
12621 ;; Get the right scope
12622 (cond
12623 ((and scope (listp scope) (symbolp (car scope)))
12624 (setq scope (eval scope)))
12625 ((eq scope 'agenda)
12626 (setq scope (org-agenda-files t)))
12627 ((eq scope 'agenda-with-archives)
12628 (setq scope (org-agenda-files t))
12629 (setq scope (org-add-archive-files scope)))
12630 ((eq scope 'file)
12631 (setq scope (list (buffer-file-name))))
12632 ((eq scope 'file-with-archives)
12633 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12634 (org-prepare-agenda-buffers scope)
12635 (while (setq file (pop scope))
12636 (with-current-buffer (org-find-base-buffer-visiting file)
12637 (save-excursion
12638 (save-restriction
12639 (widen)
12640 (goto-char (point-min))
12641 (setq res (append res (org-scan-tags func matcher))))))))))
12642 res))
12644 ;;;; Properties
12646 ;;; Setting and retrieving properties
12648 (defconst org-special-properties
12649 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12650 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12651 "The special properties valid in Org-mode.
12653 These are properties that are not defined in the property drawer,
12654 but in some other way.")
12656 (defconst org-default-properties
12657 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12658 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12659 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12660 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12661 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12662 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12663 "Some properties that are used by Org-mode for various purposes.
12664 Being in this list makes sure that they are offered for completion.")
12666 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12667 "Regular expression matching the first line of a property drawer.")
12669 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12670 "Regular expression matching the last line of a property drawer.")
12672 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12673 "Regular expression matching the first line of a property drawer.")
12675 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12676 "Regular expression matching the first line of a property drawer.")
12678 (defconst org-property-drawer-re
12679 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12680 org-property-end-re "\\)\n?")
12681 "Matches an entire property drawer.")
12683 (defconst org-clock-drawer-re
12684 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12685 org-property-end-re "\\)\n?")
12686 "Matches an entire clock drawer.")
12688 (defun org-property-action ()
12689 "Do an action on properties."
12690 (interactive)
12691 (let (c)
12692 (org-at-property-p)
12693 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12694 (setq c (read-char-exclusive))
12695 (cond
12696 ((equal c ?s)
12697 (call-interactively 'org-set-property))
12698 ((equal c ?d)
12699 (call-interactively 'org-delete-property))
12700 ((equal c ?D)
12701 (call-interactively 'org-delete-property-globally))
12702 ((equal c ?c)
12703 (call-interactively 'org-compute-property-at-point))
12704 (t (error "No such property action %c" c)))))
12706 (defun org-set-effort (&optional value)
12707 "Set the effort property of the current entry.
12708 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12709 allowed value."
12710 (interactive "P")
12711 (if (equal value 0) (setq value 10))
12712 (let* ((completion-ignore-case t)
12713 (prop org-effort-property)
12714 (cur (org-entry-get nil prop))
12715 (allowed (org-property-get-allowed-values nil prop 'table))
12716 (existing (mapcar 'list (org-property-values prop)))
12718 (val (cond
12719 ((stringp value) value)
12720 ((and allowed (integerp value))
12721 (or (car (nth (1- value) allowed))
12722 (car (org-last allowed))))
12723 (allowed
12724 (message "Select 1-9,0, [RET%s]: %s"
12725 (if cur (concat "=" cur) "")
12726 (mapconcat 'car allowed " "))
12727 (setq rpl (read-char-exclusive))
12728 (if (equal rpl ?\r)
12730 (setq rpl (- rpl ?0))
12731 (if (equal rpl 0) (setq rpl 10))
12732 (if (and (> rpl 0) (<= rpl (length allowed)))
12733 (car (nth (1- rpl) allowed))
12734 (org-completing-read "Effort: " allowed nil))))
12736 (let (org-completion-use-ido org-completion-use-iswitchb)
12737 (org-completing-read
12738 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12739 (concat "[" cur "]") "")
12740 ": ")
12741 existing nil nil "" nil cur))))))
12742 (unless (equal (org-entry-get nil prop) val)
12743 (org-entry-put nil prop val))
12744 (message "%s is now %s" prop val)))
12746 (defun org-at-property-p ()
12747 "Is cursor inside a property drawer?"
12748 (save-excursion
12749 (beginning-of-line 1)
12750 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12751 (let ((match (match-data)) ;; Keep match-data for use by calling
12752 (p (point)) ;; procedures.
12753 (range (unless (org-before-first-heading-p)
12754 (org-get-property-block))))
12755 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12756 (set-match-data match))))))
12758 (defun org-get-property-block (&optional beg end force)
12759 "Return the (beg . end) range of the body of the property drawer.
12760 BEG and END can be beginning and end of subtree, if not given
12761 they will be found.
12762 If the drawer does not exist and FORCE is non-nil, create the drawer."
12763 (catch 'exit
12764 (save-excursion
12765 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12766 (end (or end (progn (outline-next-heading) (point)))))
12767 (goto-char beg)
12768 (if (re-search-forward org-property-start-re end t)
12769 (setq beg (1+ (match-end 0)))
12770 (if force
12771 (save-excursion
12772 (org-insert-property-drawer)
12773 (setq end (progn (outline-next-heading) (point))))
12774 (throw 'exit nil))
12775 (goto-char beg)
12776 (if (re-search-forward org-property-start-re end t)
12777 (setq beg (1+ (match-end 0)))))
12778 (if (re-search-forward org-property-end-re end t)
12779 (setq end (match-beginning 0))
12780 (or force (throw 'exit nil))
12781 (goto-char beg)
12782 (setq end beg)
12783 (org-indent-line-function)
12784 (insert ":END:\n"))
12785 (cons beg end)))))
12787 (defun org-entry-properties (&optional pom which specific)
12788 "Get all properties of the entry at point-or-marker POM.
12789 This includes the TODO keyword, the tags, time strings for deadline,
12790 scheduled, and clocking, and any additional properties defined in the
12791 entry. The return value is an alist, keys may occur multiple times
12792 if the property key was used several times.
12793 POM may also be nil, in which case the current entry is used.
12794 If WHICH is nil or `all', get all properties. If WHICH is
12795 `special' or `standard', only get that subclass. If WHICH
12796 is a string only get exactly this property. Specific can be a string, the
12797 specific property we are interested in. Specifying it can speed
12798 things up because then unnecessary parsing is avoided."
12799 (setq which (or which 'all))
12800 (org-with-point-at pom
12801 (let ((clockstr (substring org-clock-string 0 -1))
12802 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12803 (case-fold-search nil)
12804 beg end range props sum-props key value string clocksum)
12805 (save-excursion
12806 (when (condition-case nil
12807 (and (org-mode-p) (org-back-to-heading t))
12808 (error nil))
12809 (setq beg (point))
12810 (setq sum-props (get-text-property (point) 'org-summaries))
12811 (setq clocksum (get-text-property (point) :org-clock-minutes))
12812 (outline-next-heading)
12813 (setq end (point))
12814 (when (memq which '(all special))
12815 ;; Get the special properties, like TODO and tags
12816 (goto-char beg)
12817 (when (and (or (not specific) (string= specific "TODO"))
12818 (looking-at org-todo-line-regexp) (match-end 2))
12819 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12820 (when (and (or (not specific) (string= specific "PRIORITY"))
12821 (looking-at org-priority-regexp))
12822 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12823 (when (and (or (not specific) (string= specific "TAGS"))
12824 (setq value (org-get-tags-string))
12825 (string-match "\\S-" value))
12826 (push (cons "TAGS" value) props))
12827 (when (and (or (not specific) (string= specific "ALLTAGS"))
12828 (setq value (org-get-tags-at)))
12829 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12830 ":"))
12831 props))
12832 (when (or (not specific) (string= specific "BLOCKED"))
12833 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12834 (when (or (not specific)
12835 (member specific org-all-time-keywords)
12836 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12837 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12838 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12839 string (if (equal key clockstr)
12840 (org-no-properties
12841 (org-trim
12842 (buffer-substring
12843 (match-beginning 3) (goto-char (point-at-eol)))))
12844 (substring (org-match-string-no-properties 3) 1 -1)))
12845 (unless key
12846 (if (= (char-after (match-beginning 3)) ?\[)
12847 (setq key "TIMESTAMP_IA")
12848 (setq key "TIMESTAMP")))
12849 (when (or (equal key clockstr) (not (assoc key props)))
12850 (push (cons key string) props))))
12854 (when (memq which '(all standard))
12855 ;; Get the standard properties, like :PROP: ...
12856 (setq range (org-get-property-block beg end))
12857 (when range
12858 (goto-char (car range))
12859 (while (re-search-forward
12860 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12861 (cdr range) t)
12862 (setq key (org-match-string-no-properties 1)
12863 value (org-trim (or (org-match-string-no-properties 2) "")))
12864 (unless (member key excluded)
12865 (push (cons key (or value "")) props)))))
12866 (if clocksum
12867 (push (cons "CLOCKSUM"
12868 (org-columns-number-to-string (/ (float clocksum) 60.)
12869 'add_times))
12870 props))
12871 (unless (assoc "CATEGORY" props)
12872 (setq value (or (org-get-category)
12873 (progn (org-refresh-category-properties)
12874 (org-get-category))))
12875 (push (cons "CATEGORY" value) props))
12876 (append sum-props (nreverse props)))))))
12878 (defun org-entry-get (pom property &optional inherit)
12879 "Get value of PROPERTY for entry at point-or-marker POM.
12880 If INHERIT is non-nil and the entry does not have the property,
12881 then also check higher levels of the hierarchy.
12882 If INHERIT is the symbol `selective', use inheritance only if the setting
12883 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12884 If the property is present but empty, the return value is the empty string.
12885 If the property is not present at all, nil is returned."
12886 (org-with-point-at pom
12887 (if (and inherit (if (eq inherit 'selective)
12888 (org-property-inherit-p property)
12890 (org-entry-get-with-inheritance property)
12891 (if (member property org-special-properties)
12892 ;; We need a special property. Use `org-entry-properties' to
12893 ;; retrieve it, but specify the wanted property
12894 (cdr (assoc property (org-entry-properties nil 'special property)))
12895 (let ((range (org-get-property-block)))
12896 (if (and range
12897 (goto-char (car range))
12898 (re-search-forward
12899 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12900 (cdr range) t))
12901 ;; Found the property, return it.
12902 (if (match-end 1)
12903 (org-match-string-no-properties 1)
12904 "")))))))
12906 (defun org-property-or-variable-value (var &optional inherit)
12907 "Check if there is a property fixing the value of VAR.
12908 If yes, return this value. If not, return the current value of the variable."
12909 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12910 (if (and prop (stringp prop) (string-match "\\S-" prop))
12911 (read prop)
12912 (symbol-value var))))
12914 (defun org-entry-delete (pom property)
12915 "Delete the property PROPERTY from entry at point-or-marker POM."
12916 (org-with-point-at pom
12917 (if (member property org-special-properties)
12918 nil ; cannot delete these properties.
12919 (let ((range (org-get-property-block)))
12920 (if (and range
12921 (goto-char (car range))
12922 (re-search-forward
12923 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12924 (cdr range) t))
12925 (progn
12926 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12928 nil)))))
12930 ;; Multi-values properties are properties that contain multiple values
12931 ;; These values are assumed to be single words, separated by whitespace.
12932 (defun org-entry-add-to-multivalued-property (pom property value)
12933 "Add VALUE to the 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 (unless (member value values)
12938 (setq values (cons value values))
12939 (org-entry-put pom property
12940 (mapconcat 'identity values " ")))))
12942 (defun org-entry-remove-from-multivalued-property (pom property value)
12943 "Remove VALUE from 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 (when (member value values)
12948 (setq values (delete value values))
12949 (org-entry-put pom property
12950 (mapconcat 'identity values " ")))))
12952 (defun org-entry-member-in-multivalued-property (pom property value)
12953 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12954 (let* ((old (org-entry-get pom property))
12955 (values (and old (org-split-string old "[ \t]"))))
12956 (setq value (org-entry-protect-space value))
12957 (member value values)))
12959 (defun org-entry-get-multivalued-property (pom property)
12960 "Return a list of values in a multivalued property."
12961 (let* ((value (org-entry-get pom property))
12962 (values (and value (org-split-string value "[ \t]"))))
12963 (mapcar 'org-entry-restore-space values)))
12965 (defun org-entry-put-multivalued-property (pom property &rest values)
12966 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12967 VALUES should be a list of strings. Spaces will be protected."
12968 (org-entry-put pom property
12969 (mapconcat 'org-entry-protect-space values " "))
12970 (let* ((value (org-entry-get pom property))
12971 (values (and value (org-split-string value "[ \t]"))))
12972 (mapcar 'org-entry-restore-space values)))
12974 (defun org-entry-protect-space (s)
12975 "Protect spaces and newline in string S."
12976 (while (string-match " " s)
12977 (setq s (replace-match "%20" t t s)))
12978 (while (string-match "\n" s)
12979 (setq s (replace-match "%0A" t t s)))
12982 (defun org-entry-restore-space (s)
12983 "Restore spaces and newline in string S."
12984 (while (string-match "%20" s)
12985 (setq s (replace-match " " t t s)))
12986 (while (string-match "%0A" s)
12987 (setq s (replace-match "\n" t t s)))
12990 (defvar org-entry-property-inherited-from (make-marker)
12991 "Marker pointing to the entry from where a property was inherited.
12992 Each call to `org-entry-get-with-inheritance' will set this marker to the
12993 location of the entry where the inheritance search matched. If there was
12994 no match, the marker will point nowhere.
12995 Note that also `org-entry-get' calls this function, if the INHERIT flag
12996 is set.")
12998 (defun org-entry-get-with-inheritance (property)
12999 "Get entry property, and search higher levels if not present."
13000 (move-marker org-entry-property-inherited-from nil)
13001 (let (tmp)
13002 (save-excursion
13003 (save-restriction
13004 (widen)
13005 (catch 'ex
13006 (while t
13007 (when (setq tmp (org-entry-get nil property))
13008 (org-back-to-heading t)
13009 (move-marker org-entry-property-inherited-from (point))
13010 (throw 'ex tmp))
13011 (or (org-up-heading-safe) (throw 'ex nil)))))
13012 (or tmp
13013 (cdr (assoc property org-file-properties))
13014 (cdr (assoc property org-global-properties))
13015 (cdr (assoc property org-global-properties-fixed))))))
13017 (defvar org-property-changed-functions nil
13018 "Hook called when the value of a property has changed.
13019 Each hook function should accept two arguments, the name of the property
13020 and the new value.")
13022 (defun org-entry-put (pom property value)
13023 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13024 (org-with-point-at pom
13025 (org-back-to-heading t)
13026 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13027 range)
13028 (cond
13029 ((equal property "TODO")
13030 (when (and (stringp value) (string-match "\\S-" value)
13031 (not (member value org-todo-keywords-1)))
13032 (error "\"%s\" is not a valid TODO state" value))
13033 (if (or (not value)
13034 (not (string-match "\\S-" value)))
13035 (setq value 'none))
13036 (org-todo value)
13037 (org-set-tags nil 'align))
13038 ((equal property "PRIORITY")
13039 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13040 (string-to-char value) ?\ ))
13041 (org-set-tags nil 'align))
13042 ((equal property "SCHEDULED")
13043 (if (re-search-forward org-scheduled-time-regexp end t)
13044 (cond
13045 ((eq value 'earlier) (org-timestamp-change -1 'day))
13046 ((eq value 'later) (org-timestamp-change 1 'day))
13047 (t (call-interactively 'org-schedule)))
13048 (call-interactively 'org-schedule)))
13049 ((equal property "DEADLINE")
13050 (if (re-search-forward org-deadline-time-regexp end t)
13051 (cond
13052 ((eq value 'earlier) (org-timestamp-change -1 'day))
13053 ((eq value 'later) (org-timestamp-change 1 'day))
13054 (t (call-interactively 'org-deadline)))
13055 (call-interactively 'org-deadline)))
13056 ((member property org-special-properties)
13057 (error "The %s property can not yet be set with `org-entry-put'"
13058 property))
13059 (t ; a non-special property
13060 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13061 (setq range (org-get-property-block beg end 'force))
13062 (goto-char (car range))
13063 (if (re-search-forward
13064 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13065 (progn
13066 (delete-region (match-beginning 1) (match-end 1))
13067 (goto-char (match-beginning 1)))
13068 (goto-char (cdr range))
13069 (insert "\n")
13070 (backward-char 1)
13071 (org-indent-line-function)
13072 (insert ":" property ":"))
13073 (and value (insert " " value))
13074 (org-indent-line-function)))))
13075 (run-hook-with-args 'org-property-changed-functions property value)))
13077 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13078 "Get all property keys in the current buffer.
13079 With INCLUDE-SPECIALS, also list the special properties that reflect things
13080 like tags and TODO state.
13081 With INCLUDE-DEFAULTS, also include properties that has special meaning
13082 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13083 With INCLUDE-COLUMNS, also include property names given in COLUMN
13084 formats in the current buffer."
13085 (let (rtn range cfmt s p)
13086 (save-excursion
13087 (save-restriction
13088 (widen)
13089 (goto-char (point-min))
13090 (while (re-search-forward org-property-start-re nil t)
13091 (setq range (org-get-property-block))
13092 (goto-char (car range))
13093 (while (re-search-forward
13094 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13095 (cdr range) t)
13096 (add-to-list 'rtn (org-match-string-no-properties 1)))
13097 (outline-next-heading))))
13099 (when include-specials
13100 (setq rtn (append org-special-properties rtn)))
13102 (when include-defaults
13103 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13104 (add-to-list 'rtn org-effort-property))
13106 (when include-columns
13107 (save-excursion
13108 (save-restriction
13109 (widen)
13110 (goto-char (point-min))
13111 (while (re-search-forward
13112 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13113 nil t)
13114 (setq cfmt (match-string 2) s 0)
13115 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13116 cfmt s)
13117 (setq s (match-end 0)
13118 p (match-string 1 cfmt))
13119 (unless (or (equal p "ITEM")
13120 (member p org-special-properties))
13121 (add-to-list 'rtn (match-string 1 cfmt))))))))
13123 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13125 (defun org-property-values (key)
13126 "Return a list of all values of property KEY."
13127 (save-excursion
13128 (save-restriction
13129 (widen)
13130 (goto-char (point-min))
13131 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13132 values)
13133 (while (re-search-forward re nil t)
13134 (add-to-list 'values (org-trim (match-string 1))))
13135 (delete "" values)))))
13137 (defun org-insert-property-drawer ()
13138 "Insert a property drawer into the current entry."
13139 (interactive)
13140 (org-back-to-heading t)
13141 (looking-at outline-regexp)
13142 (let ((indent (if org-adapt-indentation
13143 (- (match-end 0)(match-beginning 0))
13145 (beg (point))
13146 (re (concat "^[ \t]*" org-keyword-time-regexp))
13147 end hiddenp)
13148 (outline-next-heading)
13149 (setq end (point))
13150 (goto-char beg)
13151 (while (re-search-forward re end t))
13152 (setq hiddenp (org-invisible-p))
13153 (end-of-line 1)
13154 (and (equal (char-after) ?\n) (forward-char 1))
13155 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13156 (if (member (match-string 1) '("CLOCK:" ":END:"))
13157 ;; just skip this line
13158 (beginning-of-line 2)
13159 ;; Drawer start, find the end
13160 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13161 (beginning-of-line 1)))
13162 (org-skip-over-state-notes)
13163 (skip-chars-backward " \t\n\r")
13164 (if (eq (char-before) ?*) (forward-char 1))
13165 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13166 (beginning-of-line 0)
13167 (org-indent-to-column indent)
13168 (beginning-of-line 2)
13169 (org-indent-to-column indent)
13170 (beginning-of-line 0)
13171 (if hiddenp
13172 (save-excursion
13173 (org-back-to-heading t)
13174 (hide-entry))
13175 (org-flag-drawer t))))
13177 (defun org-set-property (property value)
13178 "In the current entry, set PROPERTY to VALUE.
13179 When called interactively, this will prompt for a property name, offering
13180 completion on existing and default properties. And then it will prompt
13181 for a value, offering completion either on allowed values (via an inherited
13182 xxx_ALL property) or on existing values in other instances of this property
13183 in the current file."
13184 (interactive
13185 (let* ((completion-ignore-case t)
13186 (keys (org-buffer-property-keys nil t t))
13187 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13188 (prop (if (member prop0 keys)
13189 prop0
13190 (or (cdr (assoc (downcase prop0)
13191 (mapcar (lambda (x) (cons (downcase x) x))
13192 keys)))
13193 prop0)))
13194 (cur (org-entry-get nil prop))
13195 (prompt (concat prop " value"
13196 (if (and cur (string-match "\\S-" cur))
13197 (concat " [" cur "]") "") ": "))
13198 (allowed (org-property-get-allowed-values nil prop 'table))
13199 (existing (mapcar 'list (org-property-values prop)))
13200 (val (if allowed
13201 (org-completing-read prompt allowed nil
13202 (not (get-text-property 0 'org-unrestricted
13203 (caar allowed))))
13204 (let (org-completion-use-ido org-completion-use-iswitchb)
13205 (org-completing-read prompt existing nil nil "" nil cur)))))
13206 (list prop (if (equal val "") cur val))))
13207 (unless (equal (org-entry-get nil property) value)
13208 (org-entry-put nil property value)))
13210 (defun org-delete-property (property)
13211 "In the current entry, delete PROPERTY."
13212 (interactive
13213 (let* ((completion-ignore-case t)
13214 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13215 (list prop)))
13216 (message "Property %s %s" property
13217 (if (org-entry-delete nil property)
13218 "deleted"
13219 "was not present in the entry")))
13221 (defun org-delete-property-globally (property)
13222 "Remove PROPERTY globally, from all entries."
13223 (interactive
13224 (let* ((completion-ignore-case t)
13225 (prop (org-icompleting-read
13226 "Globally remove property: "
13227 (mapcar 'list (org-buffer-property-keys)))))
13228 (list prop)))
13229 (save-excursion
13230 (save-restriction
13231 (widen)
13232 (goto-char (point-min))
13233 (let ((cnt 0))
13234 (while (re-search-forward
13235 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13236 nil t)
13237 (setq cnt (1+ cnt))
13238 (replace-match ""))
13239 (message "Property \"%s\" removed from %d entries" property cnt)))))
13241 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13243 (defun org-compute-property-at-point ()
13244 "Compute the property at point.
13245 This looks for an enclosing column format, extracts the operator and
13246 then applies it to the property in the column format's scope."
13247 (interactive)
13248 (unless (org-at-property-p)
13249 (error "Not at a property"))
13250 (let ((prop (org-match-string-no-properties 2)))
13251 (org-columns-get-format-and-top-level)
13252 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13253 (error "No operator defined for property %s" prop))
13254 (org-columns-compute prop)))
13256 (defvar org-property-allowed-value-functions nil
13257 "Hook for functions supplying allowed values for a specific property.
13258 The functions must take a single argument, the name of the property, and
13259 return a flat list of allowed values. If \":ETC\" is one of
13260 the values, this means that these values are intended as defaults for
13261 completion, but that other values should be allowed too.
13262 The functions must return nil if they are not responsible for this
13263 property.")
13265 (defun org-property-get-allowed-values (pom property &optional table)
13266 "Get allowed values for the property PROPERTY.
13267 When TABLE is non-nil, return an alist that can directly be used for
13268 completion."
13269 (let (vals)
13270 (cond
13271 ((equal property "TODO")
13272 (setq vals (org-with-point-at pom
13273 (append org-todo-keywords-1 '("")))))
13274 ((equal property "PRIORITY")
13275 (let ((n org-lowest-priority))
13276 (while (>= n org-highest-priority)
13277 (push (char-to-string n) vals)
13278 (setq n (1- n)))))
13279 ((member property org-special-properties))
13280 ((setq vals (run-hook-with-args-until-success
13281 'org-property-allowed-value-functions property)))
13283 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13284 (when (and vals (string-match "\\S-" vals))
13285 (setq vals (car (read-from-string (concat "(" vals ")"))))
13286 (setq vals (mapcar (lambda (x)
13287 (cond ((stringp x) x)
13288 ((numberp x) (number-to-string x))
13289 ((symbolp x) (symbol-name x))
13290 (t "???")))
13291 vals)))))
13292 (when (member ":ETC" vals)
13293 (setq vals (remove ":ETC" vals))
13294 (org-add-props (car vals) '(org-unrestricted t)))
13295 (if table (mapcar 'list vals) vals)))
13297 (defun org-property-previous-allowed-value (&optional previous)
13298 "Switch to the next allowed value for this property."
13299 (interactive)
13300 (org-property-next-allowed-value t))
13302 (defun org-property-next-allowed-value (&optional previous)
13303 "Switch to the next allowed value for this property."
13304 (interactive)
13305 (unless (org-at-property-p)
13306 (error "Not at a property"))
13307 (let* ((key (match-string 2))
13308 (value (match-string 3))
13309 (allowed (or (org-property-get-allowed-values (point) key)
13310 (and (member value '("[ ]" "[-]" "[X]"))
13311 '("[ ]" "[X]"))))
13312 nval)
13313 (unless allowed
13314 (error "Allowed values for this property have not been defined"))
13315 (if previous (setq allowed (reverse allowed)))
13316 (if (member value allowed)
13317 (setq nval (car (cdr (member value allowed)))))
13318 (setq nval (or nval (car allowed)))
13319 (if (equal nval value)
13320 (error "Only one allowed value for this property"))
13321 (org-at-property-p)
13322 (replace-match (concat " :" key ": " nval) t t)
13323 (org-indent-line-function)
13324 (beginning-of-line 1)
13325 (skip-chars-forward " \t")
13326 (run-hook-with-args 'org-property-changed-functions key nval)))
13328 (defun org-find-entry-with-id (ident)
13329 "Locate the entry that contains the ID property with exact value IDENT.
13330 IDENT can be a string, a symbol or a number, this function will search for
13331 the string representation of it.
13332 Return the position where this entry starts, or nil if there is no such entry."
13333 (interactive "sID: ")
13334 (let ((id (cond
13335 ((stringp ident) ident)
13336 ((symbol-name ident) (symbol-name ident))
13337 ((numberp ident) (number-to-string ident))
13338 (t (error "IDENT %s must be a string, symbol or number" ident))))
13339 (case-fold-search nil))
13340 (save-excursion
13341 (save-restriction
13342 (widen)
13343 (goto-char (point-min))
13344 (when (re-search-forward
13345 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13346 nil t)
13347 (org-back-to-heading t)
13348 (point))))))
13350 ;;;; Timestamps
13352 (defvar org-last-changed-timestamp nil)
13353 (defvar org-last-inserted-timestamp nil
13354 "The last time stamp inserted with `org-insert-time-stamp'.")
13355 (defvar org-time-was-given) ; dynamically scoped parameter
13356 (defvar org-end-time-was-given) ; dynamically scoped parameter
13357 (defvar org-ts-what) ; dynamically scoped parameter
13359 (defun org-time-stamp (arg &optional inactive)
13360 "Prompt for a date/time and insert a time stamp.
13361 If the user specifies a time like HH:MM, or if this command is called
13362 with a prefix argument, the time stamp will contain date and time.
13363 Otherwise, only the date will be included. All parts of a date not
13364 specified by the user will be filled in from the current date/time.
13365 So if you press just return without typing anything, the time stamp
13366 will represent the current date/time. If there is already a timestamp
13367 at the cursor, it will be modified."
13368 (interactive "P")
13369 (let* ((ts nil)
13370 (default-time
13371 ;; Default time is either today, or, when entering a range,
13372 ;; the range start.
13373 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13374 (save-excursion
13375 (re-search-backward
13376 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13377 (- (point) 20) t)))
13378 (apply 'encode-time (org-parse-time-string (match-string 1)))
13379 (current-time)))
13380 (default-input (and ts (org-get-compact-tod ts)))
13381 org-time-was-given org-end-time-was-given time)
13382 (cond
13383 ((and (org-at-timestamp-p t)
13384 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13385 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13386 (insert "--")
13387 (setq time (let ((this-command this-command))
13388 (org-read-date arg 'totime nil nil
13389 default-time default-input)))
13390 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13391 ((org-at-timestamp-p t)
13392 (setq time (let ((this-command this-command))
13393 (org-read-date arg 'totime nil nil default-time default-input)))
13394 (when (org-at-timestamp-p t) ; just to get the match data
13395 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13396 (replace-match "")
13397 (setq org-last-changed-timestamp
13398 (org-insert-time-stamp
13399 time (or org-time-was-given arg)
13400 inactive nil nil (list org-end-time-was-given))))
13401 (message "Timestamp updated"))
13403 (setq time (let ((this-command this-command))
13404 (org-read-date arg 'totime nil nil default-time default-input)))
13405 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13406 nil nil (list org-end-time-was-given))))))
13408 ;; FIXME: can we use this for something else, like computing time differences?
13409 (defun org-get-compact-tod (s)
13410 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13411 (let* ((t1 (match-string 1 s))
13412 (h1 (string-to-number (match-string 2 s)))
13413 (m1 (string-to-number (match-string 3 s)))
13414 (t2 (and (match-end 4) (match-string 5 s)))
13415 (h2 (and t2 (string-to-number (match-string 6 s))))
13416 (m2 (and t2 (string-to-number (match-string 7 s))))
13417 dh dm)
13418 (if (not t2)
13420 (setq dh (- h2 h1) dm (- m2 m1))
13421 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13422 (concat t1 "+" (number-to-string dh)
13423 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13425 (defun org-time-stamp-inactive (&optional arg)
13426 "Insert an inactive time stamp.
13427 An inactive time stamp is enclosed in square brackets instead of angle
13428 brackets. It is inactive in the sense that it does not trigger agenda entries,
13429 does not link to the calendar and cannot be changed with the S-cursor keys.
13430 So these are more for recording a certain time/date."
13431 (interactive "P")
13432 (org-time-stamp arg 'inactive))
13434 (defvar org-date-ovl (org-make-overlay 1 1))
13435 (org-overlay-put org-date-ovl 'face 'org-warning)
13436 (org-detach-overlay org-date-ovl)
13438 (defvar org-ans1) ; dynamically scoped parameter
13439 (defvar org-ans2) ; dynamically scoped parameter
13441 (defvar org-plain-time-of-day-regexp) ; defined below
13443 (defvar org-overriding-default-time nil) ; dynamically scoped
13444 (defvar org-read-date-overlay nil)
13445 (defvar org-dcst nil) ; dynamically scoped
13446 (defvar org-read-date-history nil)
13447 (defvar org-read-date-final-answer nil)
13449 (defun org-read-date (&optional with-time to-time from-string prompt
13450 default-time default-input)
13451 "Read a date, possibly a time, and make things smooth for the user.
13452 The prompt will suggest to enter an ISO date, but you can also enter anything
13453 which will at least partially be understood by `parse-time-string'.
13454 Unrecognized parts of the date will default to the current day, month, year,
13455 hour and minute. If this command is called to replace a timestamp at point,
13456 of to enter the second timestamp of a range, the default time is taken from the
13457 existing stamp. For example,
13458 3-2-5 --> 2003-02-05
13459 feb 15 --> currentyear-02-15
13460 sep 12 9 --> 2009-09-12
13461 12:45 --> today 12:45
13462 22 sept 0:34 --> currentyear-09-22 0:34
13463 12 --> currentyear-currentmonth-12
13464 Fri --> nearest Friday (today or later)
13465 etc.
13467 Furthermore you can specify a relative date by giving, as the *first* thing
13468 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13469 change in days weeks, months, years.
13470 With a single plus or minus, the date is relative to today. With a double
13471 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13472 +4d --> four days from today
13473 +4 --> same as above
13474 +2w --> two weeks from today
13475 ++5 --> five days from default date
13477 The function understands only English month and weekday abbreviations,
13478 but this can be configured with the variables `parse-time-months' and
13479 `parse-time-weekdays'.
13481 While prompting, a calendar is popped up - you can also select the
13482 date with the mouse (button 1). The calendar shows a period of three
13483 months. To scroll it to other months, use the keys `>' and `<'.
13484 If you don't like the calendar, turn it off with
13485 \(setq org-read-date-popup-calendar nil)
13487 With optional argument TO-TIME, the date will immediately be converted
13488 to an internal time.
13489 With an optional argument WITH-TIME, the prompt will suggest to also
13490 insert a time. Note that when WITH-TIME is not set, you can still
13491 enter a time, and this function will inform the calling routine about
13492 this change. The calling routine may then choose to change the format
13493 used to insert the time stamp into the buffer to include the time.
13494 With optional argument FROM-STRING, read from this string instead from
13495 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13496 the time/date that is used for everything that is not specified by the
13497 user."
13498 (require 'parse-time)
13499 (let* ((org-time-stamp-rounding-minutes
13500 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13501 (org-dcst org-display-custom-times)
13502 (ct (org-current-time))
13503 (def (or org-overriding-default-time default-time ct))
13504 (defdecode (decode-time def))
13505 (dummy (progn
13506 (when (< (nth 2 defdecode) org-extend-today-until)
13507 (setcar (nthcdr 2 defdecode) -1)
13508 (setcar (nthcdr 1 defdecode) 59)
13509 (setq def (apply 'encode-time defdecode)
13510 defdecode (decode-time def)))))
13511 (calendar-frame-setup nil)
13512 (calendar-move-hook nil)
13513 (calendar-view-diary-initially-flag nil)
13514 (view-diary-entries-initially nil)
13515 (calendar-view-holidays-initially-flag nil)
13516 (view-calendar-holidays-initially nil)
13517 (timestr (format-time-string
13518 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13519 (prompt (concat (if prompt (concat prompt " ") "")
13520 (format "Date+time [%s]: " timestr)))
13521 ans (org-ans0 "") org-ans1 org-ans2 final)
13523 (cond
13524 (from-string (setq ans from-string))
13525 (org-read-date-popup-calendar
13526 (save-excursion
13527 (save-window-excursion
13528 (calendar)
13529 (calendar-forward-day (- (time-to-days def)
13530 (calendar-absolute-from-gregorian
13531 (calendar-current-date))))
13532 (org-eval-in-calendar nil t)
13533 (let* ((old-map (current-local-map))
13534 (map (copy-keymap calendar-mode-map))
13535 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13536 (org-defkey map (kbd "RET") 'org-calendar-select)
13537 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13538 'org-calendar-select-mouse)
13539 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13540 'org-calendar-select-mouse)
13541 (org-defkey minibuffer-local-map [(meta shift left)]
13542 (lambda () (interactive)
13543 (org-eval-in-calendar '(calendar-backward-month 1))))
13544 (org-defkey minibuffer-local-map [(meta shift right)]
13545 (lambda () (interactive)
13546 (org-eval-in-calendar '(calendar-forward-month 1))))
13547 (org-defkey minibuffer-local-map [(meta shift up)]
13548 (lambda () (interactive)
13549 (org-eval-in-calendar '(calendar-backward-year 1))))
13550 (org-defkey minibuffer-local-map [(meta shift down)]
13551 (lambda () (interactive)
13552 (org-eval-in-calendar '(calendar-forward-year 1))))
13553 (org-defkey minibuffer-local-map [?\e (shift left)]
13554 (lambda () (interactive)
13555 (org-eval-in-calendar '(calendar-backward-month 1))))
13556 (org-defkey minibuffer-local-map [?\e (shift right)]
13557 (lambda () (interactive)
13558 (org-eval-in-calendar '(calendar-forward-month 1))))
13559 (org-defkey minibuffer-local-map [?\e (shift up)]
13560 (lambda () (interactive)
13561 (org-eval-in-calendar '(calendar-backward-year 1))))
13562 (org-defkey minibuffer-local-map [?\e (shift down)]
13563 (lambda () (interactive)
13564 (org-eval-in-calendar '(calendar-forward-year 1))))
13565 (org-defkey minibuffer-local-map [(shift up)]
13566 (lambda () (interactive)
13567 (org-eval-in-calendar '(calendar-backward-week 1))))
13568 (org-defkey minibuffer-local-map [(shift down)]
13569 (lambda () (interactive)
13570 (org-eval-in-calendar '(calendar-forward-week 1))))
13571 (org-defkey minibuffer-local-map [(shift left)]
13572 (lambda () (interactive)
13573 (org-eval-in-calendar '(calendar-backward-day 1))))
13574 (org-defkey minibuffer-local-map [(shift right)]
13575 (lambda () (interactive)
13576 (org-eval-in-calendar '(calendar-forward-day 1))))
13577 (org-defkey minibuffer-local-map ">"
13578 (lambda () (interactive)
13579 (org-eval-in-calendar '(scroll-calendar-left 1))))
13580 (org-defkey minibuffer-local-map "<"
13581 (lambda () (interactive)
13582 (org-eval-in-calendar '(scroll-calendar-right 1))))
13583 (run-hooks 'org-read-date-minibuffer-setup-hook)
13584 (unwind-protect
13585 (progn
13586 (use-local-map map)
13587 (add-hook 'post-command-hook 'org-read-date-display)
13588 (setq org-ans0 (read-string prompt default-input
13589 'org-read-date-history nil))
13590 ;; org-ans0: from prompt
13591 ;; org-ans1: from mouse click
13592 ;; org-ans2: from calendar motion
13593 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13594 (remove-hook 'post-command-hook 'org-read-date-display)
13595 (use-local-map old-map)
13596 (when org-read-date-overlay
13597 (org-delete-overlay org-read-date-overlay)
13598 (setq org-read-date-overlay nil)))))))
13600 (t ; Naked prompt only
13601 (unwind-protect
13602 (setq ans (read-string prompt default-input
13603 'org-read-date-history timestr))
13604 (when org-read-date-overlay
13605 (org-delete-overlay org-read-date-overlay)
13606 (setq org-read-date-overlay nil)))))
13608 (setq final (org-read-date-analyze ans def defdecode))
13609 (setq org-read-date-final-answer ans)
13611 (if to-time
13612 (apply 'encode-time final)
13613 (if (and (boundp 'org-time-was-given) org-time-was-given)
13614 (format "%04d-%02d-%02d %02d:%02d"
13615 (nth 5 final) (nth 4 final) (nth 3 final)
13616 (nth 2 final) (nth 1 final))
13617 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13619 (defvar def)
13620 (defvar defdecode)
13621 (defvar with-time)
13622 (defvar org-read-date-analyze-futurep nil)
13623 (defun org-read-date-display ()
13624 "Display the current date prompt interpretation in the minibuffer."
13625 (when org-read-date-display-live
13626 (when org-read-date-overlay
13627 (org-delete-overlay org-read-date-overlay))
13628 (let ((p (point)))
13629 (end-of-line 1)
13630 (while (not (equal (buffer-substring
13631 (max (point-min) (- (point) 4)) (point))
13632 " "))
13633 (insert " "))
13634 (goto-char p))
13635 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13636 " " (or org-ans1 org-ans2)))
13637 (org-end-time-was-given nil)
13638 (f (org-read-date-analyze ans def defdecode))
13639 (fmts (if org-dcst
13640 org-time-stamp-custom-formats
13641 org-time-stamp-formats))
13642 (fmt (if (or with-time
13643 (and (boundp 'org-time-was-given) org-time-was-given))
13644 (cdr fmts)
13645 (car fmts)))
13646 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13647 (when (and org-end-time-was-given
13648 (string-match org-plain-time-of-day-regexp txt))
13649 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13650 org-end-time-was-given
13651 (substring txt (match-end 0)))))
13652 (when org-read-date-analyze-futurep
13653 (setq txt (concat txt " (=>F)")))
13654 (setq org-read-date-overlay
13655 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13656 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13658 (defun org-read-date-analyze (ans def defdecode)
13659 "Analyse the combined answer of the date prompt."
13660 ;; FIXME: cleanup and comment
13661 (let ((nowdecode (decode-time (current-time)))
13662 delta deltan deltaw deltadef year month day
13663 hour minute second wday pm h2 m2 tl wday1
13664 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13665 (setq org-read-date-analyze-futurep nil)
13666 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13667 (setq ans "+0"))
13669 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13670 (setq ans (replace-match "" t t ans)
13671 deltan (car delta)
13672 deltaw (nth 1 delta)
13673 deltadef (nth 2 delta)))
13675 ;; Check if there is an iso week date in there
13676 ;; If yes, store the info and postpone interpreting it until the rest
13677 ;; of the parsing is done
13678 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13679 (setq iso-year (if (match-end 1)
13680 (org-small-year-to-year
13681 (string-to-number (match-string 1 ans))))
13682 iso-weekday (if (match-end 3)
13683 (string-to-number (match-string 3 ans)))
13684 iso-week (string-to-number (match-string 2 ans)))
13685 (setq ans (replace-match "" t t ans)))
13687 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13688 (when (string-match
13689 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13690 (setq year (if (match-end 2)
13691 (string-to-number (match-string 2 ans))
13692 (progn (setq kill-year t)
13693 (string-to-number (format-time-string "%Y"))))
13694 month (string-to-number (match-string 3 ans))
13695 day (string-to-number (match-string 4 ans)))
13696 (if (< year 100) (setq year (+ 2000 year)))
13697 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13698 t nil ans)))
13699 ;; Help matching american dates, like 5/30 or 5/30/7
13700 (when (string-match
13701 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13702 (setq year (if (match-end 4)
13703 (string-to-number (match-string 4 ans))
13704 (progn (setq kill-year t)
13705 (string-to-number (format-time-string "%Y"))))
13706 month (string-to-number (match-string 1 ans))
13707 day (string-to-number (match-string 2 ans)))
13708 (if (< year 100) (setq year (+ 2000 year)))
13709 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13710 t nil ans)))
13711 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13712 ;; If there is a time with am/pm, and *no* time without it, we convert
13713 ;; so that matching will be successful.
13714 (loop for i from 1 to 2 do ; twice, for end time as well
13715 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13716 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13717 (setq hour (string-to-number (match-string 1 ans))
13718 minute (if (match-end 3)
13719 (string-to-number (match-string 3 ans))
13721 pm (equal ?p
13722 (string-to-char (downcase (match-string 4 ans)))))
13723 (if (and (= hour 12) (not pm))
13724 (setq hour 0)
13725 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13726 (setq ans (replace-match (format "%02d:%02d" hour minute)
13727 t t ans))))
13729 ;; Check if a time range is given as a duration
13730 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13731 (setq hour (string-to-number (match-string 1 ans))
13732 h2 (+ hour (string-to-number (match-string 3 ans)))
13733 minute (string-to-number (match-string 2 ans))
13734 m2 (+ minute (if (match-end 5) (string-to-number
13735 (match-string 5 ans))0)))
13736 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13737 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13738 t t ans)))
13740 ;; Check if there is a time range
13741 (when (boundp 'org-end-time-was-given)
13742 (setq org-time-was-given nil)
13743 (when (and (string-match org-plain-time-of-day-regexp ans)
13744 (match-end 8))
13745 (setq org-end-time-was-given (match-string 8 ans))
13746 (setq ans (concat (substring ans 0 (match-beginning 7))
13747 (substring ans (match-end 7))))))
13749 (setq tl (parse-time-string ans)
13750 day (or (nth 3 tl) (nth 3 defdecode))
13751 month (or (nth 4 tl)
13752 (if (and org-read-date-prefer-future
13753 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13754 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13755 (nth 4 defdecode)))
13756 year (or (and (not kill-year) (nth 5 tl))
13757 (if (and org-read-date-prefer-future
13758 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13759 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13760 (nth 5 defdecode)))
13761 hour (or (nth 2 tl) (nth 2 defdecode))
13762 minute (or (nth 1 tl) (nth 1 defdecode))
13763 second (or (nth 0 tl) 0)
13764 wday (nth 6 tl))
13766 (when (and (eq org-read-date-prefer-future 'time)
13767 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13768 (equal day (nth 3 nowdecode))
13769 (equal month (nth 4 nowdecode))
13770 (equal year (nth 5 nowdecode))
13771 (nth 2 tl)
13772 (or (< (nth 2 tl) (nth 2 nowdecode))
13773 (and (= (nth 2 tl) (nth 2 nowdecode))
13774 (nth 1 tl)
13775 (< (nth 1 tl) (nth 1 nowdecode)))))
13776 (setq day (1+ day)
13777 futurep t))
13779 ;; Special date definitions below
13780 (cond
13781 (iso-week
13782 ;; There was an iso week
13783 (require 'cal-iso)
13784 (setq futurep nil)
13785 (setq year (or iso-year year)
13786 day (or iso-weekday wday 1)
13787 wday nil ; to make sure that the trigger below does not match
13788 iso-date (calendar-gregorian-from-absolute
13789 (calendar-absolute-from-iso
13790 (list iso-week day year))))
13791 ; FIXME: Should we also push ISO weeks into the future?
13792 ; (when (and org-read-date-prefer-future
13793 ; (not iso-year)
13794 ; (< (calendar-absolute-from-gregorian iso-date)
13795 ; (time-to-days (current-time))))
13796 ; (setq year (1+ year)
13797 ; iso-date (calendar-gregorian-from-absolute
13798 ; (calendar-absolute-from-iso
13799 ; (list iso-week day year)))))
13800 (setq month (car iso-date)
13801 year (nth 2 iso-date)
13802 day (nth 1 iso-date)))
13803 (deltan
13804 (setq futurep nil)
13805 (unless deltadef
13806 (let ((now (decode-time (current-time))))
13807 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13808 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13809 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13810 ((equal deltaw "m") (setq month (+ month deltan)))
13811 ((equal deltaw "y") (setq year (+ year deltan)))))
13812 ((and wday (not (nth 3 tl)))
13813 (setq futurep nil)
13814 ;; Weekday was given, but no day, so pick that day in the week
13815 ;; on or after the derived date.
13816 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13817 (unless (equal wday wday1)
13818 (setq day (+ day (% (- wday wday1 -7) 7))))))
13819 (if (and (boundp 'org-time-was-given)
13820 (nth 2 tl))
13821 (setq org-time-was-given t))
13822 (if (< year 100) (setq year (+ 2000 year)))
13823 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13824 (setq org-read-date-analyze-futurep futurep)
13825 (list second minute hour day month year)))
13827 (defvar parse-time-weekdays)
13829 (defun org-read-date-get-relative (s today default)
13830 "Check string S for special relative date string.
13831 TODAY and DEFAULT are internal times, for today and for a default.
13832 Return shift list (N what def-flag)
13833 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13834 N is the number of WHATs to shift.
13835 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13836 the DEFAULT date rather than TODAY."
13837 (when (and
13838 (string-match
13839 (concat
13840 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13841 "\\([0-9]+\\)?"
13842 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13843 "\\([ \t]\\|$\\)") s)
13844 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13845 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13846 (string-to-char (substring (match-string 1 s) -1))
13847 ?+))
13848 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13849 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13850 (what (if (match-end 3) (match-string 3 s) "d"))
13851 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13852 (date (if rel default today))
13853 (wday (nth 6 (decode-time date)))
13854 delta)
13855 (if wday1
13856 (progn
13857 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13858 (if (= dir ?-) (setq delta (- delta 7)))
13859 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13860 (list delta "d" rel))
13861 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13863 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13864 "Turn a user-specified date into the internal representation.
13865 The internal representation needed by the calendar is (month day year).
13866 This is a wrapper to handle the brain-dead convention in calendar that
13867 user function argument order change dependent on argument order."
13868 (if (boundp 'calendar-date-style)
13869 (cond
13870 ((eq calendar-date-style 'american)
13871 (list arg1 arg2 arg3))
13872 ((eq calendar-date-style 'european)
13873 (list arg2 arg1 arg3))
13874 ((eq calendar-date-style 'iso)
13875 (list arg2 arg3 arg1)))
13876 (if (org-bound-and-true-p european-calendar-style)
13877 (list arg2 arg1 arg3)
13878 (list arg1 arg2 arg3))))
13880 (defun org-eval-in-calendar (form &optional keepdate)
13881 "Eval FORM in the calendar window and return to current window.
13882 Also, store the cursor date in variable org-ans2."
13883 (let ((sf (selected-frame))
13884 (sw (selected-window)))
13885 (select-window (get-buffer-window "*Calendar*" t))
13886 (eval form)
13887 (when (and (not keepdate) (calendar-cursor-to-date))
13888 (let* ((date (calendar-cursor-to-date))
13889 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13890 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13891 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13892 (select-window sw)
13893 (org-select-frame-set-input-focus sf)))
13895 (defun org-calendar-select ()
13896 "Return to `org-read-date' with the date currently selected.
13897 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13898 (interactive)
13899 (when (calendar-cursor-to-date)
13900 (let* ((date (calendar-cursor-to-date))
13901 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13902 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13903 (if (active-minibuffer-window) (exit-minibuffer))))
13905 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13906 "Insert a date stamp for the date given by the internal TIME.
13907 WITH-HM means use the stamp format that includes the time of the day.
13908 INACTIVE means use square brackets instead of angular ones, so that the
13909 stamp will not contribute to the agenda.
13910 PRE and POST are optional strings to be inserted before and after the
13911 stamp.
13912 The command returns the inserted time stamp."
13913 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13914 stamp)
13915 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13916 (insert-before-markers (or pre ""))
13917 (insert-before-markers (setq stamp (format-time-string fmt time)))
13918 (when (listp extra)
13919 (setq extra (car extra))
13920 (if (and (stringp extra)
13921 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13922 (setq extra (format "-%02d:%02d"
13923 (string-to-number (match-string 1 extra))
13924 (string-to-number (match-string 2 extra))))
13925 (setq extra nil)))
13926 (when extra
13927 (backward-char 1)
13928 (insert-before-markers extra)
13929 (forward-char 1))
13930 (insert-before-markers (or post ""))
13931 (setq org-last-inserted-timestamp stamp)))
13933 (defun org-toggle-time-stamp-overlays ()
13934 "Toggle the use of custom time stamp formats."
13935 (interactive)
13936 (setq org-display-custom-times (not org-display-custom-times))
13937 (unless org-display-custom-times
13938 (let ((p (point-min)) (bmp (buffer-modified-p)))
13939 (while (setq p (next-single-property-change p 'display))
13940 (if (and (get-text-property p 'display)
13941 (eq (get-text-property p 'face) 'org-date))
13942 (remove-text-properties
13943 p (setq p (next-single-property-change p 'display))
13944 '(display t))))
13945 (set-buffer-modified-p bmp)))
13946 (if (featurep 'xemacs)
13947 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13948 (org-restart-font-lock)
13949 (setq org-table-may-need-update t)
13950 (if org-display-custom-times
13951 (message "Time stamps are overlayed with custom format")
13952 (message "Time stamp overlays removed")))
13954 (defun org-display-custom-time (beg end)
13955 "Overlay modified time stamp format over timestamp between BEG and END."
13956 (let* ((ts (buffer-substring beg end))
13957 t1 w1 with-hm tf time str w2 (off 0))
13958 (save-match-data
13959 (setq t1 (org-parse-time-string ts t))
13960 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13961 (setq off (- (match-end 0) (match-beginning 0)))))
13962 (setq end (- end off))
13963 (setq w1 (- end beg)
13964 with-hm (and (nth 1 t1) (nth 2 t1))
13965 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13966 time (org-fix-decoded-time t1)
13967 str (org-add-props
13968 (format-time-string
13969 (substring tf 1 -1) (apply 'encode-time time))
13970 nil 'mouse-face 'highlight)
13971 w2 (length str))
13972 (if (not (= w2 w1))
13973 (add-text-properties (1+ beg) (+ 2 beg)
13974 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13975 (if (featurep 'xemacs)
13976 (progn
13977 (put-text-property beg end 'invisible t)
13978 (put-text-property beg end 'end-glyph (make-glyph str)))
13979 (put-text-property beg end 'display str))))
13981 (defun org-translate-time (string)
13982 "Translate all timestamps in STRING to custom format.
13983 But do this only if the variable `org-display-custom-times' is set."
13984 (when org-display-custom-times
13985 (save-match-data
13986 (let* ((start 0)
13987 (re org-ts-regexp-both)
13988 t1 with-hm inactive tf time str beg end)
13989 (while (setq start (string-match re string start))
13990 (setq beg (match-beginning 0)
13991 end (match-end 0)
13992 t1 (save-match-data
13993 (org-parse-time-string (substring string beg end) t))
13994 with-hm (and (nth 1 t1) (nth 2 t1))
13995 inactive (equal (substring string beg (1+ beg)) "[")
13996 tf (funcall (if with-hm 'cdr 'car)
13997 org-time-stamp-custom-formats)
13998 time (org-fix-decoded-time t1)
13999 str (format-time-string
14000 (concat
14001 (if inactive "[" "<") (substring tf 1 -1)
14002 (if inactive "]" ">"))
14003 (apply 'encode-time time))
14004 string (replace-match str t t string)
14005 start (+ start (length str)))))))
14006 string)
14008 (defun org-fix-decoded-time (time)
14009 "Set 0 instead of nil for the first 6 elements of time.
14010 Don't touch the rest."
14011 (let ((n 0))
14012 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14014 (defun org-days-to-time (timestamp-string)
14015 "Difference between TIMESTAMP-STRING and now in days."
14016 (- (time-to-days (org-time-string-to-time timestamp-string))
14017 (time-to-days (current-time))))
14019 (defun org-deadline-close (timestamp-string &optional ndays)
14020 "Is the time in TIMESTAMP-STRING close to the current date?"
14021 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14022 (and (< (org-days-to-time timestamp-string) ndays)
14023 (not (org-entry-is-done-p))))
14025 (defun org-get-wdays (ts)
14026 "Get the deadline lead time appropriate for timestring TS."
14027 (cond
14028 ((<= org-deadline-warning-days 0)
14029 ;; 0 or negative, enforce this value no matter what
14030 (- org-deadline-warning-days))
14031 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14032 ;; lead time is specified.
14033 (floor (* (string-to-number (match-string 1 ts))
14034 (cdr (assoc (match-string 2 ts)
14035 '(("d" . 1) ("w" . 7)
14036 ("m" . 30.4) ("y" . 365.25)))))))
14037 ;; go for the default.
14038 (t org-deadline-warning-days)))
14040 (defun org-calendar-select-mouse (ev)
14041 "Return to `org-read-date' with the date currently selected.
14042 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14043 (interactive "e")
14044 (mouse-set-point ev)
14045 (when (calendar-cursor-to-date)
14046 (let* ((date (calendar-cursor-to-date))
14047 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14048 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14049 (if (active-minibuffer-window) (exit-minibuffer))))
14051 (defun org-check-deadlines (ndays)
14052 "Check if there are any deadlines due or past due.
14053 A deadline is considered due if it happens within `org-deadline-warning-days'
14054 days from today's date. If the deadline appears in an entry marked DONE,
14055 it is not shown. The prefix arg NDAYS can be used to test that many
14056 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14057 (interactive "P")
14058 (let* ((org-warn-days
14059 (cond
14060 ((equal ndays '(4)) 100000)
14061 (ndays (prefix-numeric-value ndays))
14062 (t (abs org-deadline-warning-days))))
14063 (case-fold-search nil)
14064 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14065 (callback
14066 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14068 (message "%d deadlines past-due or due within %d days"
14069 (org-occur regexp nil callback)
14070 org-warn-days)))
14072 (defun org-check-before-date (date)
14073 "Check if there are deadlines or scheduled entries before DATE."
14074 (interactive (list (org-read-date)))
14075 (let ((case-fold-search nil)
14076 (regexp (concat "\\<\\(" org-deadline-string
14077 "\\|" org-scheduled-string
14078 "\\) *<\\([^>]+\\)>"))
14079 (callback
14080 (lambda () (time-less-p
14081 (org-time-string-to-time (match-string 2))
14082 (org-time-string-to-time date)))))
14083 (message "%d entries before %s"
14084 (org-occur regexp nil callback) date)))
14086 (defun org-check-after-date (date)
14087 "Check if there are deadlines or scheduled entries after DATE."
14088 (interactive (list (org-read-date)))
14089 (let ((case-fold-search nil)
14090 (regexp (concat "\\<\\(" org-deadline-string
14091 "\\|" org-scheduled-string
14092 "\\) *<\\([^>]+\\)>"))
14093 (callback
14094 (lambda () (not
14095 (time-less-p
14096 (org-time-string-to-time (match-string 2))
14097 (org-time-string-to-time date))))))
14098 (message "%d entries after %s"
14099 (org-occur regexp nil callback) date)))
14101 (defun org-evaluate-time-range (&optional to-buffer)
14102 "Evaluate a time range by computing the difference between start and end.
14103 Normally the result is just printed in the echo area, but with prefix arg
14104 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14105 If the time range is actually in a table, the result is inserted into the
14106 next column.
14107 For time difference computation, a year is assumed to be exactly 365
14108 days in order to avoid rounding problems."
14109 (interactive "P")
14111 (org-clock-update-time-maybe)
14112 (save-excursion
14113 (unless (org-at-date-range-p t)
14114 (goto-char (point-at-bol))
14115 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14116 (if (not (org-at-date-range-p t))
14117 (error "Not at a time-stamp range, and none found in current line")))
14118 (let* ((ts1 (match-string 1))
14119 (ts2 (match-string 2))
14120 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14121 (match-end (match-end 0))
14122 (time1 (org-time-string-to-time ts1))
14123 (time2 (org-time-string-to-time ts2))
14124 (t1 (org-float-time time1))
14125 (t2 (org-float-time time2))
14126 (diff (abs (- t2 t1)))
14127 (negative (< (- t2 t1) 0))
14128 ;; (ys (floor (* 365 24 60 60)))
14129 (ds (* 24 60 60))
14130 (hs (* 60 60))
14131 (fy "%dy %dd %02d:%02d")
14132 (fy1 "%dy %dd")
14133 (fd "%dd %02d:%02d")
14134 (fd1 "%dd")
14135 (fh "%02d:%02d")
14136 y d h m align)
14137 (if havetime
14138 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14140 d (floor (/ diff ds)) diff (mod diff ds)
14141 h (floor (/ diff hs)) diff (mod diff hs)
14142 m (floor (/ diff 60)))
14143 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14145 d (floor (+ (/ diff ds) 0.5))
14146 h 0 m 0))
14147 (if (not to-buffer)
14148 (message "%s" (org-make-tdiff-string y d h m))
14149 (if (org-at-table-p)
14150 (progn
14151 (goto-char match-end)
14152 (setq align t)
14153 (and (looking-at " *|") (goto-char (match-end 0))))
14154 (goto-char match-end))
14155 (if (looking-at
14156 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14157 (replace-match ""))
14158 (if negative (insert " -"))
14159 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14160 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14161 (insert " " (format fh h m))))
14162 (if align (org-table-align))
14163 (message "Time difference inserted")))))
14165 (defun org-make-tdiff-string (y d h m)
14166 (let ((fmt "")
14167 (l nil))
14168 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14169 l (push y l)))
14170 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14171 l (push d l)))
14172 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14173 l (push h l)))
14174 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14175 l (push m l)))
14176 (apply 'format fmt (nreverse l))))
14178 (defun org-time-string-to-time (s)
14179 (apply 'encode-time (org-parse-time-string s)))
14180 (defun org-time-string-to-seconds (s)
14181 (org-float-time (org-time-string-to-time s)))
14183 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14184 "Convert a time stamp to an absolute day number.
14185 If there is a specifyer for a cyclic time stamp, get the closest date to
14186 DAYNR.
14187 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14188 the variable date is bound by the calendar when this is called."
14189 (cond
14190 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14191 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14192 daynr
14193 (+ daynr 1000)))
14194 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14195 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14196 (time-to-days (current-time))) (match-string 0 s)
14197 prefer show-all))
14198 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14200 (defun org-days-to-iso-week (days)
14201 "Return the iso week number."
14202 (require 'cal-iso)
14203 (car (calendar-iso-from-absolute days)))
14205 (defun org-small-year-to-year (year)
14206 "Convert 2-digit years into 4-digit years.
14207 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14208 The year 2000 cannot be abbreviated. Any year larger than 99
14209 is returned unchanged."
14210 (if (< year 38)
14211 (setq year (+ 2000 year))
14212 (if (< year 100)
14213 (setq year (+ 1900 year))))
14214 year)
14216 (defun org-time-from-absolute (d)
14217 "Return the time corresponding to date D.
14218 D may be an absolute day number, or a calendar-type list (month day year)."
14219 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14220 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14222 (defun org-calendar-holiday ()
14223 "List of holidays, for Diary display in Org-mode."
14224 (require 'holidays)
14225 (let ((hl (funcall
14226 (if (fboundp 'calendar-check-holidays)
14227 'calendar-check-holidays 'check-calendar-holidays) date)))
14228 (if hl (mapconcat 'identity hl "; "))))
14230 (defun org-diary-sexp-entry (sexp entry date)
14231 "Process a SEXP diary ENTRY for DATE."
14232 (require 'diary-lib)
14233 (let ((result (if calendar-debug-sexp
14234 (let ((stack-trace-on-error t))
14235 (eval (car (read-from-string sexp))))
14236 (condition-case nil
14237 (eval (car (read-from-string sexp)))
14238 (error
14239 (beep)
14240 (message "Bad sexp at line %d in %s: %s"
14241 (org-current-line)
14242 (buffer-file-name) sexp)
14243 (sleep-for 2))))))
14244 (cond ((stringp result) result)
14245 ((and (consp result)
14246 (stringp (cdr result))) (cdr result))
14247 (result entry)
14248 (t nil))))
14250 (defun org-diary-to-ical-string (frombuf)
14251 "Get iCalendar entries from diary entries in buffer FROMBUF.
14252 This uses the icalendar.el library."
14253 (let* ((tmpdir (if (featurep 'xemacs)
14254 (temp-directory)
14255 temporary-file-directory))
14256 (tmpfile (make-temp-name
14257 (expand-file-name "orgics" tmpdir)))
14258 buf rtn b e)
14259 (with-current-buffer frombuf
14260 (icalendar-export-region (point-min) (point-max) tmpfile)
14261 (setq buf (find-buffer-visiting tmpfile))
14262 (set-buffer buf)
14263 (goto-char (point-min))
14264 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14265 (setq b (match-beginning 0)))
14266 (goto-char (point-max))
14267 (if (re-search-backward "^END:VEVENT" nil t)
14268 (setq e (match-end 0)))
14269 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14270 (kill-buffer buf)
14271 (delete-file tmpfile)
14272 rtn))
14274 (defun org-closest-date (start current change prefer show-all)
14275 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14276 When PREFER is `past' return a date that is either CURRENT or past.
14277 When PREFER is `future', return a date that is either CURRENT or future.
14278 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14279 ;; Make the proper lists from the dates
14280 (catch 'exit
14281 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14282 dn dw sday cday n1 n2 n0
14283 d m y y1 y2 date1 date2 nmonths nm ny m2)
14285 (setq start (org-date-to-gregorian start)
14286 current (org-date-to-gregorian
14287 (if show-all
14288 current
14289 (time-to-days (current-time))))
14290 sday (calendar-absolute-from-gregorian start)
14291 cday (calendar-absolute-from-gregorian current))
14293 (if (<= cday sday) (throw 'exit sday))
14295 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14296 (setq dn (string-to-number (match-string 1 change))
14297 dw (cdr (assoc (match-string 2 change) a1)))
14298 (error "Invalid change specifyer: %s" change))
14299 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14300 (cond
14301 ((eq dw 'day)
14302 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14303 n2 (+ n1 dn)))
14304 ((eq dw 'year)
14305 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14306 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14307 (setq date1 (list m d y1)
14308 n1 (calendar-absolute-from-gregorian date1)
14309 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14310 n2 (calendar-absolute-from-gregorian date2)))
14311 ((eq dw 'month)
14312 ;; approx number of month between the two dates
14313 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14314 ;; How often does dn fit in there?
14315 (setq d (nth 1 start) m (car start) y (nth 2 start)
14316 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14317 m (+ m nm)
14318 ny (floor (/ m 12))
14319 y (+ y ny)
14320 m (- m (* ny 12)))
14321 (while (> m 12) (setq m (- m 12) y (1+ y)))
14322 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14323 (setq m2 (+ m dn) y2 y)
14324 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14325 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14326 (while (<= n2 cday)
14327 (setq n1 n2 m m2 y y2)
14328 (setq m2 (+ m dn) y2 y)
14329 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14330 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14331 ;; Make sure n1 is the earlier date
14332 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14333 (if show-all
14334 (cond
14335 ((eq prefer 'past) (if (= cday n2) n2 n1))
14336 ((eq prefer 'future) (if (= cday n1) n1 n2))
14337 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14338 (cond
14339 ((eq prefer 'past) (if (= cday n2) n2 n1))
14340 ((eq prefer 'future) (if (= cday n1) n1 n2))
14341 (t (if (= cday n1) n1 n2)))))))
14343 (defun org-date-to-gregorian (date)
14344 "Turn any specification of DATE into a gregorian date for the calendar."
14345 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14346 ((and (listp date) (= (length date) 3)) date)
14347 ((stringp date)
14348 (setq date (org-parse-time-string date))
14349 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14350 ((listp date)
14351 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14353 (defun org-parse-time-string (s &optional nodefault)
14354 "Parse the standard Org-mode time string.
14355 This should be a lot faster than the normal `parse-time-string'.
14356 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14357 hour and minute fields will be nil if not given."
14358 (if (string-match org-ts-regexp0 s)
14359 (list 0
14360 (if (or (match-beginning 8) (not nodefault))
14361 (string-to-number (or (match-string 8 s) "0")))
14362 (if (or (match-beginning 7) (not nodefault))
14363 (string-to-number (or (match-string 7 s) "0")))
14364 (string-to-number (match-string 4 s))
14365 (string-to-number (match-string 3 s))
14366 (string-to-number (match-string 2 s))
14367 nil nil nil)
14368 (error "Not a standard Org-mode time string: %s" s)))
14370 (defun org-timestamp-up (&optional arg)
14371 "Increase the date item at the cursor by one.
14372 If the cursor is on the year, change the year. If it is on the month or
14373 the day, change that.
14374 With prefix ARG, change by that many units."
14375 (interactive "p")
14376 (org-timestamp-change (prefix-numeric-value arg)))
14378 (defun org-timestamp-down (&optional arg)
14379 "Decrease the date item at the cursor by one.
14380 If the cursor is on the year, change the year. If it is on the month or
14381 the day, change that.
14382 With prefix ARG, change by that many units."
14383 (interactive "p")
14384 (org-timestamp-change (- (prefix-numeric-value arg))))
14386 (defun org-timestamp-up-day (&optional arg)
14387 "Increase the date in the time stamp by one day.
14388 With prefix ARG, change that many days."
14389 (interactive "p")
14390 (if (and (not (org-at-timestamp-p t))
14391 (org-on-heading-p))
14392 (org-todo 'up)
14393 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14395 (defun org-timestamp-down-day (&optional arg)
14396 "Decrease the date in the time stamp by one day.
14397 With prefix ARG, change that many days."
14398 (interactive "p")
14399 (if (and (not (org-at-timestamp-p t))
14400 (org-on-heading-p))
14401 (org-todo 'down)
14402 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14404 (defun org-at-timestamp-p (&optional inactive-ok)
14405 "Determine if the cursor is in or at a timestamp."
14406 (interactive)
14407 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14408 (pos (point))
14409 (ans (or (looking-at tsr)
14410 (save-excursion
14411 (skip-chars-backward "^[<\n\r\t")
14412 (if (> (point) (point-min)) (backward-char 1))
14413 (and (looking-at tsr)
14414 (> (- (match-end 0) pos) -1))))))
14415 (and ans
14416 (boundp 'org-ts-what)
14417 (setq org-ts-what
14418 (cond
14419 ((= pos (match-beginning 0)) 'bracket)
14420 ((= pos (1- (match-end 0))) 'bracket)
14421 ((org-pos-in-match-range pos 2) 'year)
14422 ((org-pos-in-match-range pos 3) 'month)
14423 ((org-pos-in-match-range pos 7) 'hour)
14424 ((org-pos-in-match-range pos 8) 'minute)
14425 ((or (org-pos-in-match-range pos 4)
14426 (org-pos-in-match-range pos 5)) 'day)
14427 ((and (> pos (or (match-end 8) (match-end 5)))
14428 (< pos (match-end 0)))
14429 (- pos (or (match-end 8) (match-end 5))))
14430 (t 'day))))
14431 ans))
14433 (defun org-toggle-timestamp-type ()
14434 "Toggle the type (<active> or [inactive]) of a time stamp."
14435 (interactive)
14436 (when (org-at-timestamp-p t)
14437 (let ((beg (match-beginning 0)) (end (match-end 0))
14438 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14439 (save-excursion
14440 (goto-char beg)
14441 (while (re-search-forward "[][<>]" end t)
14442 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14443 t t)))
14444 (message "Timestamp is now %sactive"
14445 (if (equal (char-after beg) ?<) "" "in")))))
14447 (defun org-timestamp-change (n &optional what)
14448 "Change the date in the time stamp at point.
14449 The date will be changed by N times WHAT. WHAT can be `day', `month',
14450 `year', `minute', `second'. If WHAT is not given, the cursor position
14451 in the timestamp determines what will be changed."
14452 (let ((pos (point))
14453 with-hm inactive
14454 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14455 org-ts-what
14456 extra rem
14457 ts time time0)
14458 (if (not (org-at-timestamp-p t))
14459 (error "Not at a timestamp"))
14460 (if (and (not what) (eq org-ts-what 'bracket))
14461 (org-toggle-timestamp-type)
14462 (if (and (not what) (not (eq org-ts-what 'day))
14463 org-display-custom-times
14464 (get-text-property (point) 'display)
14465 (not (get-text-property (1- (point)) 'display)))
14466 (setq org-ts-what 'day))
14467 (setq org-ts-what (or what org-ts-what)
14468 inactive (= (char-after (match-beginning 0)) ?\[)
14469 ts (match-string 0))
14470 (replace-match "")
14471 (if (string-match
14472 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14474 (setq extra (match-string 1 ts)))
14475 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14476 (setq with-hm t))
14477 (setq time0 (org-parse-time-string ts))
14478 (when (and (eq org-ts-what 'minute)
14479 (eq current-prefix-arg nil))
14480 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14481 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14482 (setcar (cdr time0) (+ (nth 1 time0)
14483 (if (> n 0) (- rem) (- dm rem))))))
14484 (setq time
14485 (encode-time (or (car time0) 0)
14486 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14487 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14488 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14489 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14490 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14491 (nthcdr 6 time0)))
14492 (when (and (member org-ts-what '(hour minute))
14493 extra
14494 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14495 (setq extra (org-modify-ts-extra
14496 extra
14497 (if (eq org-ts-what 'hour) 2 5)
14498 n dm)))
14499 (when (integerp org-ts-what)
14500 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14501 (if (eq what 'calendar)
14502 (let ((cal-date (org-get-date-from-calendar)))
14503 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14504 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14505 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14506 (setcar time0 (or (car time0) 0))
14507 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14508 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14509 (setq time (apply 'encode-time time0))))
14510 (setq org-last-changed-timestamp
14511 (org-insert-time-stamp time with-hm inactive nil nil extra))
14512 (org-clock-update-time-maybe)
14513 (goto-char pos)
14514 ;; Try to recenter the calendar window, if any
14515 (if (and org-calendar-follow-timestamp-change
14516 (get-buffer-window "*Calendar*" t)
14517 (memq org-ts-what '(day month year)))
14518 (org-recenter-calendar (time-to-days time))))))
14520 (defun org-modify-ts-extra (s pos n dm)
14521 "Change the different parts of the lead-time and repeat fields in timestamp."
14522 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14523 ng h m new rem)
14524 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14525 (cond
14526 ((or (org-pos-in-match-range pos 2)
14527 (org-pos-in-match-range pos 3))
14528 (setq m (string-to-number (match-string 3 s))
14529 h (string-to-number (match-string 2 s)))
14530 (if (org-pos-in-match-range pos 2)
14531 (setq h (+ h n))
14532 (setq n (* dm (org-no-warnings (signum n))))
14533 (when (not (= 0 (setq rem (% m dm))))
14534 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14535 (setq m (+ m n)))
14536 (if (< m 0) (setq m (+ m 60) h (1- h)))
14537 (if (> m 59) (setq m (- m 60) h (1+ h)))
14538 (setq h (min 24 (max 0 h)))
14539 (setq ng 1 new (format "-%02d:%02d" h m)))
14540 ((org-pos-in-match-range pos 6)
14541 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14542 ((org-pos-in-match-range pos 5)
14543 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14545 ((org-pos-in-match-range pos 9)
14546 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14547 ((org-pos-in-match-range pos 8)
14548 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14550 (when ng
14551 (setq s (concat
14552 (substring s 0 (match-beginning ng))
14554 (substring s (match-end ng))))))
14557 (defun org-recenter-calendar (date)
14558 "If the calendar is visible, recenter it to DATE."
14559 (let* ((win (selected-window))
14560 (cwin (get-buffer-window "*Calendar*" t))
14561 (calendar-move-hook nil))
14562 (when cwin
14563 (select-window cwin)
14564 (calendar-goto-date (if (listp date) date
14565 (calendar-gregorian-from-absolute date)))
14566 (select-window win))))
14568 (defun org-goto-calendar (&optional arg)
14569 "Go to the Emacs calendar at the current date.
14570 If there is a time stamp in the current line, go to that date.
14571 A prefix ARG can be used to force the current date."
14572 (interactive "P")
14573 (let ((tsr org-ts-regexp) diff
14574 (calendar-move-hook nil)
14575 (calendar-view-holidays-initially-flag nil)
14576 (view-calendar-holidays-initially nil)
14577 (calendar-view-diary-initially-flag nil)
14578 (view-diary-entries-initially nil))
14579 (if (or (org-at-timestamp-p)
14580 (save-excursion
14581 (beginning-of-line 1)
14582 (looking-at (concat ".*" tsr))))
14583 (let ((d1 (time-to-days (current-time)))
14584 (d2 (time-to-days
14585 (org-time-string-to-time (match-string 1)))))
14586 (setq diff (- d2 d1))))
14587 (calendar)
14588 (calendar-goto-today)
14589 (if (and diff (not arg)) (calendar-forward-day diff))))
14591 (defun org-get-date-from-calendar ()
14592 "Return a list (month day year) of date at point in calendar."
14593 (with-current-buffer "*Calendar*"
14594 (save-match-data
14595 (calendar-cursor-to-date))))
14597 (defun org-date-from-calendar ()
14598 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14599 If there is already a time stamp at the cursor position, update it."
14600 (interactive)
14601 (if (org-at-timestamp-p t)
14602 (org-timestamp-change 0 'calendar)
14603 (let ((cal-date (org-get-date-from-calendar)))
14604 (org-insert-time-stamp
14605 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14607 (defun org-minutes-to-hh:mm-string (m)
14608 "Compute H:MM from a number of minutes."
14609 (let ((h (/ m 60)))
14610 (setq m (- m (* 60 h)))
14611 (format org-time-clocksum-format h m)))
14613 (defun org-hh:mm-string-to-minutes (s)
14614 "Convert a string H:MM to a number of minutes.
14615 If the string is just a number, interpret it as minutes.
14616 In fact, the first hh:mm or number in the string will be taken,
14617 there can be extra stuff in the string.
14618 If no number is found, the return value is 0."
14619 (cond
14620 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14621 (+ (* (string-to-number (match-string 1 s)) 60)
14622 (string-to-number (match-string 2 s))))
14623 ((string-match "\\([0-9]+\\)" s)
14624 (string-to-number (match-string 1 s)))
14625 (t 0)))
14627 ;;;; Files
14629 (defun org-save-all-org-buffers ()
14630 "Save all Org-mode buffers without user confirmation."
14631 (interactive)
14632 (message "Saving all Org-mode buffers...")
14633 (save-some-buffers t 'org-mode-p)
14634 (when (featurep 'org-id) (org-id-locations-save))
14635 (message "Saving all Org-mode buffers... done"))
14637 (defun org-revert-all-org-buffers ()
14638 "Revert all Org-mode buffers.
14639 Prompt for confirmation when there are unsaved changes.
14640 Be sure you know what you are doing before letting this function
14641 overwrite your changes.
14643 This function is useful in a setup where one tracks org files
14644 with a version control system, to revert on one machine after pulling
14645 changes from another. I believe the procedure must be like this:
14647 1. M-x org-save-all-org-buffers
14648 2. Pull changes from the other machine, resolve conflicts
14649 3. M-x org-revert-all-org-buffers"
14650 (interactive)
14651 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14652 (error "Abort"))
14653 (save-excursion
14654 (save-window-excursion
14655 (mapc
14656 (lambda (b)
14657 (when (and (with-current-buffer b (org-mode-p))
14658 (with-current-buffer b buffer-file-name))
14659 (switch-to-buffer b)
14660 (revert-buffer t 'no-confirm)))
14661 (buffer-list))
14662 (when (and (featurep 'org-id) org-id-track-globally)
14663 (org-id-locations-load)))))
14665 ;;;; Agenda files
14667 ;;;###autoload
14668 (defun org-iswitchb (&optional arg)
14669 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14670 With a prefix argument, restrict available to files.
14671 With two prefix arguments, restrict available buffers to agenda files."
14672 (interactive "P")
14673 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14674 ((equal arg '(16)) (org-buffer-list 'agenda))
14675 (t (org-buffer-list)))))
14676 (switch-to-buffer
14677 (org-icompleting-read "Org buffer: "
14678 (mapcar 'list (mapcar 'buffer-name blist))
14679 nil t))))
14681 ;;;###autoload
14682 (defalias 'org-ido-switchb 'org-iswitchb)
14684 (defun org-buffer-list (&optional predicate exclude-tmp)
14685 "Return a list of Org buffers.
14686 PREDICATE can be `export', `files' or `agenda'.
14688 export restrict the list to Export buffers.
14689 files restrict the list to buffers visiting Org files.
14690 agenda restrict the list to buffers visiting agenda files.
14692 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14693 (let* ((bfn nil)
14694 (agenda-files (and (eq predicate 'agenda)
14695 (mapcar 'file-truename (org-agenda-files t))))
14696 (filter
14697 (cond
14698 ((eq predicate 'files)
14699 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14700 ((eq predicate 'export)
14701 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14702 ((eq predicate 'agenda)
14703 (lambda (b)
14704 (with-current-buffer b
14705 (and (eq major-mode 'org-mode)
14706 (setq bfn (buffer-file-name b))
14707 (member (file-truename bfn) agenda-files)))))
14708 (t (lambda (b) (with-current-buffer b
14709 (or (eq major-mode 'org-mode)
14710 (string-match "\*Org .*Export"
14711 (buffer-name b)))))))))
14712 (delq nil
14713 (mapcar
14714 (lambda(b)
14715 (if (and (funcall filter b)
14716 (or (not exclude-tmp)
14717 (not (string-match "tmp" (buffer-name b)))))
14719 nil))
14720 (buffer-list)))))
14722 (defun org-agenda-files (&optional unrestricted archives)
14723 "Get the list of agenda files.
14724 Optional UNRESTRICTED means return the full list even if a restriction
14725 is currently in place.
14726 When ARCHIVES is t, include all archive files that are really being
14727 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14728 `org-agenda-archives-mode' is t."
14729 (let ((files
14730 (cond
14731 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14732 ((stringp org-agenda-files) (org-read-agenda-file-list))
14733 ((listp org-agenda-files) org-agenda-files)
14734 (t (error "Invalid value of `org-agenda-files'")))))
14735 (setq files (apply 'append
14736 (mapcar (lambda (f)
14737 (if (file-directory-p f)
14738 (directory-files
14739 f t org-agenda-file-regexp)
14740 (list f)))
14741 files)))
14742 (when org-agenda-skip-unavailable-files
14743 (setq files (delq nil
14744 (mapcar (function
14745 (lambda (file)
14746 (and (file-readable-p file) file)))
14747 files))))
14748 (when (or (eq archives t)
14749 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14750 (setq files (org-add-archive-files files)))
14751 files))
14753 (defun org-edit-agenda-file-list ()
14754 "Edit the list of agenda files.
14755 Depending on setup, this either uses customize to edit the variable
14756 `org-agenda-files', or it visits the file that is holding the list. In the
14757 latter case, the buffer is set up in a way that saving it automatically kills
14758 the buffer and restores the previous window configuration."
14759 (interactive)
14760 (if (stringp org-agenda-files)
14761 (let ((cw (current-window-configuration)))
14762 (find-file org-agenda-files)
14763 (org-set-local 'org-window-configuration cw)
14764 (org-add-hook 'after-save-hook
14765 (lambda ()
14766 (set-window-configuration
14767 (prog1 org-window-configuration
14768 (kill-buffer (current-buffer))))
14769 (org-install-agenda-files-menu)
14770 (message "New agenda file list installed"))
14771 nil 'local)
14772 (message "%s" (substitute-command-keys
14773 "Edit list and finish with \\[save-buffer]")))
14774 (customize-variable 'org-agenda-files)))
14776 (defun org-store-new-agenda-file-list (list)
14777 "Set new value for the agenda file list and save it correctly."
14778 (if (stringp org-agenda-files)
14779 (let ((fe (org-read-agenda-file-list t)) b u)
14780 (while (setq b (find-buffer-visiting org-agenda-files))
14781 (kill-buffer b))
14782 (with-temp-file org-agenda-files
14783 (insert
14784 (mapconcat
14785 (lambda (f) ;; Keep un-expanded entries.
14786 (if (setq u (assoc f fe))
14787 (cdr u)
14789 list "\n")
14790 "\n")))
14791 (let ((org-mode-hook nil) (org-inhibit-startup t)
14792 (org-insert-mode-line-in-empty-file nil))
14793 (setq org-agenda-files list)
14794 (customize-save-variable 'org-agenda-files org-agenda-files))))
14796 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14797 "Read the list of agenda files from a file.
14798 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14799 filenames, used by `org-store-new-agenda-file-list' to write back
14800 un-expanded file names."
14801 (when (file-directory-p org-agenda-files)
14802 (error "`org-agenda-files' cannot be a single directory"))
14803 (when (stringp org-agenda-files)
14804 (with-temp-buffer
14805 (insert-file-contents org-agenda-files)
14806 (mapcar
14807 (lambda (f)
14808 (let ((e (expand-file-name (substitute-in-file-name f)
14809 org-directory)))
14810 (if pair-with-expansion
14811 (cons e f)
14812 e)))
14813 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14815 ;;;###autoload
14816 (defun org-cycle-agenda-files ()
14817 "Cycle through the files in `org-agenda-files'.
14818 If the current buffer visits an agenda file, find the next one in the list.
14819 If the current buffer does not, find the first agenda file."
14820 (interactive)
14821 (let* ((fs (org-agenda-files t))
14822 (files (append fs (list (car fs))))
14823 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14824 file)
14825 (unless files (error "No agenda files"))
14826 (catch 'exit
14827 (while (setq file (pop files))
14828 (if (equal (file-truename file) tcf)
14829 (when (car files)
14830 (find-file (car files))
14831 (throw 'exit t))))
14832 (find-file (car fs)))
14833 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14835 (defun org-agenda-file-to-front (&optional to-end)
14836 "Move/add the current file to the top of the agenda file list.
14837 If the file is not present in the list, it is added to the front. If it is
14838 present, it is moved there. With optional argument TO-END, add/move to the
14839 end of the list."
14840 (interactive "P")
14841 (let ((org-agenda-skip-unavailable-files nil)
14842 (file-alist (mapcar (lambda (x)
14843 (cons (file-truename x) x))
14844 (org-agenda-files t)))
14845 (ctf (file-truename buffer-file-name))
14846 x had)
14847 (setq x (assoc ctf file-alist) had x)
14849 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14850 (if to-end
14851 (setq file-alist (append (delq x file-alist) (list x)))
14852 (setq file-alist (cons x (delq x file-alist))))
14853 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14854 (org-install-agenda-files-menu)
14855 (message "File %s to %s of agenda file list"
14856 (if had "moved" "added") (if to-end "end" "front"))))
14858 (defun org-remove-file (&optional file)
14859 "Remove current file from the list of files in variable `org-agenda-files'.
14860 These are the files which are being checked for agenda entries.
14861 Optional argument FILE means use this file instead of the current."
14862 (interactive)
14863 (let* ((org-agenda-skip-unavailable-files nil)
14864 (file (or file buffer-file-name))
14865 (true-file (file-truename file))
14866 (afile (abbreviate-file-name file))
14867 (files (delq nil (mapcar
14868 (lambda (x)
14869 (if (equal true-file
14870 (file-truename x))
14871 nil x))
14872 (org-agenda-files t)))))
14873 (if (not (= (length files) (length (org-agenda-files t))))
14874 (progn
14875 (org-store-new-agenda-file-list files)
14876 (org-install-agenda-files-menu)
14877 (message "Removed file: %s" afile))
14878 (message "File was not in list: %s (not removed)" afile))))
14880 (defun org-file-menu-entry (file)
14881 (vector file (list 'find-file file) t))
14883 (defun org-check-agenda-file (file)
14884 "Make sure FILE exists. If not, ask user what to do."
14885 (when (not (file-exists-p file))
14886 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14887 (abbreviate-file-name file))
14888 (let ((r (downcase (read-char-exclusive))))
14889 (cond
14890 ((equal r ?r)
14891 (org-remove-file file)
14892 (throw 'nextfile t))
14893 (t (error "Abort"))))))
14895 (defun org-get-agenda-file-buffer (file)
14896 "Get a buffer visiting FILE. If the buffer needs to be created, add
14897 it to the list of buffers which might be released later."
14898 (let ((buf (org-find-base-buffer-visiting file)))
14899 (if buf
14900 buf ; just return it
14901 ;; Make a new buffer and remember it
14902 (setq buf (find-file-noselect file))
14903 (if buf (push buf org-agenda-new-buffers))
14904 buf)))
14906 (defun org-release-buffers (blist)
14907 "Release all buffers in list, asking the user for confirmation when needed.
14908 When a buffer is unmodified, it is just killed. When modified, it is saved
14909 \(if the user agrees) and then killed."
14910 (let (buf file)
14911 (while (setq buf (pop blist))
14912 (setq file (buffer-file-name buf))
14913 (when (and (buffer-modified-p buf)
14914 file
14915 (y-or-n-p (format "Save file %s? " file)))
14916 (with-current-buffer buf (save-buffer)))
14917 (kill-buffer buf))))
14919 (defun org-prepare-agenda-buffers (files)
14920 "Create buffers for all agenda files, protect archived trees and comments."
14921 (interactive)
14922 (let ((pa '(:org-archived t))
14923 (pc '(:org-comment t))
14924 (pall '(:org-archived t :org-comment t))
14925 (inhibit-read-only t)
14926 (rea (concat ":" org-archive-tag ":"))
14927 bmp file re)
14928 (save-excursion
14929 (save-restriction
14930 (while (setq file (pop files))
14931 (catch 'nextfile
14932 (if (bufferp file)
14933 (set-buffer file)
14934 (org-check-agenda-file file)
14935 (set-buffer (org-get-agenda-file-buffer file)))
14936 (widen)
14937 (setq bmp (buffer-modified-p))
14938 (org-refresh-category-properties)
14939 (setq org-todo-keywords-for-agenda
14940 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14941 (setq org-done-keywords-for-agenda
14942 (append org-done-keywords-for-agenda org-done-keywords))
14943 (setq org-todo-keyword-alist-for-agenda
14944 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14945 (setq org-drawers-for-agenda
14946 (append org-drawers-for-agenda org-drawers))
14947 (setq org-tag-alist-for-agenda
14948 (append org-tag-alist-for-agenda org-tag-alist))
14950 (save-excursion
14951 (remove-text-properties (point-min) (point-max) pall)
14952 (when org-agenda-skip-archived-trees
14953 (goto-char (point-min))
14954 (while (re-search-forward rea nil t)
14955 (if (org-on-heading-p t)
14956 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14957 (goto-char (point-min))
14958 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14959 (while (re-search-forward re nil t)
14960 (add-text-properties
14961 (match-beginning 0) (org-end-of-subtree t) pc)))
14962 (set-buffer-modified-p bmp)))))
14963 (setq org-todo-keywords-for-agenda
14964 (org-uniquify org-todo-keywords-for-agenda))
14965 (setq org-todo-keyword-alist-for-agenda
14966 (org-uniquify org-todo-keyword-alist-for-agenda)
14967 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14969 ;;;; Embedded LaTeX
14971 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14972 "Keymap for the minor `org-cdlatex-mode'.")
14974 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14975 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14976 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14977 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14978 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14980 (defvar org-cdlatex-texmathp-advice-is-done nil
14981 "Flag remembering if we have applied the advice to texmathp already.")
14983 (define-minor-mode org-cdlatex-mode
14984 "Toggle the minor `org-cdlatex-mode'.
14985 This mode supports entering LaTeX environment and math in LaTeX fragments
14986 in Org-mode.
14987 \\{org-cdlatex-mode-map}"
14988 nil " OCDL" nil
14989 (when org-cdlatex-mode (require 'cdlatex))
14990 (unless org-cdlatex-texmathp-advice-is-done
14991 (setq org-cdlatex-texmathp-advice-is-done t)
14992 (defadvice texmathp (around org-math-always-on activate)
14993 "Always return t in org-mode buffers.
14994 This is because we want to insert math symbols without dollars even outside
14995 the LaTeX math segments. If Orgmode thinks that point is actually inside
14996 an embedded LaTeX fragment, let texmathp do its job.
14997 \\[org-cdlatex-mode-map]"
14998 (interactive)
14999 (let (p)
15000 (cond
15001 ((not (org-mode-p)) ad-do-it)
15002 ((eq this-command 'cdlatex-math-symbol)
15003 (setq ad-return-value t
15004 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15006 (let ((p (org-inside-LaTeX-fragment-p)))
15007 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15008 (setq ad-return-value t
15009 texmathp-why '("Org-mode embedded math" . 0))
15010 (if p ad-do-it)))))))))
15012 (defun turn-on-org-cdlatex ()
15013 "Unconditionally turn on `org-cdlatex-mode'."
15014 (org-cdlatex-mode 1))
15016 (defun org-inside-LaTeX-fragment-p ()
15017 "Test if point is inside a LaTeX fragment.
15018 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15019 sequence appearing also before point.
15020 Even though the matchers for math are configurable, this function assumes
15021 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15022 delimiters are skipped when they have been removed by customization.
15023 The return value is nil, or a cons cell with the delimiter and
15024 and the position of this delimiter.
15026 This function does a reasonably good job, but can locally be fooled by
15027 for example currency specifications. For example it will assume being in
15028 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15029 fragments that are properly closed, but during editing, we have to live
15030 with the uncertainty caused by missing closing delimiters. This function
15031 looks only before point, not after."
15032 (catch 'exit
15033 (let ((pos (point))
15034 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15035 (lim (progn
15036 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15037 (point)))
15038 dd-on str (start 0) m re)
15039 (goto-char pos)
15040 (when dodollar
15041 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15042 re (nth 1 (assoc "$" org-latex-regexps)))
15043 (while (string-match re str start)
15044 (cond
15045 ((= (match-end 0) (length str))
15046 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15047 ((= (match-end 0) (- (length str) 5))
15048 (throw 'exit nil))
15049 (t (setq start (match-end 0))))))
15050 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15051 (goto-char pos)
15052 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15053 (and (match-beginning 2) (throw 'exit nil))
15054 ;; count $$
15055 (while (re-search-backward "\\$\\$" lim t)
15056 (setq dd-on (not dd-on)))
15057 (goto-char pos)
15058 (if dd-on (cons "$$" m))))))
15060 (defun org-inside-latex-macro-p ()
15061 "Is point inside a LaTeX macro or its arguments?"
15062 (save-match-data
15063 (org-in-regexp
15064 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15066 (defun test ()
15067 (interactive)
15068 (message "%s" (org-inside-latex-macro-p)))
15070 (defun org-try-cdlatex-tab ()
15071 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15072 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15073 - inside a LaTeX fragment, or
15074 - after the first word in a line, where an abbreviation expansion could
15075 insert a LaTeX environment."
15076 (when org-cdlatex-mode
15077 (cond
15078 ((save-excursion
15079 (skip-chars-backward "a-zA-Z0-9*")
15080 (skip-chars-backward " \t")
15081 (bolp))
15082 (cdlatex-tab) t)
15083 ((org-inside-LaTeX-fragment-p)
15084 (cdlatex-tab) t)
15085 (t nil))))
15087 (defun org-cdlatex-underscore-caret (&optional arg)
15088 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15089 Revert to the normal definition outside of these fragments."
15090 (interactive "P")
15091 (if (org-inside-LaTeX-fragment-p)
15092 (call-interactively 'cdlatex-sub-superscript)
15093 (let (org-cdlatex-mode)
15094 (call-interactively (key-binding (vector last-input-event))))))
15096 (defun org-cdlatex-math-modify (&optional arg)
15097 "Execute `cdlatex-math-modify' in LaTeX fragments.
15098 Revert to the normal definition outside of these fragments."
15099 (interactive "P")
15100 (if (org-inside-LaTeX-fragment-p)
15101 (call-interactively 'cdlatex-math-modify)
15102 (let (org-cdlatex-mode)
15103 (call-interactively (key-binding (vector last-input-event))))))
15105 (defvar org-latex-fragment-image-overlays nil
15106 "List of overlays carrying the images of latex fragments.")
15107 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15109 (defun org-remove-latex-fragment-image-overlays ()
15110 "Remove all overlays with LaTeX fragment images in current buffer."
15111 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15112 (setq org-latex-fragment-image-overlays nil))
15114 (defun org-preview-latex-fragment (&optional subtree)
15115 "Preview the LaTeX fragment at point, or all locally or globally.
15116 If the cursor is in a LaTeX fragment, create the image and overlay
15117 it over the source code. If there is no fragment at point, display
15118 all fragments in the current text, from one headline to the next. With
15119 prefix SUBTREE, display all fragments in the current subtree. With a
15120 double prefix `C-u C-u', or when the cursor is before the first headline,
15121 display all fragments in the buffer.
15122 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15123 (interactive "P")
15124 (org-remove-latex-fragment-image-overlays)
15125 (save-excursion
15126 (save-restriction
15127 (let (beg end at msg)
15128 (cond
15129 ((or (equal subtree '(16))
15130 (not (save-excursion
15131 (re-search-backward (concat "^" outline-regexp) nil t))))
15132 (setq beg (point-min) end (point-max)
15133 msg "Creating images for buffer...%s"))
15134 ((equal subtree '(4))
15135 (org-back-to-heading)
15136 (setq beg (point) end (org-end-of-subtree t)
15137 msg "Creating images for subtree...%s"))
15139 (if (setq at (org-inside-LaTeX-fragment-p))
15140 (goto-char (max (point-min) (- (cdr at) 2)))
15141 (org-back-to-heading))
15142 (setq beg (point) end (progn (outline-next-heading) (point))
15143 msg (if at "Creating image...%s"
15144 "Creating images for entry...%s"))))
15145 (message msg "")
15146 (narrow-to-region beg end)
15147 (goto-char beg)
15148 (org-format-latex
15149 (concat "ltxpng/" (file-name-sans-extension
15150 (file-name-nondirectory
15151 buffer-file-name)))
15152 default-directory 'overlays msg at 'forbuffer)
15153 (message msg "done. Use `C-c C-c' to remove images.")))))
15155 (defvar org-latex-regexps
15156 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15157 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15158 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15159 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15160 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15161 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15162 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15163 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15164 "Regular expressions for matching embedded LaTeX.")
15166 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15167 "Replace LaTeX fragments with links to an image, and produce images.
15168 Some of the options can be changed using the variable
15169 `org-format-latex-options'."
15170 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15171 (let* ((prefixnodir (file-name-nondirectory prefix))
15172 (absprefix (expand-file-name prefix dir))
15173 (todir (file-name-directory absprefix))
15174 (opt org-format-latex-options)
15175 (matchers (plist-get opt :matchers))
15176 (re-list org-latex-regexps)
15177 (org-format-latex-header-extra
15178 (plist-get (org-infile-export-plist) :latex-header-extra))
15179 (cnt 0) txt hash link beg end re e checkdir
15180 executables-checked
15181 m n block linkfile movefile ov)
15182 ;; Check the different regular expressions
15183 (while (setq e (pop re-list))
15184 (setq m (car e) re (nth 1 e) n (nth 2 e)
15185 block (if (nth 3 e) "\n\n" ""))
15186 (when (member m matchers)
15187 (goto-char (point-min))
15188 (while (re-search-forward re nil t)
15189 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15190 (not (get-text-property (match-beginning n)
15191 'org-protected))
15192 (or (not overlays)
15193 (not (eq (get-char-property (match-beginning n)
15194 'org-overlay-type)
15195 'org-latex-overlay))))
15196 (setq txt (match-string n)
15197 beg (match-beginning n) end (match-end n)
15198 cnt (1+ cnt))
15199 (let (print-length print-level) ; make sure full list is printed
15200 (setq hash (sha1 (prin1-to-string
15201 (list org-format-latex-header
15202 org-format-latex-header-extra
15203 org-export-latex-default-packages-alist
15204 org-export-latex-packages-alist
15205 org-format-latex-options
15206 forbuffer txt)))
15207 linkfile (format "%s_%s.png" prefix hash)
15208 movefile (format "%s_%s.png" absprefix hash)))
15209 (setq link (concat block "[[file:" linkfile "]]" block))
15210 (if msg (message msg cnt))
15211 (goto-char beg)
15212 (unless checkdir ; make sure the directory exists
15213 (setq checkdir t)
15214 (or (file-directory-p todir) (make-directory todir)))
15216 (unless executables-checked
15217 (org-check-external-command
15218 "latex" "needed to convert LaTeX fragments to images")
15219 (org-check-external-command
15220 "dvipng" "needed to convert LaTeX fragments to images")
15221 (setq executables-checked t))
15223 (unless (file-exists-p movefile)
15224 (org-create-formula-image
15225 txt movefile opt forbuffer))
15226 (if overlays
15227 (progn
15228 (mapc (lambda (o)
15229 (if (eq (org-overlay-get o 'org-overlay-type)
15230 'org-latex-overlay)
15231 (org-delete-overlay o)))
15232 (org-overlays-in beg end))
15233 (setq ov (org-make-overlay beg end))
15234 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
15235 (if (featurep 'xemacs)
15236 (progn
15237 (org-overlay-put ov 'invisible t)
15238 (org-overlay-put
15239 ov 'end-glyph
15240 (make-glyph (vector 'png :file movefile))))
15241 (org-overlay-put
15242 ov 'display
15243 (list 'image :type 'png :file movefile :ascent 'center)))
15244 (push ov org-latex-fragment-image-overlays)
15245 (goto-char end))
15246 (delete-region beg end)
15247 (insert (org-add-props link
15248 (list 'org-latex-src
15249 (replace-regexp-in-string "\"" "" txt)))))))))))
15251 ;; This function borrows from Ganesh Swami's latex2png.el
15252 (defun org-create-formula-image (string tofile options buffer)
15253 "This calls dvipng."
15254 (require 'org-latex)
15255 (let* ((tmpdir (if (featurep 'xemacs)
15256 (temp-directory)
15257 temporary-file-directory))
15258 (texfilebase (make-temp-name
15259 (expand-file-name "orgtex" tmpdir)))
15260 (texfile (concat texfilebase ".tex"))
15261 (dvifile (concat texfilebase ".dvi"))
15262 (pngfile (concat texfilebase ".png"))
15263 (fnh (if (featurep 'xemacs)
15264 (font-height (get-face-font 'default))
15265 (face-attribute 'default :height nil)))
15266 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15267 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15268 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15269 "Black"))
15270 (bg (or (plist-get options (if buffer :background :html-background))
15271 "Transparent")))
15272 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15273 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15274 (with-temp-file texfile
15275 (insert (org-splice-latex-header
15276 org-format-latex-header
15277 org-export-latex-default-packages-alist
15278 org-export-latex-packages-alist
15279 org-format-latex-header-extra))
15280 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15281 (require 'org-latex)
15282 (org-export-latex-fix-inputenc))
15283 (let ((dir default-directory))
15284 (condition-case nil
15285 (progn
15286 (cd tmpdir)
15287 (call-process "latex" nil nil nil texfile))
15288 (error nil))
15289 (cd dir))
15290 (if (not (file-exists-p dvifile))
15291 (progn (message "Failed to create dvi file from %s" texfile) nil)
15292 (condition-case nil
15293 (call-process "dvipng" nil nil nil
15294 "-fg" fg "-bg" bg
15295 "-D" dpi
15296 ;;"-x" scale "-y" scale
15297 "-T" "tight"
15298 "-o" pngfile
15299 dvifile)
15300 (error nil))
15301 (if (not (file-exists-p pngfile))
15302 (if org-format-latex-signal-error
15303 (error "Failed to create png file from %s" texfile)
15304 (message "Failed to create png file from %s" texfile)
15305 nil)
15306 ;; Use the requested file name and clean up
15307 (copy-file pngfile tofile 'replace)
15308 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15309 (delete-file (concat texfilebase e)))
15310 pngfile))))
15312 (defun org-splice-latex-header (tpl def-pkg pkg &optional extra)
15313 "Fill a LaTeX header template TPL.
15314 In the template, the following place holders will be recognized:
15316 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15317 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15318 [PACKAGES] \\usepackage statements for PKG
15319 [NO-PACKAGES] do not include PKG
15320 [EXTRA] the string EXTRA
15321 [NO-EXTRA] do not include EXTRA
15323 For backward compatibility, if both the positive and the negative place
15324 holder is missing, the positive one (without the \"NO-\") will be
15325 assumed to be present at the end of the template.
15326 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15327 EXTRA is a string."
15328 (let (rpl (end ""))
15329 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15330 (setq rpl (if (or (match-end 1) (not def-pkg))
15331 "" (org-latex-packages-to-string def-pkg t))
15332 tpl (replace-match rpl t t tpl))
15333 (if def-pkg (setq end (org-latex-packages-to-string def-pkg))))
15335 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15336 (setq rpl (if (or (match-end 1) (not pkg))
15337 "" (org-latex-packages-to-string pkg t))
15338 tpl (replace-match rpl t t tpl))
15339 (if pkg (setq end (concat end "\n" (org-latex-packages-to-string pkg)))))
15341 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15342 (setq rpl (if (or (match-end 1) (not extra))
15343 "" (concat extra "\n"))
15344 tpl (replace-match rpl t t tpl))
15345 (if (and extra (string-match "\\S-" extra))
15346 (setq end (concat end "\n" extra))))
15348 (if (string-match "\\S-" end)
15349 (concat tpl "\n" end)
15350 tpl)))
15352 (defun org-latex-packages-to-string (pkg &optional newline)
15353 "Turn an alist of packages into a string with the \\usepackage macros."
15354 (setq pkg (mapconcat (lambda(p)
15355 (cond
15356 ((stringp p) p)
15357 ((equal "" (car p))
15358 (format "\\usepackage{%s}" (cadr p)))
15360 (format "\\usepackage[%s]{%s}"
15361 (car p) (cadr p)))))
15363 "\n"))
15364 (if newline (concat pkg "\n") pkg))
15366 (defun org-dvipng-color (attr)
15367 "Return an rgb color specification for dvipng."
15368 (apply 'format "rgb %s %s %s"
15369 (mapcar 'org-normalize-color
15370 (color-values (face-attribute 'default attr nil)))))
15372 (defun org-normalize-color (value)
15373 "Return string to be used as color value for an RGB component."
15374 (format "%g" (/ value 65535.0)))
15376 ;;;; Key bindings
15378 ;; Make `C-c C-x' a prefix key
15379 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15381 ;; TAB key with modifiers
15382 (org-defkey org-mode-map "\C-i" 'org-cycle)
15383 (org-defkey org-mode-map [(tab)] 'org-cycle)
15384 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15385 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15386 (org-defkey org-mode-map "\M-\t" 'org-complete)
15387 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15388 ;; The following line is necessary under Suse GNU/Linux
15389 (unless (featurep 'xemacs)
15390 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15391 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15392 (define-key org-mode-map [backtab] 'org-shifttab)
15394 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15395 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15396 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15398 ;; Cursor keys with modifiers
15399 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15400 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15401 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15402 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15404 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15405 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15406 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15407 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15409 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15410 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15411 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15412 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15414 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15415 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15417 ;;; Extra keys for tty access.
15418 ;; We only set them when really needed because otherwise the
15419 ;; menus don't show the simple keys
15421 (when (or org-use-extra-keys
15422 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15423 (not window-system))
15424 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15425 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15426 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15427 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15428 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15429 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15430 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15431 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15432 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15433 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15434 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15435 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15436 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15437 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15438 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15439 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15440 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15441 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15442 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15443 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15444 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15445 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15446 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15447 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15448 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15449 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15450 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15451 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15453 ;; All the other keys
15455 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15456 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15457 (if (boundp 'narrow-map)
15458 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15459 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15460 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15461 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15462 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15463 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15464 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15465 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15466 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15467 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15468 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15469 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15470 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15471 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15472 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15473 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15474 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15475 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15476 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15477 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15478 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15479 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15480 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15481 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15482 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15483 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15484 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15485 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15486 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15487 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15488 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15489 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15490 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15491 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15492 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15493 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15494 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15495 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15496 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15497 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15498 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15499 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15500 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15501 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15502 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15503 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15504 (org-defkey org-mode-map "\C-c^" 'org-sort)
15505 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15506 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15507 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15508 (org-defkey org-mode-map "\C-m" 'org-return)
15509 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15510 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15511 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15512 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15513 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15514 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15515 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15516 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15517 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15518 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15519 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15520 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15521 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15522 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15523 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15524 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15525 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15526 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15527 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15528 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15529 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15531 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15532 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15533 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15534 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15536 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15537 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15538 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15539 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15540 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15541 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15542 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15543 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15544 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15545 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15546 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15547 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15548 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15549 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15550 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15552 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15553 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15554 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15555 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15557 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15559 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15561 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15562 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15564 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15567 (when (featurep 'xemacs)
15568 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15571 (defconst org-speed-commands-default
15573 ("Outline Navigation")
15574 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15575 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15576 ("f" . (org-speed-move-safe 'org-forward-same-level))
15577 ("b" . (org-speed-move-safe 'org-backward-same-level))
15578 ("u" . (org-speed-move-safe 'outline-up-heading))
15579 ("j" . org-goto)
15580 ("g" . (org-refile t))
15581 ("Outline Visibility")
15582 ("c" . org-cycle)
15583 ("C" . org-shifttab)
15584 (" " . org-display-outline-path)
15585 ("Outline Structure Editing")
15586 ("U" . org-shiftmetaup)
15587 ("D" . org-shiftmetadown)
15588 ("r" . org-metaright)
15589 ("l" . org-metaleft)
15590 ("R" . org-shiftmetaright)
15591 ("L" . org-shiftmetaleft)
15592 ("i" . (progn (forward-char 1) (call-interactively
15593 'org-insert-heading-respect-content)))
15594 ("^" . org-sort)
15595 ("w" . org-refile)
15596 ("a" . org-archive-subtree-default-with-confirmation)
15597 ("." . outline-mark-subtree)
15598 ("Clock Commands")
15599 ("I" . org-clock-in)
15600 ("O" . org-clock-out)
15601 ("Meta Data Editing")
15602 ("t" . org-todo)
15603 ("0" . (org-priority ?\ ))
15604 ("1" . (org-priority ?A))
15605 ("2" . (org-priority ?B))
15606 ("3" . (org-priority ?C))
15607 (";" . org-set-tags-command)
15608 ("e" . org-set-effort)
15609 ("Agenda Views etc")
15610 ("v" . org-agenda)
15611 ("/" . org-sparse-tree)
15612 ("Misc")
15613 ("o" . org-open-at-point)
15614 ("?" . org-speed-command-help)
15616 "The default speed commands.")
15618 (defun org-print-speed-command (e)
15619 (if (> (length (car e)) 1)
15620 (progn
15621 (princ "\n")
15622 (princ (car e))
15623 (princ "\n")
15624 (princ (make-string (length (car e)) ?-))
15625 (princ "\n"))
15626 (princ (car e))
15627 (princ " ")
15628 (if (symbolp (cdr e))
15629 (princ (symbol-name (cdr e)))
15630 (prin1 (cdr e)))
15631 (princ "\n")))
15633 (defun org-speed-command-help ()
15634 "Show the available speed commands."
15635 (interactive)
15636 (if (not org-use-speed-commands)
15637 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15638 (with-output-to-temp-buffer "*Help*"
15639 (princ "User-defined Speed commands\n===========================\n")
15640 (mapc 'org-print-speed-command org-speed-commands-user)
15641 (princ "\n")
15642 (princ "Built-in Speed commands\n=======================\n")
15643 (mapc 'org-print-speed-command org-speed-commands-default))
15644 (with-current-buffer "*Help*"
15645 (setq truncate-lines t))))
15647 (defun org-speed-move-safe (cmd)
15648 "Execute CMD, but make sure that the cursor always ends up in a headline.
15649 If not, return to the original position and throw an error."
15650 (interactive)
15651 (let ((pos (point)))
15652 (call-interactively cmd)
15653 (unless (and (bolp) (org-on-heading-p))
15654 (goto-char pos)
15655 (error "Boundary reached while executing %s" cmd))))
15657 (defvar org-self-insert-command-undo-counter 0)
15659 (defvar org-table-auto-blank-field) ; defined in org-table.el
15660 (defvar org-speed-command nil)
15661 (defun org-self-insert-command (N)
15662 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15663 If the cursor is in a table looking at whitespace, the whitespace is
15664 overwritten, and the table is not marked as requiring realignment."
15665 (interactive "p")
15666 (cond
15667 ((and org-use-speed-commands
15668 (or (and (bolp) (looking-at outline-regexp))
15669 (and (functionp org-use-speed-commands)
15670 (funcall org-use-speed-commands)))
15671 (setq
15672 org-speed-command
15673 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15674 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15675 (cond
15676 ((commandp org-speed-command)
15677 (setq this-command org-speed-command)
15678 (call-interactively org-speed-command))
15679 ((functionp org-speed-command)
15680 (funcall org-speed-command))
15681 ((and org-speed-command (listp org-speed-command))
15682 (eval org-speed-command))
15683 (t (let (org-use-speed-commands)
15684 (call-interactively 'org-self-insert-command)))))
15685 ((and
15686 (org-table-p)
15687 (progn
15688 ;; check if we blank the field, and if that triggers align
15689 (and (featurep 'org-table) org-table-auto-blank-field
15690 (member last-command
15691 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15692 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15693 ;; got extra space, this field does not determine column width
15694 (let (org-table-may-need-update) (org-table-blank-field))
15695 ;; no extra space, this field may determine column width
15696 (org-table-blank-field)))
15698 (eq N 1)
15699 (looking-at "[^|\n]* |"))
15700 (let (org-table-may-need-update)
15701 (goto-char (1- (match-end 0)))
15702 (delete-backward-char 1)
15703 (goto-char (match-beginning 0))
15704 (self-insert-command N)))
15706 (setq org-table-may-need-update t)
15707 (self-insert-command N)
15708 (org-fix-tags-on-the-fly)
15709 (if org-self-insert-cluster-for-undo
15710 (if (not (eq last-command 'org-self-insert-command))
15711 (setq org-self-insert-command-undo-counter 1)
15712 (if (>= org-self-insert-command-undo-counter 20)
15713 (setq org-self-insert-command-undo-counter 1)
15714 (and (> org-self-insert-command-undo-counter 0)
15715 buffer-undo-list
15716 (not (cadr buffer-undo-list)) ; remove nil entry
15717 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15718 (setq org-self-insert-command-undo-counter
15719 (1+ org-self-insert-command-undo-counter))))))))
15721 (defun org-fix-tags-on-the-fly ()
15722 (when (and (equal (char-after (point-at-bol)) ?*)
15723 (org-on-heading-p))
15724 (org-align-tags-here org-tags-column)))
15726 (defun org-delete-backward-char (N)
15727 "Like `delete-backward-char', insert whitespace at field end in tables.
15728 When deleting backwards, in tables this function will insert whitespace in
15729 front of the next \"|\" separator, to keep the table aligned. The table will
15730 still be marked for re-alignment if the field did fill the entire column,
15731 because, in this case the deletion might narrow the column."
15732 (interactive "p")
15733 (if (and (org-table-p)
15734 (eq N 1)
15735 (string-match "|" (buffer-substring (point-at-bol) (point)))
15736 (looking-at ".*?|"))
15737 (let ((pos (point))
15738 (noalign (looking-at "[^|\n\r]* |"))
15739 (c org-table-may-need-update))
15740 (backward-delete-char N)
15741 (skip-chars-forward "^|")
15742 (insert " ")
15743 (goto-char (1- pos))
15744 ;; noalign: if there were two spaces at the end, this field
15745 ;; does not determine the width of the column.
15746 (if noalign (setq org-table-may-need-update c)))
15747 (backward-delete-char N)
15748 (org-fix-tags-on-the-fly)))
15750 (defun org-delete-char (N)
15751 "Like `delete-char', but insert whitespace at field end in tables.
15752 When deleting characters, in tables this function will insert whitespace in
15753 front of the next \"|\" separator, to keep the table aligned. The table will
15754 still be marked for re-alignment if the field did fill the entire column,
15755 because, in this case the deletion might narrow the column."
15756 (interactive "p")
15757 (if (and (org-table-p)
15758 (not (bolp))
15759 (not (= (char-after) ?|))
15760 (eq N 1))
15761 (if (looking-at ".*?|")
15762 (let ((pos (point))
15763 (noalign (looking-at "[^|\n\r]* |"))
15764 (c org-table-may-need-update))
15765 (replace-match (concat
15766 (substring (match-string 0) 1 -1)
15767 " |"))
15768 (goto-char pos)
15769 ;; noalign: if there were two spaces at the end, this field
15770 ;; does not determine the width of the column.
15771 (if noalign (setq org-table-may-need-update c)))
15772 (delete-char N))
15773 (delete-char N)
15774 (org-fix-tags-on-the-fly)))
15776 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15777 (put 'org-self-insert-command 'delete-selection t)
15778 (put 'orgtbl-self-insert-command 'delete-selection t)
15779 (put 'org-delete-char 'delete-selection 'supersede)
15780 (put 'org-delete-backward-char 'delete-selection 'supersede)
15781 (put 'org-yank 'delete-selection 'yank)
15783 ;; Make `flyspell-mode' delay after some commands
15784 (put 'org-self-insert-command 'flyspell-delayed t)
15785 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15786 (put 'org-delete-char 'flyspell-delayed t)
15787 (put 'org-delete-backward-char 'flyspell-delayed t)
15789 ;; Make pabbrev-mode expand after org-mode commands
15790 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15791 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15793 ;; How to do this: Measure non-white length of current string
15794 ;; If equal to column width, we should realign.
15796 (defun org-remap (map &rest commands)
15797 "In MAP, remap the functions given in COMMANDS.
15798 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15799 (let (new old)
15800 (while commands
15801 (setq old (pop commands) new (pop commands))
15802 (if (fboundp 'command-remapping)
15803 (org-defkey map (vector 'remap old) new)
15804 (substitute-key-definition old new map global-map)))))
15806 (when (eq org-enable-table-editor 'optimized)
15807 ;; If the user wants maximum table support, we need to hijack
15808 ;; some standard editing functions
15809 (org-remap org-mode-map
15810 'self-insert-command 'org-self-insert-command
15811 'delete-char 'org-delete-char
15812 'delete-backward-char 'org-delete-backward-char)
15813 (org-defkey org-mode-map "|" 'org-force-self-insert))
15815 (defvar org-ctrl-c-ctrl-c-hook nil
15816 "Hook for functions attaching themselves to `C-c C-c'.
15817 This can be used to add additional functionality to the C-c C-c key which
15818 executes context-dependent commands.
15819 Each function will be called with no arguments. The function must check
15820 if the context is appropriate for it to act. If yes, it should do its
15821 thing and then return a non-nil value. If the context is wrong,
15822 just do nothing and return nil.")
15824 (defvar org-tab-first-hook nil
15825 "Hook for functions to attach themselves to TAB.
15826 See `org-ctrl-c-ctrl-c-hook' for more information.
15827 This hook runs as the first action when TAB is pressed, even before
15828 `org-cycle' messes around with the `outline-regexp' to cater for
15829 inline tasks and plain list item folding.
15830 If any function in this hook returns t, not other actions like table
15831 field motion visibility cycling will be done.")
15833 (defvar org-tab-after-check-for-table-hook nil
15834 "Hook for functions to attach themselves to TAB.
15835 See `org-ctrl-c-ctrl-c-hook' for more information.
15836 This hook runs after it has been established that the cursor is not in a
15837 table, but before checking if the cursor is in a headline or if global cycling
15838 should be done.
15839 If any function in this hook returns t, not other actions like visibility
15840 cycling will be done.")
15842 (defvar org-tab-after-check-for-cycling-hook nil
15843 "Hook for functions to attach themselves to TAB.
15844 See `org-ctrl-c-ctrl-c-hook' for more information.
15845 This hook runs after it has been established that not table field motion and
15846 not visibility should be done because of current context. This is probably
15847 the place where a package like yasnippets can hook in.")
15849 (defvar org-tab-before-tab-emulation-hook nil
15850 "Hook for functions to attach themselves to TAB.
15851 See `org-ctrl-c-ctrl-c-hook' for more information.
15852 This hook runs after every other options for TAB have been exhausted, but
15853 before indentation and \t insertion takes place.")
15855 (defvar org-metaleft-hook nil
15856 "Hook for functions attaching themselves to `M-left'.
15857 See `org-ctrl-c-ctrl-c-hook' for more information.")
15858 (defvar org-metaright-hook nil
15859 "Hook for functions attaching themselves to `M-right'.
15860 See `org-ctrl-c-ctrl-c-hook' for more information.")
15861 (defvar org-metaup-hook nil
15862 "Hook for functions attaching themselves to `M-up'.
15863 See `org-ctrl-c-ctrl-c-hook' for more information.")
15864 (defvar org-metadown-hook nil
15865 "Hook for functions attaching themselves to `M-down'.
15866 See `org-ctrl-c-ctrl-c-hook' for more information.")
15867 (defvar org-shiftmetaleft-hook nil
15868 "Hook for functions attaching themselves to `M-S-left'.
15869 See `org-ctrl-c-ctrl-c-hook' for more information.")
15870 (defvar org-shiftmetaright-hook nil
15871 "Hook for functions attaching themselves to `M-S-right'.
15872 See `org-ctrl-c-ctrl-c-hook' for more information.")
15873 (defvar org-shiftmetaup-hook nil
15874 "Hook for functions attaching themselves to `M-S-up'.
15875 See `org-ctrl-c-ctrl-c-hook' for more information.")
15876 (defvar org-shiftmetadown-hook nil
15877 "Hook for functions attaching themselves to `M-S-down'.
15878 See `org-ctrl-c-ctrl-c-hook' for more information.")
15879 (defvar org-metareturn-hook nil
15880 "Hook for functions attaching themselves to `M-RET'.
15881 See `org-ctrl-c-ctrl-c-hook' for more information.")
15883 (defun org-modifier-cursor-error ()
15884 "Throw an error, a modified cursor command was applied in wrong context."
15885 (error "This command is active in special context like tables, headlines or items"))
15887 (defun org-shiftselect-error ()
15888 "Throw an error because Shift-Cursor command was applied in wrong context."
15889 (if (and (boundp 'shift-select-mode) shift-select-mode)
15890 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15891 (error "This command works only in special context like headlines or timestamps")))
15893 (defun org-call-for-shift-select (cmd)
15894 (let ((this-command-keys-shift-translated t))
15895 (call-interactively cmd)))
15897 (defun org-shifttab (&optional arg)
15898 "Global visibility cycling or move to previous table field.
15899 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15900 on context.
15901 See the individual commands for more information."
15902 (interactive "P")
15903 (cond
15904 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15905 ((integerp arg)
15906 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15907 (message "Content view to level: %d" arg)
15908 (org-content (prefix-numeric-value arg2))
15909 (setq org-cycle-global-status 'overview)))
15910 (t (call-interactively 'org-global-cycle))))
15912 (defun org-shiftmetaleft ()
15913 "Promote subtree or delete table column.
15914 Calls `org-promote-subtree', `org-outdent-item',
15915 or `org-table-delete-column', depending on context.
15916 See the individual commands for more information."
15917 (interactive)
15918 (cond
15919 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15920 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15921 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15922 ((org-at-item-p) (call-interactively 'org-outdent-item))
15923 (t (org-modifier-cursor-error))))
15925 (defun org-shiftmetaright ()
15926 "Demote subtree or insert table column.
15927 Calls `org-demote-subtree', `org-indent-item',
15928 or `org-table-insert-column', depending on context.
15929 See the individual commands for more information."
15930 (interactive)
15931 (cond
15932 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15933 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15934 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15935 ((org-at-item-p) (call-interactively 'org-indent-item))
15936 (t (org-modifier-cursor-error))))
15938 (defun org-shiftmetaup (&optional arg)
15939 "Move subtree up or kill table row.
15940 Calls `org-move-subtree-up' or `org-table-kill-row' or
15941 `org-move-item-up' depending on context. See the individual commands
15942 for more information."
15943 (interactive "P")
15944 (cond
15945 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15946 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15947 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15948 ((org-at-item-p) (call-interactively 'org-move-item-up))
15949 (t (org-modifier-cursor-error))))
15951 (defun org-shiftmetadown (&optional arg)
15952 "Move subtree down or insert table row.
15953 Calls `org-move-subtree-down' or `org-table-insert-row' or
15954 `org-move-item-down', depending on context. See the individual
15955 commands for more information."
15956 (interactive "P")
15957 (cond
15958 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15959 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15960 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15961 ((org-at-item-p) (call-interactively 'org-move-item-down))
15962 (t (org-modifier-cursor-error))))
15964 (defun org-metaleft (&optional arg)
15965 "Promote heading or move table column to left.
15966 Calls `org-do-promote' or `org-table-move-column', depending on context.
15967 With no specific context, calls the Emacs default `backward-word'.
15968 See the individual commands for more information."
15969 (interactive "P")
15970 (cond
15971 ((run-hook-with-args-until-success 'org-metaleft-hook))
15972 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15973 ((or (org-on-heading-p)
15974 (and (org-region-active-p)
15975 (save-excursion
15976 (goto-char (region-beginning))
15977 (org-on-heading-p))))
15978 (call-interactively 'org-do-promote))
15979 ((or (org-at-item-p)
15980 (and (org-region-active-p)
15981 (save-excursion
15982 (goto-char (region-beginning))
15983 (org-at-item-p))))
15984 (call-interactively 'org-outdent-item))
15985 (t (call-interactively 'backward-word))))
15987 (defun org-metaright (&optional arg)
15988 "Demote subtree or move table column to right.
15989 Calls `org-do-demote' or `org-table-move-column', depending on context.
15990 With no specific context, calls the Emacs default `forward-word'.
15991 See the individual commands for more information."
15992 (interactive "P")
15993 (cond
15994 ((run-hook-with-args-until-success 'org-metaright-hook))
15995 ((org-at-table-p) (call-interactively 'org-table-move-column))
15996 ((or (org-on-heading-p)
15997 (and (org-region-active-p)
15998 (save-excursion
15999 (goto-char (region-beginning))
16000 (org-on-heading-p))))
16001 (call-interactively 'org-do-demote))
16002 ((or (org-at-item-p)
16003 (and (org-region-active-p)
16004 (save-excursion
16005 (goto-char (region-beginning))
16006 (org-at-item-p))))
16007 (call-interactively 'org-indent-item))
16008 (t (call-interactively 'forward-word))))
16010 (defun org-metaup (&optional arg)
16011 "Move subtree up or move table row up.
16012 Calls `org-move-subtree-up' or `org-table-move-row' or
16013 `org-move-item-up', depending on context. See the individual commands
16014 for more information."
16015 (interactive "P")
16016 (cond
16017 ((run-hook-with-args-until-success 'org-metaup-hook))
16018 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16019 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16020 ((org-at-item-p) (call-interactively 'org-move-item-up))
16021 (t (transpose-lines 1) (beginning-of-line -1))))
16023 (defun org-metadown (&optional arg)
16024 "Move subtree down or move table row down.
16025 Calls `org-move-subtree-down' or `org-table-move-row' or
16026 `org-move-item-down', depending on context. See the individual
16027 commands for more information."
16028 (interactive "P")
16029 (cond
16030 ((run-hook-with-args-until-success 'org-metadown-hook))
16031 ((org-at-table-p) (call-interactively 'org-table-move-row))
16032 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16033 ((org-at-item-p) (call-interactively 'org-move-item-down))
16034 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16036 (defun org-shiftup (&optional arg)
16037 "Increase item in timestamp or increase priority of current headline.
16038 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16039 depending on context. See the individual commands for more information."
16040 (interactive "P")
16041 (cond
16042 ((and org-support-shift-select (org-region-active-p))
16043 (org-call-for-shift-select 'previous-line))
16044 ((org-at-timestamp-p t)
16045 (call-interactively (if org-edit-timestamp-down-means-later
16046 'org-timestamp-down 'org-timestamp-up)))
16047 ((and (not (eq org-support-shift-select 'always))
16048 org-enable-priority-commands
16049 (org-on-heading-p))
16050 (call-interactively 'org-priority-up))
16051 ((and (not org-support-shift-select) (org-at-item-p))
16052 (call-interactively 'org-previous-item))
16053 ((org-clocktable-try-shift 'up arg))
16054 (org-support-shift-select
16055 (org-call-for-shift-select 'previous-line))
16056 (t (org-shiftselect-error))))
16058 (defun org-shiftdown (&optional arg)
16059 "Decrease item in timestamp or decrease priority of current headline.
16060 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16061 depending on context. See the individual commands for more information."
16062 (interactive "P")
16063 (cond
16064 ((and org-support-shift-select (org-region-active-p))
16065 (org-call-for-shift-select 'next-line))
16066 ((org-at-timestamp-p t)
16067 (call-interactively (if org-edit-timestamp-down-means-later
16068 'org-timestamp-up 'org-timestamp-down)))
16069 ((and (not (eq org-support-shift-select 'always))
16070 org-enable-priority-commands
16071 (org-on-heading-p))
16072 (call-interactively 'org-priority-down))
16073 ((and (not org-support-shift-select) (org-at-item-p))
16074 (call-interactively 'org-next-item))
16075 ((org-clocktable-try-shift 'down arg))
16076 (org-support-shift-select
16077 (org-call-for-shift-select 'next-line))
16078 (t (org-shiftselect-error))))
16080 (defun org-shiftright (&optional arg)
16081 "Cycle the thing at point or in the current line, depending on context.
16082 Depending on context, this does one of the following:
16084 - switch a timestamp at point one day into the future
16085 - on a headline, switch to the next TODO keyword.
16086 - on an item, switch entire list to the next bullet type
16087 - on a property line, switch to the next allowed value
16088 - on a clocktable definition line, move time block into the future"
16089 (interactive "P")
16090 (cond
16091 ((and org-support-shift-select (org-region-active-p))
16092 (org-call-for-shift-select 'forward-char))
16093 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16094 ((and (not (eq org-support-shift-select 'always))
16095 (org-on-heading-p))
16096 (let ((org-inhibit-logging
16097 (not org-treat-S-cursor-todo-selection-as-state-change))
16098 (org-inhibit-blocking
16099 (not org-treat-S-cursor-todo-selection-as-state-change)))
16100 (org-call-with-arg 'org-todo 'right)))
16101 ((or (and org-support-shift-select
16102 (not (eq org-support-shift-select 'always))
16103 (org-at-item-bullet-p))
16104 (and (not org-support-shift-select) (org-at-item-p)))
16105 (org-call-with-arg 'org-cycle-list-bullet nil))
16106 ((and (not (eq org-support-shift-select 'always))
16107 (org-at-property-p))
16108 (call-interactively 'org-property-next-allowed-value))
16109 ((org-clocktable-try-shift 'right arg))
16110 (org-support-shift-select
16111 (org-call-for-shift-select 'forward-char))
16112 (t (org-shiftselect-error))))
16114 (defun org-shiftleft (&optional arg)
16115 "Cycle the thing at point or in the current line, depending on context.
16116 Depending on context, this does one of the following:
16118 - switch a timestamp at point one day into the past
16119 - on a headline, switch to the previous TODO keyword.
16120 - on an item, switch entire list to the previous bullet type
16121 - on a property line, switch to the previous allowed value
16122 - on a clocktable definition line, move time block into the past"
16123 (interactive "P")
16124 (cond
16125 ((and org-support-shift-select (org-region-active-p))
16126 (org-call-for-shift-select 'backward-char))
16127 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16128 ((and (not (eq org-support-shift-select 'always))
16129 (org-on-heading-p))
16130 (let ((org-inhibit-logging
16131 (not org-treat-S-cursor-todo-selection-as-state-change))
16132 (org-inhibit-blocking
16133 (not org-treat-S-cursor-todo-selection-as-state-change)))
16134 (org-call-with-arg 'org-todo 'left)))
16135 ((or (and org-support-shift-select
16136 (not (eq org-support-shift-select 'always))
16137 (org-at-item-bullet-p))
16138 (and (not org-support-shift-select) (org-at-item-p)))
16139 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16140 ((and (not (eq org-support-shift-select 'always))
16141 (org-at-property-p))
16142 (call-interactively 'org-property-previous-allowed-value))
16143 ((org-clocktable-try-shift 'left arg))
16144 (org-support-shift-select
16145 (org-call-for-shift-select 'backward-char))
16146 (t (org-shiftselect-error))))
16148 (defun org-shiftcontrolright ()
16149 "Switch to next TODO set."
16150 (interactive)
16151 (cond
16152 ((and org-support-shift-select (org-region-active-p))
16153 (org-call-for-shift-select 'forward-word))
16154 ((and (not (eq org-support-shift-select 'always))
16155 (org-on-heading-p))
16156 (org-call-with-arg 'org-todo 'nextset))
16157 (org-support-shift-select
16158 (org-call-for-shift-select 'forward-word))
16159 (t (org-shiftselect-error))))
16161 (defun org-shiftcontrolleft ()
16162 "Switch to previous TODO set."
16163 (interactive)
16164 (cond
16165 ((and org-support-shift-select (org-region-active-p))
16166 (org-call-for-shift-select 'backward-word))
16167 ((and (not (eq org-support-shift-select 'always))
16168 (org-on-heading-p))
16169 (org-call-with-arg 'org-todo 'previousset))
16170 (org-support-shift-select
16171 (org-call-for-shift-select 'backward-word))
16172 (t (org-shiftselect-error))))
16174 (defun org-ctrl-c-ret ()
16175 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16176 (interactive)
16177 (cond
16178 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16179 (t (call-interactively 'org-insert-heading))))
16181 (defun org-copy-special ()
16182 "Copy region in table or copy current subtree.
16183 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16184 See the individual commands for more information."
16185 (interactive)
16186 (call-interactively
16187 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16189 (defun org-cut-special ()
16190 "Cut region in table or cut current subtree.
16191 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16192 See the individual commands for more information."
16193 (interactive)
16194 (call-interactively
16195 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16197 (defun org-paste-special (arg)
16198 "Paste rectangular region into table, or past subtree relative to level.
16199 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16200 See the individual commands for more information."
16201 (interactive "P")
16202 (if (org-at-table-p)
16203 (org-table-paste-rectangle)
16204 (org-paste-subtree arg)))
16206 (defun org-edit-special ()
16207 "Call a special editor for the stuff at point.
16208 When at a table, call the formula editor with `org-table-edit-formulas'.
16209 When at the first line of an src example, call `org-edit-src-code'.
16210 When in an #+include line, visit the include file. Otherwise call
16211 `ffap' to visit the file at point."
16212 (interactive)
16213 (cond
16214 ((org-at-table.el-p)
16215 (org-edit-src-code))
16216 ((org-at-table-p)
16217 (call-interactively 'org-table-edit-formulas))
16218 ((save-excursion
16219 (beginning-of-line 1)
16220 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16221 (find-file (org-trim (match-string 1))))
16222 ((org-edit-src-code))
16223 ((org-edit-fixed-width-region))
16224 (t (call-interactively 'ffap))))
16227 (defun org-ctrl-c-ctrl-c (&optional arg)
16228 "Set tags in headline, or update according to changed information at point.
16230 This command does many different things, depending on context:
16232 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16233 this is what we do.
16235 - If the cursor is on a statistics cookie, update it.
16237 - If the cursor is in a headline, prompt for tags and insert them
16238 into the current line, aligned to `org-tags-column'. When called
16239 with prefix arg, realign all tags in the current buffer.
16241 - If the cursor is in one of the special #+KEYWORD lines, this
16242 triggers scanning the buffer for these lines and updating the
16243 information.
16245 - If the cursor is inside a table, realign the table. This command
16246 works even if the automatic table editor has been turned off.
16248 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16249 the entire table.
16251 - If the cursor is at a footnote reference or definition, jump to
16252 the corresponding definition or references, respectively.
16254 - If the cursor is a the beginning of a dynamic block, update it.
16256 - If the current buffer is a remember buffer, close note and file
16257 it. A prefix argument of 1 files to the default location
16258 without further interaction. A prefix argument of 2 files to
16259 the currently clocking task.
16261 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16262 links in this buffer.
16264 - If the cursor is on a numbered item in a plain list, renumber the
16265 ordered list.
16267 - If the cursor is on a checkbox, toggle it."
16268 (interactive "P")
16269 (let ((org-enable-table-editor t))
16270 (cond
16271 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16272 org-occur-highlights
16273 org-latex-fragment-image-overlays)
16274 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16275 (org-remove-occur-highlights)
16276 (org-remove-latex-fragment-image-overlays)
16277 (message "Temporary highlights/overlays removed from current buffer"))
16278 ((and (local-variable-p 'org-finish-function (current-buffer))
16279 (fboundp org-finish-function))
16280 (funcall org-finish-function))
16281 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16282 ((or (looking-at (org-re org-property-start-re))
16283 (org-at-property-p))
16284 (call-interactively 'org-property-action))
16285 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16286 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16287 (or (org-on-heading-p) (org-at-item-p)))
16288 (call-interactively 'org-update-statistics-cookies))
16289 ((org-on-heading-p) (call-interactively 'org-set-tags))
16290 ((org-at-table.el-p)
16291 (message "Use C-c ' to edit table.el tables"))
16292 ((org-at-table-p)
16293 (org-table-maybe-eval-formula)
16294 (if arg
16295 (call-interactively 'org-table-recalculate)
16296 (org-table-maybe-recalculate-line))
16297 (call-interactively 'org-table-align))
16298 ((or (org-footnote-at-reference-p)
16299 (org-footnote-at-definition-p))
16300 (call-interactively 'org-footnote-action))
16301 ((org-at-item-checkbox-p)
16302 (call-interactively 'org-toggle-checkbox))
16303 ((org-at-item-p)
16304 (if arg
16305 (call-interactively 'org-toggle-checkbox)
16306 (call-interactively 'org-maybe-renumber-ordered-list)))
16307 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16308 ;; Dynamic block
16309 (beginning-of-line 1)
16310 (save-excursion (org-update-dblock)))
16311 ((save-excursion
16312 (beginning-of-line 1)
16313 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16314 (cond
16315 ((equal (match-string 1) "TBLFM")
16316 ;; Recalculate the table before this line
16317 (save-excursion
16318 (beginning-of-line 1)
16319 (skip-chars-backward " \r\n\t")
16320 (if (org-at-table-p)
16321 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16323 (let ((org-inhibit-startup-visibility-stuff t)
16324 (org-startup-align-all-tables nil))
16325 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16326 (message "Local setup has been refreshed"))))
16327 ((org-clock-update-time-maybe))
16328 (t (error "C-c C-c can do nothing useful at this location")))))
16330 (defun org-mode-restart ()
16331 "Restart Org-mode, to scan again for special lines.
16332 Also updates the keyword regular expressions."
16333 (interactive)
16334 (org-mode)
16335 (message "Org-mode restarted"))
16337 (defun org-kill-note-or-show-branches ()
16338 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16339 (interactive)
16340 (if (not org-finish-function)
16341 (call-interactively 'show-branches)
16342 (let ((org-note-abort t))
16343 (funcall org-finish-function))))
16345 (defun org-return (&optional indent)
16346 "Goto next table row or insert a newline.
16347 Calls `org-table-next-row' or `newline', depending on context.
16348 See the individual commands for more information."
16349 (interactive)
16350 (cond
16351 ((bobp) (if indent (newline-and-indent) (newline)))
16352 ((org-at-table-p)
16353 (org-table-justify-field-maybe)
16354 (call-interactively 'org-table-next-row))
16355 ((and org-return-follows-link
16356 (eq (get-text-property (point) 'face) 'org-link))
16357 (call-interactively 'org-open-at-point))
16358 ((and (org-at-heading-p)
16359 (looking-at
16360 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16361 (org-show-entry)
16362 (end-of-line 1)
16363 (newline))
16364 (t (if indent (newline-and-indent) (newline)))))
16366 (defun org-return-indent ()
16367 "Goto next table row or insert a newline and indent.
16368 Calls `org-table-next-row' or `newline-and-indent', depending on
16369 context. See the individual commands for more information."
16370 (interactive)
16371 (org-return t))
16373 (defun org-ctrl-c-star ()
16374 "Compute table, or change heading status of lines.
16375 Calls `org-table-recalculate' or `org-toggle-heading',
16376 depending on context."
16377 (interactive)
16378 (cond
16379 ((org-at-table-p)
16380 (call-interactively 'org-table-recalculate))
16382 ;; Convert all lines in region to list items
16383 (call-interactively 'org-toggle-heading))))
16385 (defun org-ctrl-c-minus ()
16386 "Insert separator line in table or modify bullet status of line.
16387 Also turns a plain line or a region of lines into list items.
16388 Calls `org-table-insert-hline', `org-toggle-item', or
16389 `org-cycle-list-bullet', depending on context."
16390 (interactive)
16391 (cond
16392 ((org-at-table-p)
16393 (call-interactively 'org-table-insert-hline))
16394 ((org-region-active-p)
16395 (call-interactively 'org-toggle-item))
16396 ((org-in-item-p)
16397 (call-interactively 'org-cycle-list-bullet))
16399 (call-interactively 'org-toggle-item))))
16401 (defun org-toggle-item ()
16402 "Convert headings or normal lines to items, items to normal lines.
16403 If there is no active region, only the current line is considered.
16405 If the first line in the region is a headline, convert all headlines to items.
16407 If the first line in the region is an item, convert all items to normal lines.
16409 If the first line is normal text, add an item bullet to each line."
16410 (interactive)
16411 (let (l2 l beg end)
16412 (if (org-region-active-p)
16413 (setq beg (region-beginning) end (region-end))
16414 (setq beg (point-at-bol)
16415 end (min (1+ (point-at-eol)) (point-max))))
16416 (save-excursion
16417 (goto-char end)
16418 (setq l2 (org-current-line))
16419 (goto-char beg)
16420 (beginning-of-line 1)
16421 (setq l (1- (org-current-line)))
16422 (if (org-at-item-p)
16423 ;; We already have items, de-itemize
16424 (while (< (setq l (1+ l)) l2)
16425 (when (org-at-item-p)
16426 (goto-char (match-beginning 2))
16427 (delete-region (match-beginning 2) (match-end 2))
16428 (and (looking-at "[ \t]+") (replace-match "")))
16429 (beginning-of-line 2))
16430 (if (org-on-heading-p)
16431 ;; Headings, convert to items
16432 (while (< (setq l (1+ l)) l2)
16433 (if (looking-at org-outline-regexp)
16434 (replace-match "- " t t))
16435 (beginning-of-line 2))
16436 ;; normal lines, turn them into items
16437 (while (< (setq l (1+ l)) l2)
16438 (unless (org-at-item-p)
16439 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16440 (replace-match "\\1- \\2")))
16441 (beginning-of-line 2)))))))
16443 (defun org-toggle-heading (&optional nstars)
16444 "Convert headings to normal text, or items or text to headings.
16445 If there is no active region, only the current line is considered.
16447 If the first line is a heading, remove the stars from all headlines
16448 in the region.
16450 If the first line is a plain list item, turn all plain list items
16451 into headings.
16453 If the first line is a normal line, turn each and every line in the
16454 region into a heading.
16456 When converting a line into a heading, the number of stars is chosen
16457 such that the lines become children of the current entry. However,
16458 when a prefix argument is given, its value determines the number of
16459 stars to add."
16460 (interactive "P")
16461 (let (l2 l itemp beg end)
16462 (if (org-region-active-p)
16463 (setq beg (region-beginning) end (region-end))
16464 (setq beg (point-at-bol)
16465 end (min (1+ (point-at-eol)) (point-max))))
16466 (save-excursion
16467 (goto-char end)
16468 (setq l2 (org-current-line))
16469 (goto-char beg)
16470 (beginning-of-line 1)
16471 (setq l (1- (org-current-line)))
16472 (if (org-on-heading-p)
16473 ;; We already have headlines, de-star them
16474 (while (< (setq l (1+ l)) l2)
16475 (when (org-on-heading-p t)
16476 (and (looking-at outline-regexp) (replace-match "")))
16477 (beginning-of-line 2))
16478 (setq itemp (org-at-item-p))
16479 (let* ((stars
16480 (if nstars
16481 (make-string (prefix-numeric-value current-prefix-arg)
16483 (save-excursion
16484 (if (re-search-backward org-complex-heading-regexp nil t)
16485 (match-string 1) ""))))
16486 (add-stars (cond (nstars "")
16487 ((equal stars "") "*")
16488 (org-odd-levels-only "**")
16489 (t "*")))
16490 (rpl (concat stars add-stars " ")))
16491 (while (< (setq l (1+ l)) l2)
16492 (if itemp
16493 (and (org-at-item-p) (replace-match rpl t t))
16494 (unless (org-on-heading-p)
16495 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16496 (replace-match (concat rpl (match-string 2))))))
16497 (beginning-of-line 2)))))))
16499 (defun org-meta-return (&optional arg)
16500 "Insert a new heading or wrap a region in a table.
16501 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16502 See the individual commands for more information."
16503 (interactive "P")
16504 (cond
16505 ((run-hook-with-args-until-success 'org-metareturn-hook))
16506 ((org-at-table-p)
16507 (call-interactively 'org-table-wrap-region))
16508 (t (call-interactively 'org-insert-heading))))
16510 ;;; Menu entries
16512 ;; Define the Org-mode menus
16513 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16514 '("Tbl"
16515 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16516 ["Next Field" org-cycle (org-at-table-p)]
16517 ["Previous Field" org-shifttab (org-at-table-p)]
16518 ["Next Row" org-return (org-at-table-p)]
16519 "--"
16520 ["Blank Field" org-table-blank-field (org-at-table-p)]
16521 ["Edit Field" org-table-edit-field (org-at-table-p)]
16522 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16523 "--"
16524 ("Column"
16525 ["Move Column Left" org-metaleft (org-at-table-p)]
16526 ["Move Column Right" org-metaright (org-at-table-p)]
16527 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16528 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16529 ("Row"
16530 ["Move Row Up" org-metaup (org-at-table-p)]
16531 ["Move Row Down" org-metadown (org-at-table-p)]
16532 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16533 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16534 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16535 "--"
16536 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16537 ("Rectangle"
16538 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16539 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16540 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16541 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16542 "--"
16543 ("Calculate"
16544 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16545 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16546 ["Edit Formulas" org-edit-special (org-at-table-p)]
16547 "--"
16548 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16549 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16550 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16551 "--"
16552 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16553 "--"
16554 ["Sum Column/Rectangle" org-table-sum
16555 (or (org-at-table-p) (org-region-active-p))]
16556 ["Which Column?" org-table-current-column (org-at-table-p)])
16557 ["Debug Formulas"
16558 org-table-toggle-formula-debugger
16559 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16560 ["Show Col/Row Numbers"
16561 org-table-toggle-coordinate-overlays
16562 :style toggle
16563 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16564 "--"
16565 ["Create" org-table-create (and (not (org-at-table-p))
16566 org-enable-table-editor)]
16567 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16568 ["Import from File" org-table-import (not (org-at-table-p))]
16569 ["Export to File" org-table-export (org-at-table-p)]
16570 "--"
16571 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16573 (easy-menu-define org-org-menu org-mode-map "Org menu"
16574 '("Org"
16575 ("Show/Hide"
16576 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16577 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16578 ["Sparse Tree..." org-sparse-tree t]
16579 ["Reveal Context" org-reveal t]
16580 ["Show All" show-all t]
16581 "--"
16582 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16583 "--"
16584 ["New Heading" org-insert-heading t]
16585 ("Navigate Headings"
16586 ["Up" outline-up-heading t]
16587 ["Next" outline-next-visible-heading t]
16588 ["Previous" outline-previous-visible-heading t]
16589 ["Next Same Level" outline-forward-same-level t]
16590 ["Previous Same Level" outline-backward-same-level t]
16591 "--"
16592 ["Jump" org-goto t])
16593 ("Edit Structure"
16594 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16595 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16596 "--"
16597 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16598 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16599 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16600 "--"
16601 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16602 "--"
16603 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16604 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16605 ["Demote Heading" org-metaright (not (org-at-table-p))]
16606 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16607 "--"
16608 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16609 "--"
16610 ["Convert to odd levels" org-convert-to-odd-levels t]
16611 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16612 ("Editing"
16613 ["Emphasis..." org-emphasize t]
16614 ["Edit Source Example" org-edit-special t]
16615 "--"
16616 ["Footnote new/jump" org-footnote-action t]
16617 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16618 ("Archive"
16619 ["Archive (default method)" org-archive-subtree-default t]
16620 "--"
16621 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16622 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16623 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16625 "--"
16626 ("Hyperlinks"
16627 ["Store Link (Global)" org-store-link t]
16628 ["Find existing link to here" org-occur-link-in-agenda-files t]
16629 ["Insert Link" org-insert-link t]
16630 ["Follow Link" org-open-at-point t]
16631 "--"
16632 ["Next link" org-next-link t]
16633 ["Previous link" org-previous-link t]
16634 "--"
16635 ["Descriptive Links"
16636 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16637 :style radio
16638 :selected (member '(org-link) buffer-invisibility-spec)]
16639 ["Literal Links"
16640 (progn
16641 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16642 :style radio
16643 :selected (not (member '(org-link) buffer-invisibility-spec))])
16644 "--"
16645 ("TODO Lists"
16646 ["TODO/DONE/-" org-todo t]
16647 ("Select keyword"
16648 ["Next keyword" org-shiftright (org-on-heading-p)]
16649 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16650 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16651 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16652 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16653 ["Show TODO Tree" org-show-todo-tree t]
16654 ["Global TODO list" org-todo-list t]
16655 "--"
16656 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16657 :selected org-enforce-todo-dependencies :style toggle :active t]
16658 "Settings for tree at point"
16659 ["Do Children sequentially" org-toggle-ordered-property :style radio
16660 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16661 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16662 ["Do Children parallel" org-toggle-ordered-property :style radio
16663 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16664 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16665 "--"
16666 ["Set Priority" org-priority t]
16667 ["Priority Up" org-shiftup t]
16668 ["Priority Down" org-shiftdown t]
16669 "--"
16670 ["Get news from all feeds" org-feed-update-all t]
16671 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16672 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16673 ("TAGS and Properties"
16674 ["Set Tags" org-set-tags-command t]
16675 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16676 "--"
16677 ["Set property" org-set-property t]
16678 ["Column view of properties" org-columns t]
16679 ["Insert Column View DBlock" org-insert-columns-dblock t])
16680 ("Dates and Scheduling"
16681 ["Timestamp" org-time-stamp t]
16682 ["Timestamp (inactive)" org-time-stamp-inactive t]
16683 ("Change Date"
16684 ["1 Day Later" org-shiftright t]
16685 ["1 Day Earlier" org-shiftleft t]
16686 ["1 ... Later" org-shiftup t]
16687 ["1 ... Earlier" org-shiftdown t])
16688 ["Compute Time Range" org-evaluate-time-range t]
16689 ["Schedule Item" org-schedule t]
16690 ["Deadline" org-deadline t]
16691 "--"
16692 ["Custom time format" org-toggle-time-stamp-overlays
16693 :style radio :selected org-display-custom-times]
16694 "--"
16695 ["Goto Calendar" org-goto-calendar t]
16696 ["Date from Calendar" org-date-from-calendar t]
16697 "--"
16698 ["Start/Restart Timer" org-timer-start t]
16699 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16700 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16701 ["Insert Timer String" org-timer t]
16702 ["Insert Timer Item" org-timer-item t])
16703 ("Logging work"
16704 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16705 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16706 ["Clock out" org-clock-out t]
16707 ["Clock cancel" org-clock-cancel t]
16708 "--"
16709 ["Mark as default task" org-clock-mark-default-task t]
16710 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16711 ["Goto running clock" org-clock-goto t]
16712 "--"
16713 ["Display times" org-clock-display t]
16714 ["Create clock table" org-clock-report t]
16715 "--"
16716 ["Record DONE time"
16717 (progn (setq org-log-done (not org-log-done))
16718 (message "Switching to %s will %s record a timestamp"
16719 (car org-done-keywords)
16720 (if org-log-done "automatically" "not")))
16721 :style toggle :selected org-log-done])
16722 "--"
16723 ["Agenda Command..." org-agenda t]
16724 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16725 ("File List for Agenda")
16726 ("Special views current file"
16727 ["TODO Tree" org-show-todo-tree t]
16728 ["Check Deadlines" org-check-deadlines t]
16729 ["Timeline" org-timeline t]
16730 ["Tags/Property tree" org-match-sparse-tree t])
16731 "--"
16732 ["Export/Publish..." org-export t]
16733 ("LaTeX"
16734 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16735 :selected org-cdlatex-mode]
16736 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16737 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16738 ["Modify math symbol" org-cdlatex-math-modify
16739 (org-inside-LaTeX-fragment-p)]
16740 ["Insert citation" org-reftex-citation t]
16741 "--"
16742 ["Export LaTeX fragments as images"
16743 (if (featurep 'org-exp)
16744 (setq org-export-with-LaTeX-fragments
16745 (not org-export-with-LaTeX-fragments))
16746 (require 'org-exp))
16747 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16748 org-export-with-LaTeX-fragments)]
16749 "--"
16750 ["Template for BEAMER" org-beamer-settings-template t])
16751 "--"
16752 ("MobileOrg"
16753 ["Push Files and Views" org-mobile-push t]
16754 ["Get Captured and Flagged" org-mobile-pull t]
16755 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16756 "--"
16757 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16758 "--"
16759 ("Documentation"
16760 ["Show Version" org-version t]
16761 ["Info Documentation" org-info t])
16762 ("Customize"
16763 ["Browse Org Group" org-customize t]
16764 "--"
16765 ["Expand This Menu" org-create-customize-menu
16766 (fboundp 'customize-menu-create)])
16767 ["Send bug report" org-submit-bug-report t]
16768 "--"
16769 ("Refresh/Reload"
16770 ["Refresh setup current buffer" org-mode-restart t]
16771 ["Reload Org (after update)" org-reload t]
16772 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16775 (defun org-info (&optional node)
16776 "Read documentation for Org-mode in the info system.
16777 With optional NODE, go directly to that node."
16778 (interactive)
16779 (info (format "(org)%s" (or node ""))))
16781 ;;;###autoload
16782 (defun org-submit-bug-report ()
16783 "Submit a bug report on Org-mode via mail.
16785 Don't hesitate to report any problems or inaccurate documentation.
16787 If you don't have setup sending mail from (X)Emacs, please copy the
16788 output buffer into your mail program, as it gives us important
16789 information about your Org-mode version and configuration."
16790 (interactive)
16791 (require 'reporter)
16792 (org-load-modules-maybe)
16793 (org-require-autoloaded-modules)
16794 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16795 (reporter-submit-bug-report
16796 "emacs-orgmode@gnu.org"
16797 (org-version)
16798 (let (list)
16799 (save-window-excursion
16800 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16801 (delete-other-windows)
16802 (erase-buffer)
16803 (insert "You are about to submit a bug report to the Org-mode mailing list.
16805 We would like to add your full Org-mode and Outline configuration to the
16806 bug report. This greatly simplifies the work of the maintainer and
16807 other experts on the mailing list.
16809 HOWEVER, some variables you have customized may contain private
16810 information. The names of customers, colleagues, or friends, might
16811 appear in the form of file names, tags, todo states, or search strings.
16812 If you answer yes to the prompt, you might want to check and remove
16813 such private information before sending the email.")
16814 (add-text-properties (point-min) (point-max) '(face org-warning))
16815 (when (yes-or-no-p "Include your Org-mode configuration ")
16816 (mapatoms
16817 (lambda (v)
16818 (and (boundp v)
16819 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16820 (or (and (symbol-value v)
16821 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16822 (and
16823 (get v 'custom-type) (get v 'standard-value)
16824 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16825 (push v list)))))
16826 (kill-buffer (get-buffer "*Warn about privacy*"))
16827 list))
16828 nil nil
16829 "Remember to cover the basics, that is, what you expected to happen and
16830 what in fact did happen. You don't know how to make a good report? See
16832 http://orgmode.org/manual/Feedback.html#Feedback
16834 Your bug report will be posted to the Org-mode mailing list.
16835 ------------------------------------------------------------------------")
16836 (save-excursion
16837 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16838 (replace-match "\\1Bug: \\3 [\\2]")))))
16841 (defun org-install-agenda-files-menu ()
16842 (let ((bl (buffer-list)))
16843 (save-excursion
16844 (while bl
16845 (set-buffer (pop bl))
16846 (if (org-mode-p) (setq bl nil)))
16847 (when (org-mode-p)
16848 (easy-menu-change
16849 '("Org") "File List for Agenda"
16850 (append
16851 (list
16852 ["Edit File List" (org-edit-agenda-file-list) t]
16853 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16854 ["Remove Current File from List" org-remove-file t]
16855 ["Cycle through agenda files" org-cycle-agenda-files t]
16856 ["Occur in all agenda files" org-occur-in-agenda-files t]
16857 "--")
16858 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16860 ;;;; Documentation
16862 ;;;###autoload
16863 (defun org-require-autoloaded-modules ()
16864 (interactive)
16865 (mapc 'require
16866 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16867 org-docbook org-exp org-html org-icalendar
16868 org-id org-latex
16869 org-publish org-remember org-table
16870 org-timer org-xoxo)))
16872 ;;;###autoload
16873 (defun org-reload (&optional uncompiled)
16874 "Reload all org lisp files.
16875 With prefix arg UNCOMPILED, load the uncompiled versions."
16876 (interactive "P")
16877 (require 'find-func)
16878 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16879 (dir-org (file-name-directory (org-find-library-name "org")))
16880 (dir-org-contrib (ignore-errors
16881 (file-name-directory
16882 (org-find-library-name "org-contribdir"))))
16883 (files
16884 (append (directory-files dir-org t file-re)
16885 (and dir-org-contrib
16886 (directory-files dir-org-contrib t file-re))))
16887 (remove-re (concat (if (featurep 'xemacs)
16888 "org-colview" "org-colview-xemacs")
16889 "\\'")))
16890 (setq files (mapcar 'file-name-sans-extension files))
16891 (setq files (mapcar
16892 (lambda (x) (if (string-match remove-re x) nil x))
16893 files))
16894 (setq files (delq nil files))
16895 (mapc
16896 (lambda (f)
16897 (when (featurep (intern (file-name-nondirectory f)))
16898 (if (and (not uncompiled)
16899 (file-exists-p (concat f ".elc")))
16900 (load (concat f ".elc") nil nil t)
16901 (load (concat f ".el") nil nil t))))
16902 files))
16903 (org-version))
16905 ;;;###autoload
16906 (defun org-customize ()
16907 "Call the customize function with org as argument."
16908 (interactive)
16909 (org-load-modules-maybe)
16910 (org-require-autoloaded-modules)
16911 (customize-browse 'org))
16913 (defun org-create-customize-menu ()
16914 "Create a full customization menu for Org-mode, insert it into the menu."
16915 (interactive)
16916 (org-load-modules-maybe)
16917 (org-require-autoloaded-modules)
16918 (if (fboundp 'customize-menu-create)
16919 (progn
16920 (easy-menu-change
16921 '("Org") "Customize"
16922 `(["Browse Org group" org-customize t]
16923 "--"
16924 ,(customize-menu-create 'org)
16925 ["Set" Custom-set t]
16926 ["Save" Custom-save t]
16927 ["Reset to Current" Custom-reset-current t]
16928 ["Reset to Saved" Custom-reset-saved t]
16929 ["Reset to Standard Settings" Custom-reset-standard t]))
16930 (message "\"Org\"-menu now contains full customization menu"))
16931 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16933 ;;;; Miscellaneous stuff
16935 ;;; Generally useful functions
16937 (defun org-get-at-bol (property)
16938 "Get text property PROPERTY at beginning of line."
16939 (get-text-property (point-at-bol) property))
16941 (defun org-find-text-property-in-string (prop s)
16942 "Return the first non-nil value of property PROP in string S."
16943 (or (get-text-property 0 prop s)
16944 (get-text-property (or (next-single-property-change 0 prop s) 0)
16945 prop s)))
16947 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16948 "Display the given MESSAGE as a warning."
16949 (if (fboundp 'display-warning)
16950 (display-warning 'org message
16951 (if (featurep 'xemacs)
16952 'warning
16953 :warning))
16954 (let ((buf (get-buffer-create "*Org warnings*")))
16955 (with-current-buffer buf
16956 (goto-char (point-max))
16957 (insert "Warning (Org): " message)
16958 (unless (bolp)
16959 (newline)))
16960 (display-buffer buf)
16961 (sit-for 0))))
16963 (defun org-in-commented-line ()
16964 "Is point in a line starting with `#'?"
16965 (equal (char-after (point-at-bol)) ?#))
16967 (defun org-in-verbatim-emphasis ()
16968 (save-match-data
16969 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16971 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16972 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16973 (if (and marker (marker-buffer marker)
16974 (buffer-live-p (marker-buffer marker)))
16975 (progn
16976 (switch-to-buffer (marker-buffer marker))
16977 (if (or (> marker (point-max)) (< marker (point-min)))
16978 (widen))
16979 (goto-char marker)
16980 (org-show-context 'org-goto))
16981 (if bookmark
16982 (bookmark-jump bookmark)
16983 (error "Cannot find location"))))
16985 (defun org-quote-csv-field (s)
16986 "Quote field for inclusion in CSV material."
16987 (if (string-match "[\",]" s)
16988 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16991 (defun org-plist-delete (plist property)
16992 "Delete PROPERTY from PLIST.
16993 This is in contrast to merely setting it to 0."
16994 (let (p)
16995 (while plist
16996 (if (not (eq property (car plist)))
16997 (setq p (plist-put p (car plist) (nth 1 plist))))
16998 (setq plist (cddr plist)))
17001 (defun org-force-self-insert (N)
17002 "Needed to enforce self-insert under remapping."
17003 (interactive "p")
17004 (self-insert-command N))
17006 (defun org-string-width (s)
17007 "Compute width of string, ignoring invisible characters.
17008 This ignores character with invisibility property `org-link', and also
17009 characters with property `org-cwidth', because these will become invisible
17010 upon the next fontification round."
17011 (let (b l)
17012 (when (or (eq t buffer-invisibility-spec)
17013 (assq 'org-link buffer-invisibility-spec))
17014 (while (setq b (text-property-any 0 (length s)
17015 'invisible 'org-link s))
17016 (setq s (concat (substring s 0 b)
17017 (substring s (or (next-single-property-change
17018 b 'invisible s) (length s)))))))
17019 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17020 (setq s (concat (substring s 0 b)
17021 (substring s (or (next-single-property-change
17022 b 'org-cwidth s) (length s))))))
17023 (setq l (string-width s) b -1)
17024 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17025 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17028 (defun org-get-indentation (&optional line)
17029 "Get the indentation of the current line, interpreting tabs.
17030 When LINE is given, assume it represents a line and compute its indentation."
17031 (if line
17032 (if (string-match "^ *" (org-remove-tabs line))
17033 (match-end 0))
17034 (save-excursion
17035 (beginning-of-line 1)
17036 (skip-chars-forward " \t")
17037 (current-column))))
17039 (defun org-remove-tabs (s &optional width)
17040 "Replace tabulators in S with spaces.
17041 Assumes that s is a single line, starting in column 0."
17042 (setq width (or width tab-width))
17043 (while (string-match "\t" s)
17044 (setq s (replace-match
17045 (make-string
17046 (- (* width (/ (+ (match-beginning 0) width) width))
17047 (match-beginning 0)) ?\ )
17048 t t s)))
17051 (defun org-fix-indentation (line ind)
17052 "Fix indentation in LINE.
17053 IND is a cons cell with target and minimum indentation.
17054 If the current indentation in LINE is smaller than the minimum,
17055 leave it alone. If it is larger than ind, set it to the target."
17056 (let* ((l (org-remove-tabs line))
17057 (i (org-get-indentation l))
17058 (i1 (car ind)) (i2 (cdr ind)))
17059 (if (>= i i2) (setq l (substring line i2)))
17060 (if (> i1 0)
17061 (concat (make-string i1 ?\ ) l)
17062 l)))
17064 (defun org-remove-indentation (code &optional n)
17065 "Remove the maximum common indentation from the lines in CODE.
17066 N may optionally be the number of spaces to remove."
17067 (with-temp-buffer
17068 (insert code)
17069 (org-do-remove-indentation n)
17070 (buffer-string)))
17072 (defun org-do-remove-indentation (&optional n)
17073 "Remove the maximum common indentation from the buffer."
17074 (untabify (point-min) (point-max))
17075 (let ((min 10000) re)
17076 (if n
17077 (setq min n)
17078 (goto-char (point-min))
17079 (while (re-search-forward "^ *[^ \n]" nil t)
17080 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17081 (unless (or (= min 0) (= min 10000))
17082 (setq re (format "^ \\{%d\\}" min))
17083 (goto-char (point-min))
17084 (while (re-search-forward re nil t)
17085 (replace-match "")
17086 (end-of-line 1))
17087 min)))
17089 (defun org-fill-template (template alist)
17090 "Find each %key of ALIST in TEMPLATE and replace it."
17091 (let ((case-fold-search nil)
17092 entry key value)
17093 (setq alist (sort (copy-sequence alist)
17094 (lambda (a b) (< (length (car a)) (length (car b))))))
17095 (while (setq entry (pop alist))
17096 (setq template
17097 (replace-regexp-in-string
17098 (concat "%" (regexp-quote (car entry)))
17099 (cdr entry) template t t)))
17100 template))
17102 (defun org-base-buffer (buffer)
17103 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17104 (if (not buffer)
17105 buffer
17106 (or (buffer-base-buffer buffer)
17107 buffer)))
17109 (defun org-trim (s)
17110 "Remove whitespace at beginning and end of string."
17111 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17112 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17115 (defun org-wrap (string &optional width lines)
17116 "Wrap string to either a number of lines, or a width in characters.
17117 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17118 that costs. If there is a word longer than WIDTH, the text is actually
17119 wrapped to the length of that word.
17120 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17121 many lines, whatever width that takes.
17122 The return value is a list of lines, without newlines at the end."
17123 (let* ((words (org-split-string string "[ \t\n]+"))
17124 (maxword (apply 'max (mapcar 'org-string-width words)))
17125 w ll)
17126 (cond (width
17127 (org-do-wrap words (max maxword width)))
17128 (lines
17129 (setq w maxword)
17130 (setq ll (org-do-wrap words maxword))
17131 (if (<= (length ll) lines)
17133 (setq ll words)
17134 (while (> (length ll) lines)
17135 (setq w (1+ w))
17136 (setq ll (org-do-wrap words w)))
17137 ll))
17138 (t (error "Cannot wrap this")))))
17140 (defun org-do-wrap (words width)
17141 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17142 (let (lines line)
17143 (while words
17144 (setq line (pop words))
17145 (while (and words (< (+ (length line) (length (car words))) width))
17146 (setq line (concat line " " (pop words))))
17147 (setq lines (push line lines)))
17148 (nreverse lines)))
17150 (defun org-split-string (string &optional separators)
17151 "Splits STRING into substrings at SEPARATORS.
17152 No empty strings are returned if there are matches at the beginning
17153 and end of string."
17154 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17155 (start 0)
17156 notfirst
17157 (list nil))
17158 (while (and (string-match rexp string
17159 (if (and notfirst
17160 (= start (match-beginning 0))
17161 (< start (length string)))
17162 (1+ start) start))
17163 (< (match-beginning 0) (length string)))
17164 (setq notfirst t)
17165 (or (eq (match-beginning 0) 0)
17166 (and (eq (match-beginning 0) (match-end 0))
17167 (eq (match-beginning 0) start))
17168 (setq list
17169 (cons (substring string start (match-beginning 0))
17170 list)))
17171 (setq start (match-end 0)))
17172 (or (eq start (length string))
17173 (setq list
17174 (cons (substring string start)
17175 list)))
17176 (nreverse list)))
17178 (defun org-quote-vert (s)
17179 "Replace \"|\" with \"\\vert\"."
17180 (while (string-match "|" s)
17181 (setq s (replace-match "\\vert" t t s)))
17184 (defun org-uuidgen-p (s)
17185 "Is S an ID created by UUIDGEN?"
17186 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17188 (defun org-context ()
17189 "Return a list of contexts of the current cursor position.
17190 If several contexts apply, all are returned.
17191 Each context entry is a list with a symbol naming the context, and
17192 two positions indicating start and end of the context. Possible
17193 contexts are:
17195 :headline anywhere in a headline
17196 :headline-stars on the leading stars in a headline
17197 :todo-keyword on a TODO keyword (including DONE) in a headline
17198 :tags on the TAGS in a headline
17199 :priority on the priority cookie in a headline
17200 :item on the first line of a plain list item
17201 :item-bullet on the bullet/number of a plain list item
17202 :checkbox on the checkbox in a plain list item
17203 :table in an org-mode table
17204 :table-special on a special filed in a table
17205 :table-table in a table.el table
17206 :link on a hyperlink
17207 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17208 :target on a <<target>>
17209 :radio-target on a <<<radio-target>>>
17210 :latex-fragment on a LaTeX fragment
17211 :latex-preview on a LaTeX fragment with overlayed preview image
17213 This function expects the position to be visible because it uses font-lock
17214 faces as a help to recognize the following contexts: :table-special, :link,
17215 and :keyword."
17216 (let* ((f (get-text-property (point) 'face))
17217 (faces (if (listp f) f (list f)))
17218 (p (point)) clist o)
17219 ;; First the large context
17220 (cond
17221 ((org-on-heading-p t)
17222 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17223 (when (progn
17224 (beginning-of-line 1)
17225 (looking-at org-todo-line-tags-regexp))
17226 (push (org-point-in-group p 1 :headline-stars) clist)
17227 (push (org-point-in-group p 2 :todo-keyword) clist)
17228 (push (org-point-in-group p 4 :tags) clist))
17229 (goto-char p)
17230 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17231 (if (looking-at "\\[#[A-Z0-9]\\]")
17232 (push (org-point-in-group p 0 :priority) clist)))
17234 ((org-at-item-p)
17235 (push (org-point-in-group p 2 :item-bullet) clist)
17236 (push (list :item (point-at-bol)
17237 (save-excursion (org-end-of-item) (point)))
17238 clist)
17239 (and (org-at-item-checkbox-p)
17240 (push (org-point-in-group p 0 :checkbox) clist)))
17242 ((org-at-table-p)
17243 (push (list :table (org-table-begin) (org-table-end)) clist)
17244 (if (memq 'org-formula faces)
17245 (push (list :table-special
17246 (previous-single-property-change p 'face)
17247 (next-single-property-change p 'face)) clist)))
17248 ((org-at-table-p 'any)
17249 (push (list :table-table) clist)))
17250 (goto-char p)
17252 ;; Now the small context
17253 (cond
17254 ((org-at-timestamp-p)
17255 (push (org-point-in-group p 0 :timestamp) clist))
17256 ((memq 'org-link faces)
17257 (push (list :link
17258 (previous-single-property-change p 'face)
17259 (next-single-property-change p 'face)) clist))
17260 ((memq 'org-special-keyword faces)
17261 (push (list :keyword
17262 (previous-single-property-change p 'face)
17263 (next-single-property-change p 'face)) clist))
17264 ((org-on-target-p)
17265 (push (org-point-in-group p 0 :target) clist)
17266 (goto-char (1- (match-beginning 0)))
17267 (if (looking-at org-radio-target-regexp)
17268 (push (org-point-in-group p 0 :radio-target) clist))
17269 (goto-char p))
17270 ((setq o (car (delq nil
17271 (mapcar
17272 (lambda (x)
17273 (if (memq x org-latex-fragment-image-overlays) x))
17274 (org-overlays-at (point))))))
17275 (push (list :latex-fragment
17276 (org-overlay-start o) (org-overlay-end o)) clist)
17277 (push (list :latex-preview
17278 (org-overlay-start o) (org-overlay-end o)) clist))
17279 ((org-inside-LaTeX-fragment-p)
17280 ;; FIXME: positions wrong.
17281 (push (list :latex-fragment (point) (point)) clist)))
17283 (setq clist (nreverse (delq nil clist)))
17284 clist))
17286 ;; FIXME: Compare with at-regexp-p Do we need both?
17287 (defun org-in-regexp (re &optional nlines visually)
17288 "Check if point is inside a match of regexp.
17289 Normally only the current line is checked, but you can include NLINES extra
17290 lines both before and after point into the search.
17291 If VISUALLY is set, require that the cursor is not after the match but
17292 really on, so that the block visually is on the match."
17293 (catch 'exit
17294 (let ((pos (point))
17295 (eol (point-at-eol (+ 1 (or nlines 0))))
17296 (inc (if visually 1 0)))
17297 (save-excursion
17298 (beginning-of-line (- 1 (or nlines 0)))
17299 (while (re-search-forward re eol t)
17300 (if (and (<= (match-beginning 0) pos)
17301 (>= (+ inc (match-end 0)) pos))
17302 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17304 (defun org-at-regexp-p (regexp)
17305 "Is point inside a match of REGEXP in the current line?"
17306 (catch 'exit
17307 (save-excursion
17308 (let ((pos (point)) (end (point-at-eol)))
17309 (beginning-of-line 1)
17310 (while (re-search-forward regexp end t)
17311 (if (and (<= (match-beginning 0) pos)
17312 (>= (match-end 0) pos))
17313 (throw 'exit t)))
17314 nil))))
17316 (defun org-in-regexps-block-p (start-re end-re)
17317 "Returns t if the current point is between matches of START-RE and END-RE.
17318 This will also return to if point is on one of the two matches."
17319 (interactive)
17320 (let ((p (point)))
17321 (save-excursion
17322 (and (or (org-at-regexp-p start-re)
17323 (re-search-backward start-re nil t))
17324 (re-search-forward end-re nil t)
17325 (>= (point) p)))))
17327 (defun org-occur-in-agenda-files (regexp &optional nlines)
17328 "Call `multi-occur' with buffers for all agenda files."
17329 (interactive "sOrg-files matching: \np")
17330 (let* ((files (org-agenda-files))
17331 (tnames (mapcar 'file-truename files))
17332 (extra org-agenda-text-search-extra-files)
17334 (when (eq (car extra) 'agenda-archives)
17335 (setq extra (cdr extra))
17336 (setq files (org-add-archive-files files)))
17337 (while (setq f (pop extra))
17338 (unless (member (file-truename f) tnames)
17339 (add-to-list 'files f 'append)
17340 (add-to-list 'tnames (file-truename f) 'append)))
17341 (multi-occur
17342 (mapcar (lambda (x)
17343 (with-current-buffer
17344 (or (get-file-buffer x) (find-file-noselect x))
17345 (widen)
17346 (current-buffer)))
17347 files)
17348 regexp)))
17350 (if (boundp 'occur-mode-find-occurrence-hook)
17351 ;; Emacs 23
17352 (add-hook 'occur-mode-find-occurrence-hook
17353 (lambda ()
17354 (when (org-mode-p)
17355 (org-reveal))))
17356 ;; Emacs 22
17357 (defadvice occur-mode-goto-occurrence
17358 (after org-occur-reveal activate)
17359 (and (org-mode-p) (org-reveal)))
17360 (defadvice occur-mode-goto-occurrence-other-window
17361 (after org-occur-reveal activate)
17362 (and (org-mode-p) (org-reveal)))
17363 (defadvice occur-mode-display-occurrence
17364 (after org-occur-reveal activate)
17365 (when (org-mode-p)
17366 (let ((pos (occur-mode-find-occurrence)))
17367 (with-current-buffer (marker-buffer pos)
17368 (save-excursion
17369 (goto-char pos)
17370 (org-reveal)))))))
17372 (defun org-occur-link-in-agenda-files ()
17373 "Create a link and search for it in the agendas.
17374 The link is not stored in `org-stored-links', it is just created
17375 for the search purpose."
17376 (interactive)
17377 (let ((link (condition-case nil
17378 (org-store-link nil)
17379 (error "Unable to create a link to here"))))
17380 (org-occur-in-agenda-files (regexp-quote link))))
17382 (defun org-uniquify (list)
17383 "Remove duplicate elements from LIST."
17384 (let (res)
17385 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17386 res))
17388 (defun org-delete-all (elts list)
17389 "Remove all elements in ELTS from LIST."
17390 (while elts
17391 (setq list (delete (pop elts) list)))
17392 list)
17394 (defun org-back-over-empty-lines ()
17395 "Move backwards over whitespace, to the beginning of the first empty line.
17396 Returns the number of empty lines passed."
17397 (let ((pos (point)))
17398 (skip-chars-backward " \t\n\r")
17399 (beginning-of-line 2)
17400 (goto-char (min (point) pos))
17401 (count-lines (point) pos)))
17403 (defun org-skip-whitespace ()
17404 (skip-chars-forward " \t\n\r"))
17406 (defun org-point-in-group (point group &optional context)
17407 "Check if POINT is in match-group GROUP.
17408 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17409 match. If the match group does ot exist or point is not inside it,
17410 return nil."
17411 (and (match-beginning group)
17412 (>= point (match-beginning group))
17413 (<= point (match-end group))
17414 (if context
17415 (list context (match-beginning group) (match-end group))
17416 t)))
17418 (defun org-switch-to-buffer-other-window (&rest args)
17419 "Switch to buffer in a second window on the current frame.
17420 In particular, do not allow pop-up frames."
17421 (let (pop-up-frames special-display-buffer-names special-display-regexps
17422 special-display-function)
17423 (apply 'switch-to-buffer-other-window args)))
17425 (defun org-combine-plists (&rest plists)
17426 "Create a single property list from all plists in PLISTS.
17427 The process starts by copying the first list, and then setting properties
17428 from the other lists. Settings in the last list are the most significant
17429 ones and overrule settings in the other lists."
17430 (let ((rtn (copy-sequence (pop plists)))
17431 p v ls)
17432 (while plists
17433 (setq ls (pop plists))
17434 (while ls
17435 (setq p (pop ls) v (pop ls))
17436 (setq rtn (plist-put rtn p v))))
17437 rtn))
17439 (defun org-move-line-down (arg)
17440 "Move the current line down. With prefix argument, move it past ARG lines."
17441 (interactive "p")
17442 (let ((col (current-column))
17443 beg end pos)
17444 (beginning-of-line 1) (setq beg (point))
17445 (beginning-of-line 2) (setq end (point))
17446 (beginning-of-line (+ 1 arg))
17447 (setq pos (move-marker (make-marker) (point)))
17448 (insert (delete-and-extract-region beg end))
17449 (goto-char pos)
17450 (org-move-to-column col)))
17452 (defun org-move-line-up (arg)
17453 "Move the current line up. With prefix argument, move it past ARG lines."
17454 (interactive "p")
17455 (let ((col (current-column))
17456 beg end pos)
17457 (beginning-of-line 1) (setq beg (point))
17458 (beginning-of-line 2) (setq end (point))
17459 (beginning-of-line (- arg))
17460 (setq pos (move-marker (make-marker) (point)))
17461 (insert (delete-and-extract-region beg end))
17462 (goto-char pos)
17463 (org-move-to-column col)))
17465 (defun org-replace-escapes (string table)
17466 "Replace %-escapes in STRING with values in TABLE.
17467 TABLE is an association list with keys like \"%a\" and string values.
17468 The sequences in STRING may contain normal field width and padding information,
17469 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17470 so values can contain further %-escapes if they are define later in TABLE."
17471 (let ((case-fold-search nil)
17472 e re rpl)
17473 (while (setq e (pop table))
17474 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17475 (while (string-match re string)
17476 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17477 (cdr e)))
17478 (setq string (replace-match rpl t t string))))
17479 string))
17482 (defun org-sublist (list start end)
17483 "Return a section of LIST, from START to END.
17484 Counting starts at 1."
17485 (let (rtn (c start))
17486 (setq list (nthcdr (1- start) list))
17487 (while (and list (<= c end))
17488 (push (pop list) rtn)
17489 (setq c (1+ c)))
17490 (nreverse rtn)))
17492 (defun org-find-base-buffer-visiting (file)
17493 "Like `find-buffer-visiting' but always return the base buffer and
17494 not an indirect buffer."
17495 (let ((buf (or (get-file-buffer file)
17496 (find-buffer-visiting file))))
17497 (if buf
17498 (or (buffer-base-buffer buf) buf)
17499 nil)))
17501 (defun org-image-file-name-regexp (&optional extensions)
17502 "Return regexp matching the file names of images.
17503 If EXTENSIONS is given, only match these."
17504 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17505 (image-file-name-regexp)
17506 (let ((image-file-name-extensions
17507 (or extensions
17508 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17509 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17510 (concat "\\."
17511 (regexp-opt (nconc (mapcar 'upcase
17512 image-file-name-extensions)
17513 image-file-name-extensions)
17515 "\\'"))))
17517 (defun org-file-image-p (file &optional extensions)
17518 "Return non-nil if FILE is an image."
17519 (save-match-data
17520 (string-match (org-image-file-name-regexp extensions) file)))
17522 (defun org-get-cursor-date ()
17523 "Return the date at cursor in as a time.
17524 This works in the calendar and in the agenda, anywhere else it just
17525 returns the current time."
17526 (let (date day defd)
17527 (cond
17528 ((eq major-mode 'calendar-mode)
17529 (setq date (calendar-cursor-to-date)
17530 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17531 ((eq major-mode 'org-agenda-mode)
17532 (setq day (get-text-property (point) 'day))
17533 (if day
17534 (setq date (calendar-gregorian-from-absolute day)
17535 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17536 (nth 2 date))))))
17537 (or defd (current-time))))
17539 (defvar org-agenda-action-marker (make-marker)
17540 "Marker pointing to the entry for the next agenda action.")
17542 (defun org-mark-entry-for-agenda-action ()
17543 "Mark the current entry as target of an agenda action.
17544 Agenda actions are actions executed from the agenda with the key `k',
17545 which make use of the date at the cursor."
17546 (interactive)
17547 (move-marker org-agenda-action-marker
17548 (save-excursion (org-back-to-heading t) (point))
17549 (current-buffer))
17550 (message
17551 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17553 ;;; Paragraph filling stuff.
17554 ;; We want this to be just right, so use the full arsenal.
17556 (defun org-indent-line-function ()
17557 "Indent line like previous, but further if previous was headline or item."
17558 (interactive)
17559 (let* ((pos (point))
17560 (itemp (org-at-item-p))
17561 (case-fold-search t)
17562 (org-drawer-regexp (or org-drawer-regexp "\000"))
17563 column bpos bcol tpos tcol bullet btype bullet-type)
17564 ;; Find the previous relevant line
17565 (beginning-of-line 1)
17566 (cond
17567 ((looking-at "#") (setq column 0))
17568 ((looking-at "\\*+ ") (setq column 0))
17569 ((and (looking-at "[ \t]*:END:")
17570 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17571 (save-excursion
17572 (goto-char (1- (match-beginning 1)))
17573 (setq column (current-column))))
17574 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17575 (save-excursion
17576 (re-search-backward
17577 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17578 (setq column (org-get-indentation (match-string 0))))
17580 (beginning-of-line 0)
17581 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17582 (not (looking-at "[ \t]*:END:"))
17583 (not (looking-at org-drawer-regexp)))
17584 (beginning-of-line 0))
17585 (cond
17586 ((looking-at "\\*+[ \t]+")
17587 (if (not org-adapt-indentation)
17588 (setq column 0)
17589 (goto-char (match-end 0))
17590 (setq column (current-column))))
17591 ((looking-at org-drawer-regexp)
17592 (goto-char (1- (match-beginning 1)))
17593 (setq column (current-column)))
17594 ((looking-at "\\([ \t]*\\):END:")
17595 (goto-char (match-end 1))
17596 (setq column (current-column)))
17597 ((org-in-item-p)
17598 (org-beginning-of-item)
17599 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17600 (setq bpos (match-beginning 1) tpos (match-end 0)
17601 bcol (progn (goto-char bpos) (current-column))
17602 tcol (progn (goto-char tpos) (current-column))
17603 bullet (match-string 1)
17604 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17605 (if (> tcol (+ bcol org-description-max-indent))
17606 (setq tcol (+ bcol 5)))
17607 (if (not itemp)
17608 (setq column tcol)
17609 (goto-char pos)
17610 (beginning-of-line 1)
17611 (if (looking-at "\\S-")
17612 (progn
17613 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17614 (setq bullet (match-string 1)
17615 btype (if (string-match "[0-9]" bullet) "n" bullet))
17616 (setq column (if (equal btype bullet-type) bcol tcol)))
17617 (setq column (org-get-indentation)))))
17618 (t (setq column (org-get-indentation))))))
17619 (goto-char pos)
17620 (if (<= (current-column) (current-indentation))
17621 (org-indent-line-to column)
17622 (save-excursion (org-indent-line-to column)))
17623 (setq column (current-column))
17624 (beginning-of-line 1)
17625 (if (looking-at
17626 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17627 (replace-match (concat (match-string 1)
17628 (format org-property-format
17629 (match-string 2) (match-string 3)))
17630 t t))
17631 (org-move-to-column column)))
17633 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17634 "Variable to store copy of `adaptive-fill-regexp'.
17635 Since `adaptive-fill-regexp' is set to never match, we need to
17636 store a backup of its value before entering `org-mode' so that
17637 the functionality can be provided as a fall-back.")
17639 (defun org-set-autofill-regexps ()
17640 (interactive)
17641 ;; In the paragraph separator we include headlines, because filling
17642 ;; text in a line directly attached to a headline would otherwise
17643 ;; fill the headline as well.
17644 (org-set-local 'comment-start-skip "^#+[ \t]*")
17645 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17646 ;; The paragraph starter includes hand-formatted lists.
17647 (org-set-local
17648 'paragraph-start
17649 (concat
17650 "\f" "\\|"
17651 "[ ]*$" "\\|"
17652 "\\*+ " "\\|"
17653 "[ \t]*#" "\\|"
17654 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17655 "[ \t]*[:|]" "\\|"
17656 "\\$\\$" "\\|"
17657 "\\\\\\(begin\\|end\\|[][]\\)"))
17658 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17659 ;; But only if the user has not turned off tables or fixed-width regions
17660 (org-set-local
17661 'auto-fill-inhibit-regexp
17662 (concat "\\*+ \\|#\\+"
17663 "\\|[ \t]*" org-keyword-time-regexp
17664 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17665 (concat
17666 "\\|[ \t]*["
17667 (if org-enable-table-editor "|" "")
17668 (if org-enable-fixed-width-editor ":" "")
17669 "]"))))
17670 ;; We use our own fill-paragraph function, to make sure that tables
17671 ;; and fixed-width regions are not wrapped. That function will pass
17672 ;; through to `fill-paragraph' when appropriate.
17673 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17674 ;; Adaptive filling: To get full control, first make sure that
17675 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17676 (unless (local-variable-p 'adaptive-fill-regexp)
17677 (org-set-local 'org-adaptive-fill-regexp-backup
17678 adaptive-fill-regexp))
17679 (org-set-local 'adaptive-fill-regexp "\000")
17680 (org-set-local 'adaptive-fill-function
17681 'org-adaptive-fill-function)
17682 (org-set-local
17683 'align-mode-rules-list
17684 '((org-in-buffer-settings
17685 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17686 (modes . '(org-mode))))))
17688 (defun org-fill-paragraph (&optional justify)
17689 "Re-align a table, pass through to fill-paragraph if no table."
17690 (let ((table-p (org-at-table-p))
17691 (table.el-p (org-at-table.el-p)))
17692 (cond ((and (equal (char-after (point-at-bol)) ?*)
17693 (save-excursion (goto-char (point-at-bol))
17694 (looking-at outline-regexp)))
17695 t) ; skip headlines
17696 (table.el-p t) ; skip table.el tables
17697 (table-p (org-table-align) t) ; align org-mode tables
17698 (t nil)))) ; call paragraph-fill
17700 ;; For reference, this is the default value of adaptive-fill-regexp
17701 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17703 (defun org-adaptive-fill-function ()
17704 "Return a fill prefix for org-mode files.
17705 In particular, this makes sure hanging paragraphs for hand-formatted lists
17706 work correctly."
17707 (cond
17708 ;; Comment line
17709 ((looking-at "#[ \t]+")
17710 (match-string-no-properties 0))
17711 ;; Description list
17712 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17713 (save-excursion
17714 (if (> (match-end 1) (+ (match-beginning 1)
17715 org-description-max-indent))
17716 (goto-char (+ (match-beginning 1) 5))
17717 (goto-char (match-end 0)))
17718 (make-string (current-column) ?\ )))
17719 ;; Ordered or unordered list
17720 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17721 (save-excursion
17722 (goto-char (match-end 0))
17723 (make-string (current-column) ?\ )))
17724 ;; Other text
17725 ((looking-at org-adaptive-fill-regexp-backup)
17726 (match-string-no-properties 0))))
17728 ;;; Other stuff.
17730 (defun org-toggle-fixed-width-section (arg)
17731 "Toggle the fixed-width export.
17732 If there is no active region, the QUOTE keyword at the current headline is
17733 inserted or removed. When present, it causes the text between this headline
17734 and the next to be exported as fixed-width text, and unmodified.
17735 If there is an active region, this command adds or removes a colon as the
17736 first character of this line. If the first character of a line is a colon,
17737 this line is also exported in fixed-width font."
17738 (interactive "P")
17739 (let* ((cc 0)
17740 (regionp (org-region-active-p))
17741 (beg (if regionp (region-beginning) (point)))
17742 (end (if regionp (region-end)))
17743 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17744 (case-fold-search nil)
17745 (re "[ \t]*\\(: \\)")
17746 off)
17747 (if regionp
17748 (save-excursion
17749 (goto-char beg)
17750 (setq cc (current-column))
17751 (beginning-of-line 1)
17752 (setq off (looking-at re))
17753 (while (> nlines 0)
17754 (setq nlines (1- nlines))
17755 (beginning-of-line 1)
17756 (cond
17757 (arg
17758 (org-move-to-column cc t)
17759 (insert ": \n")
17760 (forward-line -1))
17761 ((and off (looking-at re))
17762 (replace-match "" t t nil 1))
17763 ((not off) (org-move-to-column cc t) (insert ": ")))
17764 (forward-line 1)))
17765 (save-excursion
17766 (org-back-to-heading)
17767 (if (looking-at (concat outline-regexp
17768 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17769 (replace-match "" t t nil 1)
17770 (if (looking-at outline-regexp)
17771 (progn
17772 (goto-char (match-end 0))
17773 (insert org-quote-string " "))))))))
17775 (defun org-reftex-citation ()
17776 "Use reftex-citation to insert a citation into the buffer.
17777 This looks for a line like
17779 #+BIBLIOGRAPHY: foo plain option:-d
17781 and derives from it that foo.bib is the bibliography file relevant
17782 for this document. It then installs the necessary environment for RefTeX
17783 to work in this buffer and calls `reftex-citation' to insert a citation
17784 into the buffer.
17786 Export of such citations to both LaTeX and HTML is handled by the contributed
17787 package org-exp-bibtex by Taru Karttunen."
17788 (interactive)
17789 (let ((reftex-docstruct-symbol 'rds)
17790 (reftex-cite-format "\\cite{%l}")
17791 rds bib)
17792 (save-excursion
17793 (save-restriction
17794 (widen)
17795 (let ((case-fold-search t)
17796 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17797 (if (not (save-excursion
17798 (or (re-search-forward re nil t)
17799 (re-search-backward re nil t))))
17800 (error "No bibliography defined in file")
17801 (setq bib (concat (match-string 1) ".bib")
17802 rds (list (list 'bib bib)))))))
17803 (call-interactively 'reftex-citation)))
17805 ;;;; Functions extending outline functionality
17807 (defun org-beginning-of-line (&optional arg)
17808 "Go to the beginning of the current line. If that is invisible, continue
17809 to a visible line beginning. This makes the function of C-a more intuitive.
17810 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17811 first attempt, and only move to after the tags when the cursor is already
17812 beyond the end of the headline."
17813 (interactive "P")
17814 (let ((pos (point))
17815 (special (if (consp org-special-ctrl-a/e)
17816 (car org-special-ctrl-a/e)
17817 org-special-ctrl-a/e))
17818 refpos)
17819 (if (org-bound-and-true-p line-move-visual)
17820 (beginning-of-visual-line 1)
17821 (beginning-of-line 1))
17822 (if (and arg (fboundp 'move-beginning-of-line))
17823 (call-interactively 'move-beginning-of-line)
17824 (if (bobp)
17826 (backward-char 1)
17827 (if (org-invisible-p)
17828 (while (and (not (bobp)) (org-invisible-p))
17829 (backward-char 1)
17830 (beginning-of-line 1))
17831 (forward-char 1))))
17832 (when special
17833 (cond
17834 ((and (looking-at org-complex-heading-regexp)
17835 (= (char-after (match-end 1)) ?\ ))
17836 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17837 (point-at-eol)))
17838 (goto-char
17839 (if (eq special t)
17840 (cond ((> pos refpos) refpos)
17841 ((= pos (point)) refpos)
17842 (t (point)))
17843 (cond ((> pos (point)) (point))
17844 ((not (eq last-command this-command)) (point))
17845 (t refpos)))))
17846 ((org-at-item-p)
17847 (goto-char
17848 (if (eq special t)
17849 (cond ((> pos (match-end 4)) (match-end 4))
17850 ((= pos (point)) (match-end 4))
17851 (t (point)))
17852 (cond ((> pos (point)) (point))
17853 ((not (eq last-command this-command)) (point))
17854 (t (match-end 4))))))))
17855 (org-no-warnings
17856 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17858 (defun org-end-of-line (&optional arg)
17859 "Go to the end of the line.
17860 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17861 first attempt, and only move to after the tags when the cursor is already
17862 beyond the end of the headline."
17863 (interactive "P")
17864 (let ((special (if (consp org-special-ctrl-a/e)
17865 (cdr org-special-ctrl-a/e)
17866 org-special-ctrl-a/e)))
17867 (if (or (not special)
17868 (not (org-on-heading-p))
17869 arg)
17870 (call-interactively
17871 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17872 ((fboundp 'move-end-of-line) 'move-end-of-line)
17873 (t 'end-of-line)))
17874 (let ((pos (point)))
17875 (beginning-of-line 1)
17876 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17877 (if (eq special t)
17878 (if (or (< pos (match-beginning 1))
17879 (= pos (match-end 0)))
17880 (goto-char (match-beginning 1))
17881 (goto-char (match-end 0)))
17882 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17883 (goto-char (match-end 0))
17884 (goto-char (match-beginning 1))))
17885 (call-interactively (if (fboundp 'move-end-of-line)
17886 'move-end-of-line
17887 'end-of-line)))))
17888 (org-no-warnings
17889 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17891 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17892 (define-key org-mode-map "\C-e" 'org-end-of-line)
17893 (define-key org-mode-map [home] 'org-beginning-of-line)
17894 (define-key org-mode-map [end] 'org-end-of-line)
17896 (defun org-backward-sentence (&optional arg)
17897 "Go to beginning of sentence, or beginning of table field.
17898 This will call `backward-sentence' or `org-table-beginning-of-field',
17899 depending on context."
17900 (interactive "P")
17901 (cond
17902 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17903 (t (call-interactively 'backward-sentence))))
17905 (defun org-forward-sentence (&optional arg)
17906 "Go to end of sentence, or end of table field.
17907 This will call `forward-sentence' or `org-table-end-of-field',
17908 depending on context."
17909 (interactive "P")
17910 (cond
17911 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17912 (t (call-interactively 'forward-sentence))))
17914 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17915 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17917 (defun org-kill-line (&optional arg)
17918 "Kill line, to tags or end of line."
17919 (interactive "P")
17920 (cond
17921 ((or (not org-special-ctrl-k)
17922 (bolp)
17923 (not (org-on-heading-p)))
17924 (call-interactively 'kill-line))
17925 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17926 (kill-region (point) (match-beginning 1))
17927 (org-set-tags nil t))
17928 (t (kill-region (point) (point-at-eol)))))
17930 (define-key org-mode-map "\C-k" 'org-kill-line)
17932 (defun org-yank (&optional arg)
17933 "Yank. If the kill is a subtree, treat it specially.
17934 This command will look at the current kill and check if is a single
17935 subtree, or a series of subtrees[1]. If it passes the test, and if the
17936 cursor is at the beginning of a line or after the stars of a currently
17937 empty headline, then the yank is handled specially. How exactly depends
17938 on the value of the following variables, both set by default.
17940 org-yank-folded-subtrees
17941 When set, the subtree(s) will be folded after insertion, but only
17942 if doing so would now swallow text after the yanked text.
17944 org-yank-adjusted-subtrees
17945 When set, the subtree will be promoted or demoted in order to
17946 fit into the local outline tree structure, which means that the level
17947 will be adjusted so that it becomes the smaller one of the two
17948 *visible* surrounding headings.
17950 Any prefix to this command will cause `yank' to be called directly with
17951 no special treatment. In particular, a simple `C-u' prefix will just
17952 plainly yank the text as it is.
17954 \[1] The test checks if the first non-white line is a heading
17955 and if there are no other headings with fewer stars."
17956 (interactive "P")
17957 (org-yank-generic 'yank arg))
17959 (defun org-yank-generic (command arg)
17960 "Perform some yank-like command.
17962 This function implements the behavior described in the `org-yank'
17963 documentation. However, it has been generalized to work for any
17964 interactive command with similar behavior."
17966 ;; pretend to be command COMMAND
17967 (setq this-command command)
17969 (if arg
17970 (call-interactively command)
17972 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17973 (and (org-kill-is-subtree-p)
17974 (or (bolp)
17975 (and (looking-at "[ \t]*$")
17976 (string-match
17977 "\\`\\*+\\'"
17978 (buffer-substring (point-at-bol) (point)))))))
17979 swallowp)
17980 (cond
17981 ((and subtreep org-yank-folded-subtrees)
17982 (let ((beg (point))
17983 end)
17984 (if (and subtreep org-yank-adjusted-subtrees)
17985 (org-paste-subtree nil nil 'for-yank)
17986 (call-interactively command))
17988 (setq end (point))
17989 (goto-char beg)
17990 (when (and (bolp) subtreep
17991 (not (setq swallowp
17992 (org-yank-folding-would-swallow-text beg end))))
17993 (or (looking-at outline-regexp)
17994 (re-search-forward (concat "^" outline-regexp) end t))
17995 (while (and (< (point) end) (looking-at outline-regexp))
17996 (hide-subtree)
17997 (org-cycle-show-empty-lines 'folded)
17998 (condition-case nil
17999 (outline-forward-same-level 1)
18000 (error (goto-char end)))))
18001 (when swallowp
18002 (message
18003 "Inserted text not folded because that would swallow text"))
18005 (goto-char end)
18006 (skip-chars-forward " \t\n\r")
18007 (beginning-of-line 1)
18008 (push-mark beg 'nomsg)))
18009 ((and subtreep org-yank-adjusted-subtrees)
18010 (let ((beg (point-at-bol)))
18011 (org-paste-subtree nil nil 'for-yank)
18012 (push-mark beg 'nomsg)))
18014 (call-interactively command))))))
18016 (defun org-yank-folding-would-swallow-text (beg end)
18017 "Would hide-subtree at BEG swallow any text after END?"
18018 (let (level)
18019 (save-excursion
18020 (goto-char beg)
18021 (when (or (looking-at outline-regexp)
18022 (re-search-forward (concat "^" outline-regexp) end t))
18023 (setq level (org-outline-level)))
18024 (goto-char end)
18025 (skip-chars-forward " \t\r\n\v\f")
18026 (if (or (eobp)
18027 (and (bolp) (looking-at org-outline-regexp)
18028 (<= (org-outline-level) level)))
18029 nil ; Nothing would be swallowed
18030 t)))) ; something would swallow
18032 (define-key org-mode-map "\C-y" 'org-yank)
18034 (defun org-invisible-p ()
18035 "Check if point is at a character currently not visible."
18036 ;; Early versions of noutline don't have `outline-invisible-p'.
18037 (if (fboundp 'outline-invisible-p)
18038 (outline-invisible-p)
18039 (get-char-property (point) 'invisible)))
18041 (defun org-invisible-p2 ()
18042 "Check if point is at a character currently not visible."
18043 (save-excursion
18044 (if (and (eolp) (not (bobp))) (backward-char 1))
18045 ;; Early versions of noutline don't have `outline-invisible-p'.
18046 (if (fboundp 'outline-invisible-p)
18047 (outline-invisible-p)
18048 (get-char-property (point) 'invisible))))
18050 (defun org-back-to-heading (&optional invisible-ok)
18051 "Call `outline-back-to-heading', but provide a better error message."
18052 (condition-case nil
18053 (outline-back-to-heading invisible-ok)
18054 (error (error "Before first headline at position %d in buffer %s"
18055 (point) (current-buffer)))))
18057 (defun org-before-first-heading-p ()
18058 "Before first heading?"
18059 (save-excursion
18060 (null (re-search-backward "^\\*+ " nil t))))
18062 (defun org-on-heading-p (&optional ignored)
18063 (outline-on-heading-p t))
18064 (defun org-at-heading-p (&optional ignored)
18065 (outline-on-heading-p t))
18067 (defun org-point-at-end-of-empty-headline ()
18068 "If point is at the end of an empty headline, return t, else nil.
18069 If the heading only contains a TODO keyword, it is still still considered
18070 empty."
18071 (and (looking-at "[ \t]*$")
18072 (save-excursion
18073 (beginning-of-line 1)
18074 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18075 "\\)?[ \t]*$")))))
18076 (defun org-at-heading-or-item-p ()
18077 (or (org-on-heading-p) (org-at-item-p)))
18079 (defun org-on-target-p ()
18080 (or (org-in-regexp org-radio-target-regexp)
18081 (org-in-regexp org-target-regexp)))
18083 (defun org-up-heading-all (arg)
18084 "Move to the heading line of which the present line is a subheading.
18085 This function considers both visible and invisible heading lines.
18086 With argument, move up ARG levels."
18087 (if (fboundp 'outline-up-heading-all)
18088 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18089 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18091 (defun org-up-heading-safe ()
18092 "Move to the heading line of which the present line is a subheading.
18093 This version will not throw an error. It will return the level of the
18094 headline found, or nil if no higher level is found.
18096 Also, this function will be a lot faster than `outline-up-heading',
18097 because it relies on stars being the outline starters. This can really
18098 make a significant difference in outlines with very many siblings."
18099 (let (start-level re)
18100 (org-back-to-heading t)
18101 (setq start-level (funcall outline-level))
18102 (if (equal start-level 1)
18104 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18105 (if (re-search-backward re nil t)
18106 (funcall outline-level)))))
18108 (defun org-first-sibling-p ()
18109 "Is this heading the first child of its parents?"
18110 (interactive)
18111 (let ((re (concat "^" outline-regexp))
18112 level l)
18113 (unless (org-at-heading-p t)
18114 (error "Not at a heading"))
18115 (setq level (funcall outline-level))
18116 (save-excursion
18117 (if (not (re-search-backward re nil t))
18119 (setq l (funcall outline-level))
18120 (< l level)))))
18122 (defun org-goto-sibling (&optional previous)
18123 "Goto the next sibling, even if it is invisible.
18124 When PREVIOUS is set, go to the previous sibling instead. Returns t
18125 when a sibling was found. When none is found, return nil and don't
18126 move point."
18127 (let ((fun (if previous 're-search-backward 're-search-forward))
18128 (pos (point))
18129 (re (concat "^" outline-regexp))
18130 level l)
18131 (when (condition-case nil (org-back-to-heading t) (error nil))
18132 (setq level (funcall outline-level))
18133 (catch 'exit
18134 (or previous (forward-char 1))
18135 (while (funcall fun re nil t)
18136 (setq l (funcall outline-level))
18137 (when (< l level) (goto-char pos) (throw 'exit nil))
18138 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18139 (goto-char pos)
18140 nil))))
18142 (defun org-show-siblings ()
18143 "Show all siblings of the current headline."
18144 (save-excursion
18145 (while (org-goto-sibling) (org-flag-heading nil)))
18146 (save-excursion
18147 (while (org-goto-sibling 'previous)
18148 (org-flag-heading nil))))
18150 (defun org-show-hidden-entry ()
18151 "Show an entry where even the heading is hidden."
18152 (save-excursion
18153 (org-show-entry)))
18155 (defun org-flag-heading (flag &optional entry)
18156 "Flag the current heading. FLAG non-nil means make invisible.
18157 When ENTRY is non-nil, show the entire entry."
18158 (save-excursion
18159 (org-back-to-heading t)
18160 ;; Check if we should show the entire entry
18161 (if entry
18162 (progn
18163 (org-show-entry)
18164 (save-excursion
18165 (and (outline-next-heading)
18166 (org-flag-heading nil))))
18167 (outline-flag-region (max (point-min) (1- (point)))
18168 (save-excursion (outline-end-of-heading) (point))
18169 flag))))
18171 (defun org-get-next-sibling ()
18172 "Move to next heading of the same level, and return point.
18173 If there is no such heading, return nil.
18174 This is like outline-next-sibling, but invisible headings are ok."
18175 (let ((level (funcall outline-level)))
18176 (outline-next-heading)
18177 (while (and (not (eobp)) (> (funcall outline-level) level))
18178 (outline-next-heading))
18179 (if (or (eobp) (< (funcall outline-level) level))
18181 (point))))
18183 (defun org-get-last-sibling ()
18184 "Move to previous heading of the same level, and return point.
18185 If there is no such heading, return nil."
18186 (let ((opoint (point))
18187 (level (funcall outline-level)))
18188 (outline-previous-heading)
18189 (when (and (/= (point) opoint) (outline-on-heading-p t))
18190 (while (and (> (funcall outline-level) level)
18191 (not (bobp)))
18192 (outline-previous-heading))
18193 (if (< (funcall outline-level) level)
18195 (point)))))
18197 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18198 ;; This contains an exact copy of the original function, but it uses
18199 ;; `org-back-to-heading', to make it work also in invisible
18200 ;; trees. And is uses an invisible-OK argument.
18201 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18202 ;; Furthermore, when used inside Org, finding the end of a large subtree
18203 ;; with many children and grandchildren etc, this can be much faster
18204 ;; than the outline version.
18205 (org-back-to-heading invisible-OK)
18206 (let ((first t)
18207 (level (funcall outline-level)))
18208 (if (and (org-mode-p) (< level 1000))
18209 ;; A true heading (not a plain list item), in Org-mode
18210 ;; This means we can easily find the end by looking
18211 ;; only for the right number of stars. Using a regexp to do
18212 ;; this is so much faster than using a Lisp loop.
18213 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18214 (forward-char 1)
18215 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18216 ;; something else, do it the slow way
18217 (while (and (not (eobp))
18218 (or first (> (funcall outline-level) level)))
18219 (setq first nil)
18220 (outline-next-heading)))
18221 (unless to-heading
18222 (if (memq (preceding-char) '(?\n ?\^M))
18223 (progn
18224 ;; Go to end of line before heading
18225 (forward-char -1)
18226 (if (memq (preceding-char) '(?\n ?\^M))
18227 ;; leave blank line before heading
18228 (forward-char -1))))))
18229 (point))
18231 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18232 "Use Org version in org-mode, for dramatic speed-up."
18233 (if (eq major-mode 'org-mode)
18234 (progn
18235 (org-end-of-subtree nil t)
18236 (unless (eobp) (backward-char 1)))
18237 ad-do-it))
18239 (defun org-forward-same-level (arg &optional invisible-ok)
18240 "Move forward to the arg'th subheading at same level as this one.
18241 Stop at the first and last subheadings of a superior heading."
18242 (interactive "p")
18243 (org-back-to-heading invisible-ok)
18244 (org-on-heading-p)
18245 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18246 (re (format "^\\*\\{1,%d\\} " level))
18248 (forward-char 1)
18249 (while (> arg 0)
18250 (while (and (re-search-forward re nil 'move)
18251 (setq l (- (match-end 0) (match-beginning 0) 1))
18252 (= l level)
18253 (not invisible-ok)
18254 (progn (backward-char 1) (org-invisible-p)))
18255 (if (< l level) (setq arg 1)))
18256 (setq arg (1- arg)))
18257 (beginning-of-line 1)))
18259 (defun org-backward-same-level (arg &optional invisible-ok)
18260 "Move backward to the arg'th subheading at same level as this one.
18261 Stop at the first and last subheadings of a superior heading."
18262 (interactive "p")
18263 (org-back-to-heading)
18264 (org-on-heading-p)
18265 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18266 (re (format "^\\*\\{1,%d\\} " level))
18268 (while (> arg 0)
18269 (while (and (re-search-backward re nil 'move)
18270 (setq l (- (match-end 0) (match-beginning 0) 1))
18271 (= l level)
18272 (not invisible-ok)
18273 (org-invisible-p))
18274 (if (< l level) (setq arg 1)))
18275 (setq arg (1- arg)))))
18277 (defun org-show-subtree ()
18278 "Show everything after this heading at deeper levels."
18279 (outline-flag-region
18280 (point)
18281 (save-excursion
18282 (org-end-of-subtree t t))
18283 nil))
18285 (defun org-show-entry ()
18286 "Show the body directly following this heading.
18287 Show the heading too, if it is currently invisible."
18288 (interactive)
18289 (save-excursion
18290 (condition-case nil
18291 (progn
18292 (org-back-to-heading t)
18293 (outline-flag-region
18294 (max (point-min) (1- (point)))
18295 (save-excursion
18296 (if (re-search-forward
18297 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18298 (match-beginning 1)
18299 (point-max)))
18300 nil)
18301 (org-cycle-hide-drawers 'children))
18302 (error nil))))
18304 (defun org-make-options-regexp (kwds &optional extra)
18305 "Make a regular expression for keyword lines."
18306 (concat
18308 "#?[ \t]*\\+\\("
18309 (mapconcat 'regexp-quote kwds "\\|")
18310 (if extra (concat "\\|" extra))
18311 "\\):[ \t]*"
18312 "\\(.*\\)"))
18314 ;; Make isearch reveal the necessary context
18315 (defun org-isearch-end ()
18316 "Reveal context after isearch exits."
18317 (when isearch-success ; only if search was successful
18318 (if (featurep 'xemacs)
18319 ;; Under XEmacs, the hook is run in the correct place,
18320 ;; we directly show the context.
18321 (org-show-context 'isearch)
18322 ;; In Emacs the hook runs *before* restoring the overlays.
18323 ;; So we have to use a one-time post-command-hook to do this.
18324 ;; (Emacs 22 has a special variable, see function `org-mode')
18325 (unless (and (boundp 'isearch-mode-end-hook-quit)
18326 isearch-mode-end-hook-quit)
18327 ;; Only when the isearch was not quitted.
18328 (org-add-hook 'post-command-hook 'org-isearch-post-command
18329 'append 'local)))))
18331 (defun org-isearch-post-command ()
18332 "Remove self from hook, and show context."
18333 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18334 (org-show-context 'isearch))
18337 ;;;; Integration with and fixes for other packages
18339 ;;; Imenu support
18341 (defvar org-imenu-markers nil
18342 "All markers currently used by Imenu.")
18343 (make-variable-buffer-local 'org-imenu-markers)
18345 (defun org-imenu-new-marker (&optional pos)
18346 "Return a new marker for use by Imenu, and remember the marker."
18347 (let ((m (make-marker)))
18348 (move-marker m (or pos (point)))
18349 (push m org-imenu-markers)
18352 (defun org-imenu-get-tree ()
18353 "Produce the index for Imenu."
18354 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18355 (setq org-imenu-markers nil)
18356 (let* ((n org-imenu-depth)
18357 (re (concat "^" outline-regexp))
18358 (subs (make-vector (1+ n) nil))
18359 (last-level 0)
18360 m level head)
18361 (save-excursion
18362 (save-restriction
18363 (widen)
18364 (goto-char (point-max))
18365 (while (re-search-backward re nil t)
18366 (setq level (org-reduced-level (funcall outline-level)))
18367 (when (<= level n)
18368 (looking-at org-complex-heading-regexp)
18369 (setq head (org-link-display-format
18370 (org-match-string-no-properties 4))
18371 m (org-imenu-new-marker))
18372 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18373 (if (>= level last-level)
18374 (push (cons head m) (aref subs level))
18375 (push (cons head (aref subs (1+ level))) (aref subs level))
18376 (loop for i from (1+ level) to n do (aset subs i nil)))
18377 (setq last-level level)))))
18378 (aref subs 1)))
18380 (eval-after-load "imenu"
18381 '(progn
18382 (add-hook 'imenu-after-jump-hook
18383 (lambda ()
18384 (if (eq major-mode 'org-mode)
18385 (org-show-context 'org-goto))))))
18387 (defun org-link-display-format (link)
18388 "Replace a link with either the description, or the link target
18389 if no description is present"
18390 (save-match-data
18391 (if (string-match org-bracket-link-analytic-regexp link)
18392 (replace-match (if (match-end 5)
18393 (match-string 5 link)
18394 (concat (match-string 1 link)
18395 (match-string 3 link)))
18396 nil t link)
18397 link)))
18399 ;; Speedbar support
18401 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18402 "Overlay marking the agenda restriction line in speedbar.")
18403 (org-overlay-put org-speedbar-restriction-lock-overlay
18404 'face 'org-agenda-restriction-lock)
18405 (org-overlay-put org-speedbar-restriction-lock-overlay
18406 'help-echo "Agendas are currently limited to this item.")
18407 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18409 (defun org-speedbar-set-agenda-restriction ()
18410 "Restrict future agenda commands to the location at point in speedbar.
18411 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18412 (interactive)
18413 (require 'org-agenda)
18414 (let (p m tp np dir txt)
18415 (cond
18416 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18417 'org-imenu t))
18418 (setq m (get-text-property p 'org-imenu-marker))
18419 (with-current-buffer (marker-buffer m)
18420 (goto-char m)
18421 (org-agenda-set-restriction-lock 'subtree)))
18422 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18423 'speedbar-function 'speedbar-find-file))
18424 (setq tp (previous-single-property-change
18425 (1+ p) 'speedbar-function)
18426 np (next-single-property-change
18427 tp 'speedbar-function)
18428 dir (speedbar-line-directory)
18429 txt (buffer-substring-no-properties (or tp (point-min))
18430 (or np (point-max))))
18431 (with-current-buffer (find-file-noselect
18432 (let ((default-directory dir))
18433 (expand-file-name txt)))
18434 (unless (org-mode-p)
18435 (error "Cannot restrict to non-Org-mode file"))
18436 (org-agenda-set-restriction-lock 'file)))
18437 (t (error "Don't know how to restrict Org-mode's agenda")))
18438 (org-move-overlay org-speedbar-restriction-lock-overlay
18439 (point-at-bol) (point-at-eol))
18440 (setq current-prefix-arg nil)
18441 (org-agenda-maybe-redo)))
18443 (eval-after-load "speedbar"
18444 '(progn
18445 (speedbar-add-supported-extension ".org")
18446 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18447 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18448 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18449 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18450 (add-hook 'speedbar-visiting-tag-hook
18451 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18454 ;;; Fixes and Hacks for problems with other packages
18456 ;; Make flyspell not check words in links, to not mess up our keymap
18457 (defun org-mode-flyspell-verify ()
18458 "Don't let flyspell put overlays at active buttons."
18459 (and (not (get-text-property (point) 'keymap))
18460 (not (get-text-property (point) 'org-no-flyspell))))
18462 (defun org-remove-flyspell-overlays-in (beg end)
18463 "Remove flyspell overlays in region."
18464 (and (org-bound-and-true-p flyspell-mode)
18465 (fboundp 'flyspell-delete-region-overlays)
18466 (flyspell-delete-region-overlays beg end))
18467 (add-text-properties beg end '(org-no-flyspell t)))
18469 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18470 (eval-after-load "bookmark"
18471 '(if (boundp 'bookmark-after-jump-hook)
18472 ;; We can use the hook
18473 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18474 ;; Hook not available, use advice
18475 (defadvice bookmark-jump (after org-make-visible activate)
18476 "Make the position visible."
18477 (org-bookmark-jump-unhide))))
18479 ;; Make sure saveplace shows the location if it was hidden
18480 (eval-after-load "saveplace"
18481 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18482 "Make the position visible."
18483 (org-bookmark-jump-unhide)))
18485 ;; Make sure ecb shows the location if it was hidden
18486 (eval-after-load "ecb"
18487 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18488 "Make hierarchy visible when jumping into location from ECB tree buffer."
18489 (if (eq major-mode 'org-mode)
18490 (org-show-context))))
18492 (defun org-bookmark-jump-unhide ()
18493 "Unhide the current position, to show the bookmark location."
18494 (and (org-mode-p)
18495 (or (org-invisible-p)
18496 (save-excursion (goto-char (max (point-min) (1- (point))))
18497 (org-invisible-p)))
18498 (org-show-context 'bookmark-jump)))
18500 ;; Make session.el ignore our circular variable
18501 (eval-after-load "session"
18502 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18504 ;;;; Experimental code
18506 (defun org-closed-in-range ()
18507 "Sparse tree of items closed in a certain time range.
18508 Still experimental, may disappear in the future."
18509 (interactive)
18510 ;; Get the time interval from the user.
18511 (let* ((time1 (org-float-time
18512 (org-read-date nil 'to-time nil "Starting date: ")))
18513 (time2 (org-float-time
18514 (org-read-date nil 'to-time nil "End date:")))
18515 ;; callback function
18516 (callback (lambda ()
18517 (let ((time
18518 (org-float-time
18519 (apply 'encode-time
18520 (org-parse-time-string
18521 (match-string 1))))))
18522 ;; check if time in interval
18523 (and (>= time time1) (<= time time2))))))
18524 ;; make tree, check each match with the callback
18525 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18527 ;;;; Finish up
18529 (provide 'org)
18531 (run-hooks 'org-load-hook)
18533 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18535 ;;; org.el ends here